aiutil

package module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2026 License: MIT Imports: 16 Imported by: 3 modules, 2 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.

README

ai-util

Chat, stream, and run tool-calling agents. No dependencies beyond the standard library.

Install

go get github.com/ztkent/ai-util

Set OPENROUTER_API_KEY. Any OpenRouter model works.

Chat

client := aiutil.New("")

resp, err := client.Chat(ctx, &aiutil.Request{
    Model:     "poolside/laguna-s-2.1:free",
    Messages:  []aiutil.Message{aiutil.User("Explain goroutines in one sentence.")},
    MaxTokens: 200,
})
fmt.Println(resp.Message.Content, resp.Usage.TotalTokens)

Stream

resp, err := client.ChatStream(ctx, req, func(e aiutil.Event) error {
    if e.Type == aiutil.EventText {
        fmt.Print(e.Text)
    }
    return nil
})

ChatStream returns the same *Response as Chat, so you get the full message and usage after the stream ends.

Agent

An Agent runs the tool loop for you: it calls the model, executes any tools, feeds the results back, and repeats until the model answers.

weather := aiutil.Tool{
    Name:        "get_weather",
    Description: "Get the current weather for a city.",
    Parameters: map[string]any{
        "type": "object",
        "properties": map[string]any{
            "city": map[string]any{"type": "string"},
        },
        "required": []string{"city"},
    },
    Handler: func(ctx context.Context, args json.RawMessage) (string, error) {
        var in struct{ City string }
        json.Unmarshal(args, &in)
        return in.City + ": 21°C, sunny", nil
    },
}

agent := aiutil.NewAgent(client, "poolside/laguna-s-2.1:free",
    aiutil.WithSystem("Be concise."),
    aiutil.WithTools(weather),
)

resp, err := agent.Run(ctx, "What's the weather in Paris?")

RunStream is the same but emits Events. The conversation is kept in agent.History(); call agent.Reset() to clear it.

Observing and accounting for calls

NewAgent accepts any ChatClient, so you can wrap a *Client to observe or account for calls (for example, a cost ledger):

type ChatClient interface {
    Chat(ctx context.Context, req *Request) (*Response, error)
    ChatStream(ctx context.Context, req *Request, onEvent func(Event) error) (*Response, error)
}

Per-turn hooks let you track usage and abort mid-loop:

agent := aiutil.NewAgent(client, model,
    aiutil.WithOnUsage(func(u aiutil.Usage) error {
        ledger.Record(u)
        if ledger.OverBudget() {
            return errBudgetExceeded // aborts the run
        }
        return nil
    }),
    aiutil.WithOnTurn(func(resp *aiutil.Response) error { return nil }),
)

Usage has Add and IsZero helpers for aggregating across turns.

Context and tool-output limits
aiutil.WithMaxContextTokens(100_000) // trim oldest history before each call
aiutil.WithMaxToolOutput(8_000)      // truncate large tool results

Per-tool timeouts are set on the Tool:

aiutil.Tool{Name: "shell", Timeout: 30 * time.Second, Handler: run}
Structured output

Ask for JSON conforming to a schema, and parse it with retries:

schema := aiutil.Schema("answer", map[string]any{
    "type": "object",
    "properties": map[string]any{"n": map[string]any{"type": "integer"}},
})
var out struct{ N int }
_, err := agent.RunJSON(ctx, "give me n", schema, &out, aiutil.WithMaxAttempts(3))

The schema is applied per call, so it never leaks into the agent's state or other runs. You can also set it on a single run:

resp, err := agent.Run(ctx, "give me n", aiutil.WithSchema(schema))

WithJSONMode() asks for any JSON object; Request.ResponseSchema sets the schema directly on a raw client call.

Multimodal messages
msg := aiutil.UserParts(
    aiutil.TextPart("what is in this image?"),
    aiutil.ImagePart("https://example.com/a.png"),
)
Persisting conversations

Message and ToolCall are JSON-serializable, so history can be stored and restored (for example, to replay a run):

raw, _ := json.Marshal(agent.History())
// later
var msgs []aiutil.Message
json.Unmarshal(raw, &msgs)
agent := aiutil.NewAgent(client, model, aiutil.WithHistory(msgs...))
Embeddings and model listing
emb, err := client.Embed(ctx, &aiutil.EmbeddingRequest{Model: "...", Input: []string{"hello"}})
models, err := client.ListModels(ctx)

Request fields

Field Notes
Model Falls back to WithDefaultModel.
Messages Required.
Tools Tools the model may call.
ToolChoice "auto", "none", "required", or a specific function.
Temperature, TopP *float64 so 0 is a real value, not "unset".
MaxTokens Output cap.
Stop Stop sequences.
JSONMode Ask for a JSON object.

Events

Type Meaning
EventText A chunk of assistant text (Text).
EventToolCall A completed tool call (ToolCall).
EventToolResult A tool's output (ToolCall, Result).
EventUsage Token usage for the call (Usage).
EventDone Stream finished (Response).

Errors

Non-2xx responses and upstream failures return *APIError:

if apiErr, ok := aiutil.IsAPIError(err); ok {
    fmt.Println(apiErr.StatusCode, apiErr.Message)
}

Transient failures (429, 5xx, network) are retried automatically with exponential backoff, honoring Retry-After. Tune with WithRetry, or override per request with Request.Retry.

Agent.Run returns ErrMaxTurns (detect with errors.Is) when it exceeds MaxTurns without a final answer.

Options

  • WithDefaultModel(model)
  • WithBaseURL(url)
  • WithHTTPClient(hc)
  • WithRetry(policy)

Agent options:

  • WithSystem(prompt)
  • WithTools(tools...)
  • WithMaxTurns(n)
  • WithMaxToolOutput(n)
  • WithMaxContextTokens(n)
  • WithOnUsage(fn)
  • WithOnTurn(fn)
  • WithHistory(msgs...)

Testing

go test ./...                                          # unit tests (mock server)
OPENROUTER_API_KEY=... go test -tags=integration ./... # live, prefer free models

Override the integration model with OPENROUTER_TEST_MODEL.

Documentation

Index

Constants

This section is empty.

Variables

View Source
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

func Schema added in v1.4.0

func Schema(name string, schema map[string]any) map[string]any

Schema builds a response_format value for structured output. name labels the schema; schema is a JSON Schema object. Pass the result as Request.ResponseSchema.

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

func IsAPIError(err error) (*APIError, bool)

IsAPIError reports whether err is an *APIError and returns it.

func (*APIError) Error added in v1.3.0

func (e *APIError) Error() string

func (*APIError) Retryable added in v1.3.0

func (e *APIError) Retryable() bool

Retryable reports whether the request may succeed if retried.

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) History added in v1.3.0

func (a *Agent) History() []Message

History returns a copy of the conversation so far.

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

func (a *Agent) Run(ctx context.Context, input string, opts ...RunOption) (*Response, error)

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.

func (*Agent) RunStream added in v1.3.0

func (a *Agent) RunStream(ctx context.Context, input string, onEvent func(Event) error, opts ...RunOption) (*Response, error)

RunStream is Run with streaming events delivered to onEvent (falling back to the agent's OnEvent when onEvent is nil).

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 New added in v1.3.0

func New(apiKey string, opts ...Option) *Client

New creates a Client. If apiKey is empty, OPENROUTER_API_KEY is used.

func (*Client) Chat added in v1.3.0

func (c *Client) Chat(ctx context.Context, req *Request) (*Response, error)

Chat performs a completion and returns the full response.

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

Embed returns embeddings for the given inputs. It uses the same client, base URL, and retry policy as chat calls.

func (*Client) ListModels

func (c *Client) ListModels(ctx context.Context) ([]ModelInfo, error)

ListModels returns the models available from the provider. It is used to seed a local model catalog.

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 Embedding added in v1.4.0

type Embedding struct {
	Index     int
	Embedding []float32
}

Embedding is one vector result.

type EmbeddingRequest added in v1.4.0

type EmbeddingRequest struct {
	Model string
	Input []string
}

EmbeddingRequest describes an embeddings call.

type EmbeddingResponse added in v1.4.0

type EmbeddingResponse struct {
	Model      string
	Embeddings []Embedding
	Usage      Usage
}

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 Assistant added in v1.3.0

func Assistant(text string) Message

Assistant returns an assistant message.

func System added in v1.3.0

func System(text string) Message

System returns a system message.

func ToolResult added in v1.3.0

func ToolResult(callID, content string) Message

ToolResult returns a tool message carrying the output of a tool call.

func User added in v1.3.0

func User(text string) Message

User returns a user message.

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

type ModelPricing struct {
	Prompt     float64 // USD per token
	Completion float64 // USD per token
}

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

func WithBaseURL(url string) Option

WithBaseURL overrides the API base URL.

func WithDefaultModel added in v1.3.0

func WithDefaultModel(model string) Option

WithDefaultModel sets the model used when a Request leaves Model empty.

func WithHTTPClient added in v1.0.0

func WithHTTPClient(hc *http.Client) Option

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 Response added in v1.3.0

type Response struct {
	ID           string
	Model        string
	Message      Message
	FinishReason string
	Usage        Usage
}

Response is the result of a 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 Role added in v1.3.0

type Role string

Role identifies who produced a message.

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

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

func WithMaxAttempts(n int) RunOption

WithMaxAttempts sets how many times RunJSON retries invalid JSON.

func WithSchema added in v1.4.0

func WithSchema(schema map[string]any) RunOption

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.

func (ToolCall) ParseArgs added in v1.3.0

func (c ToolCall) ParseArgs(v any) error

ParseArgs unmarshals the call's JSON arguments into v.

type Usage added in v1.3.0

type Usage struct {
	PromptTokens     int
	CompletionTokens int
	TotalTokens      int
}

Usage reports token counts for a request.

func (Usage) Add added in v1.4.0

func (u Usage) Add(other Usage) Usage

Add returns the sum of two Usage values.

func (Usage) IsZero added in v1.4.0

func (u Usage) IsZero() bool

IsZero reports whether all token counts are zero.

Directories

Path Synopsis
A tour of ai-util: chat, streaming, and a tool-calling agent.
A tour of ai-util: chat, streaming, and a tool-calling agent.

Jump to

Keyboard shortcuts

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