Documentation
¶
Index ¶
- Variables
- type AssistantMsg
- type Message
- type Messages
- type Model
- type ModelFetcher
- type Option
- type Options
- type ParsedToolCall
- type Provider
- type ReasoningEffort
- type RegisterFunc
- type Registry
- func (r *Registry) AllModels() []Model
- func (r *Registry) CreateStream(ctx context.Context, opts StreamOptions) (<-chan StreamEvent, error)
- func (r *Registry) FetchModels(ctx context.Context, name string) ([]Model, error)
- func (r *Registry) Provider(name string) (Provider, error)
- func (r *Registry) Register(p Provider)
- func (r *Registry) RegisterAll(fns ...RegisterFunc)
- func (r *Registry) ResolveModel(ref string) (Provider, string, error)
- type Role
- type StreamEvent
- type StreamEventType
- type StreamOptions
- type SystemMsg
- type ToolCall
- type ToolCallResult
- type ToolChoice
- type ToolChoiceAuto
- type ToolChoiceNone
- type ToolChoiceRequired
- type ToolChoiceTool
- type ToolDefinition
- type ToolSet
- type ToolSpec
- type TypedToolCall
- type Usage
- type UserMsg
Constants ¶
This section is empty.
Variables ¶
var ( ErrNotFound = errors.New("not found") ErrBadRequest = errors.New("bad request") )
Common errors
Functions ¶
This section is empty.
Types ¶
type AssistantMsg ¶ added in v0.5.0
AssistantMsg contains an assistant response, optionally with tool calls.
func (*AssistantMsg) MarshalJSON ¶ added in v0.5.0
func (m *AssistantMsg) MarshalJSON() ([]byte, error)
func (*AssistantMsg) Role ¶ added in v0.5.0
func (m *AssistantMsg) Role() Role
func (*AssistantMsg) Validate ¶ added in v0.5.0
func (m *AssistantMsg) Validate() error
type Message ¶
type Message interface {
Role() Role
Validate() error
json.Marshaler
// contains filtered or unexported methods
}
Message is the interface all message types implement.
type Messages ¶ added in v0.5.0
type Messages []Message
Messages is a slice of Message with JSON unmarshal support.
func (*Messages) UnmarshalJSON ¶ added in v0.5.0
type Model ¶
type Model struct {
ID string `json:"id"`
Name string `json:"name"`
Provider string `json:"provider"`
}
Model represents an LLM model.
type ModelFetcher ¶
ModelFetcher is an optional interface providers can implement to list models dynamically from their API instead of returning a static list.
type Option ¶ added in v0.12.0
type Option func(*Options)
Option configures provider options.
func APIKeyFromEnv ¶ added in v0.12.0
APIKeyFromEnv returns an Option that reads the API key from environment variables. It tries each candidate in order, returning the first non-empty value. Returns an error at call time if none of the candidates are set.
func WithAPIKey ¶ added in v0.12.0
WithAPIKey sets a static API key.
func WithAPIKeyFunc ¶ added in v0.12.0
WithAPIKeyFunc sets a dynamic API key resolver. The function is called on each CreateStream() call, enabling:
- Lazy key resolution (fetch from secret manager on first use)
- Key rotation (fetch fresh key each time)
- Context-aware resolution (respect timeouts/cancellation)
func WithBaseURL ¶ added in v0.12.0
WithBaseURL sets a custom base URL for the provider.
type Options ¶ added in v0.12.0
type Options struct {
// BaseURL is the base URL for the provider's API.
BaseURL string
// APIKeyFunc returns the API key for authentication.
// It is called on each CreateStream() call, allowing for lazy/dynamic resolution.
APIKeyFunc func(ctx context.Context) (string, error)
}
Options holds configuration shared across providers.
type ParsedToolCall ¶
ParsedToolCall is the interface for parsed tool call results. Use a type switch on the concrete *TypedToolCall[T] to access typed params.
Example:
switch c := call.(type) {
case *TypedToolCall[GetWeatherParams]:
fmt.Println(c.Params.Location) // strongly typed
case *TypedToolCall[SearchParams]:
fmt.Println(c.Params.Query)
}
type Provider ¶
type Provider interface {
Name() string
Models() []Model
CreateStream(ctx context.Context, opts StreamOptions) (<-chan StreamEvent, error)
}
Provider is the interface each LLM backend must implement.
type ReasoningEffort ¶ added in v0.7.0
type ReasoningEffort string
ReasoningEffort controls the amount of reasoning for reasoning models. Lower values result in faster responses with fewer reasoning tokens.
const ( // ReasoningEffortNone disables reasoning (GPT-5.1+ only). ReasoningEffortNone ReasoningEffort = "none" // ReasoningEffortMinimal uses minimal reasoning effort. ReasoningEffortMinimal ReasoningEffort = "minimal" // ReasoningEffortLow uses low reasoning effort. ReasoningEffortLow ReasoningEffort = "low" // ReasoningEffortMedium uses medium reasoning effort (default for most models before GPT-5.1). ReasoningEffortMedium ReasoningEffort = "medium" // ReasoningEffortHigh uses high reasoning effort. ReasoningEffortHigh ReasoningEffort = "high" // ReasoningEffortXHigh uses extra high reasoning effort (codex-max+ only). ReasoningEffortXHigh ReasoningEffort = "xhigh" )
func (ReasoningEffort) Valid ¶ added in v0.8.0
func (r ReasoningEffort) Valid() bool
Valid returns true if the ReasoningEffort is a known valid value or empty.
type RegisterFunc ¶ added in v0.13.0
type RegisterFunc func(*Registry)
RegisterFunc is a function that conditionally registers a provider with a registry. Each provider package exports a MaybeRegister function of this type.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry holds all registered providers and resolves model references.
func (*Registry) CreateStream ¶
func (r *Registry) CreateStream(ctx context.Context, opts StreamOptions) (<-chan StreamEvent, error)
CreateStream is a convenience that resolves a model ref and delegates to the provider.
func (*Registry) FetchModels ¶
FetchModels returns models for a specific provider. If the provider implements ModelFetcher, it fetches models dynamically from the API. Otherwise it falls back to the static Models() list.
func (*Registry) RegisterAll ¶ added in v0.13.0
func (r *Registry) RegisterAll(fns ...RegisterFunc)
RegisterAll calls all provided registration functions.
type StreamEvent ¶
type StreamEvent struct {
Type StreamEventType
Delta string
Reasoning string
ToolCall *ToolCall
Error error
Usage *Usage
}
StreamEvent is a single event emitted by a provider during streaming.
type StreamEventType ¶
type StreamEventType string
StreamEventType identifies the kind of streaming event from a provider.
const ( StreamEventDelta StreamEventType = "delta" StreamEventReasoning StreamEventType = "reasoning" StreamEventToolCall StreamEventType = "tool_call" StreamEventDone StreamEventType = "done" StreamEventError StreamEventType = "error" )
type StreamOptions ¶
type StreamOptions struct {
Model string
Messages Messages
Tools []ToolDefinition
ToolChoice ToolChoice // nil defaults to Auto when Tools provided
ReasoningEffort ReasoningEffort // Controls reasoning for reasoning models (OpenAI)
}
StreamOptions configures a provider CreateStream call.
func (StreamOptions) Validate ¶ added in v0.6.0
func (o StreamOptions) Validate() error
Validate checks that the options are valid.
type SystemMsg ¶ added in v0.5.0
type SystemMsg struct {
Content string
}
SystemMsg contains a system prompt.
func (*SystemMsg) MarshalJSON ¶ added in v0.5.0
type ToolCall ¶
ToolCall represents a request from the LLM to invoke a tool.
func (ToolCall) MarshalJSON ¶ added in v0.5.0
func (*ToolCall) UnmarshalJSON ¶ added in v0.5.0
type ToolCallResult ¶
ToolCallResult contains the result of executing a tool call.
func (*ToolCallResult) MarshalJSON ¶ added in v0.5.0
func (m *ToolCallResult) MarshalJSON() ([]byte, error)
func (*ToolCallResult) Role ¶ added in v0.5.0
func (m *ToolCallResult) Role() Role
func (*ToolCallResult) Validate ¶ added in v0.5.0
func (m *ToolCallResult) Validate() error
type ToolChoice ¶ added in v0.6.0
type ToolChoice interface {
// contains filtered or unexported methods
}
ToolChoice controls whether and which tools the model should call.
type ToolChoiceAuto ¶ added in v0.6.0
type ToolChoiceAuto struct{}
ToolChoiceAuto lets the model decide whether to call tools. This is the default behavior when ToolChoice is nil.
type ToolChoiceNone ¶ added in v0.6.0
type ToolChoiceNone struct{}
ToolChoiceNone prevents the model from calling any tools.
type ToolChoiceRequired ¶ added in v0.6.0
type ToolChoiceRequired struct{}
ToolChoiceRequired forces the model to call at least one tool.
type ToolChoiceTool ¶ added in v0.6.0
type ToolChoiceTool struct {
Name string
}
ToolChoiceTool forces the model to call a specific tool by name.
type ToolDefinition ¶
type ToolDefinition struct {
Name string `json:"name"`
Description string `json:"description"`
Parameters map[string]any `json:"parameters"`
}
ToolDefinition describes a tool that the model can invoke. This is used when sending tools to a provider's API.
func ToolDefinitionFor ¶
func ToolDefinitionFor[T any](name, description string) ToolDefinition
ToolDefinitionFor creates a ToolDefinition from a Go struct type using reflection. The struct's fields are converted to a JSON Schema that describes the tool's parameters.
Field tags:
- `json:"fieldName"` - Sets the parameter name (required)
- `jsonschema:"description=..."` - Describes the parameter
- `jsonschema:"required"` - Marks the parameter as required
- `jsonschema:"enum=val1,enum=val2"` - Restricts to specific values
Example:
type GetWeatherParams struct {
Location string `json:"location" jsonschema:"description=City name,required"`
Unit string `json:"unit" jsonschema:"description=Temperature unit,enum=celsius,enum=fahrenheit"`
}
tool := ToolDefinitionFor[GetWeatherParams]("get_weather", "Get current weather")
func (ToolDefinition) Validate ¶ added in v0.8.0
func (t ToolDefinition) Validate() error
Validate checks that the tool definition is valid.
type ToolSet ¶
type ToolSet struct {
// contains filtered or unexported fields
}
ToolSet manages a collection of tool specifications. It provides tool definitions for sending to providers and parses raw tool calls into strongly-typed results with validation.
func NewToolSet ¶
func NewToolSet(tools ...toolRegistration) *ToolSet
NewToolSet creates a ToolSet from one or more tool specs.
Example:
tools := NewToolSet(
NewToolSpec[GetWeatherParams]("get_weather", "Get weather"),
NewToolSpec[SearchParams]("search", "Search the web"),
)
func (*ToolSet) Definitions ¶
func (ts *ToolSet) Definitions() []ToolDefinition
Definitions returns all tool definitions for sending to providers.
func (*ToolSet) Parse ¶
func (ts *ToolSet) Parse(calls []ToolCall) ([]ParsedToolCall, error)
Parse converts raw ToolCalls (from stream events) into typed ParsedToolCalls. Each tool call's arguments are validated against its JSON Schema before parsing.
Successfully parsed calls are always returned. Errors from unknown tool names or validation/parse failures are collected and returned as a joined error. The error is non-fatal - you get all successfully parsed calls.
Example:
calls, err := tools.Parse(rawToolCalls)
if err != nil {
log.Printf("parse warnings: %v", err)
}
for _, call := range calls {
switch c := call.(type) {
case *TypedToolCall[GetWeatherParams]:
fmt.Println(c.Params.Location)
}
}
type ToolSpec ¶
type ToolSpec[T any] struct { // contains filtered or unexported fields }
ToolSpec[T] is a type-safe tool specification that pairs a tool name/description with a Go struct that defines the parameter schema. It includes a compiled JSON Schema for runtime validation.
func NewToolSpec ¶
NewToolSpec creates a typed tool specification from a parameter struct. The struct's fields define the JSON Schema for the tool's parameters. Field tags are the same as ToolDefinitionFor: json, jsonschema.
Example:
type GetWeatherParams struct {
Location string `json:"location" jsonschema:"description=City name,required"`
}
spec := NewToolSpec[GetWeatherParams]("get_weather", "Get current weather")
func (*ToolSpec[T]) Definition ¶
func (s *ToolSpec[T]) Definition() ToolDefinition
Definition returns the ToolDefinition for sending to providers.
type TypedToolCall ¶
type TypedToolCall[T any] struct { ID string // Original tool call ID (for sending results back) Name string // Tool name Params T // Parsed, validated parameters }
TypedToolCall[T] holds a parsed tool call with strongly-typed parameters.
func (*TypedToolCall[T]) ToolCallID ¶
func (c *TypedToolCall[T]) ToolCallID() string
ToolCallID returns the tool call ID.
func (*TypedToolCall[T]) ToolName ¶
func (c *TypedToolCall[T]) ToolName() string
ToolName returns the tool name.
type Usage ¶
type Usage struct {
InputTokens int
OutputTokens int
TotalTokens int
Cost float64
// Detailed breakdown (provider-specific, may be zero)
CachedTokens int // Prompt tokens served from cache
ReasoningTokens int // Tokens used for model reasoning
}
Usage holds token counts and cost from a provider response.
type UserMsg ¶ added in v0.5.0
type UserMsg struct {
Content string
}
UserMsg contains user input.