providers

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2026 License: MIT Imports: 19 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

Index

Constants

View Source
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"
)
View Source
const (
	ReasoningEffortNone    = "none"
	ReasoningEffortMinimal = "minimal"
	ReasoningEffortLow     = "low"
	ReasoningEffortMedium  = DefaultReasoningEffort
	ReasoningEffortHigh    = "high"
	ReasoningEffortXHigh   = "xhigh"
)
View Source
const DefaultFallbackContextWindowTokens = 128_000

DefaultFallbackContextWindowTokens is assumed for a model whose window is unknown.

View Source
const DefaultMaxOutputTokens int64 = 16384

DefaultMaxOutputTokens applies when nothing more specific names an output limit.

Variables

View Source
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")
)
View Source
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.

View Source
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 CanonicalProviderID(providerID string) string

func CheckToolCalls added in v0.2.1

func CheckToolCalls(adapter string, calls []ToolCall) error

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 DefaultReasoningEffortForModel(providerID string, providerType string, modelID string) string

func IsContextOverflow added in v0.2.0

func IsContextOverflow(err error) bool

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

func IsContextOverflowText(text string) bool

IsContextOverflowText recognises a provider's wording of a request over the window.

func IsLoopbackURL added in v0.2.1

func IsLoopbackURL(raw string) bool

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

func IsSupportedImageMIMEType(mimeType string) bool

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

func NewHTTPClient() *http.Client

NewHTTPClient returns the client for model requests: no whole-request deadline, but a response body silent for defaultStreamIdleTimeout fails.

func NormalizeModelID

func NormalizeModelID(providerID string, providerType string, modelID string) string

func NormalizeOptionalProviderType added in v0.1.5

func NormalizeOptionalProviderType(providerType string) string

func NormalizeProviderID

func NormalizeProviderID(value string) string

func NormalizeProviderType added in v0.1.5

func NormalizeProviderType(providerType string) string

func NormalizeReasoningEffort

func NormalizeReasoningEffort(value string) string

func NormalizeReasoningEffortForModel added in v0.1.4

func NormalizeReasoningEffortForModel(providerID string, providerType string, modelID string, value string) string

func ParseRetryDelay added in v0.2.1

func ParseRetryDelay(value string) time.Duration

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 ReasoningEffortsForModel(providerID string, providerType string, modelID string) []string

func RegisterContextWindowTokens added in v0.1.10

func RegisterContextWindowTokens(providerID string, modelID string, tokens int)

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

func ResolveContextWindowTokens(providerID string, providerType string, modelID string) int

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 ScanSSE

func ScanSSE(ctx context.Context, body io.Reader, handle func(SSEEvent) error) error

ScanSSE reads SSE frames from body and invokes handle for each event payload.

func StreamText

func StreamText(ctx context.Context, delta string) error

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

func NewStreamError(provider string, status int, code string, message string) *APIError

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.

func (*APIError) Error added in v0.2.0

func (e *APIError) Error() string

func (*APIError) Retryable added in v0.2.0

func (e *APIError) Retryable() bool

Retryable reports a failure that may pass when the same request is sent again.

type BaseURLOption added in v0.1.1

type BaseURLOption struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	URL  string `json:"url"`
}

type Capabilities

type Capabilities struct {
	ModelDiscovery  bool `json:"model_discovery,omitempty"`
	ReasoningEffort bool `json:"reasoning_effort,omitempty"`
	ToolCalling     bool `json:"tool_calling,omitempty"`
	ImageInput      bool `json:"image_input,omitempty"`
	NormalizeModel  bool `json:"normalize_model,omitempty"`
}

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

func ClassifyError(err error) (ErrorKind, time.Duration)

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.

func (ErrorKind) Retryable added in v0.2.1

func (k ErrorKind) Retryable() bool

Retryable reports a kind that may pass when the same request is sent again.

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

type ModelCapabilities struct {
	ToolCalling     bool
	ImageInput      bool
	ReasoningEffort bool
}

ModelCapabilities is what a runtime's model accepts.

type ModelCapabilityInput added in v0.1.4

type ModelCapabilityInput struct {
	ProviderID   string
	ProviderType string
	ModelID      string
}

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

type OutputLimiter interface {
	OutputLimits() (current int64, ceiling int64)
}

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

type ReasoningBlock struct {
	Text         string
	Signature    string
	RedactedData string
}

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 Runtime

type Runtime interface {
	Generate(ctx context.Context, request Request) (Response, error)
}

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

type RuntimeIdentifier interface {
	Identity() (provider string, model string)
}

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 SSEEvent

type SSEEvent struct {
	Type string
	Data string
}

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

type TextStreamFunc func(delta string) error

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.

func (Usage) IsZero added in v0.2.0

func (u Usage) IsZero() bool

Directories

Path Synopsis
ai

Jump to

Keyboard shortcuts

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