llm

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: Apache-2.0 Imports: 30 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

Overview

Package llm normalises several vendor chat APIs behind one streaming interface: OpenAI-compatible, OpenAI, Anthropic, Gemini, and custom endpoints.

Index

Constants

View Source
const (
	RoleSystem    = "system"
	RoleUser      = "user"
	RoleAssistant = "assistant"
	RoleTool      = "tool"
)

Roles used in Message.

Variables

View Source
var ErrStreamTruncated = errors.New("the provider's response ended before it was complete")

ErrStreamTruncated is returned when a response body ended before the provider signalled the answer was finished. A gateway that loses its upstream closes the body cleanly, so end of body on its own says nothing about whether the answer is complete; only the provider's terminal marker does. Retryable classifies it as worth another attempt, since a cut turn produced no usable answer and replaying the request is safe.

View Source
var ErrUnsupported = errors.New("operation not supported by this provider")

ErrUnsupported is returned by adapters that lack a capability.

Functions

func IsAuthError

func IsAuthError(err error) bool

IsAuthError reports whether err came back as 401/403.

func IsRateLimit

func IsRateLimit(err error) bool

IsRateLimit reports whether err came back as 429.

func IsUnreachable

func IsUnreachable(err error) bool

IsUnreachable reports whether err is a connection failure rather than a response from the provider.

func IsUnsupported added in v0.4.0

func IsUnsupported(err error) bool

IsUnsupported reports that a provider does not expose the optional model catalogue endpoint. A 404/405 is different from a timeout, malformed body, or server error: the credential may still be usable for chat.

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.

func Retryable

func Retryable(err error) bool

Retryable reports whether an error is worth another attempt: a rate limit, a server-side error, or a connection failure. Auth failures and other 4xx are permanent and are not retried.

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

func New(o Options) (Client, error)

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 EncodedReasoning added in v0.4.0

type EncodedReasoning struct {
	Omit           bool
	Body           map[string]any
	GeminiThinking map[string]any
}

EncodedReasoning is the official request fragment for one chosen value.

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

type FallbackEntry struct {
	Client Client
	Model  string
}

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"`
	// ThoughtSignature is Gemini part-level metadata for assistant text
	// (non-tool) turns. Echoed on the text part when re-sending history.
	ThoughtSignature string `json:"thought_signature,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.

func (Message) ToolName

func (m Message) ToolName() string

ToolName is the function name a tool result belongs to. Providers that key results by name rather than call id (Gemini) rely on it.

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"`
	ReasoningCap  *OfficialReasoningCapability `json:"reasoning_capability,omitempty"`
}

ModelInfo describes one model offered by a provider.

type OfficialReasoningCapability added in v0.4.0

type OfficialReasoningCapability struct {
	Wire   string   `json:"wire,omitempty"`
	Values []string `json:"values,omitempty"`
	// Default is the provider's documented default when the field is omitted.
	Default string `json:"default,omitempty"`
}

OfficialReasoningCapability is the native reasoning control for one official provider+model. Values are the strings that provider's API accepts.

func OfficialReasoning added in v0.4.0

func OfficialReasoning(kind, baseURL, model string) OfficialReasoningCapability

OfficialReasoning returns the native ladder for a known official endpoint. Any other host is a custom endpoint: the picker offers the full official value list and the request carries reasoning_effort as that string.

func (OfficialReasoningCapability) AllowsOff added in v0.4.0

func (c OfficialReasoningCapability) AllowsOff() bool

AllowsOff reports whether the official API accepts a disable value.

func (OfficialReasoningCapability) Encode added in v0.4.0

Encode maps a user-selected official value onto the provider request. Empty effort is Auto: omit the field so the provider default applies. Values the model does not advertise are omitted rather than remapped.

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
	// SessionID is an optional stable conversation id (e.g. Antares session).
	// Gemini adapters use it for gateway sticky routing / implicit cache
	// affinity on reverse proxies that fingerprint Gemini CLI sessions.
	SessionID 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 // provider-native value; empty means Auto
	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"`
	// ThoughtSignature is Gemini part-level metadata for the final text turn.
	// Agent history must copy this onto the assistant Message for multi-turn
	// continuity when the model is not making tool calls.
	ThoughtSignature string `json:"thought_signature,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
	// ThoughtSignature is Gemini's encrypted reasoning state that must be
	// echoed back on the same functionCall part in the next request.
	// Without it, multi-turn tool use returns HTTP 400 ("Function call is
	// missing a thought_signature"). Official SDKs and Gemini CLI preserve
	// this; when absent, clients inject "skip_thought_signature_validator".
	// See https://ai.google.dev/gemini-api/docs/thinking#signatures
	ThoughtSignature string `json:"thought_signature,omitempty"`
}

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

func (u Usage) ContextSize() int

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.

Jump to

Keyboard shortcuts

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