providers

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2026 License: MIT Imports: 17 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")
)
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 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 IsRetryableGenerationError added in v0.2.0

func IsRetryableGenerationError(err error) bool

IsRetryableGenerationError is for failures before any output or tool effects. Authentication, invalid requests, and application errors are not retried.

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 OpenAIErrorStatus added in v0.2.0

func OpenAIErrorStatus(code string) int

OpenAIErrorStatus is the HTTP status an OpenAI-style error code stands for, or 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, providerType 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, providerType string, modelID string, metadata ModelMetadataRegistration)

func ResolveContextWindowTokens added in v0.1.10

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

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 RetryAfterDelay added in v0.2.0

func RetryAfterDelay(header string, now time.Time, fallback time.Duration) time.Duration

RetryAfterDelay supports both HTTP forms. Callers may decline a retry whose delay exceeds their budget, but must not retry before the server's deadline.

func RuntimeProviderTypeForTransport added in v0.1.11

func RuntimeProviderTypeForTransport(transport ProviderTransport, providerType string) string

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, message string, header http.Header) *APIError

NewAPIError classifies an HTTP error response; header may be nil.

func NewStreamError added in v0.2.0

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

NewStreamError classifies an error event inside a stream; code is the HTTP-style status the event carries, or 0.

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"`
	CatalogID       string          `json:"catalog_id,omitempty"`
	Name            string          `json:"name"`
	Type            string          `json:"type"`
	Implemented     bool            `json:"implemented"`
	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"
	ErrorOverloaded      ErrorKind = "overloaded"
	ErrorContextOverflow ErrorKind = "context_overflow"
	ErrorAuth            ErrorKind = "auth"
	ErrorInvalid         ErrorKind = "invalid"
)

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"`
}

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
}

func NormalizeMessages

func NormalizeMessages(messages []Message, mode ToolUseMode) []Message

type ModelCapabilities added in v0.1.1

type ModelCapabilities struct {
	ToolCalling        bool
	ParallelToolCalls  bool
	ImageInput         bool
	ReasoningEffort    bool
	ReasoningMode      ReasoningMode
	ReasoningWithTools bool
	NormalizeModel     bool
}

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"`
	ParallelToolCalls      bool                `json:"parallel_tool_calls,omitempty"`
	ImageInput             bool                `json:"image_input,omitempty"`
	ReasoningEffort        bool                `json:"reasoning_effort,omitempty"`
	ReasoningMode          ReasoningMode       `json:"reasoning_mode,omitempty"`
	ReasoningWithTools     bool                `json:"reasoning_with_tools,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"`
	ContextSource          ModelMetadataSource `json:"context_source,omitempty"`
	CapabilitySource       ModelMetadataSource `json:"capability_source,omitempty"`
}

func ResolveModelMetadata added in v0.1.11

func ResolveModelMetadata(providerID string, providerType string, modelID string) ModelMetadata

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"
	ProviderAuthExternal ProviderAuthMode = "external"
)

type ProviderPolicy added in v0.1.11

type ProviderPolicy struct {
	CatalogID           string
	Known               bool
	Implemented         bool
	Name                string
	Type                string
	AuthMode            ProviderAuthMode
	RequiresAPIKey      bool
	AuthStatusLabel     string
	Transport           ProviderTransport
	RuntimeProviderType string
	RequiresBaseURL     bool
	Capabilities        Capabilities
	ModelsURL           string
	PublicModelCatalog  bool
	ChatHeaders         map[string]string
	DefaultBaseURL      string
	BaseURLOptions      []BaseURLOption
	DefaultModel        string
	APIKeyEnv           string
	Notes               string
}

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
	Transport           ProviderTransport
	RuntimeProviderType string
	ModelsURL           string
	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 ProviderTransport added in v0.1.11

type ProviderTransport string
const (
	ProviderTransportOpenAIChat       ProviderTransport = "openai_chat"
	ProviderTransportOpenAIResponses  ProviderTransport = "openai_responses"
	ProviderTransportAnthropicMessage ProviderTransport = "anthropic_messages"
	ProviderTransportGeminiNative     ProviderTransport = "gemini_native"
)

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 ReasoningMode added in v0.1.1

type ReasoningMode string
const (
	ReasoningModeNone           ReasoningMode = ""
	ReasoningModeOpenAIEffort   ReasoningMode = "openai_effort"
	ReasoningModeGeminiThinking ReasoningMode = "gemini_thinking"
)

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
	// MetadataID is the provider ID learned model metadata is kept under.
	MetadataID   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 an API key or base URL.

type RuntimeCapabilityProvider added in v0.1.1

type RuntimeCapabilityProvider interface {
	ModelCapabilities() ModelCapabilities
}

type RuntimeConfig added in v0.2.0

type RuntimeConfig struct {
	ProviderID      string
	CatalogID       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.

func (RuntimeConfig) CatalogKey added in v0.2.0

func (c RuntimeConfig) CatalogKey() string

CatalogKey names the catalog entry the provider was set up from.

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