llm

package
v0.1.0-alpha.61 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 11, 2026 License: GPL-3.0 Imports: 34 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package llm provides local model provider adapters.

Index

Constants

View Source
const (
	// ManagedLlamaVersion is the upstream release installed and owned by MagicHandy.
	ManagedLlamaVersion = "b11149"
	// ManagedLlamaCommit pins the exact upstream source represented by ManagedLlamaVersion.
	ManagedLlamaCommit = "d2e54583c7452353eb35d40431281f6ee984332f"
)
View Source
const (
	ManagedRuntimeStateMissing  = "missing"
	ManagedRuntimeStateReady    = "ready"
	ManagedRuntimeStateOutdated = "outdated"
	ManagedRuntimeStateInvalid  = "invalid"
)

Managed llama.cpp runtime states reported to the API and UI.

View Source
const (
	RuntimeBuildStatusQueued    = "queued"
	RuntimeBuildStatusBuilding  = "building"
	RuntimeBuildStatusComplete  = "complete"
	RuntimeBuildStatusFailed    = "failed"
	RuntimeBuildStatusCancelled = "cancelled"
)

Managed llama.cpp installation states reported to the API and UI.

View Source
const (
	// CatalogFitRecommended marks the first curated model, in catalog order,
	// that the detected GPU holds.
	CatalogFitRecommended = "recommended"
	// CatalogFitSupported marks another curated model the hardware holds.
	CatalogFitSupported = "supported"
	// CatalogFitBelowMinimum means the GPU has less memory than the model needs.
	CatalogFitBelowMinimum = "below_minimum"
	// CatalogFitUnknownVRAM means an NVIDIA GPU was found but its memory was not.
	CatalogFitUnknownVRAM = "unknown_vram"
	// CatalogFitNoGPU means no NVIDIA GPU was found; local chat would be too slow.
	CatalogFitNoGPU = "no_gpu"
)

Catalog fit values describe how one curated model matches the detected GPU.

View Source
const (
	// TemplateFixSourceKnown marks a fix applied automatically because the
	// model embeds a chat template MagicHandy has measured.
	TemplateFixSourceKnown = "known"
	// TemplateFixSourceUser marks a fix the user turned on for a template
	// with the same defect that MagicHandy has not measured.
	TemplateFixSourceUser = "user"
)

Where a model's template fix comes from.

View Source
const (
	// ImportStatusQueued identifies an import waiting for its copy goroutine.
	ImportStatusQueued = "queued"
	// ImportStatusCopying identifies an active verified copy.
	ImportStatusCopying = "copying"
	// ImportStatusComplete identifies a committed managed model.
	ImportStatusComplete = "complete"
	// ImportStatusFailed identifies an import that did not commit.
	ImportStatusFailed = "failed"
	// ImportStatusCancelled identifies an explicitly cancelled import.
	ImportStatusCancelled = "cancelled"
)
View Source
const (
	// ModelSourceGGUF identifies a user-selected standalone GGUF file.
	ModelSourceGGUF = "gguf"
	// ModelSourceOllama identifies a GGUF copied from an Ollama library.
	ModelSourceOllama = "ollama"
)
View Source
const (
	// ImportStatusDownloading identifies an active verified catalog download.
	ImportStatusDownloading = "downloading"
)
View Source
const (
	// TemplateFixGemma4CloseThinking swaps in Google's Gemma 4 chat template
	// with an empty thought channel closed whenever thinking is off. Several
	// fine-tuned Gemma 4 builds ship an older template without that close and
	// start hidden reasoning on every turn: replies take seconds and often run
	// out of tokens before the JSON the app needs.
	TemplateFixGemma4CloseThinking = "gemma4-close-thinking"
)

Chat template fixes MagicHandy can apply when it launches a managed model.

Variables

View Source
var (
	// ErrModelNotFound reports a missing managed model record.
	ErrModelNotFound = errors.New("managed model not found")
	// ErrModelSelected prevents deleting the model selected by settings.
	ErrModelSelected = errors.New("selected model cannot be removed")
	// ErrImportNotFound reports an unknown in-memory import job.
	ErrImportNotFound = errors.New("model import not found")
	// ErrModelInventoryUnavailable classifies internal inventory failures for API callers.
	ErrModelInventoryUnavailable = errors.New("managed model inventory is unavailable")
)
View Source
var ErrNoTemplateFix = errors.New("this model has no chat template fix to change")

ErrNoTemplateFix reports a model with no chat template fix to change.

View Source
var ErrOutputTruncated = errors.New("LLM output reached the maximum token limit")

ErrOutputTruncated reports that a provider exhausted its generation budget.

Functions

func BudgetChatRequest

func BudgetChatRequest(request ChatRequest, contextSize int) (ChatRequest, PromptBudget, error)

BudgetChatRequest preserves complete system/developer messages and the final exchange (including a repair's original user turn). Only oldest history is removed. An oversized essential prompt fails clearly instead of losing control rules.

func CatalogFit

func CatalogFit(model CatalogModel, hardware CatalogHardware) string

CatalogFit rates one curated model against the detected GPU. Only measured memory needs are used: a smaller card is told the model will not fit rather than being offered an untested recommendation. The first entry in catalog order that fits is recommended, so each card gets the best model it holds.

func ChooseOpenAICandidate

func ChooseOpenAICandidate(ctx context.Context, options OpenAIOptions, evidence string, choices []DecisionChoice) (string, error)

ChooseOpenAICandidate uses separately authorized API-key billing. It has no refresh/retry/fallback into any other credential or inference service.

func DomainOutput

func DomainOutput(raw string, original json.RawMessage) (string, error)

DomainOutput restores omission only where our original contract permitted omission. Required nulls remain invalid; explicit empty arrays/objects remain intact, including clear-layer operations. Semantic parsers still run next.

func IsCloudOutcome

func IsCloudOutcome(err error) bool

IsCloudOutcome keeps a cloud failure out of local repair/fallback paths.

func ManagedLlamaRuntimeRoot

func ManagedLlamaRuntimeRoot(dataDir string) string

ManagedLlamaRuntimeRoot returns the private directory for app-owned runner builds.

func OpenAISchema

func OpenAISchema(raw json.RawMessage) (json.RawMessage, error)

OpenAISchema maps our omission-based domain schemas into OpenAI strict schemas. Optional fields become required nullable fields on the wire only. The original schema remains the authority for omission versus explicit clear.

func PromptInputByteLimit

func PromptInputByteLimit(contextSize, outputTokens, reasoningTokens, schemaBytes int) int

PromptInputByteLimit is shared with composition so optional memories are selected within the same conservative context policy as provider admission.

func SuggestedOllamaModelsPath

func SuggestedOllamaModelsPath() string

SuggestedOllamaModelsPath returns Ollama's configured or platform-default library root without requiring the daemon to be running.

func TerminateManagedRunnerProcess

func TerminateManagedRunnerProcess(_ string, _ int) error

TerminateManagedRunnerProcess rejects the recovery action outside the currently supported Windows managed desktop runtime.

func ValidateCloudModel

func ValidateCloudModel(model string) error

ValidateCloudModel bounds model identifiers before constructing a request.

Types

type CatalogHardware

type CatalogHardware struct {
	NVIDIA  bool
	VRAMMiB int
}

CatalogHardware carries the GPU facts a recommendation needs.

type CatalogModel

type CatalogModel struct {
	ID            string `json:"id"`
	DisplayName   string `json:"display_name"`
	Summary       string `json:"summary"`
	Family        string `json:"family"`
	ParameterSize string `json:"parameter_size"`
	Quantization  string `json:"quantization"`
	SizeBytes     int64  `json:"size_bytes"`
	SHA256        string `json:"sha256"`
	License       string `json:"license"`
	LicenseURL    string `json:"license_url"`
	SourceName    string `json:"source_name"`
	SourceURL     string `json:"source_url"`
	DownloadURL   string `json:"download_url"`
	// VRAMMiB is the dedicated GPU memory the model uses at the default context.
	VRAMMiB int `json:"vram_mib"`
	// MinVRAMMiB leaves room for the desktop beside VRAMMiB.
	MinVRAMMiB int `json:"min_vram_mib"`
	// Default marks the model the prompts are tuned against; setup chooses it
	// when the GPU's memory cannot be read.
	Default bool `json:"default"`
}

CatalogModel is one curated, checksum-pinned model the app can download.

Entries are content-addressed Ollama registry blobs, whose URL names the SHA-256 digest, or Hugging Face files pinned to one repository commit. Either way the download is verified against SHA256 before it enters the store. The catalog ships with each release; nothing fetches or updates it at runtime.

func CatalogModels

func CatalogModels() []CatalogModel

CatalogModels returns a copy of the curated download catalog.

func FindCatalogModel

func FindCatalogModel(id string) (CatalogModel, bool)

FindCatalogModel returns one curated entry by its stable ID.

type ChatRequest

type ChatRequest struct {
	Messages      []Message
	Model         string
	Temperature   float64
	TopP          float64
	RepeatPenalty float64
	RepeatLastN   int
	MaxTokens     int
	ReasoningMode string
	// JSONSchema optionally constrains generation; callers still validate semantics.
	JSONSchema json.RawMessage
	// ReasoningBudgetTokens is used only by providers with an explicit bounded-thinking API.
	ReasoningBudgetTokens int
	// OnBudget receives bounded prompt accounting without prompt contents.
	OnBudget   func(PromptBudget)     `json:"-"`
	OnProgress func(ProviderProgress) `json:"-"`
	// PreserveTailMessages protects a repair's original user turn as well as
	// the malformed response and repair instruction. Ordinary requests use one.
	PreserveTailMessages int
	// HistoryMessagesDropped accounts for whole messages removed by the
	// composer before provider admission (never includes their contents).
	HistoryMessagesDropped int
}

ChatRequest is the provider-neutral streaming chat request.

type CloudError

type CloudError struct {
	Kind string
}

CloudError is a safe, typed outcome. Remote error text can contain request data, so it is deliberately never included in logs or diagnostics.

func (*CloudError) Error

func (e *CloudError) Error() string

func (*CloudError) HoldMotion

func (e *CloudError) HoldMotion() bool

HoldMotion prevents a declined, stale, or unavailable cloud plan from triggering deterministic library fallback or another billing path.

type CloudModel

type CloudModel struct {
	Slug                     string           `json:"slug"`
	DisplayName              string           `json:"display_name"`
	Visibility               string           `json:"visibility"`
	DefaultReasoningLevel    string           `json:"default_reasoning_level,omitempty"`
	SupportedReasoningLevels []ReasoningLevel `json:"supported_reasoning_levels,omitempty"`
	ContextWindow            int              `json:"context_window,omitempty"`
}

CloudModel is an account-visible model from the Responses provider catalog.

type CompatibleOptions

type CompatibleOptions struct {
	HTTPProviderOptions
	Provider            string
	Token               TokenSource
	OutputMode          string
	SupportedParameters []string
	AllowFallbacks      bool
	AllowedProviders    []string
	DataCollection      string
	ZeroDataRetention   bool
}

CompatibleOptions declares protocol capabilities independently of llama.cpp. OpenRouter discovers model support; generic servers use the explicit saved capability policy, and a generic server on this computer with no saved policy gets the standard defaults described at localDefaults. Neither path emits local health or sampling extensions.

type CompatibleProvider

type CompatibleProvider struct {
	// contains filtered or unexported fields
}

CompatibleProvider is an ordinary Chat Completions adapter, not a local llama.cpp server and not ChatGPT plan usage.

func NewCompatibleProvider

func NewCompatibleProvider(options CompatibleOptions) (*CompatibleProvider, error)

NewCompatibleProvider constructs a credential-bound Chat Completions client.

func (*CompatibleProvider) Models

func (p *CompatibleProvider) Models(ctx context.Context) ([]HostedModel, error)

Models reads the provider's catalog without local health/load requests.

func (*CompatibleProvider) Status

Status reports catalog availability; readiness still requires generation.

func (*CompatibleProvider) StreamChat

func (p *CompatibleProvider) StreamChat(ctx context.Context, request ChatRequest, onDelta func(string) error) (string, error)

StreamChat releases output only after a successful terminal stream event.

type DecisionChoice

type DecisionChoice struct {
	Value       string `json:"value"`
	Description string `json:"description"`
}

DecisionChoice is an entire prevalidated candidate, not one independent axis.

type HTTPProviderOptions

type HTTPProviderOptions struct {
	BaseURL string
	Model   string
	Client  *http.Client
	Timeout time.Duration
	// ContextSize is known for managed runtimes; zero uses the app's bounded
	// input policy without claiming a remote server has this context available.
	ContextSize int
}

HTTPProviderOptions configures a local HTTP-backed provider.

type HostedModel

type HostedModel struct {
	ID                     string   `json:"id"`
	Name                   string   `json:"name"`
	SupportedParameters    []string `json:"supported_parameters,omitempty"`
	ReasoningEfforts       []string `json:"reasoning_efforts,omitempty"`
	DefaultReasoningEffort string   `json:"default_reasoning_effort,omitempty"`
	ContextLength          int      `json:"context_length,omitempty"`
}

HostedModel is provider catalog metadata, independent of local runtimes.

type ImportJob

type ImportJob struct {
	ID          string `json:"id"`
	Source      string `json:"source"`
	DisplayName string `json:"display_name"`
	Status      string `json:"status"`
	BytesCopied int64  `json:"bytes_copied"`
	TotalBytes  int64  `json:"total_bytes"`
	ModelID     string `json:"model_id,omitempty"`
	Error       string `json:"error,omitempty"`
	StartedAt   string `json:"started_at"`
	UpdatedAt   string `json:"updated_at"`
}

ImportJob is a progress snapshot for one explicit model copy.

type LlamaCPPProvider

type LlamaCPPProvider struct {
	// contains filtered or unexported fields
}

LlamaCPPProvider talks to llama-server through its OpenAI-compatible API.

func NewLlamaCPPProvider

func NewLlamaCPPProvider(options HTTPProviderOptions) (*LlamaCPPProvider, error)

NewLlamaCPPProvider creates a llama.cpp HTTP provider.

func (*LlamaCPPProvider) Status

Status checks the llama.cpp health endpoint without loading or downloading a model.

func (*LlamaCPPProvider) StreamChat

func (p *LlamaCPPProvider) StreamChat(ctx context.Context, request ChatRequest, onDelta func(string) error) (string, error)

StreamChat streams chat text from llama.cpp's OpenAI-compatible endpoint.

type LoadableProvider

type LoadableProvider interface {
	Provider

	Load(ctx context.Context) ProviderStatus
	Unload(ctx context.Context) ProviderStatus
}

LoadableProvider can explicitly load and unload provider runtime state.

type ManagedLlamaCPPOptions

type ManagedLlamaCPPOptions struct {
	HTTPProviderOptions
	RunnerPath  string
	ModelPath   string
	ContextSize int
	// ChatTemplateFile replaces the model's embedded chat template when a
	// known template fix applies; empty keeps the embedded template.
	ChatTemplateFile string
}

ManagedLlamaCPPOptions configures a managed llama-server process.

type ManagedLlamaCPPProvider

type ManagedLlamaCPPProvider struct {
	// contains filtered or unexported fields
}

ManagedLlamaCPPProvider starts and owns one configured llama-server process.

func NewManagedLlamaCPPProvider

func NewManagedLlamaCPPProvider(options ManagedLlamaCPPOptions) (*ManagedLlamaCPPProvider, error)

NewManagedLlamaCPPProvider creates a managed llama.cpp provider.

func (*ManagedLlamaCPPProvider) Close

func (p *ManagedLlamaCPPProvider) Close() error

Close permanently retires this provider. Unload alone permits later loading.

func (*ManagedLlamaCPPProvider) Load

Load starts the configured llama-server process and waits for readiness.

func (*ManagedLlamaCPPProvider) LoadReport

LoadReport returns what the runner reported while loading the model.

func (*ManagedLlamaCPPProvider) ProcessID

func (p *ManagedLlamaCPPProvider) ProcessID() int

ProcessID reports the process currently owned by this provider, if any.

func (*ManagedLlamaCPPProvider) Status

Status returns managed runner state without starting a process.

func (*ManagedLlamaCPPProvider) StreamChat

func (p *ManagedLlamaCPPProvider) StreamChat(ctx context.Context, request ChatRequest, onDelta func(string) error) (string, error)

StreamChat loads the configured runner if needed and streams chat text.

func (*ManagedLlamaCPPProvider) Unload

Unload stops the managed llama-server process.

type ManagedLlamaRuntimeBuild

type ManagedLlamaRuntimeBuild struct {
	ID        string `json:"id"`
	Backend   string `json:"backend"`
	Status    string `json:"status"`
	Message   string `json:"message"`
	Output    string `json:"output,omitempty"`
	StartedAt string `json:"started_at"`
	UpdatedAt string `json:"updated_at"`
}

ManagedLlamaRuntimeBuild is one in-process runtime installation job.

type ManagedLlamaRuntimeManager

type ManagedLlamaRuntimeManager struct {
	// contains filtered or unexported fields
}

ManagedLlamaRuntimeManager owns explicit installation jobs for the managed runner.

func OpenManagedLlamaRuntimeManager

func OpenManagedLlamaRuntimeManager(dataDir string) (*ManagedLlamaRuntimeManager, error)

OpenManagedLlamaRuntimeManager prepares app-owned runtime storage.

func (*ManagedLlamaRuntimeManager) CancelBuild

CancelBuild cancels the active runtime installation and its process tree.

func (*ManagedLlamaRuntimeManager) Close

func (m *ManagedLlamaRuntimeManager) Close()

Close cancels and waits for a runtime installation before app shutdown completes.

func (*ManagedLlamaRuntimeManager) Snapshot

Snapshot returns installed runtime state and the current/recent build job.

func (*ManagedLlamaRuntimeManager) StartBuild

StartBuild installs the pinned upstream runtime without accepting paths or URLs.

type ManagedLlamaRuntimeSnapshot

type ManagedLlamaRuntimeSnapshot struct {
	Runtime ManagedLlamaRuntimeStatus `json:"runtime"`
	Build   *ManagedLlamaRuntimeBuild `json:"build,omitempty"`
}

ManagedLlamaRuntimeSnapshot combines installed state with the current build.

type ManagedLlamaRuntimeStatus

type ManagedLlamaRuntimeStatus struct {
	State             string   `json:"state"`
	Installed         bool     `json:"installed"`
	Current           bool     `json:"current"`
	BuildSupported    bool     `json:"build_supported"`
	SupportedBackends []string `json:"supported_backends"`
	ExpectedVersion   string   `json:"expected_version"`
	Version           string   `json:"version,omitempty"`
	Commit            string   `json:"commit,omitempty"`
	Backend           string   `json:"backend,omitempty"`
	Source            string   `json:"source,omitempty"`
	BuiltAt           string   `json:"built_at,omitempty"`
	Message           string   `json:"message"`
	RunnerPath        string   `json:"-"`
}

ManagedLlamaRuntimeStatus is the backend-authoritative app-owned runner state.

func InspectManagedLlamaRuntime

func InspectManagedLlamaRuntime(dataDir string) ManagedLlamaRuntimeStatus

InspectManagedLlamaRuntime validates the active runtime manifest and runner path.

type ManagedLoadReport

type ManagedLoadReport struct {
	// OffloadedLayers and TotalLayers come from llama.cpp's
	// "offloaded N/M layers to GPU" line; both are zero until it appears.
	OffloadedLayers int `json:"offloaded_layers"`
	TotalLayers     int `json:"total_layers"`
}

ManagedLoadReport is what the managed runner said about placing the model while it loaded. A model that does not fully fit on the GPU still runs, but every reply slows down, which users otherwise only notice as lag.

func (ManagedLoadReport) FullyOffloaded

func (report ManagedLoadReport) FullyOffloaded() bool

FullyOffloaded reports a load that put every layer on the GPU.

type ManagedRunnerProcess

type ManagedRunnerProcess struct {
	PID        int    `json:"pid"`
	Executable string `json:"executable"`
}

ManagedRunnerProcess identifies an already-running copy of the exact executable configured for MagicHandy's managed llama.cpp runtime.

func FindManagedRunnerProcesses

func FindManagedRunnerProcesses(_ string, _ int) ([]ManagedRunnerProcess, error)

FindManagedRunnerProcesses is currently implemented for Windows, where the managed desktop installer and duplicate-runtime recovery workflow are used.

type Message

type Message struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

Message is one chat turn sent to a local model provider.

type ModelManager

type ModelManager struct {
	// contains filtered or unexported fields
}

ModelManager owns durable model metadata and managed file imports.

func OpenModelManager

func OpenModelManager(dataDir string) (*ModelManager, error)

OpenModelManager opens the inventory and prepares private model directories.

func OpenModelManagerWithDatabase

func OpenModelManagerWithDatabase(database *dbstore.DB) (*ModelManager, error)

OpenModelManagerWithDatabase borrows the process-owned datastore.

func (*ModelManager) CancelImport

func (m *ModelManager) CancelImport(id string) (ImportJob, error)

CancelImport cancels a queued or active copy. Completed history remains.

func (*ModelManager) CatalogModelInstalled

func (m *ModelManager) CatalogModelInstalled(ctx context.Context, model CatalogModel) (string, error)

CatalogModelInstalled returns the ready managed model holding a curated digest.

func (*ModelManager) CatalogPartialBytes

func (m *ModelManager) CatalogPartialBytes(model CatalogModel) int64

CatalogPartialBytes reports how much of a curated model a resumable partial holds.

func (*ModelManager) Close

func (m *ModelManager) Close() error

Close cancels imports, waits for copy loops, and closes the inventory.

func (*ModelManager) Delete

func (m *ModelManager) Delete(ctx context.Context, id, selectedID string) error

Delete removes only a MagicHandy-owned model copy. The selected model is protected so a running/configured provider never loses its backing file.

func (*ModelManager) DownloadsDir

func (m *ModelManager) DownloadsDir() string

DownloadsDir is where partial imports and catalog downloads are staged.

func (*ModelManager) Import

func (m *ModelManager) Import(id string) (ImportJob, error)

Import returns one import progress snapshot.

func (*ModelManager) ImportJobs

func (m *ModelManager) ImportJobs() []ImportJob

ImportJobs returns newest jobs first.

func (*ModelManager) List

func (m *ModelManager) List(ctx context.Context) ([]ModelRecord, error)

List returns inventory rows with filesystem state checked cheaply by size.

func (*ModelManager) Model

func (m *ModelManager) Model(ctx context.Context, id string) (ModelRecord, error)

Model returns one managed model by stable ID.

func (*ModelManager) ScanOllama

func (m *ModelManager) ScanOllama(ctx context.Context, root string) (OllamaScan, error)

ScanOllama parses manifests and validates local model blobs without hashing multi-gigabyte files. The digest is verified during the explicit copy.

func (*ModelManager) SetTemplateFix

func (m *ModelManager) SetTemplateFix(ctx context.Context, id string, enabled bool) (ModelRecord, error)

SetTemplateFix turns the offered template fix on or off for one model. A fix built in for a known template cannot be turned off.

func (*ModelManager) Snapshot

func (m *ModelManager) Snapshot(ctx context.Context) (ModelSnapshot, error)

Snapshot returns managed models and current/recent import jobs.

func (*ModelManager) StartCatalogDownload

func (m *ModelManager) StartCatalogDownload(ctx context.Context, model CatalogModel) (ImportJob, error)

StartCatalogDownload downloads one curated model into the managed store. Callers pass an entry from FindCatalogModel; HTTP handlers never accept a free-form URL. A model already in the store with the same digest completes immediately without touching the network.

func (*ModelManager) StartGGUFImport

func (m *ModelManager) StartGGUFImport(path, displayName string) (ImportJob, error)

StartGGUFImport starts a managed copy of one user-selected GGUF file.

func (*ModelManager) StartOllamaImport

func (m *ModelManager) StartOllamaImport(ctx context.Context, root, candidateID string) (ImportJob, error)

StartOllamaImport revalidates a scanned candidate and starts an atomic copy.

func (*ModelManager) Summary

func (m *ModelManager) Summary(ctx context.Context, selectedID string) (ModelSummary, error)

Summary counts inventory without inspecting unselected files. A nonempty selectedID is checked on every call, so removal/size/mtime changes use the same validation and compatibility-cache invalidation as an explicit Model read. An empty ID requests counts only (for external providers or absent runtimes).

func (*ModelManager) TemplateFixFile

func (m *ModelManager) TemplateFixFile(fix string) (string, error)

TemplateFixFile writes the fix's template beneath the model store and returns the path the runner loads with --chat-template-file.

type ModelRecord

type ModelRecord struct {
	ID            string `json:"id"`
	DisplayName   string `json:"display_name"`
	Provider      string `json:"provider"`
	Source        string `json:"source"`
	SourceName    string `json:"source_name,omitempty"`
	Format        string `json:"format"`
	Family        string `json:"family,omitempty"`
	ParameterSize string `json:"parameter_size,omitempty"`
	Quantization  string `json:"quantization,omitempty"`
	SizeBytes     int64  `json:"size_bytes"`
	SHA256        string `json:"sha256"`
	ModelPath     string `json:"model_path"`
	License       string `json:"license,omitempty"`
	ImportedAt    string `json:"imported_at"`
	UpdatedAt     string `json:"updated_at"`
	State         string `json:"state"`
	Message       string `json:"message,omitempty"`
	// Architecture is the GGUF general.architecture of a ready model.
	Architecture string `json:"architecture,omitempty"`
	// TemplateFix names the chat template fix the runner applies when this
	// model launches, and TemplateFixSource says why (known or user).
	TemplateFix       string `json:"template_fix,omitempty"`
	TemplateFixSource string `json:"template_fix_source,omitempty"`
	// TemplateFixOffer names a fix the user may turn on for a template with a
	// recognized defect that MagicHandy has not measured.
	TemplateFixOffer string `json:"template_fix_offer,omitempty"`
	// contains filtered or unexported fields
}

ModelRecord is one managed llama.cpp-compatible model copy.

type ModelSnapshot

type ModelSnapshot struct {
	Models    []ModelRecord `json:"models"`
	Imports   []ImportJob   `json:"imports"`
	StorePath string        `json:"store_path"`
}

ModelSnapshot is the backend-authoritative model-manager view.

type ModelSummary

type ModelSummary struct {
	ModelCount        int
	ActiveImportCount int
	SelectedReady     bool
}

ModelSummary is the compact status view; full metadata belongs to inventory UI.

type OllamaCandidate

type OllamaCandidate struct {
	ID              string `json:"id"`
	Name            string `json:"name"`
	Format          string `json:"format,omitempty"`
	Family          string `json:"family,omitempty"`
	ParameterSize   string `json:"parameter_size,omitempty"`
	Quantization    string `json:"quantization,omitempty"`
	SizeBytes       int64  `json:"size_bytes"`
	Digest          string `json:"digest,omitempty"`
	License         string `json:"license,omitempty"`
	Importable      bool   `json:"importable"`
	Reason          string `json:"reason,omitempty"`
	ImportedModelID string `json:"imported_model_id,omitempty"`
	// contains filtered or unexported fields
}

OllamaCandidate is one filesystem manifest that may be copied into the managed llama.cpp model store.

type OllamaModelInfo

type OllamaModelInfo struct {
	Name          string `json:"name"`
	Model         string `json:"model,omitempty"`
	ModifiedAt    string `json:"modified_at,omitempty"`
	SizeBytes     int64  `json:"size_bytes"`
	Digest        string `json:"digest,omitempty"`
	Format        string `json:"format,omitempty"`
	Family        string `json:"family,omitempty"`
	ParameterSize string `json:"parameter_size,omitempty"`
	Quantization  string `json:"quantization,omitempty"`
}

OllamaModelInfo is one model reported by Ollama's non-loading tags endpoint.

func ListOllamaModels

func ListOllamaModels(ctx context.Context, baseURL string, client *http.Client) ([]OllamaModelInfo, error)

ListOllamaModels lists daemon-managed models without requiring a selected model and without loading or downloading model data.

type OllamaProvider

type OllamaProvider struct {
	// contains filtered or unexported fields
}

OllamaProvider talks to an externally managed Ollama daemon.

func NewOllamaProvider

func NewOllamaProvider(options HTTPProviderOptions) (*OllamaProvider, error)

NewOllamaProvider creates an Ollama HTTP provider.

func (*OllamaProvider) Status

Status checks Ollama daemon reachability without loading or downloading a model.

func (*OllamaProvider) StreamChat

func (p *OllamaProvider) StreamChat(ctx context.Context, request ChatRequest, onDelta func(string) error) (string, error)

StreamChat streams chat text from Ollama's /api/chat endpoint.

type OllamaScan

type OllamaScan struct {
	Path       string            `json:"path"`
	Candidates []OllamaCandidate `json:"candidates"`
}

OllamaScan is a bounded snapshot of one Ollama model library.

type OpenAIOptions

type OpenAIOptions struct {
	// PlanUsage enables SIWC's preview field restrictions. API-key Responses
	// keeps its separate parameter capabilities and billing authorization.
	PlanUsage       bool
	Model           string
	ReasoningEffort string
	Token           TokenSource
	Client          *http.Client
	Timeout         time.Duration
	// ContextSize is the app's conservative input admission window, not a
	// request to enlarge the provider model. Zero preserves the 32K default.
	ContextSize int
	// BaseURL is injectable for protocol tests; the app uses the public API.
	BaseURL string
}

OpenAIOptions is separate from the local runtime's sampling/health options.

type OpenAIResponsesProvider

type OpenAIResponsesProvider struct {
	// contains filtered or unexported fields
}

OpenAIResponsesProvider implements ChatGPT plan inference through Responses.

func NewOpenAIResponsesProvider

func NewOpenAIResponsesProvider(options OpenAIOptions) (*OpenAIResponsesProvider, error)

NewOpenAIResponsesProvider keeps ChatGPT plan and API-key protocols distinct.

func (*OpenAIResponsesProvider) Models

Models reads the authenticated provider catalog, preserving provider order.

func (*OpenAIResponsesProvider) Status

Status reports model discovery, independently of real-generation readiness.

func (*OpenAIResponsesProvider) StreamChat

func (p *OpenAIResponsesProvider) StreamChat(ctx context.Context, request ChatRequest, onDelta func(string) error) (string, error)

StreamChat buffers Responses output until terminal completion is confirmed.

type PromptBudget

type PromptBudget struct {
	InputBytes             int `json:"input_bytes"`
	LimitBytes             int `json:"limit_bytes"`
	HistoryMessagesDropped int `json:"history_messages_dropped"`
}

PromptBudget reports byte accounting, never an exact tokenizer count. One UTF-8 byte per input token is a deliberately conservative admission estimate for byte-fallback tokenizers. Remote servers may have smaller contexts.

type Provider

type Provider interface {
	StreamChat(ctx context.Context, request ChatRequest, onDelta func(string) error) (string, error)
	Status(ctx context.Context) ProviderStatus
}

Provider streams text from one local LLM runtime.

type ProviderProgress

type ProviderProgress struct {
	Activity           bool
	LoadMillis         int64
	PromptEvalMillis   int64
	PromptTokens       int
	GeneratedTokens    int
	CachedPromptTokens int
	// ReasoningChars counts hidden reasoning characters in this update. The
	// text itself never leaves the provider; the count lets the model check
	// notice a model that reasons silently while thinking is off.
	ReasoningChars int
	// DecodeMillis and DecodeTokens time the generation phase when the
	// provider reports it, for a tokens-per-second figure.
	DecodeMillis int64
	DecodeTokens int
}

ProviderProgress carries timing and counters only. Hidden reasoning and prompt contents are deliberately excluded from diagnostics and callbacks.

type ProviderStatus

type ProviderStatus struct {
	Provider       string   `json:"provider"`
	BaseURL        string   `json:"base_url"`
	Model          string   `json:"model"`
	Available      bool     `json:"available"`
	ModelAvailable bool     `json:"model_available"`
	Managed        bool     `json:"managed"`
	Loaded         bool     `json:"loaded"`
	Loading        bool     `json:"loading,omitempty"`
	Models         []string `json:"models,omitempty"`
	Message        string   `json:"message,omitempty"`
}

ProviderStatus is a diagnostics-safe provider readiness snapshot.

type ReasoningLevel

type ReasoningLevel struct {
	Effort string `json:"effort"`
}

ReasoningLevel is account-specific catalog metadata, separate from local runtime reasoning switches and paid service tiers.

type TokenSource

type TokenSource func(context.Context) (string, error)

TokenSource returns the credential for one captured account registration. Implementations refresh host-side; credentials never enter request settings.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL