runtime

package
v0.9.4 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 10 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 runtime defines the inference Runtime interface (SPEC §A1.3) and its adapters. llama.cpp is supervised as a subprocess (never cgo); the mock runtime backs tests and --standalone demos.

Index

Constants

View Source
const MockRuntimeBuildID = "mock-runtime-v1"

MockRuntimeBuildID identifies the in-process mock as a runtime build. It is deliberately distinct from any real llama.cpp build id so that fingerprint expected outputs generated against a mock can never be mistaken for a reference for real hardware (SPEC §2.2).

Variables

View Source
var ErrNotLoaded = errors.New("runtime: model not loaded")

ErrNotLoaded is returned when an Instance is used after Shutdown or before the backing process is ready.

View Source
var ErrRuntimeTooOld = errors.New("runtime: build too old for this model")

ErrRuntimeTooOld is returned when a model needs a runtime build newer than the one this node runs (a decision model on a llama.cpp build that predates /v1/systemone).

Functions

func IsInvalidInput added in v0.7.0

func IsInvalidInput(err error) bool

IsInvalidInput reports whether err is (or wraps) an InvalidInputError.

Types

type BuildIdentified

type BuildIdentified interface {
	RuntimeBuildID() string
}

BuildIdentified is implemented by runtime instances that know which runtime build they are running. The daemon reports this in its CapabilityProfile; it is one third of the fingerprint trust tuple (model_sha, quant, runtime_build_id) — SPEC §2.2, §A2.5.

type Chunk

type Chunk struct {
	Delta string
	// Reasoning is a chain-of-thought delta (OpenAI's `reasoning_content`).
	// Empty for models the runtime cannot parse, whose thinking then
	// arrives inline in Delta (e.g. as `<think>…</think>`).
	Reasoning    string
	TokenCount   int
	Done         bool
	FinishReason string // "stop", "length", "cancelled", "error"
	Usage        *Usage
	Embeddings   [][]float32
	Decision     []DecisionAnswer // KindDecision: one per question, in order
	Err          string
}

Chunk is one streamed unit. For KindEmbedding a single final chunk carries Embeddings; for KindDecision a single final chunk carries Decision. Usage is set on the final chunk.

Every token the model produces is relayed as either Delta (the answer) or Reasoning (chain-of-thought, for models whose runtime separates it), and TokenCount covers both: the customer is billed for reasoning tokens and canary comparison diffs the whole stream, so nothing is dropped on the node. A chunk may carry both when the runtime emits them together.

type CompletionRequest

type CompletionRequest struct {
	ID             string
	Model          string // requested model id ("" = node default)
	Kind           Kind
	Messages       []Message // KindChat
	Prompt         string    // KindCompletion
	EmbeddingInput []string  // KindEmbedding
	// Decision is the KindDecision payload. The result is a single final
	// Chunk carrying Decision answers (in question order) and Usage.
	Decision *DecisionInput
	Params   GenerationParams
	// Origin says who asked, for the live activity view only: "local"
	// (the local API; also what "" means), "mesh" (a coordinator
	// dispatch) or "challenge" (a fingerprint probe). The runtime
	// ignores it.
	Origin string
}

type DecisionAnswer added in v0.7.0

type DecisionAnswer struct {
	QuestionID    string
	Type          DecisionType
	Choice        string  // choice: the most probable option key
	Score         float64 // score: expected level index
	Noul          float64 // noul: probability the statement is true
	Probabilities []DecisionProbability
	Confidence    float64 // choice and score: 0..1
}

DecisionAnswer is the typed answer to one question. Probabilities are ordered like the question's options and empty for noul.

type DecisionInput added in v0.7.0

type DecisionInput struct {
	StateJSON string // compact JSON: string, object or array
	Questions []DecisionQuestion
}

DecisionInput is a validated /v1/systemone request: the state and the questions in request order (ids unique).

type DecisionOption added in v0.7.0

type DecisionOption struct {
	// Key is the option key (choice), the level index "0", "1", … (score)
	// or "true"/"false" (noul, only when described).
	Key string
	// DescriptionJSON is compact JSON (string, object or array); "" means
	// JSON null: the option has no description.
	DescriptionJSON string
}

DecisionOption is one possible answer. Order is part of the contract: the model reads the options in the order the customer wrote them.

type DecisionProbability added in v0.7.0

type DecisionProbability struct {
	Key         string
	Probability float64
}

DecisionProbability is the probability of one option (or score level).

type DecisionQuestion added in v0.7.0

type DecisionQuestion struct {
	ID               string
	Type             DecisionType
	InstructionsJSON string // compact JSON: string, object or array
	Options          []DecisionOption
}

DecisionQuestion is one typed question. Options is a list, never a map, so the order survives every hop.

type DecisionType added in v0.7.0

type DecisionType int

DecisionType is the type of one decision question (and of its answer); it mirrors typesv1.DecisionQuestionType.

const (
	DecisionChoice DecisionType = iota + 1 // pick one labelled option
	DecisionScore                          // place on an ordered scale
	DecisionNoul                           // probability a statement is true
)

func (DecisionType) String added in v0.7.0

func (t DecisionType) String() string

String is the public name of the type ("choice", "score", "noul").

type GenerationParams

type GenerationParams struct {
	Seed             uint64
	Temperature      float64
	TopP             float64
	MaxTokens        int
	Stop             []string
	FrequencyPenalty float64
	PresencePenalty  float64
}

GenerationParams: seed is always set upstream so retries and canary comparisons are deterministic for greedy decoding (SPEC §6).

type Instance

type Instance interface {
	Complete(ctx context.Context, req CompletionRequest) (TokenStream, error)
	Health(ctx context.Context) (Stats, error)
	Shutdown(ctx context.Context) error
}

Instance is one loaded model.

type InvalidInputError added in v0.7.0

type InvalidInputError struct{ Msg string }

InvalidInputError means the runtime rejected the input itself (too many options for this model, a prompt over its context — llama-server's 400): another node would reject it too, so the request must not be retried elsewhere. Callers test with errors.As.

func (*InvalidInputError) Error added in v0.7.0

func (e *InvalidInputError) Error() string

type Kind

type Kind int

Kind mirrors typesv1.RequestKind for runtime-local use.

const (
	KindChat Kind = iota + 1
	KindCompletion
	KindEmbedding
	KindDecision
)

type Message

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

type MockRuntime

type MockRuntime struct {
	// TokensPerSec throttles generation; <= 0 means unthrottled.
	TokensPerSec float64
	// FailLoads causes the next N Load calls to fail (supervisor tests).
	FailLoads int
	// ReasoningTokens makes chat generations emit this many chain-of-thought
	// tokens (Chunk.Reasoning) before the answer, the way llama.cpp's
	// reasoning_content parsing does for reasoning models. They count
	// toward max_tokens and completion_tokens like any other token.
	ReasoningTokens int
}

MockRuntime is a deterministic in-process runtime used by tests, the fake coordinator path, and `flockd --standalone --runtime=mock`. Same seed -> same output, so it also exercises the fingerprint-challenge flow.

func NewMockRuntime

func NewMockRuntime(tps float64) *MockRuntime

NewMockRuntime returns a mock producing ~tps tokens/second.

func (*MockRuntime) Load

type ModelSpec

type ModelSpec struct {
	ID            string
	Family        string
	Quant         string
	SHA256        string
	Path          string // local GGUF path (part 1 of a sharded model)
	ContextLength int
	Embeddings    bool // model is served for /v1/embeddings
	// Decision marks a typed decision model served for /v1/systemone
	// (KindDecision): it answers bounded questions with probabilities and
	// generates no tokens. Mutually exclusive with Embeddings.
	Decision bool
	// MmprojPath is the vision projector sidecar passed to the runtime
	// (llama-server --mmproj); "" when the model has none.
	MmprojPath string
	// SizeBytes is what the artifact occupies on disk across all of its
	// files; 0 = unknown (the runtime stats Path instead).
	SizeBytes int64
}

ModelSpec identifies a locally available model artifact ready to load. It is derived from the catalog's typesv1.ModelSpec after download+verify.

type ModelSupporter added in v0.7.0

type ModelSupporter interface {
	SupportsModel(ctx context.Context, m ModelSpec) error
}

ModelSupporter is implemented by runtimes that can tell, without loading, that their build cannot serve a model. modelops and assign ask before downloading so an unservable placement is refused up front.

type ResourceBudget

type ResourceBudget struct {
	MaxVRAMPercent int
	MaxRAMMB       int64
	// MaxConcurrent is the slot ceiling (budget.max_concurrent, or the
	// hardware default when that is 0).
	MaxConcurrent int
	// Slots and ContextTokens are what memory.PlanContext decided for
	// this load: --parallel and --ctx-size. 0 = unplanned; the adapter
	// falls back to MaxConcurrent and its own context resolution.
	Slots         int
	ContextTokens int
}

ResourceBudget is the operator-configured ceiling passed to Load, plus the layout admission planned for this particular load.

type Runtime

type Runtime interface {
	Load(ctx context.Context, m ModelSpec, res ResourceBudget) (Instance, error)
}

Runtime loads models into serving Instances. Exactly per SPEC §A1.3.

type Stats

type Stats struct {
	Healthy      bool
	ModelID      string
	QueueDepth   int
	TokensPerSec float64
	MemUsedMB    int64
	Restarts     int
}

Stats is the Health snapshot.

type TokenStream

type TokenStream interface {
	Recv() (Chunk, error)
	Close() error
}

TokenStream yields Chunks until io.EOF. Close releases resources early (cancels generation server-side where supported).

func NewChanStream

func NewChanStream(ch <-chan Chunk, cancel context.CancelFunc) TokenStream

NewChanStream builds a TokenStream from a channel; cancel (may be nil) is invoked on Close.

type Usage

type Usage struct {
	PromptTokens     int
	CompletionTokens int
}

func Drain

func Drain(ts TokenStream) (text string, usage Usage, finish string, err error)

Drain reads a stream to completion and concatenates deltas. Convenience for non-streaming callers (challenges, tests). Reasoning deltas are discarded here; callers that must relay them use DrainAll.

func DrainAll added in v0.5.0

func DrainAll(ts TokenStream) (text, reasoning string, usage Usage, finish string, err error)

DrainAll is Drain that also concatenates the reasoning deltas (localapi non-stream mode emits them as message.reasoning_content).

Directories

Path Synopsis
Package llamacpp adapts a supervised llama-server subprocess to the runtime.Runtime interface (SPEC §A1.3: subprocess, never cgo).
Package llamacpp adapts a supervised llama-server subprocess to the runtime.Runtime interface (SPEC §A1.3: subprocess, never cgo).

Jump to

Keyboard shortcuts

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