Documentation
¶
Overview ¶
Package agent defines the Agent: a set of instructions, a model and tools, plus the decision loop that drives them.
An Agent is a reusable definition that holds no session state: the same Agent can run for many sessions concurrently. Loading, persisting, queuing and compacting sessions is the job of the runner package.
Index ¶
- Constants
- Variables
- func SubAgentTool(cfg SubAgentConfig) tool.Tool
- func WithSubAgentExecutor(ctx context.Context, exec SubAgentExecutor) context.Context
- type Agent
- type Event
- type EventSink
- type EventType
- type Input
- type Middleware
- type Result
- type RunNext
- type Status
- type SubAgentConfig
- type SubAgentDetails
- type SubAgentExecutor
- type SubAgentInput
- type ToolInvocation
- type ToolNext
- type Turn
- type TurnInfo
- type TurnNext
- type TurnResult
- type WrapToolFunc
Constants ¶
const SubAgentTaskType = "sub_agent"
SubAgentTaskType is the tool.Task.Type of sub-agent tasks.
const SubAgentToolName = "sub_agent"
SubAgentToolName is the name of the sub-agent tool.
Variables ¶
var ErrMaxTurnsExceeded = errors.New("agent: max turns exceeded")
ErrMaxTurnsExceeded means the loop had not ended when MaxTurns was reached. Result is still valid.
Functions ¶
func SubAgentTool ¶
func SubAgentTool(cfg SubAgentConfig) tool.Tool
SubAgentTool returns a tool that lets an Agent hand sub-tasks to sub-agents running in the background. The model decides whether to delegate and to whom.
Sub-agents only run in the background: the tool returns a task ID (the child session ID) immediately, and when the sub-task ends its result comes back to the main session as a notice message. Sub-tasks are listed and stopped with the task tool (tool/task), which should be provided alongside this one. Sub-agents start cold: they only see the task description written by the main Agent and run to the end in a fresh context.
The tool depends on background tasks (tool.NeedsTaskManager) and is only offered to a main Agent run by the runner: it does not appear when the Agent is used directly or is already a sub-agent, so sub-agents cannot spawn sub-agents.
The general sub-agent borrows the main Agent's model, model options (except the output format), tools and limits, and uses its own instruction; the main Agent's middlewares belong to the main Agent and are not inherited, while middlewares for every run are applied by the runtime (the runner). A sub-agent notice is appended to the system prompt of every sub-agent. Inherited tools are the same instances as the main Agent's, not copies; a tool's sequential constraint only holds within one run, so a background sub-agent may call the same tool at the same time as the main Agent. The fallback limit of a sub-task is the turn limit (Agent.MaxTurns).
func WithSubAgentExecutor ¶
func WithSubAgentExecutor(ctx context.Context, exec SubAgentExecutor) context.Context
WithSubAgentExecutor sets who executes sub-tasks under this ctx.
Types ¶
type Agent ¶
type Agent struct {
// Name and Description identify the Agent. When it is given to SubAgentTool as a specialized sub-agent,
// the model picks it by Name, and Description says what it is good at.
Name string
Description string
// Instruction is the system prompt. When InstructionFunc is set, it generates the prompt at the start of each run instead,
// for prompts that vary per session. Instructions contributed by toolsets are appended after it.
Instruction string
InstructionFunc func(ctx context.Context, info tool.RunInfo) (string, error)
// Model is the default model; Input.Model overrides it for a single run.
Model chat.Client
// Options are passed unchanged to every model call; Metadata additionally carries turn_index.
Options chat.Options
// Tools are the fixed tools; Toolsets are resolved once at the start of each run and provide tools that vary per session.
// Tool names must be unique across both.
Tools []tool.Tool
Toolsets []tool.Toolset
// MaxTurns limits the number of model calls in a run, 20 by default.
MaxTurns int
// SequentialTools runs each batch of tool calls sequentially; by default they run concurrently, and a batch runs sequentially when any of its tools declares tool.Sequential.
SequentialTools bool
// MaxParallelTools limits how many tools of a batch run concurrently, 8 by default.
MaxParallelTools int
// ToolTimeout is the default timeout of a single tool execution, 0 for none; a tool can declare its own with tool.Timeouter.
// On timeout an error result is returned and the loop continues without waiting for the tool, so tools should honor ctx cancellation.
ToolTimeout time.Duration
// MaxToolResultBytes limits the total bytes of text in a single tool result, 100000 by default, negative for no limit.
// Beyond it the start and end are kept with a note of how many bytes were omitted; images and Details are not affected.
MaxToolResultBytes int
// Middlewares are this Agent's own middlewares, the first being outermost; see Middleware. Sub-agents do not inherit them;
// middlewares that apply to every Agent (approval, auditing, tracing) belong to the runtime and come from runner.Config.Middlewares.
Middlewares []Middleware
}
Agent is the definition of an agent. Beyond the zero value, at least Model must be set, unless every run sets Input.Model.
Extensions at the model call level (logging, usage, retries, fallbacks) wrap Model with chat.Chain; Middlewares cover the loop itself: the run, each turn, each turn's model request, and tool execution.
func (*Agent) Run ¶
Run drives the Agent to the end: it calls the model, executes tools and returns their results to the model until the model gives a final reply.
error is nil only when the run completes normally (Result.Status is StatusCompleted). A failed model call returns a *chat.Error, cancellation returns the ctx error, and reaching the turn limit returns ErrMaxTurnsExceeded; in these three cases Result is still valid and contains the messages produced so far. Result may be nil for invalid input, or when a toolset, middleware or event handler fails.
type Event ¶
type Event struct {
Type EventType
TurnIndex int
// Message is a snapshot of the assistant or tool result message. It is safe to keep but read-only:
// it shares the bytes of media data and tool arguments with the streaming message, so do not modify its content.
Message *chat.Message
// AssistantEvent is the model stream event carried by message_update; its Message matches the snapshot above.
AssistantEvent *chat.Event
ToolCall *chat.ToolCall
Update *tool.Update
Result *tool.Result
Turn *Turn
RunResult *Result
Err error
}
Event is a structured event emitted by the agent.
func (Event) TextDelta ¶
TextDelta returns the reply text delta of this event, or "" when it is not a text delta event.
func (Event) ThinkingDelta ¶
ThinkingDelta returns the thinking text delta of this event, or "" when it is not a thinking delta event.
type EventType ¶
type EventType string
EventType is the type of an event during an Agent run.
const ( EventAgentStart EventType = "agent_start" EventAgentEnd EventType = "agent_end" EventTurnStart EventType = "turn_start" EventTurnEnd EventType = "turn_end" EventMessageStart EventType = "message_start" EventMessageUpdate EventType = "message_update" EventMessageEnd EventType = "message_end" EventToolExecutionStart EventType = "tool_execution_start" EventToolExecutionUpdate EventType = "tool_execution_update" EventToolExecutionEnd EventType = "tool_execution_end" )
type Input ¶
type Input struct {
tool.RunInfo
// Messages is the history so far and must end with a user message or a tool result.
Messages []chat.Message
// Emit receives the events of the run; returning an error stops the run.
Emit EventSink
// Steering is called after each turn; the messages it returns are injected before the next model call, for interjecting mid-run.
// It never interrupts tools that are executing.
Steering func(ctx context.Context) ([]chat.Message, error)
// FollowUp is called when the loop would otherwise end; returning messages continues the run, for queued follow-up tasks.
FollowUp func(ctx context.Context) ([]chat.Message, error)
// Model overrides Agent.Model for this run when set. General sub-agents started by the run use it too;
// specialized sub-agents keep their own Model. Agent.Options are passed unchanged, so leave model-specific
// options such as Options.Model and MaxTokens unset when runs switch between models.
Model chat.Client
// Middlewares belong to this run only. They sit inside Agent.Middlewares and are not inherited by sub-agents.
// Upper layers (such as the runner's history compaction) use them to hook into the run.
Middlewares []Middleware
}
Input is the input of a run.
func Parts ¶
func Parts(blocks ...chat.ContentBlock) Input
Parts returns an input with a single user message made of several content blocks, such as some text and a few images.
type Middleware ¶
type Middleware struct {
// WrapRun wraps a run, covering the resolution of the system prompt and tools as well as every turn.
WrapRun func(ctx context.Context, info tool.RunInfo, next RunNext) (*Result, error)
// WrapTurn wraps a turn: injecting pending messages, calling the model, executing tools. See TurnResult.
// next may be called at most once; when it is not called the turn does not run and the returned result goes straight to the outer layer.
WrapTurn func(ctx context.Context, turn TurnInfo, next TurnNext) (*TurnResult, error)
// WrapModel wraps a model call: it can rewrite the request, observe or rewrite events, or call next zero or several times.
// The returned sequence must honor the chat.Client.Stream contract. req.Messages is a copy that can be changed directly.
// The tools callable in this turn are those in the request of the last call to next; tools not offered are not executed even if called.
// Extensions at the model call level that are unrelated to the run (retries, rate limiting, usage) wrap Model with chat.Chain.
WrapModel func(ctx context.Context, turn TurnInfo, req chat.Request, next chat.StreamFunc) iter.Seq[chat.Event]
// WrapTool wraps a tool execution; see WrapToolFunc.
WrapTool WrapToolFunc
}
Middleware is a set of hooks wrapping an Agent run; every field may be nil. From outside in, the four hooks wrap a run, each of its turns, and the model call and tool executions within a turn; each layer gets next and decides whether and how to continue. One concern (tracing, auditing, human approval) can be packaged as one Middleware.
Middlewares form a chain of responsibility with the first being outermost, which also decides the order of the same hook across layers.
func BeforeModel ¶
BeforeModel builds a middleware that only modifies the request before the model call. req.Messages is a copy that can be changed directly, and tools removed from req.Tools cannot be called in this turn. Returning an error fails the model call, and the run ends with StatusFailed.
type Result ¶
type Result struct {
Status Status
// Messages are all messages added by the run, in the order they entered history.
Messages []chat.Message
// Final is the last assistant message.
Final *chat.Message
// Usage is the total tokens consumed by model calls and inside tools.
Usage chat.Usage
Turns int
Duration time.Duration
}
Result is the result of a run.
func RunJSON ¶
RunJSON runs the Agent and decodes the final reply into T, for cases that need a structured result, such as a step in a workflow.
When a.Options.Output is nil the schema is generated from T (T should be a struct). Tools, middlewares and events work as usual, and the format only constrains the final reply. When the reply is not valid JSON or does not match the schema, the validation error is given to the model and the Agent runs once more; this repair emits another pair of agent_start / agent_end events.
The format constraint is sent with every model call, and capable models still call tools in intermediate turns. Some weaker models (claude-haiku-4-5 in testing) may skip the tools under the constraint and make up a result; switch to a stronger model when that happens.
Errors mean the same as for Run; in addition, output still invalid after the repair returns a *chat.Error of Kind chat.KindInvalidOutput. Result is still valid when error is non-nil, with the messages and usage of both runs.
type Status ¶
type Status string
Status is how a run ended.
const ( // StatusCompleted means the model gave a final reply, or the run ended normally through WrapTurn or a tool's Terminate. StatusCompleted Status = "completed" // StatusMaxTurns means MaxTurns was reached; ErrMaxTurnsExceeded is returned as well. StatusMaxTurns Status = "max_turns" // StatusFailed means a model call failed; Run also returns the corresponding *chat.Error. StatusFailed Status = "failed" // StatusAborted means ctx was canceled; Run also returns the ctx error. StatusAborted Status = "aborted" )
type SubAgentConfig ¶
type SubAgentConfig struct {
// Agents are specialized sub-agents, each using its own definition. The model picks them by Name, and Description goes into the tool description.
Agents []*Agent
// Instruction is the system prompt of the general sub-agent; an empty one uses a built-in neutral instruction.
// The general sub-agent does not reuse the main Agent's instruction, which is usually written for a coordinator; the main Agent puts background and constraints into the task.
Instruction string
// ExcludeTools are tool names the general sub-agent does not inherit, for tools that should not be handed to sub-tasks (such as actions with side effects).
// When the main Agent has no toolsets, every name must be one of its tools, and a wrong name makes the sub-task fail to start;
// with toolsets the tools vary per session and cannot be checked.
ExcludeTools []string
}
SubAgentConfig configures the sub-agent tool. The zero value works: a single general sub-agent.
type SubAgentDetails ¶
type SubAgentDetails struct {
// Agent is the name of the specialized sub-agent, empty for a general one.
Agent string `json:"agent,omitempty"`
// Task is the full task description written by the main Agent.
Task string `json:"task"`
// Turns is the number of turns started so far, and LastTool the most recently called tool.
Turns int `json:"turns"`
LastTool string `json:"last_tool,omitempty"`
Usage chat.Usage `json:"usage"`
}
SubAgentDetails are the Details of a sub-agent task snapshot (tool.Task). The task ID is the ID of the child session holding all its messages.
type SubAgentExecutor ¶
SubAgentExecutor starts sub-tasks in the background: they are registered with the other background tasks, listed and stopped through tool.TaskManager, and the executor sends their results back to the parent session when they end. The agent package keeps no sub-task state; the runner implements it.
type SubAgentInput ¶
type SubAgentInput struct {
// Agent is the complete definition used by this sub-task.
Agent *Agent
// Parent is the run that started the sub-task.
Parent tool.RunInfo
// Description is a short note for the user; Task is the task description written by the main Agent and the sub-agent's entire input.
Description string
Task string
}
SubAgentInput describes a sub-task to start, passed to a SubAgentExecutor.
type ToolInvocation ¶
type ToolInvocation struct {
tool.RunInfo
TurnIndex int
AssistantMessage chat.Message
Call chat.ToolCall
Tool tool.Tool
// Args are the arguments about to be passed to the tool, already validated against the schema; they are validated again if a middleware changes them.
Args []byte
}
ToolInvocation is one tool call, passed to WrapToolFunc.
type ToolNext ¶
type ToolNext func(ctx context.Context, inv *ToolInvocation) *tool.Result
ToolNext continues the tool call. Errors and panics from the tool have already been turned into IsError results.
type Turn ¶
Turn holds a turn's model response and its tool results. Messages injected at the start of a turn (steering, follow-up) are not here; they are emitted as message events with the same TurnIndex.
type TurnInfo ¶
TurnInfo describes a turn about to start. A turn is one iteration of the inner loop: inject pending messages, call the model once, and execute the tool calls it produced. TurnIndex is numbered consecutively from 0 within a run.
type TurnNext ¶
type TurnNext func(ctx context.Context) (*TurnResult, error)
TurnNext runs the turn and returns its result.
type TurnResult ¶
type TurnResult struct {
tool.RunInfo
TurnIndex int
Turn Turn
// An empty Status continues the run; otherwise the run ends with that status: StatusFailed when the model failed, StatusAborted when canceled.
// A middleware can set StatusCompleted to end the run without processing steering and follow-up;
// clearing StatusFailed recovers from the failure, and the loop calls the model again with Messages. It should then also replace Messages
// (by compacting history, for example), or the next turn fails the same way. The recovered turn also counts toward MaxTurns.
Status Status
// Messages is the full history including this turn; when the run continues it becomes the history of later turns, so replacing it compacts history.
// Result.Messages is still every message produced by the run and is not affected by the replacement.
Messages []chat.Message
}
TurnResult is the result of a turn. WrapTurn may change Status and Messages before passing it outward, and the loop continues from the outermost result. The turn's messages were already emitted as events during the turn (the runner persists them from those), so changing Turn does not affect them.
type WrapToolFunc ¶
type WrapToolFunc func(ctx context.Context, inv *ToolInvocation, next ToolNext) (*tool.Result, error)
WrapToolFunc wraps one tool execution: it can change arguments, rewrite the result, time it, or ask for human approval, and it can intercept the call by returning a result without calling next. It is called concurrently when tools run in parallel. A returned error does not stop the run; it is given to the model as an error result.