provider

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 13 Imported by: 1 module, 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 provider defines the model-provider contract and the registry that lets applications plug in new providers.

Nothing in this package depends on a specific wire protocol. A provider only has to turn a Request into a stream of events and a final Response. The concrete wire dialects (provider/openaicompat, provider/responses and provider/messages) share the Collector, which assembles that Response from deltas, and the request helpers in wire.go.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Classify

func Classify(status int, retryAfterHeader string) (bool, time.Duration)

Classify reports whether a status is worth retrying and how long to wait, parsed from a Retry-After header. It reads the wall clock; tests use classifyAt for a fixed now.

func ContentParts

func ContentParts[T any](m message.Message, text func(string) T, image func(url string) T) []T

ContentParts renders a message that carries parts as a dialect's content array: the text first, then one entry per usable image. It returns nil for a message without parts, which the caller sends as a plain string so a text-only request is byte-for-byte what it was before images existed. A part of an unknown kind, or an image with no bytes, is skipped.

func ImageURL

func ImageURL(p message.ContentPart) string

ImageURL returns where an image part's bytes can be fetched from: its own URL, or a data: URL built from its inline base64. It is empty for any other part kind and for an image with neither.

func MapTools

func MapTools[T any](tools []ToolDef, conv func(ToolFunction) T) []T

MapTools converts tool definitions to a dialect's own tool type.

func MergeJSON

func MergeJSON(raw []byte, opts map[string]any) ([]byte, error)

MergeJSON applies opts over the JSON object raw with MergeOptions and returns the merged object, so a ProviderOptions entry can add or replace a request field. Numbers are carried as written: decoding them to float64 would round an integer past 2^53 in a tool schema or an option.

func MergeOptions

func MergeOptions(base, over map[string]any) map[string]any

MergeOptions returns a new map. Keys in over replace keys in base, except when both values are map[string]any, which merge recursively. Slices are replaced rather than appended. Neither input is modified, and nil inputs are treated as empty.

func Names

func Names() []string

Names returns the registered provider names, sorted.

func NormalizeFinish

func NormalizeFinish(s string) string

NormalizeFinish maps provider-specific finish reasons onto the small set the agent loop understands: stop, length, tool_calls, content_filter, or error. An empty or unknown reason becomes "".

func Register

func Register(p Provider)

Register adds a provider to the process-wide registry. It is meant to be called during startup (typically from an init function or explicit wiring) and panics on duplicate or unnamed registration so configuration mistakes surface immediately.

func RegisterModel

func RegisterModel(m Model)

RegisterModel adds a model to the catalog, replacing any entry with the same ID.

func SplitSystem

func SplitSystem(msgs []message.Message) (system string, rest []message.Message)

SplitSystem lifts the system messages out of a transcript for the dialects that carry the system prompt outside the message list. It joins them with a blank line, skipping empty ones, and returns the remaining messages in order.

Types

type CacheControl

type CacheControl struct {
	Type string `json:"type"`
}

CacheControl is the explicit prompt-cache marker the dialects share. Its wire form is {"type":"ephemeral"}. A top-level marker is automatic caching: the provider places the breakpoint at the end of the prompt and advances it as the loop appends, so every turn reuses the previous turn's prefix.

func RequestCacheControl

func RequestCacheControl(req Request) *CacheControl

RequestCacheControl returns the marker req should carry, or nil for none.

An explicit Request.PromptCache always wins, so a caller can opt in on a model that caches by itself or opt out on one that does not. Otherwise the decision comes from the catalog: a known model that does not cache implicitly gets a marker, and a model the catalog does not know gets none, so an unknown endpoint never receives a parameter it may reject.

type Collector

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

Collector builds a Response from the deltas of one streamed completion and hands each delta to the caller as a StreamEvent. All three wire dialects feed one, so the rules for text, reasoning, usage, tool-call assembly and finish reasons are written once. It is not safe for concurrent use.

func NewCollector

func NewCollector(model string, onEvent func(StreamEvent)) *Collector

NewCollector starts a response for model. onEvent may be nil.

func (*Collector) Finish

func (c *Collector) Finish(reason string) *Response

Finish completes the response after a stream that ended cleanly. It assembles the tool calls in index order and delivers them, then sets the finish reason from the provider's own: a stop that comes with tool calls is reported as tool_calls, since that is what the agent has to act on.

func (*Collector) Partial

func (c *Collector) Partial() *Response

Partial returns the response as far as it has been delivered: text and reasoning, no tool calls. A failed stream returns it with the error so the caller keeps what the model already said, and never a half-built call.

func (*Collector) Reasoning

func (c *Collector) Reasoning(s string)

Reasoning appends reasoning text and delivers it.

func (*Collector) SetModel

func (c *Collector) SetModel(model string)

SetModel records the model name the server reports, when it reports one.

func (*Collector) Text

func (c *Collector) Text(s string)

Text appends assistant text and delivers it.

func (*Collector) ToolCall

func (c *Collector) ToolCall(index int, id, typ, name, args string)

ToolCall folds one fragment into the call at index. The first non-empty id, type and name win, because later fragments repeat them or omit them and a stray different value must not rename a call already keyed by index. args is appended. Nothing is delivered until Finish, so a consumer never sees half an argument list.

func (*Collector) Usage

func (c *Collector) Usage(u Usage)

Usage records u as the response's usage, replacing any earlier value, and delivers it. Providers report running totals, so the latest report wins.

type CostMultiplier added in v0.3.4

type CostMultiplier struct {
	Factor float64
	Window string
}

CostMultiplier is one time-based price factor with the window it applies in, in the catalog's own terms (such as weekday peak hours).

type Error

type Error struct {
	Status  int
	Code    string
	Message string
	// Body is the response body of a failed HTTP request, scrubbed of the
	// request's credentials and cut to a fixed bound but otherwise verbatim, for
	// a caller that parses the provider's own error JSON. Error() never prints it.
	Body       string
	Retryable  bool
	RetryAfter time.Duration
	Err        error
}

Error is what a provider returns for a failed request. Retryable and RetryAfter tell the agent loop whether and when to try again.

func (*Error) Error

func (e *Error) Error() string

Error renders the failure for logs and error chains.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap exposes the underlying cause to errors.Is and errors.As.

type Model

type Model struct {
	// ID is the stable id used in config and sessions.
	ID string
	// Name is the display name.
	Name string
	// Provider is the provider name this model is served by.
	Provider string
	// Slug is the provider's wire model id.
	Slug string
	// ContextWindow is the total token budget, when known.
	ContextWindow int
	// MaxOutputTokens bounds one response, when known.
	MaxOutputTokens int
	// InPerM and OutPerM are listed dollars per million tokens.
	InPerM  float64
	OutPerM float64
	// InputModalities lists the input kinds the model accepts, such as "text"
	// and "image". Empty means text only, the safe default for a model Nova
	// does not know. It mirrors OpenRouter's input_modalities.
	InputModalities []string
	// OutputModalities lists what the model produces, such as "text" or
	// "decisions". Empty means text only, the safe default for a chat model.
	// It mirrors OpenRouter's output_modalities.
	OutputModalities []string
	// Voices lists the voice identifiers a speech model accepts, such as
	// "af_heart" or "alloy". Empty means the roster did not report any, which
	// is the case for every model that is not a speech model. It mirrors
	// OpenRouter's supported_voices.
	Voices []string
	// ImplicitCaching reports that the provider caches a repeated request
	// prefix on its own, so Nova must not send an explicit cache marker.
	// False is the safe default: an anthropic-style model needs the marker to
	// cache at all, and a model the catalog does not know is never marked.
	ImplicitCaching bool
	// ReasoningEfforts lists the reasoning effort tiers the model accepts,
	// such as low, high, or max. Empty means the model has no effort
	// control; a model the catalog does not know sends none either.
	ReasoningEfforts []string
	// ToolChoice lists the tool_choice variants the model accepts, such as
	// auto, none, required, or tool. Empty means unknown: a model the
	// catalog does not describe is sent tools without a choice variant.
	ToolChoice []string
	// PriceTiers lists the prompt-size price bands above the base InPerM
	// and OutPerM rates, ascending by AboveTokens. Empty means flat
	// pricing at any prompt size.
	PriceTiers []PriceTier
	// CostMultipliers lists the time-based price factors, such as a peak
	// doubling. Display-only: scheduling around them is the caller's job.
	CostMultipliers []CostMultiplier
	// MonthlyLimitUSD is the subscription's monthly allowance for this
	// model in dollars, Go base plan. Plus and Teams plans raise it; a
	// model with no plan limit is zero. Docs-only data, not a price.
	MonthlyLimitUSD float64
}

Model describes one selectable model. The catalog is code-defined, so a stored model id keeps resolving even when a provider changes its slug, and pricing is available for cost accounting and caps.

func GetModel

func GetModel(id string) (Model, bool)

GetModel returns a catalog entry by ID.

func Models

func Models() []Model

Models returns the catalog sorted by provider then id.

func (Model) AcceptsImages

func (m Model) AcceptsImages() bool

AcceptsImages reports whether the model declares image input. A model with no modalities is text only, so this is false for anything Nova does not know.

func (Model) SupportsDecisions

func (m Model) SupportsDecisions() bool

SupportsDecisions reports whether the model is a decision model that speaks the Decisions API. A model with no output modalities is a chat model, so this is false for anything Nova does not know.

func (Model) SupportsEmbeddings added in v0.3.0

func (m Model) SupportsEmbeddings() bool

SupportsEmbeddings reports whether the model is an embedding model. The live roster marks one with the "embeddings" output modality; a model with no modalities is a chat model, so this is false for anything Nova does not know.

func (Model) SupportsSpeech added in v0.4.0

func (m Model) SupportsSpeech() bool

SupportsSpeech reports whether the model is a text-to-speech model. The live roster marks one with the "speech" output modality; a model with no modalities is a chat model, so this is false for anything Nova does not know.

func (Model) SupportsTranscription added in v0.4.0

func (m Model) SupportsTranscription() bool

SupportsTranscription reports whether the model is a speech-to-text model. The live roster marks one with the "transcription" output modality; a model with no modalities is a chat model, so this is false for anything Nova does not know.

type OpencodeUsage added in v0.3.4

type OpencodeUsage struct {
	Allowance     *float64 `json:"allowance"`
	ListCost      *float64 `json:"list_cost"`
	BillingSource string   `json:"billing_source"`
}

OpencodeUsage is the usage.opencode object OpenCode Go attaches to every usage report, beside the dialect's own token counts and cost. Allowance and ListCost are pointers so a reported zero (a free model) reads differently from an absent object, the same rule the cost field already uses.

type PriceTier added in v0.3.4

type PriceTier struct {
	AboveTokens int
	InPerM      float64
	OutPerM     float64
}

PriceTier is one prompt-size price band: above AboveTokens prompt tokens, InPerM and OutPerM replace the model's base rates.

type Provider

type Provider interface {
	// Name is the stable provider id used by the registry and model catalog.
	Name() string
	// Stream performs one completion request.
	Stream(ctx context.Context, req Request, onEvent func(StreamEvent)) (*Response, error)
}

Provider is a model backend.

Stream must call onEvent for each incremental chunk (text, reasoning, and fully-assembled tool calls) and return the finalized Response. Implementations must honor ctx cancellation and must return a non-nil error on failure. It is safe for onEvent to be nil.

func Get

func Get(name string) (Provider, bool)

Get returns a registered provider by name.

type Request

type Request struct {
	Model string
	// ModelID is the stable catalog id that Model (the wire slug) was derived
	// from. A router uses it to pick the provider, because a slug alone does not
	// name one; wire providers ignore it. Empty means Model is the catalog id.
	ModelID    string
	Messages   []message.Message
	Tools      []ToolDef
	ToolChoice any
	// ParallelToolCalls asks a chat-completions provider to allow (true) or
	// forbid (false) several tool calls in one message. Nil sends nothing. It is
	// only meaningful with tools, so the wire omits it from a request that has
	// none, such as the wrap-up request. Dialects without the notion ignore it.
	ParallelToolCalls *bool
	Temperature       *float64
	MaxTokens         int
	Stop              []string
	// ReasoningEffort asks for a reasoning tier. The tiers vary by
	// provider (OpenRouter-style low/medium/high; Go spans minimal to
	// max); the catalog's ReasoningEfforts lists what a model takes.
	// "" sends none.
	ReasoningEffort string
	ProviderOptions map[string]any // merged into the wire body by the provider
	ExtraHeaders    map[string]string
	// PromptCache overrides whether the request carries an explicit prompt
	// cache marker. Nil means decide from the catalog; see
	// RequestCacheControl. A pointer, so true and false are both meaningful.
	PromptCache *bool
}

Request is one completion request. The system prompt is carried as the leading system message in Messages, mirroring the model-facing transcript.

type Response

type Response struct {
	Message      message.Message
	FinishReason string
	Usage        Usage
	Model        string
	// Provider is the id of the provider that served the call. A plain
	// provider reports its own name; a router reports the attempt that
	// answered, so a logged call is attributable to the backend that ran it.
	Provider string
}

Response is the finalized result of one provider call.

type StreamEvent

type StreamEvent struct {
	Type     StreamEventType
	Text     string
	ToolCall *message.ToolCall
	Usage    *Usage
	Err      error
}

StreamEvent is one chunk delivered while a response is generated.

type StreamEventType

type StreamEventType string

StreamEventType identifies a streaming event.

const (
	// StreamTextDelta carries a chunk of assistant text.
	StreamTextDelta StreamEventType = "text_delta"
	// StreamReasoningDelta carries a chunk of reasoning/thinking text.
	StreamReasoningDelta StreamEventType = "reasoning_delta"
	// StreamToolCall is emitted once a tool call is fully assembled.
	StreamToolCall StreamEventType = "tool_call"
	// StreamUsage carries a mid-stream usage update.
	StreamUsage StreamEventType = "usage"
	// StreamError reports a mid-stream failure; the call still returns an error.
	StreamError StreamEventType = "error"
)

type ToolDef

type ToolDef struct {
	Type     string       `json:"type"`
	Function ToolFunction `json:"function"`
}

ToolDef is a tool offered to the model, in OpenAI function-calling shape.

type ToolFunction

type ToolFunction struct {
	Name        string         `json:"name"`
	Description string         `json:"description"`
	Parameters  map[string]any `json:"parameters,omitempty"`
}

ToolFunction describes one callable function.

type Usage

type Usage struct {
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens"`
	ReasoningTokens  int `json:"reasoning_tokens,omitempty"`
	TotalTokens      int `json:"total_tokens"`
	CachedTokens     int `json:"cached_tokens,omitempty"`
	// CacheWriteTokens counts tokens written into a prompt cache this call.
	// A cold cache pays the write rate for the prefix it stores.
	CacheWriteTokens int     `json:"cache_write_tokens,omitempty"`
	CostUSD          float64 `json:"cost_usd,omitempty"`
	CostSource       string  `json:"cost_source,omitempty"` // "provider", "allowance", "catalog", or ""
	// AllowanceUSD is the dollars of a subscription allowance this call
	// consumed (Go's usage.opencode.allowance). It is part of CostUSD, not
	// in addition to it: CostUSD is what the call consumed, CostSource says
	// whose dollars they were. Zero with CostSource "allowance" is a
	// reported zero (a free model), distinct from an absent allowance.
	AllowanceUSD float64 `json:"allowance_usd,omitempty"`
	// ListCostUSD is the list price of the same call
	// (Go's usage.opencode.list_cost): what it would have cost at retail.
	// It is informational only and never added to CostUSD.
	ListCostUSD float64 `json:"list_cost_usd,omitempty"`
	// BillingSource is the provider-reported billing source, such as "go",
	// "go-plus", "balance", "free", or "byok". Empty means the
	// provider did not say.
	BillingSource string `json:"billing_source,omitempty"`
}

Usage reports token and cost accounting for one provider call.

func (*Usage) Add

func (u *Usage) Add(o Usage)

Add accumulates another usage record into u.

func (*Usage) ApplyOpencode added in v0.3.4

func (u *Usage) ApplyOpencode(o *OpencodeUsage)

ApplyOpencode folds a present usage.opencode object into u. The allowance becomes the call's cost with source "allowance", because Go reports cost 0 for a covered call and the allowance is what the turn consumed. A nil object is a no-op, so dialects call this unconditionally after mapping their own fields.

Directories

Path Synopsis
Package chat is the one-shot completion seam for non-agent work: titles, suggestions, extraction, and the other cheap calls an app makes outside the loop.
Package chat is the one-shot completion seam for non-agent work: titles, suggestions, extraction, and the other cheap calls an app makes outside the loop.
Package messages implements the Anthropic Messages API with streaming and tool use.
Package messages implements the Anthropic Messages API with streaming and tool use.
Package openaicompat implements the OpenAI chat-completions API with streaming and function/tool calling.
Package openaicompat implements the OpenAI chat-completions API with streaming and function/tool calling.
Package opencodego is the OpenCode Go preset: one provider that sends each model to the wire dialect its endpoint uses (chat completions, Responses, or Messages), with a code-defined catalog and a live model overlay.
Package opencodego is the OpenCode Go preset: one provider that sends each model to the wire dialect its endpoint uses (chat completions, Responses, or Messages), with a code-defined catalog and a live model overlay.
Package openrouter provides an OpenRouter preset over the OpenAI-compatible provider.
Package openrouter provides an OpenRouter preset over the OpenAI-compatible provider.
Package responses implements the OpenAI Responses API with streaming and function calling.
Package responses implements the OpenAI Responses API with streaming and function calling.
Package route is a provider router a library consumer builds from values: named providers, per-model attempt chains, and a fallback predicate.
Package route is a provider router a library consumer builds from values: named providers, per-model attempt chains, and a fallback predicate.
Package ssestream is the shared POST + Server-Sent Events transport for every streaming dialect: chat-completions (openaicompat), Responses, and Messages.
Package ssestream is the shared POST + Server-Sent Events transport for every streaming dialect: chat-completions (openaicompat), Responses, and Messages.

Jump to

Keyboard shortcuts

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