Documentation
¶
Index ¶
- Variables
- func Schema(name string, schema map[string]any) map[string]any
- type APIError
- type Agent
- func (a *Agent) History() []Message
- func (a *Agent) Reset()
- func (a *Agent) Run(ctx context.Context, input string, opts ...RunOption) (*Response, error)
- func (a *Agent) RunJSON(ctx context.Context, input string, schema map[string]any, v any, ...) (*Response, error)
- func (a *Agent) RunStream(ctx context.Context, input string, onEvent func(Event) error, ...) (*Response, error)
- type AgentOption
- func WithHistory(msgs ...Message) AgentOption
- func WithMaxContextTokens(n int) AgentOption
- func WithMaxToolOutput(n int) AgentOption
- func WithMaxTurns(n int) AgentOption
- func WithOnTurn(fn func(*Response) error) AgentOption
- func WithOnUsage(fn func(Usage) error) AgentOption
- func WithSystem(prompt string) AgentOption
- func WithTools(tools ...Tool) AgentOption
- type ChatClient
- type Client
- func (c *Client) Chat(ctx context.Context, req *Request) (*Response, error)
- func (c *Client) ChatStream(ctx context.Context, req *Request, onEvent func(Event) error) (*Response, error)
- func (c *Client) Embed(ctx context.Context, req *EmbeddingRequest) (*EmbeddingResponse, error)
- func (c *Client) ListModels(ctx context.Context) ([]ModelInfo, error)
- type ContentPart
- type Embedding
- type EmbeddingRequest
- type EmbeddingResponse
- type Event
- type EventType
- type Message
- type ModelInfo
- type ModelPricing
- type Option
- type Request
- type Response
- type RetryPolicy
- type Role
- type RunOption
- type Tool
- type ToolCall
- type Usage
Constants ¶
This section is empty.
Variables ¶
var ErrMaxTurns = errors.New("agent: exceeded max turns without a final answer")
ErrMaxTurns is returned when an agent exceeds MaxTurns without producing a final answer. Use errors.Is to detect it.
Functions ¶
Types ¶
type APIError ¶ added in v1.3.0
type APIError struct {
StatusCode int // HTTP status code
Code string // provider error code, when present
Message string // human-readable message
Body string // raw response body, for debugging
RetryAfter time.Duration // server-suggested wait, when provided
}
APIError is returned when OpenRouter responds with a non-2xx status.
func IsAPIError ¶ added in v1.3.0
IsAPIError reports whether err is an *APIError and returns it.
type Agent ¶ added in v1.3.0
type Agent struct {
// MaxTurns caps model calls per Run to prevent infinite tool loops.
// Defaults to 10.
MaxTurns int
// MaxToolOutput truncates each tool result to this many bytes before it is
// fed back to the model. 0 disables truncation.
MaxToolOutput int
// MaxContextTokens, when > 0, trims the oldest history before each model
// call so the estimated prompt stays within the limit.
MaxContextTokens int
// OnEvent, when set, receives streaming events during RunStream.
OnEvent func(Event) error
// OnUsage, when set, is called after every model call with that call's
// usage. Returning an error aborts the run.
OnUsage func(Usage) error
// OnTurn, when set, is called after every model call with the full
// response. Returning an error aborts the run.
OnTurn func(*Response) error
// contains filtered or unexported fields
}
Agent runs a multi-turn conversation, executing tools and feeding their results back to the model until it produces a final answer.
An Agent is safe for concurrent use, but a single Run holds the agent's lock for its duration. Callbacks (OnEvent, OnUsage, OnTurn) must not call back into the same Agent, or they will deadlock.
func NewAgent ¶ added in v1.3.0
func NewAgent(client ChatClient, model string, opts ...AgentOption) *Agent
NewAgent creates an Agent bound to a client and model. The client may be a *Client or any ChatClient implementation (for example, a cost-ledger wrapper).
func (*Agent) Reset ¶ added in v1.3.0
func (a *Agent) Reset()
Reset clears the conversation history.
func (*Agent) Run ¶ added in v1.3.0
Run sends a user message and drives the tool loop to completion, returning the model's final response. The full exchange is appended to history.
func (*Agent) RunJSON ¶ added in v1.4.0
func (a *Agent) RunJSON(ctx context.Context, input string, schema map[string]any, v any, opts ...RunOption) (*Response, error)
RunJSON runs the agent and unmarshals the final message into v. It asks the model for JSON conforming to schema and, if the reply is not valid JSON, retries with a corrective message. The schema is applied per call, so it never leaks into the agent's state or other runs.
Retries default to 1; override with WithMaxAttempts. Other RunOptions are passed through to each attempt.
type AgentOption ¶ added in v1.3.0
type AgentOption func(*Agent)
AgentOption configures an Agent.
func WithHistory ¶ added in v1.3.0
func WithHistory(msgs ...Message) AgentOption
WithHistory seeds the conversation with prior messages.
func WithMaxContextTokens ¶ added in v1.4.0
func WithMaxContextTokens(n int) AgentOption
WithMaxContextTokens trims history to stay within an estimated token budget.
func WithMaxToolOutput ¶ added in v1.4.0
func WithMaxToolOutput(n int) AgentOption
WithMaxToolOutput truncates each tool result to n bytes (0 disables).
func WithMaxTurns ¶ added in v1.3.0
func WithMaxTurns(n int) AgentOption
WithMaxTurns caps the number of model calls per Run.
func WithOnTurn ¶ added in v1.4.0
func WithOnTurn(fn func(*Response) error) AgentOption
WithOnTurn registers a callback invoked after every model call.
func WithOnUsage ¶ added in v1.4.0
func WithOnUsage(fn func(Usage) error) AgentOption
WithOnUsage registers a callback invoked after every model call.
func WithSystem ¶ added in v1.3.0
func WithSystem(prompt string) AgentOption
WithSystem sets the system prompt.
func WithTools ¶ added in v1.3.0
func WithTools(tools ...Tool) AgentOption
WithTools registers tools the agent may call.
type ChatClient ¶ added in v1.4.0
type ChatClient interface {
Chat(ctx context.Context, req *Request) (*Response, error)
ChatStream(ctx context.Context, req *Request, onEvent func(Event) error) (*Response, error)
}
ChatClient is the subset of Client used by Agent. Implementations may wrap a *Client to observe or account for calls (for example, a cost ledger).
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client talks to the OpenRouter API.
func (*Client) ChatStream ¶ added in v1.3.0
func (c *Client) ChatStream(ctx context.Context, req *Request, onEvent func(Event) error) (*Response, error)
ChatStream performs a streaming completion. onEvent is called for each text chunk and completed tool call; the final Response is returned and also delivered as an EventDone.
func (*Client) Embed ¶ added in v1.4.0
func (c *Client) Embed(ctx context.Context, req *EmbeddingRequest) (*EmbeddingResponse, error)
Embed returns embeddings for the given inputs. It uses the same client, base URL, and retry policy as chat calls.
type ContentPart ¶ added in v1.4.0
type ContentPart struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
ImageURL string `json:"image_url,omitempty"`
}
ContentPart is one part of a multimodal message. Type is "text" or "image_url". For "text", Text is set; for "image_url", ImageURL is set.
func ImagePart ¶ added in v1.4.0
func ImagePart(url string) ContentPart
ImagePart returns an image content part for the given URL (http(s) or data URI).
func TextPart ¶ added in v1.4.0
func TextPart(text string) ContentPart
TextPart returns a text content part.
type EmbeddingRequest ¶ added in v1.4.0
EmbeddingRequest describes an embeddings call.
type EmbeddingResponse ¶ added in v1.4.0
EmbeddingResponse is the result of an embeddings call.
type Event ¶ added in v1.3.0
type Event struct {
Type EventType
Text string // set for EventText
ToolCall ToolCall // set for EventToolCall
Result string // set for EventToolResult
Usage Usage // set for EventUsage
Response *Response // set for EventDone
}
Event is emitted during streaming.
type EventType ¶ added in v1.3.0
type EventType string
EventType classifies a streaming event.
const ( EventText EventType = "text" // a chunk of assistant text EventToolCall EventType = "tool_call" // a completed tool call EventToolResult EventType = "tool_result" // a tool's output EventUsage EventType = "usage" // token usage for the call EventDone EventType = "done" // stream finished; Response is set )
type Message ¶ added in v1.3.0
type Message struct {
Role Role `json:"role"`
Content string `json:"content,omitempty"`
// Parts, when set, carries multimodal content and takes precedence over
// Content when the message is sent to the model.
Parts []ContentPart `json:"parts,omitempty"`
// ToolCalls is set on assistant messages that request tool execution.
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
// ToolCallID links a RoleTool message back to the call it answers.
ToolCallID string `json:"tool_call_id,omitempty"`
// Name optionally identifies the tool or participant.
Name string `json:"name,omitempty"`
}
Message is a single entry in a conversation. It is a value type so that slices of messages are cheap to copy and never nil.
Message is JSON-serializable so conversations can be persisted and restored (for example, to replay an agent run). Seed an agent with WithHistory.
func ToolResult ¶ added in v1.3.0
ToolResult returns a tool message carrying the output of a tool call.
func UserParts ¶ added in v1.4.0
func UserParts(parts ...ContentPart) Message
UserParts returns a user message built from multimodal parts.
type ModelInfo ¶ added in v1.4.0
type ModelInfo struct {
ID string
Name string
ContextLength int
Pricing ModelPricing
}
ModelInfo describes a model available from the provider.
type ModelPricing ¶ added in v1.4.0
ModelPricing is the per-token price in USD, as reported by the provider.
type Option ¶ added in v1.0.0
type Option func(*Client)
Option configures a Client.
func WithBaseURL ¶ added in v1.0.0
WithBaseURL overrides the API base URL.
func WithDefaultModel ¶ added in v1.3.0
WithDefaultModel sets the model used when a Request leaves Model empty.
func WithHTTPClient ¶ added in v1.0.0
WithHTTPClient sets a custom HTTP client.
func WithRetry ¶ added in v1.2.4
func WithRetry(p RetryPolicy) Option
WithRetry sets the retry policy.
type Request ¶ added in v1.3.0
type Request struct {
Model string
Messages []Message
Tools []Tool
// ToolChoice controls tool use: "auto", "none", "required", or a specific
// function. Nil lets the provider decide.
ToolChoice any
// Pointer fields distinguish "unset" from a meaningful zero value, so
// Temperature: ptr(0) is a valid request.
Temperature *float64
TopP *float64
MaxTokens int
Stop []string
// JSONMode asks the model to return a JSON object.
JSONMode bool
// ResponseSchema, when set, asks the model to return JSON conforming to the
// given JSON Schema (an object with "name", "strict", and "schema" keys).
// It implies JSONMode.
ResponseSchema map[string]any
// Retry overrides the client's retry policy for this request.
Retry *RetryPolicy
}
Request describes a single chat completion.
type RetryPolicy ¶ added in v1.3.0
type RetryPolicy struct {
MaxAttempts int // total attempts, including the first
BaseDelay time.Duration // delay before the second attempt
MaxDelay time.Duration // upper bound on any single delay
}
RetryPolicy controls how failed requests are retried.
func DefaultRetryPolicy ¶ added in v1.3.0
func DefaultRetryPolicy() RetryPolicy
DefaultRetryPolicy retries transient failures with exponential backoff.
type RunOption ¶ added in v1.4.0
type RunOption func(*runConfig)
RunOption configures a single Run.
func WithJSONMode ¶ added in v1.4.0
func WithJSONMode() RunOption
WithJSONMode asks this run for a JSON object without a schema.
func WithMaxAttempts ¶ added in v1.4.0
WithMaxAttempts sets how many times RunJSON retries invalid JSON.
func WithSchema ¶ added in v1.4.0
WithSchema constrains this run's output to a JSON schema (see Schema).
type Tool ¶ added in v1.3.0
type Tool struct {
Name string
Description string
Parameters any
// Timeout, when > 0, bounds how long the handler may run.
Timeout time.Duration
// Handler runs the tool. The returned string is fed back to the model.
// Returning an error feeds the error text back so the model can recover.
Handler func(ctx context.Context, args json.RawMessage) (string, error)
}
Tool is a function the model may call. Parameters is a JSON Schema object (typically a map[string]any) describing the arguments.
type ToolCall ¶ added in v1.3.0
type ToolCall struct {
ID string `json:"id"`
Name string `json:"name"`
Arguments string `json:"arguments"` // raw JSON arguments
}
ToolCall is a model's request to run a tool.