Documentation
¶
Overview ¶
Package llm normalises several vendor chat APIs behind one streaming interface: OpenAI-compatible, OpenAI, Anthropic, Gemini, and custom endpoints.
Index ¶
- Constants
- Variables
- func IsAuthError(err error) bool
- func IsRateLimit(err error) bool
- func IsUnreachable(err error) bool
- func PollCopilotToken(ctx context.Context, dc *DeviceCode) (string, error)
- func Retryable(err error) bool
- type AudioClient
- type Client
- type DeviceCode
- type Event
- type EventType
- type FallbackEntry
- type Message
- type ModelInfo
- type Options
- type Part
- type Request
- type Response
- type Tool
- type ToolCall
- type TransportError
- type Usage
Constants ¶
const ( RoleSystem = "system" RoleUser = "user" RoleAssistant = "assistant" RoleTool = "tool" )
Roles used in Message.
Variables ¶
var ErrUnsupported = errors.New("operation not supported by this provider")
ErrUnsupported is returned by adapters that lack a capability.
Functions ¶
func IsAuthError ¶
IsAuthError reports whether err came back as 401/403.
func IsRateLimit ¶
IsRateLimit reports whether err came back as 429.
func IsUnreachable ¶
IsUnreachable reports whether err is a connection failure rather than a response from the provider.
func PollCopilotToken ¶
func PollCopilotToken(ctx context.Context, dc *DeviceCode) (string, error)
PollCopilotToken polls until the user authorises and returns the GitHub OAuth token. It blocks up to the device code's lifetime.
Types ¶
type AudioClient ¶
type AudioClient interface {
// Speak synthesises speech from text, returning the audio bytes and the file
// extension for them (e.g. "mp3").
Speak(ctx context.Context, model, voice, format, text string) ([]byte, string, error)
// Transcribe turns speech audio into text.
Transcribe(ctx context.Context, model, filename string, audio []byte) (string, error)
}
AudioClient is an optional capability: text-to-speech and speech-to-text. Adapters that support it (the OpenAI family) implement it; callers type-assert.
type Client ¶
type Client interface {
// Kind reports the adapter family (openai, anthropic, gemini, ...).
Kind() string
// Chat runs a non-streaming completion.
Chat(ctx context.Context, req Request) (*Response, error)
// Stream runs a completion, invoking emit for each incremental event. The
// final Response is returned once the stream completes.
Stream(ctx context.Context, req Request, emit func(Event) error) (*Response, error)
// Models lists available models; providers that cannot enumerate return nil.
Models(ctx context.Context) ([]ModelInfo, error)
// Embed produces embedding vectors, or ErrUnsupported.
Embed(ctx context.Context, model string, inputs []string) ([][]float32, error)
}
Client is a provider adapter.
func New ¶
New builds the adapter matching kind. Unknown kinds fall back to the OpenAI-compatible adapter, which covers most self-hosted endpoints.
func NewFallback ¶
func NewFallback(entries []FallbackEntry) Client
NewFallback wraps an ordered list of clients. The first is primary. With one entry it returns that client unwrapped, so there is no overhead when no fallback is configured.
type DeviceCode ¶
type DeviceCode struct {
DeviceCode string `json:"device_code"`
UserCode string `json:"user_code"`
VerificationURI string `json:"verification_uri"`
ExpiresIn int `json:"expires_in"`
Interval int `json:"interval"`
}
DeviceCode is the first step of the GitHub device flow: show the user the code and URL, then poll with Verificaton until they authorise.
func StartCopilotLogin ¶
func StartCopilotLogin(ctx context.Context) (*DeviceCode, error)
StartCopilotLogin begins the device flow and returns the code to show the user.
type Event ¶
type Event struct {
Type EventType `json:"type"`
Delta string `json:"delta,omitempty"`
Index int `json:"index,omitempty"`
ToolCallID string `json:"tool_call_id,omitempty"`
ToolName string `json:"tool_name,omitempty"`
Usage *Usage `json:"usage,omitempty"`
Err string `json:"error,omitempty"`
}
Event is one incremental streaming update.
type EventType ¶
type EventType string
EventType enumerates streaming callbacks.
const ( EventText EventType = "text" EventReasoning EventType = "reasoning" EventToolCallStart EventType = "tool_call_start" EventToolCallDelta EventType = "tool_call_delta" EventToolCallEnd EventType = "tool_call_end" EventUsage EventType = "usage" EventDone EventType = "done" EventError EventType = "error" )
type FallbackEntry ¶
FallbackEntry is one client and the model to ask it for.
type Message ¶
type Message struct {
Role string `json:"role"`
Content string `json:"content,omitempty"`
Parts []Part `json:"parts,omitempty"`
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
ToolCallID string `json:"tool_call_id,omitempty"`
Name string `json:"name,omitempty"`
Reasoning string `json:"reasoning,omitempty"`
// CacheHint marks a prefix boundary for providers that support prompt caching.
CacheHint bool `json:"cache_hint,omitempty"`
}
Message is one conversation element in provider-neutral form.
type ModelInfo ¶
type ModelInfo struct {
ID string `json:"id"`
Name string `json:"name"`
Provider string `json:"provider"`
ContextWindow int `json:"context_window"`
MaxOutput int `json:"max_output"`
InputCost float64 `json:"input_cost"` // USD per 1M tokens
OutputCost float64 `json:"output_cost"` // USD per 1M tokens
Vision bool `json:"vision"`
Tools bool `json:"tools"`
Reasoning bool `json:"reasoning"`
}
ModelInfo describes one model offered by a provider.
type Options ¶
type Options struct {
Kind string
BaseURL string
APIKey string
Headers map[string]string
Timeout time.Duration
ProviderID string
HTTPClient *http.Client
// Retries is how many times a transient failure (429, 5xx, connection
// drop) is retried with backoff before giving up. Zero disables retrying.
Retries int
// RetryBaseDelay is the first backoff step; it doubles each attempt. Zero
// uses a sensible default.
RetryBaseDelay time.Duration
// APIVersion is the Azure OpenAI api-version query parameter. Ignored by
// other kinds.
APIVersion string
// Region is the AWS region for Bedrock, e.g. "us-east-1". Empty reads
// AWS_REGION / AWS_DEFAULT_REGION.
Region string
}
Options configures an adapter instance.
type Part ¶
type Part struct {
Type string `json:"type"` // text|image|file
Text string `json:"text,omitempty"`
MimeType string `json:"mime_type,omitempty"`
// Data is base64 without a data: prefix; URL is used when the source is remote.
Data string `json:"data,omitempty"`
URL string `json:"url,omitempty"`
}
Part is one element of a multimodal message.
type Request ¶
type Request struct {
Model string
System string
Messages []Message
Tools []Tool
ToolChoice string // auto|none|required|<tool name>
Temperature float64
TopP float64
MaxTokens int
StopSequences []string
ReasoningEffort string // none|low|medium|high
ParallelToolCalls bool
PromptCache bool
Extra map[string]any
}
Request is a normalised completion request.
type Response ¶
type Response struct {
Content string `json:"content"`
Reasoning string `json:"reasoning,omitempty"`
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
FinishReason string `json:"finish_reason"`
Model string `json:"model"`
Usage Usage `json:"usage"`
Raw json.RawMessage
}
Response is the final result of a completion.
type Tool ¶
type Tool struct {
Name string `json:"name"`
Description string `json:"description"`
Parameters map[string]any `json:"parameters"`
}
Tool is a function the model may call.
type ToolCall ¶
type ToolCall struct {
ID string `json:"id"`
Name string `json:"name"`
Arguments string `json:"arguments"` // raw JSON
}
ToolCall is a model request to invoke a tool.
type TransportError ¶
type TransportError struct {
Host string
Kind string // refused|dns|timeout|tls|network
// contains filtered or unexported fields
}
TransportError is a connection failure, as opposed to a response the provider actually sent. Callers use it to tell "your key is wrong" apart from "nothing is listening there".
func (*TransportError) Error ¶
func (e *TransportError) Error() string
func (*TransportError) Unwrap ¶
func (e *TransportError) Unwrap() error
type Usage ¶
type Usage struct {
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
CacheReadTokens int `json:"cache_read_tokens"`
CacheWriteTokens int `json:"cache_write_tokens"`
ReasoningTokens int `json:"reasoning_tokens"`
ContextTokens int `json:"context_tokens"`
Cost float64 `json:"cost"`
}
Usage reports token accounting for one call.
ContextTokens is the provider-normalised size of the prompt that occupied the model context for this call. It is deliberately separate from cache billing fields: OpenAI-compatible and Gemini APIs report cached tokens as a subset of InputTokens, while Anthropic reports them alongside InputTokens. Consumers must not infer context size by blindly adding cache fields.
func (Usage) ContextSize ¶ added in v0.3.0
ContextSize returns the provider-normalised prompt size for context-window accounting. Adapters with cache counters whose semantics differ set ContextTokens explicitly. The conservative fallback treats InputTokens as the complete prompt so an unknown adapter cannot double-count a cache subset.