Documentation
¶
Overview ¶
Package llmapi defines the Service interface for AI model providers and the request/response types exchanged with them.
Index ¶
- Constants
- Variables
- type ContentPart
- type ContentPartType
- type DialogueUsage
- type DoneData
- type ErrContextWindowExceeded
- type Event
- type EventType
- type FinishReason
- type FunctionCall
- type FunctionDefinition
- type Message
- type ModelEntry
- type RateLimitInfo
- type ReasoningBlock
- type ReasoningEffort
- type ReasoningSummary
- type Request
- type ResponseFormat
- type ResponseFormatJSONSchema
- type ResponseFormatType
- type Role
- type Service
- type Tool
- type ToolCall
- type ToolChoice
- type ToolType
- type Usage
Constants ¶
const DefaultModel = "default"
DefaultModel is the reserved alias name that resolves to the router's configured default model, or — when unset — the latest authenticated provider's flagship model.
Variables ¶
var ErrModelNotFound = errors.New("llm: model not found")
ErrModelNotFound is returned by Service.GetModel when the requested model is not known to the service. Callers can detect it with errors.Is.
Functions ¶
This section is empty.
Types ¶
type ContentPart ¶
type ContentPart struct {
Type ContentPartType `json:"Type"`
Text string `json:"Text,omitempty"`
ImageURL string `json:"ImageURL,omitempty"`
}
ContentPart represents textual or image content in a Message.
func NewContentPartFromImage ¶
func NewContentPartFromImage(img image.Image) (ContentPart, error)
NewContentPartFromImage converts an image.Image into a ContentPart.
func NewContentPartFromImageURL ¶
func NewContentPartFromImageURL(url string) ContentPart
NewContentPartFromImageURL returns a ContentPart from an image URL.
type ContentPartType ¶
type ContentPartType uint8
ContentPartType identifies the type of a ContentPart.
const ( // ContentPartTypeText identifies a text content part. ContentPartTypeText ContentPartType = iota // ContentPartTypeImageURL identifies an image URL content part. ContentPartTypeImageURL )
type DialogueUsage ¶
type DialogueUsage struct {
TokensSent int `json:"InputTokens"`
TokensReceived int `json:"OutputTokens"`
TokensReasoned int `json:"ReasoningTokens"`
TokensCached int `json:"CachedTokens"`
TokensCacheCreated int `json:"CacheCreatedTokens"`
Completions int `json:"Completions"`
ToolCalls int `json:"ToolCalls"`
TotalDuration time.Duration `json:"TotalDuration"`
InferenceDuration time.Duration `json:"InferenceDuration"`
ToolCallDuration time.Duration `json:"ToolCallDuration"`
}
DialogueUsage accumulates usage statistics across an entire dialogue session.
type DoneData ¶
type DoneData struct {
Message Message
FinishReason FinishReason
Usage Usage
}
DoneData holds the final message and usage when a stream completes.
type ErrContextWindowExceeded ¶
type ErrContextWindowExceeded struct {
Count, Max int
}
ErrContextWindowExceeded is returned when the number of tokens in a request exceeds the context window of a model. Users are encouraged to retry with a reduced number of messages.
func (*ErrContextWindowExceeded) Error ¶
func (e *ErrContextWindowExceeded) Error() string
Error satisfies the error interface.
func (*ErrContextWindowExceeded) Is ¶
func (e *ErrContextWindowExceeded) Is(target error) bool
Is satisfies the error interface.
func (*ErrContextWindowExceeded) Unwrap ¶
func (e *ErrContextWindowExceeded) Unwrap() error
Unwrap satisfies the error interface.
type Event ¶
type Event struct {
Type EventType
Text string // EventTextDelta
Reasoning string // EventReasoningDelta
ToolCall *ToolCall // EventToolCallDone — complete tool call
DoneData *DoneData // EventStreamDone
Error error // EventStreamError
RateLimit *RateLimitInfo // EventRateLimitWarning
}
Event is a typed streaming event from an LLM provider.
type EventType ¶
type EventType int
EventType identifies the kind of streaming event.
const ( // EventTextDelta is a text content delta. EventTextDelta EventType = iota // EventReasoningDelta is a reasoning content delta. EventReasoningDelta // EventToolCallDone signals a single tool call is complete. EventToolCallDone // EventStreamDone signals the response is complete. EventStreamDone // EventStreamError signals a stream error. EventStreamError // EventStreamReset signals the consumer should discard accumulated state // because a mid-stream retry is in progress. EventStreamReset // EventRateLimitWarning signals a rate limit warning from the provider. // The client composes the message; downstream layers display it as-is. EventRateLimitWarning )
type FinishReason ¶
type FinishReason string
FinishReason is the reason why the message choice was returned.
const ( // FinishReasonStop API returned complete message, // or a message terminated by one of the stop sequences provided via the stop parameter FinishReasonStop FinishReason = "stop" // FinishReasonLength Incomplete model output due to max_tokens parameter or token limit FinishReasonLength FinishReason = "length" // FinishReasonToolCall The model decided to use one of the tools provided. FinishReasonToolCall FinishReason = "tool_calls" // FinishReasonContentFilter Omitted content due to a flag from our content filters FinishReasonContentFilter FinishReason = "content_filter" // FinishReasonNull API response still in progress or incomplete FinishReasonNull FinishReason = "null" // FinishReasonPause The provider paused a long-running turn and expects the // caller to re-send the conversation, including the partial assistant // message, so the model can resume (e.g. Anthropic's pause_turn). FinishReasonPause FinishReason = "pause" // FinishReasonRefusal The model declined to continue for safety reasons. // This is terminal; the caller should surface it distinctly rather than // treating it as a normal completion. FinishReasonRefusal FinishReason = "refusal" )
type FunctionCall ¶
FunctionCall is a function call requested by the model.
type FunctionDefinition ¶
type FunctionDefinition struct {
Name string
Description string
// Parameters is an object describing the function.
// You can pass a raw byte array describing the schema,
// or you can pass in a struct which serializes to the proper JSONSchema.
Parameters any
}
FunctionDefinition defines functions that can be "called" by the model.
type Message ¶
type Message struct {
Role Role `json:"Role"`
Content string `json:"Content"`
MultiContent []ContentPart `json:"MultiContent,omitempty"`
ToolCalls []ToolCall `json:"ToolCalls,omitempty"`
ToolCallID string `json:"ToolCallID,omitempty"`
Name string `json:"Name,omitempty"`
// ReasoningContent is the human-readable reasoning text for display and is
// lossy; ReasoningBlocks is the source of truth for replaying reasoning
// back to the model (it preserves per-block signatures and order). When a
// provider requires replay, populate ReasoningBlocks, not ReasoningContent.
ReasoningContent string `json:"ReasoningContent,omitempty"`
ReasoningBlocks []ReasoningBlock `json:"ReasoningBlocks,omitempty"`
// ProviderItems carries opaque provider-specific items that must be
// threaded back into the next request to maintain stateful continuity
// (e.g. ChatGPT Codex backend reasoning items with encrypted_content
// when store=false). Each entry is the raw JSON of a single item,
// preserved in the order it was emitted by the provider. Cross-provider
// code should treat this field as opaque.
ProviderItems []json.RawMessage `json:"ProviderItems,omitempty"`
}
Message is a message in a chat with an assistant LLM.
func (*Message) UnmarshalJSON ¶
UnmarshalJSON handles both the new format and the old persisted format where tool calls were in a Metadata field and multi-content was OtherContent.
type ModelEntry ¶
type ModelEntry struct {
// Name is the model identifier (e.g. "gpt-4o", "claude-opus-4-6").
Name string
// Provider identifies which LLM provider serves this model
// (e.g. "openai", "anthropic", "gemini", "ollama").
Provider string
// ContextWindow is the nominal maximum context window in tokens.
ContextWindow int
// BaseURL is the provider-specific API base URL.
// Empty string means use the provider's default.
BaseURL string
// ProjectorPath is the absolute path to an optional multimodal projector
// GGUF (mmproj) associated with a local llama.cpp model. Empty for
// providers that do not use a separate projector file.
ProjectorPath string
}
ModelEntry describes a model available through a Service.
type RateLimitInfo ¶
type RateLimitInfo struct {
// WaitDuration is non-zero when the client is actively waiting before a retry.
WaitDuration time.Duration
// Message is a human-readable warning composed by the client.
Message string
}
RateLimitInfo carries a provider-composed rate limit warning.
type ReasoningBlock ¶ added in v0.0.87
type ReasoningBlock struct {
Kind string `json:"Kind"`
Text string `json:"Text,omitempty"`
Signature string `json:"Signature,omitempty"`
Data string `json:"Data,omitempty"`
}
ReasoningBlock is a reasoning block preserved for replaying back to the model.
type ReasoningEffort ¶
type ReasoningEffort string
ReasoningEffort controls the amount of reasoning effort for reasoning models.
const ( // ReasoningEffortNone disables explicit reasoning effort. ReasoningEffortNone ReasoningEffort = "none" // ReasoningEffortMinimal requests minimal reasoning effort. ReasoningEffortMinimal ReasoningEffort = "minimal" // ReasoningEffortLow requests low reasoning effort. ReasoningEffortLow ReasoningEffort = "low" // ReasoningEffortMedium requests medium reasoning effort. ReasoningEffortMedium ReasoningEffort = "medium" // ReasoningEffortHigh requests high reasoning effort. ReasoningEffortHigh ReasoningEffort = "high" // ReasoningEffortXHigh requests extra-high reasoning effort. ReasoningEffortXHigh ReasoningEffort = "xhigh" // ReasoningEffortMax requests the maximum supported reasoning effort. ReasoningEffortMax ReasoningEffort = "max" // ReasoningEffortUltra requests an ultra reasoning effort above max, // supported only by select frontier models (e.g. gpt-5.6-sol). ReasoningEffortUltra ReasoningEffort = "ultra" )
type ReasoningSummary ¶
type ReasoningSummary string
ReasoningSummary controls the level of reasoning summary output.
const ( // ReasoningSummaryAuto lets the provider choose the summary level. ReasoningSummaryAuto ReasoningSummary = "auto" // ReasoningSummaryConcise requests a concise reasoning summary. ReasoningSummaryConcise ReasoningSummary = "concise" // ReasoningSummaryDetailed requests a detailed reasoning summary. ReasoningSummaryDetailed ReasoningSummary = "detailed" // ReasoningSummaryDisabled disables reasoning summaries. ReasoningSummaryDisabled ReasoningSummary = "disabled" )
type Request ¶
type Request struct {
Messages []Message
Tools []Tool
ToolChoice ToolChoice
ParallelToolCalls *bool
ReasoningEffort ReasoningEffort
ReasoningSummary ReasoningSummary
MaxOutputTokens int
ResponseFormat *ResponseFormat
// PromptCacheKey is a stable identifier (typically the dialogue ID)
// that the provider uses for server-side prompt caching. Requests
// sharing the same key get a ~90% discount on repeated input-token
// prefixes. Works without storing responses server-side, preserving
// Zero Data Retention compatibility.
PromptCacheKey string
// TokenCount, when set, is used for the context-window safety check
// instead of calling CountTokens. The agent loop pre-computes this
// from the provider-reported usage (or CountTokens + tool estimate on
// the first turn), so passing it here avoids a redundant re-count on
// every CreateCompletion call.
TokenCount int
}
Request is the request type for chat completions.
type ResponseFormat ¶
type ResponseFormat struct {
Type ResponseFormatType `json:"type,omitempty"`
JSONSchema *ResponseFormatJSONSchema `json:"json_schema,omitempty"`
}
ResponseFormat specifies per-request structured output.
type ResponseFormatJSONSchema ¶
type ResponseFormatJSONSchema struct {
Name string
Description string
Schema json.Marshaler
Strict bool
}
ResponseFormatJSONSchema is the JSON schema configuration.
type ResponseFormatType ¶
type ResponseFormatType string
ResponseFormatType identifies the response format type.
const ( // ResponseFormatTypeText requests plain text output. ResponseFormatTypeText ResponseFormatType = "text" // ResponseFormatTypeJSONObject requests JSON object output. ResponseFormatTypeJSONObject ResponseFormatType = "json_object" // ResponseFormatTypeJSONSchema requests JSON schema-constrained output. ResponseFormatTypeJSONSchema ResponseFormatType = "json_schema" )
type Service ¶
type Service interface {
// CreateCompletion attempts to complete the given request using
// the given model. Returns a stream of typed events.
// This method should return ErrContextWindowExceeded if a request
// exceeds the context window of the selected model.
CreateCompletion(
ctx context.Context,
model ModelEntry,
request Request,
) (iterator.Iterator[Event], error)
// CountTokens returns the approximate token count for the given
// messages under the given model's tokenizer.
CountTokens(model ModelEntry, messages []Message) (int, error)
// Models returns an iterator over all available model entries.
Models() iterator.Iterator[ModelEntry]
// GetModel returns the canonical entry for the given model. Callers
// typically pass a ModelEntry with only Name set; the returned
// entry carries the full provider metadata. GetModel returns
// ErrModelNotFound if the model is not known to the service.
GetModel(ctx context.Context, model ModelEntry) (ModelEntry, error)
}
Service encapsulates communications with an AI-capabilities provider. All methods take the model name explicitly so a single Service can route requests to different providers per call.
type Tool ¶
type Tool struct {
Type ToolType
Function FunctionDefinition
}
Tool is a resource that the model may use (like functions, files, etc.).
type ToolCall ¶
type ToolCall struct {
ID string
Type ToolType
Function FunctionCall
// ProviderFields carries opaque provider-specific data attached to this
// individual tool call that must be threaded back into the next request
// to maintain stateful continuity (e.g. Gemini 3+ requires the
// per-call thought_signature to be echoed on the functionCall part).
// Each value is the raw JSON of a single field. Cross-provider code
// should treat this map as opaque and leave unknown keys untouched.
ProviderFields map[string]json.RawMessage `json:"ProviderFields,omitempty"`
}
ToolCall is the result of a model call to a tool.
type ToolChoice ¶
type ToolChoice string
ToolChoice controls whether and how the model should use tools when tools are present on a request.
const ( // ToolChoiceAuto lets the provider/model decide whether to call a tool. ToolChoiceAuto ToolChoice = "auto" // ToolChoiceRequired requires the model to emit at least one tool call. ToolChoiceRequired ToolChoice = "required" // ToolChoiceNone forbids tool use even if tools are declared. ToolChoiceNone ToolChoice = "none" )