llm

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 30, 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 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 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 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"`
	// 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"`
}

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"`
	Cost             float64 `json:"cost"`
}

Usage reports token accounting for one call.

Jump to

Keyboard shortcuts

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