runtime

package
v0.8.3 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2026 License: Apache-2.0, MIT Imports: 20 Imported by: 0

Documentation

Overview

Package runtime resolves one model's effective settings and assembles its authenticated endpoint. Provider definitions and catalog metadata are shared; model credentials and connection settings are resolved independently per row.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ApplyCompat

func ApplyCompat(settings any, compat any)

ApplyCompat writes the set fields of an overlay struct onto a settings struct with matching field names, dereferencing pointers. Slices and maps replace the default wholesale (no element merge) except map[string]any ExtraBody-style fields, which merge key by key.

func ApplyOverlay

func ApplyOverlay(data []byte, baseDir string) error

ApplyOverlay and LoadOverlay retain the legacy unvalidated composition API. Application configuration uses Initialize/Reload, which validate before publication.

func DecodeCompat

func DecodeCompat(raw json.RawMessage, into any) error

DecodeCompat unmarshals a flat compat object into the overlay type for an API. Unknown keys are rejected so typos in models.json surface early.

func DetectByURL

func DetectByURL(baseURL string) string

DetectByURL infers a legacy provider using the default runtime.

func Initialize

func Initialize(configDir string) error

Initialize is the application composition entry point. A failed deployment overlay leaves the previous catalog generation untouched.

func LoadOverlay

func LoadOverlay(configDir string) error

LoadOverlay loads deployment JSON into the default runtime without resolution validation.

func ReadDeploymentOverlay

func ReadDeploymentOverlay(configDir string) (data []byte, baseDir string, err error)

ReadDeploymentOverlay reads config/models.json (or the path in MODELS_CONFIG). A missing file returns nil data and no error; baseDir resolves the overlay's relative icon paths.

func Register

func Register(definition *providers.Definition, entries ...models.ModelSpec)

Register adds a built-in definition and separate catalog to the default runtime.

func Reload

func Reload(data []byte, baseDir string) error

Reload replaces the deployment overlay without retaining removed overrides.

func RestoreSnapshot

func RestoreSnapshot(s Snapshot)

RestoreSnapshot restores the default runtime.

func ValidateRow

func ValidateRow(modelName string, modelType types.ModelType, params *types.ModelParameters) error

ValidateRow checks that a stored model row resolves against the catalog.

It is the one gate shared by every write path — the REST create/update handlers and the declarative builtin_models.yaml loader — so an unknown protocol, a bad compat key or an invalid thinking level is rejected where it is written instead of surfacing as a failed chat call much later.

Every model type is checked: all of them are built from runtime.Resolve, so a row that does not resolve cannot be used and should fail the save rather than the first call.

Types

type Capabilities

type Capabilities = models.Capabilities

Capabilities is the frontend contract, independent of runtime assembly.

type Connection

type Connection struct {
	ModelID     string
	Credentials api.Credentials
	Headers     map[string]string
	Extra       map[string]string
	Client      *http.Client
}

Connection contains only one configured model's credentials and transport settings. It is never cached in the provider registry or model catalog.

type ModelSpecPatch

type ModelSpecPatch struct {
	Name            string               `json:"name,omitempty"`
	API             api.API              `json:"api,omitempty"`
	Reasoning       *bool                `json:"reasoning,omitempty"`
	Input           []string             `json:"input,omitempty"`
	ContextWindow   int                  `json:"context_window,omitempty"`
	MaxOutputTokens int                  `json:"max_output_tokens,omitempty"`
	Cost            *models.ModelCost    `json:"cost,omitempty"`
	ThinkingLevels  api.ThinkingLevelMap `json:"thinking_levels,omitempty"`
	Compat          json.RawMessage      `json:"compat,omitempty"`
	Aliases         []string             `json:"aliases,omitempty"`
	Deprecated      *bool                `json:"deprecated,omitempty"`
}

ModelSpecPatch is a partial models.ModelSpec.

type OverlayFile

type OverlayFile struct {
	Providers map[string]OverlayProvider `json:"providers"`
}

OverlayFile is the schema of config/models.json. It mirrors pi's ~/.pi/agent/models.json: a "providers" object keyed by provider id where each entry either patches a built-in vendor or declares a new one.

type OverlayProvider

type OverlayProvider struct {
	Name         string            `json:"name,omitempty"`
	Names        map[string]string `json:"names,omitempty"`
	Description  string            `json:"description,omitempty"`
	Descriptions map[string]string `json:"descriptions,omitempty"`
	Website      string            `json:"website,omitempty"`
	// API is the default chat protocol for new vendors (and overrides it
	// for built-in ones).
	API api.API `json:"api,omitempty"`
	// BaseURL sets the chat base URL; BaseURLs sets per-type URLs keyed by
	// chat | embedding | rerank | vlm | asr.
	BaseURL  string            `json:"base_url,omitempty"`
	BaseURLs map[string]string `json:"base_urls,omitempty"`
	// APIKey is the deployment-level key used when a model row stores none.
	// Supports ${ENV} / $ENV interpolation.
	APIKey       string              `json:"api_key,omitempty"`
	Headers      map[string]string   `json:"headers,omitempty"`
	Auth         providers.AuthStyle `json:"auth,omitempty"`
	RequiresAuth *bool               `json:"requires_auth,omitempty"`
	ModelTypes   []string            `json:"model_types,omitempty"`
	URLPatterns  []string            `json:"url_patterns,omitempty"`
	// Icon is a path to an SVG file (relative to the overlay file) or an
	// inline "<svg ...>" string.
	Icon string `json:"icon,omitempty"`
	// Compat is the flat protocol overlay applied at vendor level for API.
	Compat json.RawMessage `json:"compat,omitempty"`
	// ThinkingLevels patches the vendor level map.
	ThinkingLevels map[string]*string `json:"thinking_levels,omitempty"`
	// Models are upserted by id into the vendor catalog. Entries stay raw so
	// an upsert against an existing id can patch only the keys the operator
	// actually wrote (see applyOverlayProvider).
	Models []json.RawMessage `json:"models,omitempty"`
	// ModelOverrides patch existing entries by id without restating them.
	ModelOverrides map[string]ModelSpecPatch `json:"model_overrides,omitempty"`
}

OverlayProvider patches or declares one vendor.

type Provider

type Provider struct {
	*providers.Definition
	// contains filtered or unexported fields
}

Provider combines a provider definition with a catalog from the same runtime generation. Public queries return owned definitions; the catalog is immutable.

func Get

func Get(id string) (*Provider, bool)

Get queries the default runtime.

func List

func List() []*Provider

List queries the default runtime.

func ListByType

func ListByType(kind types.ModelType) []*Provider

ListByType queries the default runtime for one capability.

func (*Provider) FindModel

func (p *Provider) FindModel(name string, kind types.ModelType) (models.ModelSpec, bool)

FindModel matches an exact ID, alias or family within this view.

func (*Provider) Models

func (p *Provider) Models() []models.ModelSpec

Models returns owned entries from this view, including hidden rules.

func (*Provider) ModelsByType

func (p *Provider) ModelsByType(kind types.ModelType) []models.ModelSpec

ModelsByType returns visible entries for the requested capability.

func (*Provider) Resolve

func (p *Provider) Resolve(ref Ref) (*Resolved, error)

Resolve uses this view's definition and catalog even after the runtime reloads.

type Ref

type Ref struct {
	Provider  string
	Model     string
	BaseURL   string
	ModelType types.ModelType
	Extra     map[string]string
	Override  *types.ModelSpecOverride
	// TruncatePromptTokens is an embedding row's
	// embedding_parameters.truncate_prompt_tokens. It is a first-class column
	// rather than an extra_config key, which is why it arrives here instead
	// of in Extra.
	TruncatePromptTokens int
}

Ref identifies one configured model.

type Resolved

type Resolved struct {
	Vendor *providers.Definition
	// Spec is the effective catalog entry (synthesized when unknown).
	Spec models.ModelSpec
	// Cataloged reports whether the model name matched a catalog entry.
	Cataloged bool
	API       api.API
	BaseURL   string
	// RemoteModel is the id sent on the wire.
	RemoteModel    string
	ThinkingLevels api.ThinkingLevelMap

	OpenAICompletions  api.OpenAICompletionsSettings
	OpenAIResponses    api.OpenAIResponsesSettings
	AnthropicMessages  api.AnthropicMessagesSettings
	GoogleGenerativeAI api.GoogleGenerativeAISettings

	// RerankAPI and Rerank are filled only when the reference asked for a
	// rerank model. Chat resolution is on every request's hot path, so the
	// rerank overlay is not merged for it.
	RerankAPI api.RerankAPI
	Rerank    api.RerankSettings

	// EmbeddingAPI and Embeddings are filled only for an embedding reference,
	// for the same reason.
	EmbeddingAPI api.EmbeddingAPI
	Embeddings   api.EmbeddingsSettings

	// TranscriptionAPI and Transcriptions are filled only for an ASR
	// reference.
	TranscriptionAPI api.TranscriptionAPI
	Transcriptions   api.TranscriptionsSettings
}

Resolved is the fully merged view of one model: which vendor, which protocol, which settings.

func Resolve

func Resolve(ref Ref) (*Resolved, error)

Resolve merges the vendor, catalog entry, extra-config and per-row overrides for a model reference. It never fails for unknown vendors or models: they degrade to the generic OpenAI-compatible baseline.

func (*Resolved) Capabilities

func (r *Resolved) Capabilities() Capabilities

Capabilities summarizes the resolved model for API responses.

func (*Resolved) Endpoint

func (r *Resolved) Endpoint(kind types.ModelType, c Connection) (api.Endpoint, error)

Endpoint assembles authentication, headers and vendor endpoint routing for every capability. Protocol clients receive the result without knowing vendors.

type Runtime

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

Runtime owns provider definitions, model catalogs and deployment overrides. Separate instances can be configured without changing any other instance.

func Default

func Default() *Runtime

Default is the application runtime used by the existing model factories. New is available to callers that need an isolated configuration.

func New

func New() *Runtime

New explicitly composes fresh built-in definitions and independent catalogs.

func (*Runtime) ApplyOverlay

func (rt *Runtime) ApplyOverlay(data []byte, baseDir string) error

ApplyOverlay applies overlay JSON to the registry. baseDir resolves relative icon paths.

func (*Runtime) DetectByURL

func (rt *Runtime) DetectByURL(baseURL string) string

DetectByURL applies legacy provider inference without exposing registry state.

func (*Runtime) Get

func (rt *Runtime) Get(id string) (*Provider, bool)

Get returns an owned provider view from the current generation.

func (*Runtime) Initialize

func (rt *Runtime) Initialize(configDir string) error

Initialize loads and validates deployment configuration for this instance.

func (*Runtime) List

func (rt *Runtime) List() []*Provider

List returns owned provider views from one generation, ordered by Order and ID.

func (*Runtime) ListByType

func (rt *Runtime) ListByType(kind types.ModelType) []*Provider

ListByType returns owned views supporting the requested capability.

func (*Runtime) LoadOverlay

func (rt *Runtime) LoadOverlay(configDir string) error

LoadOverlay reads config/models.json (or the path in MODELS_CONFIG) and applies it to the registry. A missing file is not an error.

func (*Runtime) Register

func (rt *Runtime) Register(definition *providers.Definition, entries ...models.ModelSpec)

Register adds an owned built-in definition and its independently supplied catalog. Deployment overrides never mutate this baseline.

func (*Runtime) Reload

func (rt *Runtime) Reload(data []byte, baseDir string) error

Reload validates and publishes a replacement deployment overlay for this instance.

func (*Runtime) Resolve

func (rt *Runtime) Resolve(ref Ref) (*Resolved, error)

Resolve merges one model against a single generation of this runtime.

func (*Runtime) RestoreSnapshot

func (rt *Runtime) RestoreSnapshot(s Snapshot)

RestoreSnapshot restores an owned copy for rollback or isolated tests.

func (*Runtime) SnapshotCurrent

func (rt *Runtime) SnapshotCurrent() Snapshot

SnapshotCurrent retains the current generation and its built-in baseline.

func (*Runtime) WithOverlay

func (rt *Runtime) WithOverlay(data []byte, baseDir string) (*Runtime, error)

WithOverlay builds an independent candidate on top of this generation. It never publishes partial changes or mutates either input layer. Unlike Reload, this explicitly retains the deployment layer beneath a UI overlay.

type Snapshot

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

Snapshot captures provider definitions and their model catalogs together. It also retains the built-in baseline used when replacing deployment overrides.

func SnapshotCurrent

func SnapshotCurrent() Snapshot

SnapshotCurrent captures the default runtime for rollback or isolated tests.

type UnsupportedModelError

type UnsupportedModelError struct{ Provider, Model, Reason string }

UnsupportedModelError records an intentional refusal for an unimplemented API.

func (*UnsupportedModelError) Error

func (e *UnsupportedModelError) Error() string

Jump to

Keyboard shortcuts

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