model

package
v0.0.0-...-ecee8c2 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 9 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 model is the capability-typed model layer. Every model call, chat or video, is an invocation with one contract (Invoker): start, events, result, cancel, lookup. Vendor protocols (one streamed reply, submit and poll, webhook, WebSocket, command line) are adapter details. Callers either block (Invoke) or follow events. See ADR-0006 and docs/architecture/model-layer.md.

Chat messages and tool definitions travel as JSON of github.com/cloudwego/eino/schema values, so the contract types do not depend on eino itself. The chat adapter in model/chat maps them to eino's types; the embedding adapter here maps Request.Texts to an eino Embedder. Registry holds the part every adapter owes regardless of protocol: idempotent starts, the ordered event log, the result, cancellation and lookup. It forgets ended invocations past a retention window and an ended bound, so an adapter's memory does not grow with every call it ever served (REQ-MODEL-088).

Provider construction (vendor SDKs, eino-ext, OpenAI-compatible endpoints for MiniMax and GLM) and routing are WP-L3-04. Structured-output shaping lives in model/structured and the call middleware (attempt budget, retries, timeouts, metering, call log) in model/middleware.

Index

Constants

View Source
const DefaultMaxEnded = 10_000

DefaultMaxEnded is how many ended invocations a registry keeps when no ended bound is set.

View Source
const DefaultRetention = time.Hour

DefaultRetention is how long a registry keeps an ended invocation when no retention window is set: one hour after the invocation ends.

Variables

This section is empty.

Functions

func MapError

func MapError(err error) error

MapError returns err as a platform error. A *core.Error passes through; a canceled or expired context becomes "cancelled" or a retryable "timeout"; any other error becomes a non-retryable "vendor_error" with message "vendor call failed" that wraps the original in Cause. Adapters use it at the boundary of a vendor call so callers see one error taxonomy (ADR-0006).

Types

type AssetRef

type AssetRef struct {
	BlobKey string `json:"blob_key"`
	SHA256  string `json:"sha256"`
	Media   string `json:"media"`
	Mime    string `json:"mime"`
}

AssetRef points to content-addressed blob storage.

type Capability

type Capability string

Capability is what a model can do.

const (
	CapChat           Capability = "chat"
	CapEmbed          Capability = "embed"
	CapImageGenerate  Capability = "image.generate"
	CapImageEdit      Capability = "image.edit"
	CapImageUpscale   Capability = "image.upscale"
	CapVideoGenerate  Capability = "video.generate" // text→video and image→video via input slots
	CapVideoLipsync   Capability = "video.lipsync"
	CapAudioTTS       Capability = "audio.tts"
	CapAudioASR       Capability = "audio.asr"
	CapAudioMusic     Capability = "audio.music"
	CapWorkflowGraph  Capability = "workflow.graph"  // graph-based generation servers
	CapBrowserSession Capability = "browser.session" // a browser runner session (ADR-0009)
)

type Descriptor

type Descriptor struct {
	ID       string          `json:"id"`
	Provider string          `json:"provider"`
	Caps     []Capability    `json:"caps"`
	Params   json.RawMessage `json:"params_schema"` // JSON Schema; validated before start
	Inputs   []InputSlot     `json:"inputs"`
	Price    string          `json:"price"` // CEL over `params`, `usage` and `rates` returning milli-points
	Protocol Protocol        `json:"protocol"`
	Locality Locality        `json:"locality"`
}

Descriptor is catalog data for one model.

func Select

func Select(ds []Descriptor, modelID string, op Capability) (Descriptor, error)

Select returns the descriptor in ds that serves modelID with capability op. It fails with "not_found" when no descriptor holds the id and "unsupported" when the model exists but does not declare op. Adapters use it so a request reaches the vendor only when the adapter can serve it.

type Embedding

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

Embedding adapts an eino embedding model to the Invoker contract. It answers a request with a single reply: start sends the batch, and the result carries the vectors, one per input text in order (the "single" protocol of docs/architecture/model-layer.md §1). It publishes no events.

func NewEmbedding

func NewEmbedding(cfg EmbeddingConfig) (*Embedding, error)

NewEmbedding returns an embedding adapter. It fails with "invalid_argument" when a dependency is missing and "unsupported" when no descriptor declares the embed capability.

func (*Embedding) Cancel

func (e *Embedding) Cancel(ctx context.Context, h Handle) error

Cancel ends the invocation as cancelled.

func (*Embedding) Describe

func (e *Embedding) Describe(context.Context) ([]Descriptor, error)

Describe lists the models this adapter serves.

func (*Embedding) Events

func (e *Embedding) Events(ctx context.Context, h Handle, after int64) (<-chan Event, error)

Events follows any progress the adapter publishes. Embeddings publish none; the channel closes when the invocation ends.

func (*Embedding) Lookup

func (e *Embedding) Lookup(ctx context.Context, clientRef string) (*Handle, error)

Lookup resolves a client ref to its invocation.

func (*Embedding) Result

func (e *Embedding) Result(ctx context.Context, h Handle) (Result, error)

Result waits for the vectors.

func (*Embedding) Start

func (e *Embedding) Start(ctx context.Context, r Request) (Handle, error)

Start sends the embedding batch and returns at once. It is idempotent per ClientRef while the adapter's registry retains the invocation: a repeated start returns the original handle. Once the client ref is evicted, a start opens a new invocation (REQ-MODEL-088).

type EmbeddingConfig

type EmbeddingConfig struct {
	// Provider names the vendor on every handle and descriptor.
	Provider string
	// Descriptors are the models this adapter serves. Each must declare the
	// embed capability; Select routes a request to one by id and capability.
	Descriptors []Descriptor
	// Embedder is the eino embedding model the adapter drives. Every eino-ext
	// embedding provider satisfies it.
	Embedder einoEmbedding.Embedder
	// Clock is the adapter registry's clock, read for the end times and the
	// retention window of ended invocations. It is required.
	Clock core.Clock
}

EmbeddingConfig describes one embedding adapter.

type Event

type Event struct {
	Seq      int64           `json:"seq"`
	Kind     EventKind       `json:"kind"`
	Text     string          `json:"text,omitempty"`
	Audio    []byte          `json:"audio,omitempty"`
	Progress float64         `json:"progress,omitempty"`
	Attempt  int             `json:"attempt,omitempty"`
	Data     json.RawMessage `json:"data,omitempty"`
}

Event is one ordered piece of partial output.

type EventKind

type EventKind string

EventKind is the kind of partial output.

const (
	EventText      EventKind = "text"
	EventReasoning EventKind = "reasoning"
	EventToolCall  EventKind = "tool_call"
	EventAudio     EventKind = "audio"
	EventProgress  EventKind = "progress"
	EventReset     EventKind = "reset" // discard partial output; a new attempt follows
)

type Failure

type Failure struct {
	Code      core.Code `json:"code"`
	Message   string    `json:"message"`
	Retryable bool      `json:"retryable,omitempty"`
	// RetryAfter is the provider's wait hint, carried so a caller that
	// reconstructs the failure still honours REQ-MODEL-052.
	RetryAfter time.Duration `json:"retry_after,omitempty"`
}

Failure is the error an invocation records in Result.Error when it fails. It carries the platform code so a caller that follows events can classify the end of an invocation without parsing vendor text.

func FailureOf

func FailureOf(err error) Failure

FailureOf describes err as a Failure suitable for persisting on Result.Error. A *core.Error keeps its code and message; any other error keeps code vendor_error with the fixed message "vendor call failed" so raw vendor text never lands in the stored record. Call MapError first when the original should remain on Cause for in-process callers. A nil error is an internal failure: it only reaches here from a bug, never from a vendor.

type Handle

type Handle struct {
	Provider  string `json:"provider"`
	ID        string `json:"id"` // vendor id, or an adapter-local id for streamed calls
	ClientRef string `json:"client_ref"`
}

Handle identifies a started invocation. It is valid only for the tenant that started the invocation. Provider may be empty on a handle returned by Lookup or replayed from storage; identity is the (tenant, client ref) pair. A non-empty Provider that does not match the registry's is not_found.

type InputSlot

type InputSlot struct {
	Name     string `json:"name"`
	Media    string `json:"media"` // text|messages|image|video|audio
	Required bool   `json:"required"`
	Max      int    `json:"max,omitempty"`
}

InputSlot names an input, e.g. prompt, messages, first_frame, reference, audio, mask.

type Invoker

type Invoker interface {
	Describe(ctx context.Context) ([]Descriptor, error)
	// Start begins an invocation and returns at once. It is idempotent per ClientRef
	// while the provider's registry retains that invocation: after the client ref is
	// evicted, a start begins a new invocation (REQ-MODEL-088).
	Start(ctx context.Context, r Request) (Handle, error)
	// Events delivers partial output with Seq > after; the channel closes when the invocation ends.
	Events(ctx context.Context, h Handle, after int64) (<-chan Event, error)
	// Result waits for the end of the invocation.
	Result(ctx context.Context, h Handle) (Result, error)
	Cancel(ctx context.Context, h Handle) error
	// Lookup resolves an ambiguous start. It returns (nil, nil) when the
	// provider has nothing for clientRef, and an error with core.CodeUnsupported
	// when it cannot answer.
	Lookup(ctx context.Context, clientRef string) (*Handle, error)
}

Invoker is implemented by every provider adapter. Every call uses the tenant of ctx; handles are valid only for the tenant that started the invocation.

type Locality

type Locality string

Locality says where a model can run.

const (
	LocalityCloud        Locality = "cloud"
	LocalityMachineLocal Locality = "machine_local" // local apps and servers: never routed in the cloud profile
	LocalityWorker       Locality = "worker"        // served by a connected worker that declared it (ADR-0012)
)

type Option

type Option func(*registryOptions) error

Option configures a Registry at construction.

func WithClock

func WithClock(clock core.Clock) Option

WithClock sets the clock the retention window and end times are read on. It is required: a registry never falls back to the system clock, so the gate cannot depend on wall time by omission.

func WithRetention

func WithRetention(window time.Duration, maxEnded int) Option

WithRetention sets both retention bounds. window is how long an ended invocation is kept after its end; maxEnded is how many ended invocations are kept. A zero window or a zero maxEnded keeps that bound's default (DefaultRetention, DefaultMaxEnded); a negative one is invalid_argument. There is no value that means unbounded.

type Output

type Output struct {
	URL   string `json:"url,omitempty"`
	Path  string `json:"path,omitempty"` // command-line providers
	Media string `json:"media"`
	Mime  string `json:"mime"`
}

Output is a produced file not yet ingested into blob storage.

type Protocol

type Protocol string

Protocol is how a vendor delivers results. It only matters inside adapters.

const (
	ProtocolStream  Protocol = "stream"  // one request, streamed reply (chat, streaming TTS)
	ProtocolSingle  Protocol = "single"  // one request, one reply (embeddings)
	ProtocolPoll    Protocol = "poll"    // submit, then poll
	ProtocolWebhook Protocol = "webhook" // submit, vendor calls back
	ProtocolSocket  Protocol = "socket"  // submit, progress over WebSocket
	ProtocolCommand Protocol = "command" // local command line
)

type Registry

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

Registry keeps the live invocations of one adapter, scoped to the tenant carried by each call's context. It supplies what every adapter owes the contract regardless of its vendor: a start that is idempotent per client ref within a tenant, an ordered event log that can be followed from a cursor, a result that waits for the end, cancellation and lookup (REQ-MODEL-001, ADR-0006). Adapters own the vendor call and publish into a Run.

A Registry is safe for concurrent use. It keeps an ended invocation for its retention window after its end and no longer, and while it holds more ended invocations than its ended bound it evicts them oldest-ended first; it never evicts a running invocation (REQ-MODEL-088). An evicted client ref answers exactly as one the registry never held: Lookup finds no invocation, Events, Result and Cancel answer not_found, and Begin opens a new invocation. The sweep runs inline in those methods, on the registry's core.Clock, so what a caller observes depends only on end times and clock readings: no timer and no goroutine per invocation (design R3).

func NewRegistry

func NewRegistry(provider string, opts ...Option) (*Registry, error)

NewRegistry returns an empty registry for the named provider. It requires WithClock and fails with invalid_argument without one, naming the option; an invalid bound fails the same way.

func (*Registry) Begin

func (g *Registry) Begin(ctx context.Context, clientRef string) (*Run, bool, error)

Begin returns the run for clientRef, opening one when none exists within the tenant of ctx. The boolean reports whether the run already existed, which is how an adapter keeps Start idempotent per client ref in that tenant: it publishes nothing in that case. It fails with invalid_argument when ctx carries no tenant. Each run is keyed by (tenant, client ref). clientRef must not be empty; adapters reject such a request before beginning.

The run's context is detached from ctx's cancellation but keeps its values, because an invocation outlives the request that started it (ADR-0005) and ends through Cancel, not through the caller's start context.

func (*Registry) Cancel

func (g *Registry) Cancel(ctx context.Context, h Handle) error

Cancel ends the invocation as cancelled and cancels the vendor call's context. It requires the tenant of ctx; a handle that belongs to another tenant, or to nobody, is not_found like an unknown handle. Cancelling an invocation that already ended is a no-op.

func (*Registry) Events

func (g *Registry) Events(ctx context.Context, h Handle, after int64) (<-chan Event, error)

Events follows the invocation's output with Seq > after. It requires the tenant of ctx; a handle that belongs to another tenant, or to nobody, is not_found like an unknown handle. The channel closes when the invocation ends and every remaining event has been delivered.

func (*Registry) Lookup

func (g *Registry) Lookup(ctx context.Context, clientRef string) (*Handle, error)

Lookup resolves a client ref to its invocation within the tenant of ctx. It requires that tenant; without one it fails with invalid_argument. A client ref that belongs to another tenant, or to nobody, returns (nil, nil), the same as an unknown ref in this tenant. A registry only resolves refs it owns.

func (*Registry) Provider

func (g *Registry) Provider() string

Provider is the provider name the registry stamps on every handle.

func (*Registry) Result

func (g *Registry) Result(ctx context.Context, h Handle) (Result, error)

Result waits for the invocation to end and returns its result. It requires the tenant of ctx; a handle that belongs to another tenant, or to nobody, is not_found like an unknown handle. A failed or cancelled invocation returns that state in the result, not an error; the error is reserved for an unknown handle and for the caller's own context.

type Request

type Request struct {
	Model        string                `json:"model"`
	Op           Capability            `json:"op"`
	Messages     json.RawMessage       `json:"messages,omitempty"` // chat transcript (eino schema messages)
	Tools        json.RawMessage       `json:"tools,omitempty"`
	OutputSchema json.RawMessage       `json:"output_schema,omitempty"` // structured output
	Text         map[string]string     `json:"text,omitempty"`
	Texts        []string              `json:"texts,omitempty"` // embedding inputs, in order
	Assets       map[string][]AssetRef `json:"assets,omitempty"`
	Params       json.RawMessage       `json:"params,omitempty"`
	Seed         *int64                `json:"seed,omitempty"`
	ClientRef    string                `json:"client_ref"`
}

Request starts an invocation. ClientRef is the idempotency key and is identical across retries of the same logical invocation.

type Result

type Result struct {
	State    State           `json:"state"`
	Message  json.RawMessage `json:"message,omitempty"` // chat reply or structured output
	Vectors  [][]float32     `json:"vectors,omitempty"` // embeddings
	Outputs  []Output        `json:"outputs,omitempty"` // files
	Usage    *Usage          `json:"usage,omitempty"`
	CostMpts int64           `json:"cost_mpts"`
	Error    json.RawMessage `json:"error,omitempty"`
}

Result is how an invocation ended.

func Invoke

func Invoke(ctx context.Context, p Invoker, r Request) (Result, error)

Invoke starts an invocation and waits for its result: the blocking form of the contract, for callers that do not follow events. The adapter keeps publishing into its event buffer while Invoke waits, so a blocking caller cannot starve the invocation.

type Run

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

Run is one live invocation. An adapter publishes its vendor output as events and ends it with Succeed, Fail or Cancel.

func (*Run) Cancel

func (r *Run) Cancel() bool

Cancel ends the invocation as cancelled and cancels the vendor call. It returns false when the invocation had already ended.

func (*Run) Context

func (r *Run) Context() context.Context

Context is the vendor call's context. It is cancelled when the invocation is cancelled or ends.

func (*Run) Done

func (r *Run) Done() <-chan struct{}

Done is closed when the invocation ends, whether it succeeded, failed or was cancelled.

func (*Run) Fail

func (r *Run) Fail(err error) bool

Fail ends the invocation as failed. It maps err with MapError then records FailureOf(err) so Result.Error never carries raw vendor text; the original stays on MapError's Cause for in-process callers.

func (*Run) Finish

func (r *Run) Finish(res Result) bool

Finish ends the invocation with res. It returns false when it had already ended, so a late vendor callback cannot overwrite a cancellation.

func (*Run) Handle

func (r *Run) Handle() Handle

Handle identifies the invocation.

func (*Run) Publish

func (r *Run) Publish(e Event) bool

Publish appends one event and assigns its sequence number. It returns false when the invocation has already ended, in which case the event is dropped. Publish is the only writer of r.events; each appended event gets Seq == len before append, and after append events[i].Seq == i+1 for every slot.

func (*Run) SetID

func (r *Run) SetID(id string)

SetID records the adapter's identifier for the invocation, so a handle from Lookup carries the vendor id rather than the client ref and a caller can address the vendor through it. An adapter calls it once, after the vendor accepts the start; the registry keeps no separate id table.

func (*Run) Succeed

func (r *Run) Succeed(res Result) bool

Succeed ends the invocation as succeeded.

type State

type State string

State is the terminal or current state of an invocation.

const (
	StateRunning   State = "running"
	StateSucceeded State = "succeeded"
	StateFailed    State = "failed"
	StateCancelled State = "cancelled"
)

type Usage

type Usage struct {
	InputTokens     int64 `json:"input_tokens"`
	OutputTokens    int64 `json:"output_tokens"`
	CachedTokens    int64 `json:"cached_tokens,omitempty"`
	ReasoningTokens int64 `json:"reasoning_tokens,omitempty"`
}

Usage is token accounting for language models.

Directories

Path Synopsis
Package catalog holds the descriptors that a model id stands for and the price table that says what a call of it costs.
Package catalog holds the descriptors that a model id stands for and the price table that says what a call of it costs.
Package chat adapts an eino chat model to the model.Invoker contract.
Package chat adapts an eino chat model to the model.Invoker contract.
Package middleware runs every chat call through one fixed chain:
Package middleware runs every chat call through one fixed chain:
Package node implements the `model` node handler (ADR-0011).
Package node implements the `model` node handler (ADR-0011).
Package providers implements the manifest-driven model providers and the model router.
Package providers implements the manifest-driven model providers and the model router.
sim
Package sim holds in-process simulators for the manifest-driven providers.
Package sim holds in-process simulators for the manifest-driven providers.
Package structured shapes the output of a chat call into JSON that satisfies an output schema.
Package structured shapes the output of a chat call into JSON that satisfies an output schema.
Package worker implements the platform side of ADR-0012 §1 to §11: pools, the descriptors their workers declare, the SQL queue with its classes, fairness and ageing, leases by free capacity, draining and pausing, the worker journal, restart-safe redelivery, worker_lost, spill-over, metrics and worker administration, and routing by labels.
Package worker implements the platform side of ADR-0012 §1 to §11: pools, the descriptors their workers declare, the SQL queue with its classes, fairness and ageing, leases by free capacity, draining and pausing, the worker journal, restart-safe redelivery, worker_lost, spill-over, metrics and worker administration, and routing by labels.

Jump to

Keyboard shortcuts

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