Documentation
¶
Index ¶
- Constants
- Variables
- func CanonicalProviderID(providerID string) string
- func CheckToolCalls(adapter string, calls []ToolCall) error
- func DefaultReasoningEffortForModel(providerID string, providerType string, modelID string) string
- func IsContextOverflow(err error) bool
- func IsContextOverflowText(text string) bool
- func IsLoopbackURL(raw string) bool
- func IsSupportedImageMIMEType(mimeType string) bool
- func NewHTTPClient() *http.Client
- func NormalizeModelID(providerID string, providerType string, modelID string) string
- func NormalizeOptionalProviderType(providerType string) string
- func NormalizeProviderID(value string) string
- func NormalizeProviderType(providerType string) string
- func NormalizeReasoningEffort(value string) string
- func NormalizeReasoningEffortForModel(providerID string, providerType string, modelID string, value string) string
- func ParseRetryDelay(value string) time.Duration
- func ReasoningEfforts() []string
- func ReasoningEffortsForModel(providerID string, providerType string, modelID string) []string
- func RegisterContextWindowTokens(providerID string, modelID string, tokens int)
- func RegisterModelMetadata(providerID string, modelID string, metadata ModelMetadataRegistration)
- func ResolveContextWindowTokens(providerID string, providerType string, modelID string) int
- func ResolveMaxOutputTokens(requested int, configured int64, providerID, providerType, modelID string) int64
- func SaveModelMetadata()
- func ScanSSE(ctx context.Context, body io.Reader, handle func(SSEEvent) error) error
- func StreamText(ctx context.Context, delta string) error
- func UseModelMetadataCache(path string)
- func WithTextStream(ctx context.Context, fn TextStreamFunc) context.Context
- type APIError
- type BaseURLOption
- type Capabilities
- type CatalogEntry
- type ErrorKind
- type ImageContent
- type Message
- type ModelCapabilities
- type ModelCapabilityInput
- type ModelCapabilitySet
- type ModelMetadata
- type ModelMetadataRegistration
- type ModelMetadataSource
- type OpenAIChatOptions
- type OutputLimiter
- type ProviderAuthMode
- type ProviderPolicy
- type ProviderSpec
- type ReasoningBlock
- type Request
- type Response
- type Runtime
- type RuntimeBase
- type RuntimeCapabilityProvider
- type RuntimeConfig
- type RuntimeIdentifier
- type SSEEvent
- type StopReason
- type TextStreamFunc
- type ToolCall
- type ToolChoice
- type ToolDefinition
- type ToolUseMode
- type Usage
Constants ¶
const ( TypeOpenAICompat = "openai-compatible" TypeOpenAICodex = "openai-codex" TypeAnthropic = "anthropic-compatible" TypeGemini = "gemini" DefaultOpenAICompatModel = "gpt-5.4-mini" DefaultOpenAICodexModel = "gpt-5.4" DefaultAnthropicModel = "claude-sonnet-4-5" DefaultGeminiModel = "gemini-2.5-flash" DefaultReasoningEffort = "medium" )
const ( ReasoningEffortNone = "none" ReasoningEffortMinimal = "minimal" ReasoningEffortLow = "low" ReasoningEffortMedium = DefaultReasoningEffort ReasoningEffortHigh = "high" ReasoningEffortXHigh = "xhigh" )
const DefaultFallbackContextWindowTokens = 128_000
DefaultFallbackContextWindowTokens is assumed for a model whose window is unknown.
const DefaultMaxOutputTokens int64 = 16384
DefaultMaxOutputTokens applies when nothing more specific names an output limit.
Variables ¶
var ( ErrEmptyResponse = errors.New("empty assistant reply") ErrIncompleteResponse = errors.New("provider stream ended before completion") ErrMalformedToolCall = errors.New("model produced a malformed tool call") // ErrReauthRequired marks credentials only a new sign-in can fix. ErrReauthRequired = errors.New("sign-in expired") )
var ErrSSEComplete = errors.New("SSE complete")
ErrSSEComplete lets a protocol decoder stop at its terminal event even if the upstream keeps the HTTP connection open after that event.
var ErrStreamIdle = errors.New("provider stream idle timeout")
ErrStreamIdle marks a response body that stayed silent past the idle timeout.
Functions ¶
func CanonicalProviderID ¶ added in v0.1.11
func CheckToolCalls ¶ added in v0.2.1
CheckToolCalls fails a reply with a tool call that has no name or whose arguments are not valid JSON; the engine hands the error back to the model.
func DefaultReasoningEffortForModel ¶ added in v0.1.4
func IsContextOverflow ¶ added in v0.2.0
IsContextOverflow reports a request over the model window. Providers that only describe it in an error event's text are recognised by its wording.
func IsContextOverflowText ¶ added in v0.2.0
IsContextOverflowText recognises a provider's wording of a request over the window.
func IsLoopbackURL ¶ added in v0.2.1
IsLoopbackURL reports a base URL on this machine (localhost or a loopback IP), where model servers usually take no API key.
func IsSupportedImageMIMEType ¶ added in v0.2.0
IsSupportedImageMIMEType reports whether image data can be sent inline to every image-capable provider. Other image/* files (for example SVG) stay attachment references only.
func NewHTTPClient ¶ added in v0.2.0
NewHTTPClient returns the client for model requests: no whole-request deadline, but a response body silent for defaultStreamIdleTimeout fails.
func NormalizeModelID ¶
func NormalizeOptionalProviderType ¶ added in v0.1.5
func NormalizeProviderID ¶
func NormalizeProviderType ¶ added in v0.1.5
func NormalizeReasoningEffortForModel ¶ added in v0.1.4
func ParseRetryDelay ¶ added in v0.2.1
ParseRetryDelay reads a delay a provider wrote in an error body, such as Gemini's "41.5s" or Codex's resets_in_seconds; 0 when it names none.
func ReasoningEfforts ¶
func ReasoningEfforts() []string
func ReasoningEffortsForModel ¶ added in v0.1.4
func RegisterContextWindowTokens ¶ added in v0.1.10
RegisterContextWindowTokens records a context window a live listing reported.
func RegisterModelMetadata ¶ added in v0.1.11
func RegisterModelMetadata(providerID string, modelID string, metadata ModelMetadataRegistration)
RegisterModelMetadata records what providerID's live listing reported for modelID.
func ResolveContextWindowTokens ¶ added in v0.1.10
ResolveContextWindowTokens is the catalog window of a provider's model.
func ResolveMaxOutputTokens ¶ added in v0.2.0
func ResolveMaxOutputTokens(requested int, configured int64, providerID, providerType, modelID string) int64
ResolveMaxOutputTokens picks the request value, then the provider config, then the model catalog limit when it is below the default, then the default.
func SaveModelMetadata ¶ added in v0.2.0
func SaveModelMetadata()
SaveModelMetadata persists the registered metadata once a listing is done.
func StreamText ¶
StreamText forwards a streamed text delta to the sink attached to ctx.
func UseModelMetadataCache ¶ added in v0.2.0
func UseModelMetadataCache(path string)
UseModelMetadataCache loads what earlier listings learned from path and makes SaveModelMetadata write there; an empty path keeps the metadata in memory.
func WithTextStream ¶
func WithTextStream(ctx context.Context, fn TextStreamFunc) context.Context
WithTextStream attaches an optional text delta sink to the request context.
Types ¶
type APIError ¶ added in v0.2.0
type APIError struct {
Provider string
Status int
Kind ErrorKind
Message string
RetryAfter time.Duration
}
APIError is an error the provider reported, over HTTP or as a stream event (Status 0). RetryAfter is the server's requested wait, if it gave one.
func NewAPIError ¶ added in v0.2.0
func NewAPIError(provider string, status int, code string, message string, header http.Header) *APIError
NewAPIError classifies an HTTP error response. code is the error code or type the body names ("" if none); header may be nil.
func NewStreamError ¶ added in v0.2.0
NewStreamError classifies an error event inside a stream; status is the HTTP-style status the event carries, or 0, and code its error code or type.
type BaseURLOption ¶ added in v0.1.1
type Capabilities ¶
type CatalogEntry ¶
type CatalogEntry struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
RequiresBaseURL bool `json:"requires_base_url"`
Capabilities Capabilities `json:"capabilities"`
DefaultBaseURL string `json:"default_base_url,omitempty"`
BaseURLOptions []BaseURLOption `json:"base_url_options,omitempty"`
DefaultModel string `json:"default_model,omitempty"`
APIKeyEnv string `json:"api_key_env,omitempty"`
Notes string `json:"notes,omitempty"`
}
type ErrorKind ¶ added in v0.2.0
type ErrorKind string
ErrorKind says what a provider error means for the caller.
const ( ErrorRateLimit ErrorKind = "rate_limit" // too many requests now; wait RetryAfter ErrorOverloaded ErrorKind = "overloaded" // server busy or failing ErrorTransient ErrorKind = "transient" // network or stream cut before the reply ended ErrorAuth ErrorKind = "auth" // bad or expired credentials ErrorQuota ErrorKind = "quota" // out of credit or plan usage; waiting minutes will not help ErrorContextOverflow ErrorKind = "context_overflow" ErrorPermanent ErrorKind = "permanent" // the same request fails again )
func ClassifyError ¶ added in v0.2.1
ClassifyError says what a generation failure means for a retry: its kind and the wait the server asked for (0 if none). A canceled context and application errors are permanent.
type ImageContent ¶
type ImageContent struct {
MIMEType string `json:"mime_type,omitempty"`
DataBase64 string `json:"data_base64,omitempty"`
Name string `json:"name,omitempty"`
StoragePath string `json:"storage_path,omitempty"`
Temporary bool `json:"temporary,omitempty"`
Size int64 `json:"size,omitempty"`
}
func (ImageContent) DataURL ¶ added in v0.2.1
func (img ImageContent) DataURL() string
DataURL is the image as a data: URL.
func (ImageContent) MediaType ¶ added in v0.2.1
func (img ImageContent) MediaType() string
MediaType is the image's MIME type without parameters. When none is given it is read from the data's magic bytes, else image/jpeg.
type Message ¶
type Message struct {
Role string
Content string
ReasoningContent *string
Reasoning []ReasoningBlock // signed or encrypted reasoning, sent back unchanged
Images []ImageContent
ToolCallID string
ToolCalls []ToolCall
IsError bool // a failed tool result
}
type ModelCapabilities ¶ added in v0.1.1
ModelCapabilities is what a runtime's model accepts.
type ModelCapabilityInput ¶ added in v0.1.4
type ModelCapabilitySet ¶ added in v0.1.4
type ModelCapabilitySet struct {
ProviderCapabilities Capabilities
RuntimeCapabilities ModelCapabilities
ReasoningEfforts []string
DefaultReasoningEffort string
}
func ResolveModelCapabilities ¶ added in v0.1.1
func ResolveModelCapabilities(input ModelCapabilityInput) ModelCapabilitySet
type ModelMetadata ¶ added in v0.1.11
type ModelMetadata struct {
ID string `json:"id,omitempty"`
ContextWindow int `json:"context_window,omitempty"`
MaxOutputTokens int `json:"max_output_tokens,omitempty"`
ToolCalling bool `json:"tool_calling,omitempty"`
ImageInput bool `json:"image_input,omitempty"`
ReasoningEffort bool `json:"reasoning_effort,omitempty"`
ReasoningEfforts []string `json:"reasoning_efforts,omitempty"`
DefaultReasoningEffort string `json:"default_reasoning_effort,omitempty"`
SupportedParameters []string `json:"supported_parameters,omitempty"`
Source ModelMetadataSource `json:"source,omitempty"`
}
func ResolveModelMetadata ¶ added in v0.1.11
func ResolveModelMetadata(providerID string, providerType string, modelID string) ModelMetadata
ResolveModelMetadata is what a provider's model can do: the provider's live listing first, then the static rules for its type, then the fallback.
type ModelMetadataRegistration ¶ added in v0.1.11
type ModelMetadataRegistration struct {
ContextWindow int `json:"context_window,omitempty"`
MaxOutputTokens int `json:"max_output_tokens,omitempty"`
ToolCalling *bool `json:"tool_calling,omitempty"`
ImageInput *bool `json:"image_input,omitempty"`
ReasoningEffort *bool `json:"reasoning_effort,omitempty"`
ReasoningEfforts []string `json:"reasoning_efforts,omitempty"`
SupportedParameters []string `json:"supported_parameters,omitempty"`
}
ModelMetadataRegistration is what a live listing reports for one model; nil and zero fields are unknown.
type ModelMetadataSource ¶ added in v0.1.11
type ModelMetadataSource string
const ( ModelMetadataSourceLiveCatalog ModelMetadataSource = "live_catalog" ModelMetadataSourceStaticRule ModelMetadataSource = "static_rule" ModelMetadataSourceFallback ModelMetadataSource = "fallback" )
type OpenAIChatOptions ¶ added in v0.1.11
type OpenAIChatOptions struct {
Headers map[string]string
MaxCompletionTokens bool // send max_completion_tokens instead of max_tokens
PromptCacheKey bool // send prompt_cache_key; only OpenAI's own endpoint is known to accept it
ContentCacheControl bool // mark cache breakpoints in content parts; OpenRouter passes them to Claude models
}
OpenAIChatOptions are what an OpenAI-compatible endpoint needs beyond the standard chat completions request.
func ResolveOpenAIChatOptions ¶ added in v0.1.11
func ResolveOpenAIChatOptions(providerID string, baseURL string, model string) OpenAIChatOptions
type OutputLimiter ¶ added in v0.2.0
OutputLimiter reports the output limit a runtime sends when a request names none and the most its model accepts (0 = unknown). A runtime without it sends no limit the engine could raise.
type ProviderAuthMode ¶ added in v0.1.11
type ProviderAuthMode string
const ( ProviderAuthAPIKey ProviderAuthMode = "api_key" ProviderAuthOAuth ProviderAuthMode = "oauth" )
type ProviderPolicy ¶ added in v0.1.11
type ProviderPolicy struct {
CatalogID string
Known bool
Name string
Type string
AuthMode ProviderAuthMode
RequiresAPIKey bool
AuthStatusLabel string
RequiresBaseURL bool
Capabilities Capabilities
PublicModelCatalog bool
ChatHeaders map[string]string
DefaultBaseURL string
BaseURLOptions []BaseURLOption
DefaultModel string
APIKeyEnv string
Notes string
}
ProviderPolicy is the catalog entry of a built-in provider, or the type defaults of a custom one. CatalogID is the canonical id an alias stands for.
func PolicyForProvider ¶ added in v0.1.11
func PolicyForProvider(providerID string, providerType string) ProviderPolicy
type ProviderSpec ¶ added in v0.1.11
type ProviderSpec struct {
Order int
Entry CatalogEntry
Aliases []string
Auth ProviderAuthMode
PublicModelCatalog bool
ChatHeaders map[string]string // extra headers of an OpenAI-compatible chat endpoint
}
func ProviderSpecByID ¶ added in v0.1.11
func ProviderSpecByID(providerID string) (ProviderSpec, bool)
func ProviderSpecs ¶ added in v0.1.11
func ProviderSpecs() []ProviderSpec
type ReasoningBlock ¶ added in v0.2.0
ReasoningBlock is provider reasoning that must be sent back as received. Signature: Anthropic thinking signature or Gemini thought signature. RedactedData: Anthropic redacted thinking or Responses API encrypted reasoning.
type Request ¶
type Request struct {
SystemPrompt string
Messages []Message
Tools []ToolDefinition
MaxOutputTokens int // 0 = provider config, then model catalog, then DefaultMaxOutputTokens
ToolChoice ToolChoice // tools stay defined with ToolChoiceNone so the cached prefix survives
CacheKey string // session id; adapters use it for prompt_cache_key or cache breakpoints
}
type Response ¶
type Response struct {
Text string
ReasoningContent *string
Model string
Provider string
Reasoning []ReasoningBlock
ToolCalls []ToolCall
StopReason StopReason
Usage Usage
}
type RuntimeBase ¶ added in v0.2.0
type RuntimeBase struct {
Client *http.Client
APIKey string
BaseURL string
Model string
MaxOutputTokens int64
ProviderID string
ProviderType string
Capabilities ModelCapabilities
}
RuntimeBase is the state every adapter keeps and the answers it gives the same way; adapters embed it.
func NewRuntimeBase ¶ added in v0.2.0
func NewRuntimeBase(cfg RuntimeConfig, providerType string, defaultModel string) RuntimeBase
NewRuntimeBase trims cfg, applies the adapter's defaults and resolves the model's capabilities; a user who disabled tool use gets no tool calling.
func (*RuntimeBase) CatalogOutputLimits ¶ added in v0.2.0
func (b *RuntimeBase) CatalogOutputLimits() (int64, int64)
CatalogOutputLimits is OutputLimits for an adapter that sends the configured or catalog limit as is.
func (*RuntimeBase) Identity ¶ added in v0.2.0
func (b *RuntimeBase) Identity() (string, string)
func (*RuntimeBase) ModelCapabilities ¶ added in v0.2.0
func (b *RuntimeBase) ModelCapabilities() ModelCapabilities
func (*RuntimeBase) RequireKeyAndURL ¶ added in v0.2.0
func (b *RuntimeBase) RequireKeyAndURL(adapter string) error
RequireKeyAndURL fails a base that lacks a base URL, or an API key for a server other than a local one.
type RuntimeCapabilityProvider ¶ added in v0.1.1
type RuntimeCapabilityProvider interface {
ModelCapabilities() ModelCapabilities
}
type RuntimeConfig ¶ added in v0.2.0
type RuntimeConfig struct {
ProviderID string
Type string
APIKey string
BaseURL string
Model string
MaxOutputTokens int64
ReasoningEffort string
ToolUseMode ToolUseMode
HTTPClient *http.Client
}
RuntimeConfig is what every adapter is built from. ProviderID is the configured provider's canonical id; learned model metadata is kept under it.
type RuntimeIdentifier ¶ added in v0.2.0
RuntimeIdentifier reports the Provider and Model a runtime puts on its responses, so signed reasoning is replayed only to the model that made it.
type StopReason ¶ added in v0.2.0
type StopReason string
StopReason says why generation ended, normalised across providers.
const ( StopEndTurn StopReason = "end_turn" StopToolUse StopReason = "tool_use" StopMaxTokens StopReason = "max_tokens" StopRefusal StopReason = "refusal" StopContentFilter StopReason = "content_filter" )
func ResolveStopReason ¶ added in v0.2.0
func ResolveStopReason(reason StopReason, toolCalls int) StopReason
ResolveStopReason reconciles a mapped wire reason with the reply itself: gateways report "stop" alongside tool calls, or "tool_calls" without any.
func (StopReason) AllowsEmptyReply ¶ added in v0.2.0
func (r StopReason) AllowsEmptyReply() bool
AllowsEmptyReply reports whether a reply with neither text nor tool calls is a valid outcome for this reason rather than a failed generation.
type TextStreamFunc ¶
func TextStreamFromContext ¶
func TextStreamFromContext(ctx context.Context) TextStreamFunc
TextStreamFromContext returns the text delta sink attached to ctx, if any.
type ToolCall ¶
type ToolCall struct {
ID string `json:"id"`
Name string `json:"name"`
Arguments json.RawMessage `json:"arguments,omitempty"`
}
type ToolChoice ¶ added in v0.2.0
type ToolChoice string
ToolChoice limits tool use for one request.
const ( ToolChoiceAuto ToolChoice = "" ToolChoiceNone ToolChoice = "none" )
type ToolDefinition ¶
type ToolDefinition struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
InputSchema json.RawMessage `json:"input_schema,omitempty"`
}
type ToolUseMode ¶
type ToolUseMode string
const ( ToolUseNative ToolUseMode = "native" ToolUseDisabled ToolUseMode = "disabled" )
func NormalizeOptionalToolUseMode ¶
func NormalizeOptionalToolUseMode(value ToolUseMode) ToolUseMode
func NormalizeToolUseMode ¶
func NormalizeToolUseMode(value ToolUseMode) ToolUseMode
func (ToolUseMode) Label ¶ added in v0.2.0
func (m ToolUseMode) Label() string
Label is the mode as setup screens show it.
type Usage ¶
type Usage struct {
PromptTokens int64 `json:"prompt_tokens,omitempty"`
OutputTokens int64 `json:"output_tokens,omitempty"`
CacheReadTokens int64 `json:"cache_read_tokens,omitempty"`
CacheWriteTokens int64 `json:"cache_write_tokens,omitempty"`
ReasoningTokens int64 `json:"reasoning_tokens,omitempty"`
ProviderRaw json.RawMessage `json:"provider_raw,omitempty"`
}
Usage is normalised by every adapter: PromptTokens is the whole input, cache reads and writes included; OutputTokens includes ReasoningTokens.
Source Files
¶
- api_error.go
- catalog.go
- context_window.go
- contract.go
- generation_errors.go
- httpclient.go
- images.go
- max_output.go
- model_capabilities.go
- model_image_input.go
- model_metadata.go
- model_metadata_cache.go
- openai_chat_options.go
- policy.go
- provider_anthropic.go
- provider_gemini.go
- provider_openai.go
- provider_openai_compatible_gateways.go
- provider_qwen.go
- provider_specs_helpers.go
- provider_type.go
- registry.go
- request_normalize.go
- retry.go
- runtime_config.go
- sse.go
- stop_reason.go
- stream.go
- toolcalls.go