agent

package module
v0.0.0-...-d1566f9 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Overview

Package agent provides the building blocks for an LLM agent harness: a provider-agnostic agent loop, tool abstractions with JSON-schema generation, a permission policy hook, and event streaming.

The package deliberately contains no application shell. A CLI or web program wires the pieces together:

prov := openai.New(openai.Config{Model: "gpt-5", APIKey: key})
a := agent.New(prov,
	agent.WithSystemPrompt("You are a coding agent."),
	agent.WithTools(tools...),
	agent.WithPermissionPolicy(myPolicy),
)
res, err := a.Stream(ctx, agent.Call{
	Prompt:  "fix the failing test",
	OnEvent: func(ctx context.Context, e agent.Event) error { render(ctx, e); return nil },
})

Companion packages

Message history

A conversation is a []Message. The agent never mutates the caller's slice; the history after a call is returned in Result.Messages and includes the system prompt (when configured), the user prompt, every assistant message, and one tool-result message for every tool call the model made.

Events

Both Generate and Stream deliver events through Call.OnEvent, together with the call's context so that a handler can render them in the locale the context carries. Generate synthesizes the delta events (a single delta per text or reasoning block) so that a UI can use one code path in either mode. If OnEvent returns an error the call aborts with that error.

Steering a running call

Input that arrives while a call runs (a person typing to a working agent) goes to Call.Steer, taken at the start of the next step, after the tool results of the one before, or to Call.FollowUp, taken only when the model has ended its turn. A Queue holds it between its arrival and its taking, for any number of goroutines. EventSteer and EventFollowUp say when it was taken.

Permissions

Before each tool runs the agent consults the configured PermissionPolicy. A plain denial is fed back to the model as a tool result, every remaining tool call of that assistant message receives a synthetic "not executed" result, and the call ends with StopReasonPermissionDenied. A denial with Permission.Continue set instead delivers Permission.Feedback to the model and the loop keeps running, so the model can adjust its approach.

Tool results

Tool output delivered to the model is capped at 64 KiB (with a truncation note) as a backstop for third-party tools, and tools may return ToolResult.Images picture parts alongside text, for example screenshots or images read from the workspace.

Index

Examples

Constants

View Source
const DefaultMaxSteps = 40

DefaultMaxSteps bounds a single agent call when neither WithMaxSteps nor Call.MaxSteps sets a budget.

Variables

This section is empty.

Functions

func ContextWithSessionID

func ContextWithSessionID(ctx context.Context, id string) context.Context

ContextWithSessionID returns a context carrying a session identifier. Tools can read it with SessionIDFromContext to attribute requests (for example a question) to a session.

func ContextWithSubAgent

func ContextWithSubAgent(ctx context.Context) context.Context

ContextWithSubAgent returns a context marked as running inside a sub-agent. Permission prompts read the mark with SubAgentFromContext to tell the user whose call they are approving.

func SchemaFor

func SchemaFor[T any]() map[string]any

SchemaFor derives a JSON Schema object for T, used as the parameters schema of a Tool built with NewTool.

Conventions:

  • Struct fields map to object properties. The json tag controls the property name and omission ("-" skips the field); the description tag supplies the property description.
  • A field is required unless it has the omitempty or omitzero tag option or is a pointer.
  • The enum, default and minimum tags add the corresponding JSON Schema keywords (enum is a comma-separated list; values are parsed according to the field's schema type).
  • Slices and arrays map to arrays, string-keyed maps to objects with additionalProperties, pointers to the schema of their element. Struct objects declare additionalProperties: false so they are usable in provider strict mode.
  • time.Time maps to a date-time string, []byte to a string (JSON encodes it base64), json.RawMessage to an unconstrained schema, interface{} to an unconstrained schema.
  • An embedded struct without a json tag is inlined into the parent object.

SchemaFor panics when T contains a cycle, an unsupported kind (chan, func, complex), or a map with non-string keys — these are programmer errors in a tool definition, not runtime conditions.

func SessionIDFromContext

func SessionIDFromContext(ctx context.Context) string

SessionIDFromContext returns the session identifier attached with ContextWithSessionID, or "" when none is set.

func SubAgentFromContext

func SubAgentFromContext(ctx context.Context) bool

SubAgentFromContext reports whether the context was marked with ContextWithSubAgent.

Types

type Agent

type Agent struct {
	// contains filtered or unexported fields
}

Agent runs the tool loop against a Provider.

An Agent is immutable after New and safe for concurrent use, as long as the underlying provider and tools are.

func New

func New(provider Provider, opts ...Option) *Agent

New creates an Agent. It panics when provider is nil, a tool has an empty name, or two tools share a name — these are wiring errors, not runtime conditions.

func (*Agent) Generate

func (a *Agent) Generate(ctx context.Context, call Call) (*Result, error)

Generate runs the tool loop without streaming. The delta events are synthesized as single blocks so that handlers written for [Stream] work in both modes.

The result is nil only when the call fails before its first step: it has no messages, or the provider cannot supply the model. Any later error comes with the partial result — the history and steps up to the failure, with an empty StopReason unless the call was cancelled.

Example
package main

import (
	"context"
	"fmt"

	"gitlab.com/zygoon/go-agent"
	"gitlab.com/zygoon/go-agent/internal/lmtest"
)

func main() {
	prov := &lmtest.Provider{LM: &lmtest.FakeLM{Script: []lmtest.Scripted{lmtest.TextResponse("hi!")}}}
	a := agent.New(prov, agent.WithModel("demo"))

	res, err := a.Generate(context.Background(), agent.Call{Prompt: "hello"})
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	fmt.Println(res.Text())
}
Output:
hi!

func (*Agent) Stream

func (a *Agent) Stream(ctx context.Context, call Call) (*Result, error)

Stream runs the tool loop, delivering provider text, reasoning and tool-input deltas to Call.OnEvent as they arrive. Results and errors are as for Agent.Generate.

func (*Agent) Tools

func (a *Agent) Tools() []ToolDef

Tools returns the definitions of the agent's tools.

type Call

type Call struct {
	// Messages is the prior history, oldest first. It is never mutated;
	// the post-call history is returned in [Result.Messages].
	Messages []Message
	// Prompt, when non-empty, is appended as a user message.
	Prompt string
	// Images, when set, are attached to that user message as picture
	// parts (screenshots, diagrams, ...).
	Images []Image
	// Model overrides the agent's default model for this call.
	Model string
	// MaxSteps overrides the agent's step budget for this call.
	MaxSteps int
	// Temperature overrides the agent's default temperature for this
	// call; nil keeps the default.
	Temperature *float64
	// MaxTokens overrides the agent's default completion token cap for
	// this call; zero keeps the default.
	MaxTokens int64
	// Extra overrides individual provider-specific body fields for this
	// call, layered over [WithExtra].
	Extra map[string]any
	// ToolChoice overrides tool selection for this call. Nil means the
	// agent decides: auto, except that the final step forces "none" so
	// a turn over the step budget still ends with a text summary.
	ToolChoice *ToolChoice
	// ParallelToolCalls forwards the provider's parallel_tool_calls
	// hint; nil leaves the provider default.
	ParallelToolCalls *bool
	// Steer, when set, is asked for input to give the model while the
	// call runs: it is polled at the start of every step, after the
	// previous step's tool results are in the history and before the
	// step's request is built, and what it returns is appended to the
	// history (user messages, in order) and announced with
	// [EventSteer]. It is never polled while a tool runs, so every
	// tool call has its result before a steered message follows it.
	// It is also polled when the model ends its turn without calling
	// a tool, so input that arrived during the last step continues
	// the turn instead of waiting for the next one; see FollowUp for
	// the same rule on the last allowed step. [Queue.Drain] fits.
	Steer func(ctx context.Context) []Message
	// FollowUp, when set, is polled only where the call would end
	// because the model finished its turn (after Steer, which is
	// asked first). Messages it returns are appended to the history,
	// announced with [EventFollowUp], and the call goes on, so it
	// takes input that must not interrupt work in progress. Neither
	// callback is polled where a call ends otherwise (a stopped
	// tool, a denied permission, cancellation, an error, a truncated
	// reply) or on the last allowed step, which has no step left to
	// answer them: the input stays with its owner. [Queue.Drain]
	// fits.
	FollowUp func(ctx context.Context) []Message
	// OnEvent receives the call's events together with the call's
	// context, which carries the locale, session ID and other values
	// given to [Agent.Generate] or [Agent.Stream]. Events of the same
	// call are delivered sequentially. Returning an error aborts the
	// call with that error. The final event of a cancelled call
	// arrives with ctx already done: its values remain readable, but
	// the event must not be dropped because of it.
	OnEvent func(ctx context.Context, e Event) error
}

Call describes one agent invocation.

type Content

type Content struct {
	// Text is the visible assistant or user text.
	Text string `json:"text,omitempty"`
	// Reasoning holds the assistant's reasoning/thinking text when the
	// provider reported one. Providers replay it on later requests when
	// their protocol calls for it.
	Reasoning string `json:"reasoning,omitempty"`
	// ReasoningPresent reports that the model produced a reasoning
	// part for this assistant message, even an empty one. It tells
	// "reasoned, with nothing to show" apart from "did not reason",
	// which some providers need to replay the message faithfully.
	ReasoningPresent bool `json:"reasoning_present,omitempty"`
	// ToolCalls are the tool invocations requested by an assistant
	// message.
	ToolCalls []ToolCall `json:"tool_calls,omitempty"`
	// Result is the tool output answered by a tool-result message
	// (Role == RoleTool).
	Result *ToolOutput `json:"result,omitempty"`
	// Images are picture parts of a user message (role user) or of an
	// assistant message when the provider returned them.
	Images []Image `json:"images,omitempty"`
	// ProviderData carries provider-specific message metadata (such as
	// OpenRouter's reasoning_details) verbatim from the response back
	// into the next request. It is opaque to the agent and keyed by
	// the provider and protocol that wrote it (e.g. "openai.chat"), so
	// a history replayed to another backend never feeds one's data to
	// the other: a provider reads and writes only its own keys and
	// leaves the rest in place.
	ProviderData map[string]json.RawMessage `json:"provider_data,omitempty"`
}

Content is the body of a Message.

type Event

type Event struct {
	Type EventType
	// Step is the 1-based agent step the event belongs to. Provider-level
	// delta events carry 0 until the agent relays them.
	Step int

	// Text is the fragment for EventTextDelta.
	Text string
	// Reasoning is the fragment for EventReasoningDelta.
	Reasoning string

	// ToolCallID, ToolName and ArgumentsDelta describe
	// EventToolInputDelta. ToolCallID and ToolName hold the most recent
	// values seen for the call (IDs and names arrive on the first
	// fragment only).
	ToolCallID     string
	ToolName       string
	ArgumentsDelta string

	// ToolCall is the complete call for EventToolCall.
	ToolCall *ToolCall
	// Result is the outcome for EventToolResult.
	Result *ToolResult

	// Messages are the messages added to the history for EventSteer
	// and EventFollowUp.
	Messages []Message
	// Assistant is the complete assistant message for EventStepFinish.
	Assistant *Message
	// FinishReason is set on EventStepFinish.
	FinishReason FinishReason
	// Usage is set on EventStepFinish (per-step) and EventFinish
	// (cumulative for the call).
	Usage *Usage
	// StopReason is set on EventFinish.
	StopReason StopReason
	// Err is set on EventError.
	Err error
}

Event is the unified streaming unit, used by both LanguageModel implementations and the agent loop. Fields not relevant to the event type are zero.

type EventType

type EventType string

EventType identifies an Event.

const (
	// EventStepStart precedes one model round-trip.
	EventStepStart EventType = "step_start"
	// EventTextDelta carries a fragment of assistant text. In generate
	// mode the whole text block arrives as one delta.
	EventTextDelta EventType = "text_delta"
	// EventReasoningDelta carries a fragment of reasoning text.
	EventReasoningDelta EventType = "reasoning_delta"
	// EventToolInputDelta carries a fragment of a streaming tool call's
	// arguments. Stream mode only.
	EventToolInputDelta EventType = "tool_input_delta"
	// EventToolCall carries a complete tool call, before permission
	// review and execution.
	EventToolCall EventType = "tool_call"
	// EventToolResult carries the outcome of a tool run.
	EventToolResult EventType = "tool_result"
	// EventStepFinish carries the complete assistant message for a step.
	EventStepFinish EventType = "step_finish"
	// EventSteer carries messages taken from [Call.Steer] into the
	// history: just before the step they are given to (Step is that
	// step), or, when the model had ended its turn, after the step
	// that ended it (Step is that step) and before the next.
	EventSteer EventType = "steer"
	// EventFollowUp carries messages taken from [Call.FollowUp] into
	// the history to continue a turn the model had ended.
	EventFollowUp EventType = "follow_up"
	// EventFinish is the final event of a successful call.
	EventFinish EventType = "finish"
	// EventError reports a failed call; it is the last event emitted.
	EventError EventType = "error"
)

type FinishReason

type FinishReason string

FinishReason is why the model stopped producing tokens. It is one of the constants below whatever the provider's own spelling: LanguageModel implementations translate their wire values, and the agent loop relies on FinishReasonLength and FinishReasonContentFilter to discard partial tool calls.

const (
	// FinishReasonStop means the model finished its answer (or hit a
	// stop sequence).
	FinishReasonStop FinishReason = "stop"
	// FinishReasonLength means the output hit a token limit and was
	// cut short.
	FinishReasonLength FinishReason = "length"
	// FinishReasonToolCalls means the model stopped to call tools.
	FinishReasonToolCalls FinishReason = "tool_calls"
	// FinishReasonContentFilter means the provider withheld or cut
	// the output (a content filter, a refusal).
	FinishReasonContentFilter FinishReason = "content_filter"
	// FinishReasonOther is a reason the provider could not map to the
	// ones above. The agent treats it like FinishReasonStop.
	FinishReasonOther FinishReason = "other"
)

Reasons the model stopped producing tokens.

type Image

type Image struct {
	// Data is the base64-encoded image bytes (standard encoding, no
	// data-URL prefix). It is empty when URL is set.
	Data string `json:"data,omitempty"`
	// MimeType is the media type, e.g. "image/png".
	MimeType string `json:"mime_type,omitempty"`
	// URL, when set, references the image instead of embedding it.
	URL string `json:"url,omitempty"`
}

Image is an image attachment: inline base64 data or a remote URL.

type LLMRequest

type LLMRequest struct {
	// Messages is the conversation so far, oldest first.
	Messages []Message
	// Tools are the tools the model may call.
	Tools []ToolDef
	// Temperature is the sampling temperature; nil leaves the provider
	// default.
	Temperature *float64
	// MaxTokens caps the completion; zero leaves the provider default.
	MaxTokens int64
	// Extra carries provider-specific request body fields (merged into
	// the request body by implementations that support it).
	Extra map[string]any
	// ToolChoice selects which tools the model may call. The zero
	// value leaves the provider default (usually auto).
	ToolChoice ToolChoice
	// ParallelToolCalls toggles the provider's parallel_tool_calls
	// hint; nil leaves the provider default.
	ParallelToolCalls *bool
}

LLMRequest is a single request to a LanguageModel.

type LLMResponse

type LLMResponse struct {
	// Message is the assistant message: text, reasoning, and/or tool
	// calls.
	Message Message
	// FinishReason is the provider's reason the model stopped.
	FinishReason FinishReason
	// Usage is the token consumption of this request.
	Usage Usage
}

LLMResponse is a complete model reply.

type LanguageModel

type LanguageModel interface {
	// Generate performs one round-trip and returns the complete reply.
	Generate(ctx context.Context, req LLMRequest) (*LLMResponse, error)

	// Stream performs one round-trip, delivering
	// [EventTextDelta], [EventReasoningDelta] and [EventToolInputDelta]
	// events to onEvent as they arrive. onEvent runs on the caller's
	// goroutine; returning an error aborts the stream and Stream returns
	// that error. The returned response is always complete, even when no
	// events were requested (onEvent may be nil).
	Stream(ctx context.Context, req LLMRequest, onEvent func(Event) error) (*LLMResponse, error)
}

LanguageModel is one model behind one provider, fixed when Provider.LanguageModel creates it. Implementations must be safe for concurrent use: an Agent may run several calls at once, and sub-agents share the provider with their parent.

type Message

type Message struct {
	Role    Role    `json:"role"`
	Content Content `json:"content"`
	// ToolCallID is set on tool-result messages and matches the ID of
	// the [ToolCall] being answered.
	ToolCallID string `json:"tool_call_id,omitempty"`
}

Message is a single conversation message.

Messages and the types they contain marshal to a stable JSON form with snake_case keys and empty fields omitted, so a history can be saved and fed back as Call.Messages later. Keys are only ever added to that form, never renamed or removed.

func NewAssistantMessage

func NewAssistantMessage(text string) Message

NewAssistantMessage returns an assistant message carrying text.

func NewAssistantMessageWithCalls

func NewAssistantMessageWithCalls(text string, calls []ToolCall) Message

NewAssistantMessageWithCalls returns an assistant message carrying text and tool calls.

func NewSystemMessage

func NewSystemMessage(text string) Message

NewSystemMessage returns a system message.

func NewToolResultMessage

func NewToolResultMessage(toolCallID string, out ToolOutput) Message

NewToolResultMessage returns a tool-result message answering the tool call with the given ID.

func NewUserMessage

func NewUserMessage(text string) Message

NewUserMessage returns a user message.

type Option

type Option func(*Agent)

Option configures an Agent. Options are applied by New.

func WithCompaction

func WithCompaction(fn func(ctx context.Context, msgs []Message) ([]Message, error)) Option

WithCompaction installs fn, called with the message history before every LLM request — including the first — and free to rewrite it, so a long chain of steps can trim itself instead of overflowing the context window. Returning the input history unchanged skips the rewrite. fn runs on the calling goroutine.

An error from fn ends the call the way a provider error does. A best-effort compactor that would rather carry on returns the input history and a nil error instead.

func WithExtra

func WithExtra(extra map[string]any) Option

WithExtra adds provider-specific request body fields (e.g. reasoning_effort, top_p) merged into every request. Call.Extra overrides individual keys for one call.

func WithMaxSteps

func WithMaxSteps(n int) Option

WithMaxSteps sets the default step budget for a call. Non-positive values keep the current budget.

func WithMaxTokens

func WithMaxTokens(n int64) Option

WithMaxTokens sets the default completion token cap sent with every request. Call.MaxTokens overrides it for one call.

func WithModel

func WithModel(model string) Option

WithModel sets the default model name passed to the provider. It can be overridden per call with Call.Model.

func WithPermissionPolicy

func WithPermissionPolicy(p PermissionPolicy) Option

WithPermissionPolicy sets the policy consulted before each tool runs. A nil policy (the default) allows everything.

func WithSystemPrompt

func WithSystemPrompt(prompt string) Option

WithSystemPrompt prepends a system message to every request. When the call's history already starts with exactly this system message (the pattern when feeding Result.Messages back as history), it is not added a second time.

func WithTemperature

func WithTemperature(t float64) Option

WithTemperature sets the default sampling temperature sent with every request. Call.Temperature overrides it for one call.

func WithTools

func WithTools(tools ...Tool) Option

WithTools registers tools. It may be called multiple times to append. Duplicate tool names panic in New.

type Permission

type Permission struct {
	// Allowed reports whether the call may run.
	Allowed bool
	// Feedback explains a denial to the model. It replaces the
	// generic denial message as the tool result.
	Feedback string
	// Continue lets the model respond to a denial instead of ending
	// the turn with [StopReasonPermissionDenied]. It applies only to
	// denials; set it together with Feedback so the model knows what
	// to change.
	Continue bool
}

Permission is a policy's decision about one tool call.

type PermissionFunc

type PermissionFunc func(ctx context.Context, req PermissionRequest) (Permission, error)

PermissionFunc adapts a function to PermissionPolicy.

func (PermissionFunc) Allow

Allow implements PermissionPolicy.

type PermissionPolicy

type PermissionPolicy interface {
	// Allow reports whether the call may run. When it returns
	// Allowed=false without Continue, the tool is not executed: the
	// model receives a "permission denied" tool result and the call
	// ends with [StopReasonPermissionDenied]. With Continue set, the
	// denial is delivered (with Feedback when set) as a tool result
	// and the loop keeps running so the model can adapt. An error
	// fails the permission check the same way a plain denial does.
	Allow(ctx context.Context, req PermissionRequest) (Permission, error)
}

PermissionPolicy decides whether a tool call may run.

The agent loop consults the policy once per tool call, before the tool executes. The calls belonging to one Call are made sequentially, but the policy is shared by every call of the agent, so it must be safe for concurrent use. A nil policy allows everything.

func AllowAll

func AllowAll() PermissionPolicy

AllowAll returns a policy that allows every call.

func DenyAll

func DenyAll() PermissionPolicy

DenyAll returns a policy that denies every call, ending the turn.

type PermissionRequest

type PermissionRequest struct {
	// ToolCall is the call the model made.
	ToolCall ToolCall
	// Definition is the definition of the tool being called.
	Definition ToolDef
}

PermissionRequest describes a tool execution pending policy review.

type Provider

type Provider interface {
	// LanguageModel returns the model for the given name. An empty name
	// selects the provider's default model. It fails when the name is
	// unknown or the provider's configuration is invalid, so a call
	// ends before any request is sent.
	LanguageModel(model string) (LanguageModel, error)
}

Provider hands out [LanguageModel]s.

type Queue

type Queue struct {
	// contains filtered or unexported fields
}

Queue is a first-in, first-out queue of messages for a running call, safe for use from many goroutines: whatever receives input (a connection, a UI) [Queue.Push]es, and the call takes it with Queue.Drain, which has the signature of Call.Steer and Call.FollowUp. It is unbounded, so nothing pushed is dropped; the zero value is an empty queue ready to use, and a Queue must not be copied after first use.

func (*Queue) Drain

func (q *Queue) Drain(context.Context) []Message

Drain removes and returns everything queued, oldest first, or nil when there is nothing. It ignores ctx; it takes one to be a Call.Steer.

func (*Queue) Len

func (q *Queue) Len() int

Len is the number of messages queued.

func (*Queue) Push

func (q *Queue) Push(msgs ...Message)

Push appends msgs to the queue.

type Result

type Result struct {
	// Messages is the full history after the call: the input messages,
	// the system prompt (when configured), the user prompt, and every
	// assistant and tool message produced by the loop.
	Messages []Message
	// Steps records each model round-trip.
	Steps []Step
	// Usage is the cumulative token consumption of the call.
	Usage Usage
	// StopReason explains why the loop ended. It is empty when the call
	// returned an error.
	StopReason StopReason
}

Result is the outcome of an agent call.

func (*Result) LastAssistant

func (r *Result) LastAssistant() *Message

LastAssistant returns the final assistant message produced by the call, or nil when the model produced none.

func (*Result) Text

func (r *Result) Text() string

Text returns the assistant text produced across all steps of the call, the text of each step separated from the next by a blank line.

type Role

type Role string

Role identifies the author of a Message.

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

Message author roles.

type Step

type Step struct {
	// Index is the 1-based step number.
	Index int
	// Assistant is the message the model produced, after suppression of
	// truncated tool calls.
	Assistant Message
	// FinishReason is the provider's finish reason for this step.
	FinishReason FinishReason
	// Usage is the token consumption of this step's own model call.
	Usage Usage
	// SubUsage is the token consumption of nested work reported by
	// tools during this step (a sub-agent's calls, via
	// [ToolResult.Usage]). It is not part of this step's own model
	// call — reporting it as such would inflate the prompt size a
	// "context" figure draws from — but it counts toward
	// [Result.Usage].
	SubUsage Usage
}

Step records one completed model round-trip within a call.

type StopReason

type StopReason string

StopReason explains why an agent call ended.

const (
	// StopReasonEndTurn is set when the model finished on its own with
	// no pending tool calls.
	StopReasonEndTurn StopReason = "end_turn"
	// StopReasonMaxSteps is set when the step budget ran out.
	StopReasonMaxSteps StopReason = "max_steps"
	// StopReasonPermissionDenied is set when the permission policy
	// refused a tool call.
	StopReasonPermissionDenied StopReason = "permission_denied"
	// StopReasonToolStop is set when a tool requested the turn to end.
	StopReasonToolStop StopReason = "tool_stop"
	// StopReasonTruncated is set when the provider cut the response
	// short (finish_reason=length or content_filter); any partial tool
	// calls were discarded.
	StopReasonTruncated StopReason = "truncated"
	// StopReasonCancelled is set when the context was cancelled.
	StopReasonCancelled StopReason = "cancelled"
)

type Tool

type Tool interface {
	// Definition returns the model-facing description.
	Definition() ToolDef
	// Run executes the call. A non-nil result is delivered to the model
	// as a tool message.
	//
	// Errors are converted into IsError results so the model can react,
	// except when ctx is done: in that case the error aborts the agent
	// call. Set [ToolResult].StopTurn to end the turn after the result
	// is recorded.
	Run(ctx context.Context, call ToolCall) (ToolResult, error)
}

Tool is a function the model can invoke. Implementations must be safe for concurrent use: an Agent may run several calls at once, and sub-agents share tools with their parent.

func NewTool

func NewTool[T any](name, description string, fn func(ctx context.Context, params T, call ToolCall) (ToolResult, error)) Tool

NewTool adapts a typed function to Tool. The JSON schema for the parameters is derived from T with SchemaFor; the model's argument JSON is decoded into T before fn runs.

NewTool panics if name is empty, if no schema can be derived for T, or if T's schema is not a JSON object: models pass tool arguments as an object, so T is a struct (or a pointer to one) or a string-keyed map.

func ReadOnly

func ReadOnly(t Tool) Tool

ReadOnly marks t's definition as read-only and returns the wrapper. Use it for tools that never mutate state so permission policies can auto-approve them. The wrapper has an Unwrap() Tool method that returns t, for code that needs other methods of the original tool.

type ToolCall

type ToolCall struct {
	// ID correlates the call with its [ToolResult] message.
	ID string `json:"id"`
	// Name is the tool the model asked for.
	Name string `json:"name"`
	// Arguments is the raw JSON arguments object produced by the model.
	// It may be invalid JSON when the model misbehaves; tools must
	// tolerate that by reporting an error result.
	Arguments string `json:"arguments"`
	// ProviderData carries provider-specific per-call metadata (such as
	// Gemini's thought_signature) verbatim from the response back into
	// the next request. See [Content.ProviderData] for the keys.
	ProviderData map[string]json.RawMessage `json:"provider_data,omitempty"`
}

ToolCall is a model-requested tool invocation.

type ToolChoice

type ToolChoice struct {
	// Mode selects how the model may use tools; empty leaves the
	// provider default.
	Mode ToolChoiceMode
	// FunctionName forces a single named function when set.
	FunctionName string
}

ToolChoice is a request's tool-selection hint: a ToolChoiceMode, or FunctionName to force one function. The zero value means no preference.

type ToolChoiceMode

type ToolChoiceMode string

ToolChoiceMode is how a model may use the tools of a request.

const (
	// ToolChoiceModeAuto lets the model decide whether to call tools.
	ToolChoiceModeAuto ToolChoiceMode = "auto"
	// ToolChoiceModeNone forbids tool calls.
	ToolChoiceModeNone ToolChoiceMode = "none"
	// ToolChoiceModeRequired makes the model call at least one tool.
	ToolChoiceModeRequired ToolChoiceMode = "required"
)

Tool selection modes.

type ToolDef

type ToolDef struct {
	// Name is the identifier the model uses when calling the tool.
	Name string
	// Description explains to the model when to use the tool.
	Description string
	// Parameters is a JSON Schema object describing the arguments.
	Parameters map[string]any
	// ReadOnly marks a tool that only observes state and never
	// mutates it. It is not sent to the provider; permission policies
	// use it to approve calls without prompting.
	ReadOnly bool
}

ToolDef is the model-facing description of a tool.

type ToolOutput

type ToolOutput struct {
	// Output is the text delivered to the model in the tool message.
	Output string `json:"output"`
	// IsError marks the result as a failure so the model can react.
	IsError bool `json:"is_error,omitempty"`
	// Images are picture parts delivered alongside Output.
	Images []Image `json:"images,omitempty"`
}

ToolOutput is the part of a ToolResult delivered to the model and kept in history, as the Content.Result of a tool-result message.

type ToolResult

type ToolResult struct {
	// Output is the text delivered to the model in the tool message.
	Output string
	// IsError marks the result as a failure so the model can react.
	IsError bool
	// StopTurn asks the agent loop to end the turn after this result is
	// recorded. The result is still delivered to the model; the model is
	// simply not asked for another response in this call.
	StopTurn bool
	// Images are picture parts delivered alongside Output (for
	// example a screenshot, or a PNG read from the workspace).
	Images []Image
	// Usage, when set, reports extra token consumption spent while
	// producing this result — a sub-agent's model calls, say. The
	// agent folds it into the call's totals so nested work is
	// counted too.
	Usage Usage
}

ToolResult is the outcome of running a tool, as Tool.Run returns it. Only Output, IsError and Images are kept in history (as ToolOutput); StopTurn and Usage are consumed by the agent loop.

type Usage

type Usage struct {
	PromptTokens     int64 `json:"prompt_tokens,omitempty"`
	CompletionTokens int64 `json:"completion_tokens,omitempty"`
	TotalTokens      int64 `json:"total_tokens,omitempty"`
	// CachedTokens counts prompt tokens served from the provider's
	// prompt cache (prompt_tokens_details.cached_tokens).
	CachedTokens int64 `json:"cached_tokens,omitempty"`
	// ReasoningTokens counts completion tokens spent on reasoning
	// (completion_tokens_details.reasoning_tokens).
	ReasoningTokens int64 `json:"reasoning_tokens,omitempty"`
}

Usage reports token consumption for one or more model calls.

func (*Usage) Add

func (u *Usage) Add(other Usage)

Add accumulates other into u.

Directories

Path Synopsis
internal
l10n
Package l10n owns the module's translation catalogs.
Package l10n owns the module's translation catalogs.
lit
Package lit holds string constants shared by more than one package of the module: a literal spelled out in two packages is a goconst finding, so each one lives here exactly once.
Package lit holds string constants shared by more than one package of the module: a literal spelled out in two packages is a goconst finding, so each one lives here exactly once.
lmtest
Package lmtest holds the scripted fake language model shared by the tests of agent and of the packages that drive a agent.Agent (the tool packages under tools/).
Package lmtest holds the scripted fake language model shared by the tests of agent and of the packages that drive a agent.Agent (the tool packages under tools/).
strutil
Package strutil holds the string helpers shared by more than one package of the module.
Package strutil holds the string helpers shared by more than one package of the module.
provider
openai
Package openai implements a agent.Provider speaking the OpenAI-compatible chat-completions protocol directly over HTTP.
Package openai implements a agent.Provider speaking the OpenAI-compatible chat-completions protocol directly over HTTP.
tools
fs
Package fs provides workspace file tools restricted to an os.Root: read, write, edit, apply_patch, list, glob and grep.
Package fs provides workspace file tools restricted to an os.Root: read, write, edit, apply_patch, list, glob and grep.
mcp
Package mcp connects an agent to the tools of an MCP server: Client lists a server's tools and calls them, and Tools turns them into [goagent.Tool] values, so they go through the agent's [goagent.PermissionPolicy] like any other tool.
Package mcp connects an agent to the tools of an MCP server: Client lists a server's tools and calls them, and Tools turns them into [goagent.Tool] values, so they go through the agent's [goagent.PermissionPolicy] like any other tool.
question
Package question lets the model ask the user structured questions and block until an answer arrives.
Package question lets the model ask the user structured questions and block until an answer arrives.
shell
Package shell provides a bash execution tool and a companion tool that runs and manages background processes.
Package shell provides a bash execution tool and a companion tool that runs and manages background processes.
task
Package task holds the sub-agent task tool: it runs a fresh, isolated agent on a self-contained prompt and returns only that agent's final summary to the caller's conversation.
Package task holds the sub-agent task tool: it runs a fresh, isolated agent on a self-contained prompt and returns only that agent's final summary to the caller's conversation.
webfetch
Package webfetch provides a tool that retrieves a URL and returns its text content for the model.
Package webfetch provides a tool that retrieves a URL and returns its text content for the model.

Jump to

Keyboard shortcuts

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