llm

package
v0.1.0-alpha.49 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2026 License: GPL-3.0 Imports: 29 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 = "b9966"
	// ManagedLlamaCommit pins the exact upstream source represented by ManagedLlamaVersion.
	ManagedLlamaCommit = "c749cb041706647f460bb918cccc9d91995205ab"
)
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 (
	// 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"
)

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 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 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 ManagedLlamaRuntimeRoot

func ManagedLlamaRuntimeRoot(dataDir string) string

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

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.

Types

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
}

ChatRequest is the provider-neutral streaming chat request.

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 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
}

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) 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 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) 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) 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) Snapshot

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

Snapshot returns managed models and current/recent import jobs.

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).

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"`
}

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 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
}

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.

Jump to

Keyboard shortcuts

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