Documentation
¶
Overview ¶
Package tool provides tool definition and execution for AI models. This mirrors the ai-sdk tool() and dynamicTool() functionality.
Index ¶
- Variables
- func ValidateToolInput(tool Tool, input any) error
- type Attachment
- type CallOptions
- type ContextKey
- type Definition
- func (d *Definition) Build() Tool
- func (d *Definition) Description(desc string) *Definition
- func (d *Definition) Execute(fn ExecuteFunc) *Definition
- func (d *Definition) InputExample(input json.RawMessage) *Definition
- func (d *Definition) InputExamples(examples []ToolInputExample) *Definition
- func (d *Definition) Schema(schema json.RawMessage) *Definition
- func (d *Definition) SchemaFromStruct(v any) *Definition
- type ExecuteFunc
- type Executor
- type FatalToolError
- type Info
- type LocalExecutor
- type ParseToolCallOptions
- type ParsedToolCall
- type PermissionRequest
- type RawToolCall
- type RepairToolCallContext
- type RepairToolCallFunc
- type Request
- type Response
- type Result
- type Set
- type Tool
- type ToolInputExample
Constants ¶
This section is empty.
Variables ¶
var DebugExecutor = os.Getenv("DEBUG_EXECUTOR") != ""
DebugExecutor enables debug logging for tool execution
Functions ¶
func ValidateToolInput ¶
ValidateToolInput validates that the input matches the tool's schema. This is a separate function for when you need explicit validation.
Types ¶
type Attachment ¶
type Attachment struct {
Data string `json:"data"` // base64 encoded
MimeType string `json:"mimeType"` // e.g., "image/png"
Filename string `json:"filename,omitempty"`
}
Attachment represents a file attachment in a tool result.
type CallOptions ¶
CallOptions contains options passed to tool execution.
type ContextKey ¶
type ContextKey string
ContextKey is the type for tool execution context keys.
const ( // SessionIDKey is the context key for session identification. SessionIDKey ContextKey = "sessionID" // WorkDirKey is the context key for the working directory. WorkDirKey ContextKey = "workDir" // RunnerKey is the context key for the runner instance (optional). RunnerKey ContextKey = "runner" )
Context keys for tool execution. These are used by LocalExecutor and should be used by tool implementations.
type Definition ¶
type Definition struct {
// contains filtered or unexported fields
}
Definition is a builder for creating tools.
func (*Definition) Description ¶
func (d *Definition) Description(desc string) *Definition
Description sets the tool description.
func (*Definition) Execute ¶
func (d *Definition) Execute(fn ExecuteFunc) *Definition
Execute sets the execution function.
func (*Definition) InputExample ¶
func (d *Definition) InputExample(input json.RawMessage) *Definition
InputExample appends a single example input to the tool definition. Each input should be a JSON-encoded object matching the tool's input schema.
func (*Definition) InputExamples ¶
func (d *Definition) InputExamples(examples []ToolInputExample) *Definition
InputExamples replaces the tool's example list.
func (*Definition) Schema ¶
func (d *Definition) Schema(schema json.RawMessage) *Definition
Schema sets the JSON schema for the tool input.
func (*Definition) SchemaFromStruct ¶
func (d *Definition) SchemaFromStruct(v any) *Definition
SchemaFromStruct generates a JSON schema from a struct type.
type ExecuteFunc ¶
type ExecuteFunc func(ctx context.Context, input json.RawMessage, opts CallOptions) (Result, error)
ExecuteFunc is the function signature for tool execution. It receives the parsed input and returns a result or error.
type Executor ¶
type Executor interface {
// Execute runs a tool and returns the result.
// The executor handles all local concerns (file system, permissions, etc.)
Execute(ctx context.Context, req Request) (Response, error)
// Tools returns information about available tools.
// This is used to build the tool list for the LLM.
Tools() []Info
}
Executor abstracts tool execution, allowing tools to run locally or remotely. This enables separating the LLM orchestration from tool execution, supporting architectures where tools run in isolated containers.
type FatalToolError ¶
FatalToolError is an interface that errors can implement to indicate they should not be fed back to the model as tool results. When a tool returns an error implementing this interface, the executor propagates it instead of converting it to a Response. This is used for errors like permission timeouts that should suspend the run, not be retried by the model.
type Info ¶
type Info struct {
Name string `json:"name"`
Description string `json:"description"`
InputSchema json.RawMessage `json:"input_schema"`
}
Info contains metadata about a tool for LLM consumption.
type LocalExecutor ¶
type LocalExecutor struct {
// contains filtered or unexported fields
}
LocalExecutor executes tools in the current process. This is the default executor for CLI usage.
func NewLocalExecutor ¶
func NewLocalExecutor(tools Set, activeTools []string) *LocalExecutor
NewLocalExecutor creates a new local executor with the given tools.
func (*LocalExecutor) SetActiveTools ¶
func (e *LocalExecutor) SetActiveTools(activeTools []string)
SetActiveTools updates the active tools filter.
type ParseToolCallOptions ¶
type ParseToolCallOptions struct {
// ToolCall is the raw tool call from the model.
ToolCall RawToolCall
// Tools is the set of available tools. May be nil.
Tools Set
// RepairToolCall is an optional function to repair invalid tool calls.
RepairToolCall RepairToolCallFunc
// System is the system message (for repair context).
System string
// Messages is the conversation history (for repair context).
Messages []message.Message
}
ParseToolCallOptions contains options for ParseToolCall.
type ParsedToolCall ¶
type ParsedToolCall struct {
Type string `json:"type"` // "tool-call"
ToolCallID string `json:"toolCallId"`
ToolName string `json:"toolName"`
// Input is the parsed JSON input (may be any JSON value)
Input any `json:"input"`
// Title is the optional tool title
Title string `json:"title,omitempty"`
// Dynamic indicates this is a dynamic tool call
Dynamic bool `json:"dynamic,omitempty"`
// Invalid indicates the tool call failed validation
Invalid bool `json:"invalid,omitempty"`
// Error contains the validation error if Invalid is true
Error error `json:"error,omitempty"`
// ProviderExecuted indicates the tool was executed by the provider
ProviderExecuted bool `json:"providerExecuted,omitempty"`
// ProviderMetadata contains provider-specific metadata
ProviderMetadata map[string]any `json:"providerMetadata,omitempty"`
}
ParsedToolCall represents a validated and parsed tool call. Source: ai-sdk/packages/ai/src/generate-text/tool-call.ts
func ParseToolCall ¶
func ParseToolCall(opts ParseToolCallOptions) *ParsedToolCall
ParseToolCall validates and parses a tool call from the model. This mirrors ai-sdk's parseToolCall function.
Source: ai-sdk/packages/ai/src/generate-text/parse-tool-call.ts
type PermissionRequest ¶
type PermissionRequest struct {
// Permission type (e.g., "bash", "edit", "external_directory")
Permission string `json:"permission"`
// Patterns that need approval (e.g., command, file path)
Patterns []string `json:"patterns"`
// Description of what the tool wants to do
Description string `json:"description,omitempty"`
// Metadata contains additional context
Metadata map[string]any `json:"metadata,omitempty"`
}
PermissionRequest represents a request for permission to perform an action.
type RawToolCall ¶
type RawToolCall struct {
Type string `json:"type"` // "tool-call"
ToolCallID string `json:"toolCallId"`
ToolName string `json:"toolName"`
Input string `json:"input"` // JSON string of the input
// Dynamic indicates the tool is not statically defined
Dynamic bool `json:"dynamic,omitempty"`
// ProviderExecuted indicates the tool was executed by the provider
ProviderExecuted bool `json:"providerExecuted,omitempty"`
// ProviderMetadata contains provider-specific metadata
ProviderMetadata map[string]any `json:"providerMetadata,omitempty"`
}
RawToolCall represents a tool call from the language model before validation. Source: ai-sdk/packages/provider/src/language-model/v4/language-model-v4-tool-call.ts (LanguageModelV4ToolCall)
type RepairToolCallContext ¶
type RepairToolCallContext struct {
// ToolCall is the invalid tool call.
ToolCall RawToolCall
// Tools is the set of available tools.
Tools Set
// InputSchema returns the JSON schema for a tool by name.
InputSchema func(toolName string) json.RawMessage
// System is the system message.
System string
// Messages is the conversation history.
Messages []message.Message
// Error is the validation error that triggered repair.
Error error
}
RepairToolCallContext contains context for the repair function.
type RepairToolCallFunc ¶
type RepairToolCallFunc func(ctx RepairToolCallContext) (*RawToolCall, error)
RepairToolCallFunc is a function that attempts to repair an invalid tool call. Return nil to indicate the repair was unsuccessful.
type Request ¶
type Request struct {
// ToolCallID is the unique identifier for this tool call (from LLM)
ToolCallID string `json:"tool_call_id"`
// ToolName is the name of the tool to execute
ToolName string `json:"tool_name"`
// Input is the tool-specific input (JSON)
Input json.RawMessage `json:"input"`
// SessionID identifies the session for file tracking and permissions
SessionID string `json:"session_id,omitempty"`
// WorkDir is the working directory for the tool
WorkDir string `json:"work_dir,omitempty"`
}
Request represents a tool execution request.
type Response ¶
type Response struct {
// Output is the tool's text output
Output string `json:"output"`
// Title is an optional title for the result
Title string `json:"title,omitempty"`
// Error is set if the tool execution failed
Error string `json:"error,omitempty"`
// IsError indicates whether this response represents an error
IsError bool `json:"is_error,omitempty"`
// NoExecute is true when the tool has no execute function.
// This matches ai-sdk behavior where tools without execute return undefined.
NoExecute bool `json:"no_execute,omitempty"`
// Metadata contains optional structured data
Metadata map[string]any `json:"metadata,omitempty"`
// Attachments contains optional file attachments
Attachments []Attachment `json:"attachments,omitempty"`
// PermissionRequired is set when the tool needs permission to proceed.
// The orchestrator should handle this by requesting permission and
// potentially re-executing the tool.
PermissionRequired *PermissionRequest `json:"permission_required,omitempty"`
}
Response represents a tool execution response.
type Result ¶
type Result struct {
Output string `json:"output"`
Title string `json:"title,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
Attachments []Attachment `json:"attachments,omitempty"`
}
Result represents the output of a tool execution.
type Set ¶
Set is a collection of tools indexed by name.
func (Set) Ordered ¶
Ordered returns tools as a slice in deterministic order. If activeTools is provided, returns only those tools in the specified order. Otherwise, returns all tools sorted alphabetically by name. This matches ai-sdk's behavior where tools are converted to an ordered array at the core level before being passed to providers.
type Tool ¶
type Tool struct {
// Type is "" (function tool) or "provider" (provider-defined tool).
Type string `json:"type,omitempty"`
// ProviderID is the canonical id for provider-defined tools, e.g.
// "google.google_search", "openai.web_search". Empty for function tools.
ProviderID string `json:"providerID,omitempty"`
// Args is the JSON-encoded argument payload for provider-defined tools.
// Empty when the tool takes no args.
Args json.RawMessage `json:"args,omitempty"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
InputSchema json.RawMessage `json:"inputSchema,omitempty"` // JSON Schema (function tools)
// InputExamples is an optional list of example inputs that show the
// language model what the tool input should look like. Mirrors ai-sdk's
// LanguageModelV4FunctionTool.inputExamples. Providers that natively
// accept examples (e.g. Anthropic via input_examples) pass them through;
// others can use middleware.AddToolInputExamples to serialize them into
// the description instead.
InputExamples []ToolInputExample `json:"inputExamples,omitempty"`
Execute ExecuteFunc `json:"-"`
ProviderOptions map[string]any `json:"providerOptions,omitempty"`
}
Tool represents a tool that can be called by the AI model.
Two shapes are supported:
- Function tool (default, Type=""): user-defined, has InputSchema + optional Execute. Provider serializes as a function declaration.
- Provider-defined tool (Type="provider"): a built-in the provider runs server-side (web_search, googleSearch, code_interpreter, ...). ProviderID carries the canonical id (e.g. "google.google_search") and Args carries the JSON-encoded arguments.
Mirrors ai-sdk's LanguageModelV4FunctionTool | LanguageModelV4ProviderDefinedTool union.
type ToolInputExample ¶
type ToolInputExample struct {
Input json.RawMessage `json:"input"`
}
ToolInputExample is a single example input for a tool. Mirrors ai-sdk's { input: JSONObject } shape.