tool

package
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: MIT Imports: 6 Imported by: 1 module, 0 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.

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

Constants

This section is empty.

Variables

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

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

func NewContext

func NewContext(ctx context.Context, info RunInfo, call chat.ToolCall, update func(Update) error) *Context

NewContext creates a tool execution context. Progress reports are ignored when update is nil. Tests of tools can build a context with it directly.

func (*Context) Update

func (c *Context) Update(u Update) error

Update reports execution progress, mainly for UIs and logs. It returns an error once the execution timed out and was abandoned.

type Instructor

type Instructor interface {
	Instructions(ctx context.Context, info RunInfo) (string, error)
}

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

func WithTimeout(d time.Duration) Option

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.

func Error

func Error(text string) *Result

Error returns an error result in text form.

func Text

func Text(text string) *Result

Text returns a result with a single text block.

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

type TaskResult struct {
	Text string
	// Details, when set, replace Task.Details.
	Details any
}

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

type Timeouter interface {
	Timeout() time.Duration
}

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

func Defer(t Tool) Tool

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

type Toolset interface {
	Tools(ctx context.Context, info RunInfo) ([]Tool, error)
}

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.

func DeferAll added in v0.2.3

func DeferAll(set Toolset) Toolset

DeferAll marks every tool of a toolset as deferred, see Defer. Its Instructor, if any, is passed through.

type Update

type Update struct {
	Content []chat.ContentBlock
	Details any
}

Update is a partial result during tool execution.

Directories

Path Synopsis
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.

Jump to

Keyboard shortcuts

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