Documentation
¶
Overview ¶
Package tool defines the tools an Agent can call: the tool interface, the execution context, results, and toolsets that provide tools in bulk.
Writing a tool only needs this package; the Agent definition and loop live in the agent package, and toolsets such as skills in their own packages.
Index ¶
- Variables
- func WithTaskManager(ctx context.Context, m TaskManager) context.Context
- type Context
- type Instructor
- type NeedsTaskManager
- type Option
- type Result
- type RunInfo
- type Sequential
- type Task
- type TaskManager
- type TaskResult
- type TaskSpec
- type TaskStatus
- type TaskUpdate
- type Timeouter
- type Tool
- type Toolset
- type Update
Constants ¶
This section is empty.
Variables ¶
var ErrAbandoned = errors.New("tool: execution timed out, progress is no longer reported")
ErrAbandoned is the error a tool gets when it reports progress after its execution timed out and was abandoned.
var ErrTaskNotFound = errors.New("tool: task not found or already finished")
ErrTaskNotFound means the task does not exist, has ended and delivered its result, or belongs to another session.
Functions ¶
func WithTaskManager ¶
func WithTaskManager(ctx context.Context, m TaskManager) context.Context
WithTaskManager sets who manages background tasks under this ctx; a nil m means background tasks are not supported.
Types ¶
type Context ¶
type Context struct {
context.Context
RunInfo
// Call is the tool call issued by the model.
Call chat.ToolCall
// contains filtered or unexported fields
}
Context is what a tool receives when it executes. It is a context.Context, so cancellation and timeouts work as usual, and it also carries the session, run and call of this invocation.
type Instructor ¶
Instructor is an optional interface for toolsets: the returned text is appended to the system prompt to tell the model how to use these tools (such as the catalog of available skills). An empty string appends nothing.
type NeedsTaskManager ¶
type NeedsTaskManager interface {
NeedsTaskManager() bool
}
NeedsTaskManager is an optional interface for tools: returning true means the tool depends on background tasks, and the Agent hides it when there is no TaskManager.
type Option ¶
type Option func(*typed)
Option adjusts a tool created by New.
func RunSequentially ¶
func RunSequentially() Option
RunSequentially requires the whole batch of calls containing this tool to run sequentially.
func WithTimeout ¶
WithTimeout sets the tool's execution timeout, which takes precedence over the Agent's default.
type Result ¶
type Result struct {
// Content enters the model context of the next turn.
Content []chat.ContentBlock
// Details is structured data for the UI, logs and business, never sent to the model.
Details any
// IsError marks an error result.
IsError bool
// Terminate asks to end the run after this turn; it takes effect only when every result of the batch asks for it.
Terminate bool
// Usage is the tokens consumed inside the tool (for example when the tool calls a model itself), counted in the run's total usage.
Usage chat.Usage
}
Result is the final result of a tool execution.
type RunInfo ¶
type RunInfo struct {
// SessionID is the session this run writes to. Every sub-agent task has a session of its own,
// so inside a sub-agent it is not the user's session; use RootSessionID for that.
SessionID string
RunID string
// ParentSessionID is the session that started this sub-agent task, or empty when it is not one.
ParentSessionID string
// RootSessionID is the session where everything started: it equals SessionID in the main run and is passed down through parent sessions to sub-agent tasks.
// Tools that look up data by the user's conversation should use it. When empty, the Agent runtime sets it to SessionID.
RootSessionID string
// Depth is the sub-agent nesting depth: 0 for the main Agent and 1 for the sub-agents it spawns.
// Middlewares such as approval and auditing can use it to tell who made a call. Set by the Agent runtime.
Depth int
// AgentName is the Name of the running Agent, empty for a general sub-agent. Set by the Agent runtime.
AgentName string
}
RunInfo identifies a run. When an Agent is used directly without a session, the session fields may be empty.
type Sequential ¶
type Sequential interface {
Sequential() bool
}
Sequential is an optional interface for tools: returning true means the whole batch of calls containing it must run sequentially, for tools with side effects or that cannot run concurrently.
type Task ¶
type Task struct {
ID string `json:"id"`
Type string `json:"type"`
// SessionID is the session that spawned the task; its result is sent back there.
SessionID string `json:"session_id"`
Description string `json:"description"`
Status TaskStatus `json:"status"`
StartedAt time.Time `json:"started_at"`
EndedAt time.Time `json:"ended_at,omitzero"`
// Output is the tail of what the task has printed; only the latest part is kept while it runs.
Output string `json:"output,omitempty"`
// Result is the task's final result, sent back to the session as the notice body.
Result string `json:"result,omitempty"`
Error string `json:"error,omitempty"`
// Details hold type-specific information, such as a sub-agent's turns or a command's exit code.
Details any `json:"details,omitempty"`
}
Task is a snapshot of a background task. Sub-agents, background commands and other kinds of tasks share it, told apart by Type.
type TaskManager ¶
type TaskManager interface {
// Start starts a task and returns immediately.
Start(ctx context.Context, spec TaskSpec) (Task, error)
// List returns the tasks spawned by the session whose results have not been delivered, ordered by start time.
List(ctx context.Context) []Task
// Get returns a snapshot of a task.
Get(ctx context.Context, id string) (Task, error)
// Stop stops a task and returns its final snapshot once it has ended.
Stop(ctx context.Context, id string) (Task, error)
}
TaskManager manages the background tasks of one session and is provided by the runtime (the runner): tasks outlive the tool call that started them, and their results come back to the session as notices. It only sees and acts on tasks spawned by this session. Its methods may be called concurrently.
func TaskManagerFrom ¶
func TaskManagerFrom(ctx context.Context) TaskManager
TaskManagerFrom returns the background task manager under ctx, or nil when background tasks are not supported. Tools just call TaskManagerFrom(ctx).
type TaskResult ¶
TaskResult is the result of a finished task.
type TaskSpec ¶
type TaskSpec struct {
Type string
Description string
// Run executes the task until it completes or ctx is canceled, reporting progress through report.
// Returning an error fails the task; a task halted by Stop has the stopped status.
Run func(ctx context.Context, report func(TaskUpdate)) (TaskResult, error)
}
TaskSpec describes a task to run in the background.
type TaskStatus ¶
type TaskStatus string
TaskStatus is the status of a background task.
const ( TaskRunning TaskStatus = "running" TaskCompleted TaskStatus = "completed" // TaskFailed means the task did not complete normally; see Task.Error for why. TaskFailed TaskStatus = "failed" TaskStopped TaskStatus = "stopped" )
type TaskUpdate ¶
type TaskUpdate struct {
// Output is new output, appended to Task.Output.
Output string
// Details, when set, replace Task.Details.
Details any
// Event is the task's own progress event, passed unchanged to the runtime's progress callback, such as a sub-agent's run events.
Event any
}
TaskUpdate is one progress report of a running task.
type Timeouter ¶
Timeouter is an optional interface for tools that declare their own execution timeout, which takes precedence over the Agent's default.
type Tool ¶
type Tool interface {
Def() chat.ToolDef
Execute(ctx *Context, args json.RawMessage) (*Result, error)
}
Tool is a tool the model can call.
An error returned by Execute does not stop the run; it is given to the model as an error result so it can correct itself. Arguments are validated against Def().InputSchema before the call.
func Defer ¶ added in v0.2.3
Defer marks a tool as deferred (see chat.ToolDef.Deferred): the model does not see it until it finds it through the provider's tool search. Use it for tools that are rarely needed; keep the few tools used in most turns loaded. The optional interfaces Sequential, Timeouter and NeedsTaskManager are passed through.
func New ¶
func New[In any](name, description string, fn func(ctx *Context, in In) (*Result, error), opts ...Option) Tool
New creates a tool from a typed parameter struct: the parameter schema is generated from In and arguments are decoded automatically.
In should be a struct. Fields without omitempty are required parameters; field descriptions are given with the `jsonschema:"description=..."` tag. A schema that cannot be generated from In is a programming error and panics.
type Toolset ¶
Toolset is a source that provides tools in bulk, such as a set of skills or an MCP server.
Tools is called once at the start of each run and may return different tools per session; the tool list stays the same within a run, so the prompt cache is not broken.
type Update ¶
type Update struct {
Content []chat.ContentBlock
Details any
}
Update is a partial result during tool execution.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package history provides the built-in tool history: it lets the model look up the messages of its session that compaction replaced with a summary, since a summary keeps the gist but not every detail.
|
Package history provides the built-in tool history: it lets the model look up the messages of its session that compaction replaced with a summary, since a summary keeps the gist but not every detail. |
|
Package shell provides the built-in command tool shell: the model can run a command in the foreground and get its output, or run it in the background and receive the result as a notice in the session when it ends.
|
Package shell provides the built-in command tool shell: the model can run a command in the foreground and get its output, or run it in the background and receive the result as a notice in the session when it ends. |
|
Package skill provides skills: focused instructions for the model, optionally with resource files.
|
Package skill provides skills: focused instructions for the model, optionally with resource files. |
|
Package task provides the built-in background task tool task: it lists and stops the background tasks spawned by the current session, for every kind of task, including sub-agents and background commands.
|
Package task provides the built-in background task tool task: it lists and stops the background tasks spawned by the current session, for every kind of task, including sub-agents and background commands. |
|
Package todo provides the built-in checklist tool todo_write: the model breaks a multi-step task into a checklist and updates its progress as it goes.
|
Package todo provides the built-in checklist tool todo_write: the model breaks a multi-step task into a checklist and updates its progress as it goes. |