Documentation
¶
Overview ¶
Package tool provides tool definition and execution for AI models. This mirrors the ai-sdk tool() and dynamicTool() functionality.
Index ¶
- Variables
- func OutputForError(err error) message.ToolResultOutput
- func SuccessOutput(r Result) message.ToolResultOutput
- 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) OutputSchema(schema json.RawMessage) *Definition
- func (d *Definition) OutputSchemaFromStruct(v any) *Definition
- func (d *Definition) Schema(schema json.RawMessage) *Definition
- func (d *Definition) SchemaFromStruct(v any) *Definition
- type DeniedError
- type ExecuteFunc
- type Executor
- type FatalToolError
- type Info
- type Kind
- 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
- type TypedDef
- type TypedFunc
Constants ¶
This section is empty.
Variables ¶
var DebugExecutor = os.Getenv("DEBUG_EXECUTOR") != ""
DebugExecutor enables debug logging for tool execution
Functions ¶
func OutputForError ¶ added in v0.1.4
func OutputForError(err error) message.ToolResultOutput
OutputForError classifies a non-nil tool error into the matching ToolResultOutput variant: a DeniedError (directly or wrapped) → ExecutionDeniedOutput; anything else → ErrorTextOutput. This is the single error-classification rule used everywhere a tool error is turned into a result.
func SuccessOutput ¶ added in v0.1.4
func SuccessOutput(r Result) message.ToolResultOutput
SuccessOutput builds the success ToolResultOutput for a Result: a ContentOutput when there are attachments (a leading text item plus file/image-data items), otherwise a plain TextOutput.
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) OutputSchema ¶
func (d *Definition) OutputSchema(schema json.RawMessage) *Definition
OutputSchema sets the JSON schema describing the tool's result.
func (*Definition) OutputSchemaFromStruct ¶
func (d *Definition) OutputSchemaFromStruct(v any) *Definition
OutputSchemaFromStruct generates the result JSON schema from a struct type.
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 DeniedError ¶ added in v0.1.4
type DeniedError struct {
Reason string
}
DeniedError marks a tool call the user or policy refused to run. A tool Execute returning a DeniedError (directly or wrapped) is classified as message.ExecutionDeniedOutput rather than an error — kept distinct so the model re-reasons correctly and the UI can show it differently.
func (DeniedError) Error ¶ added in v0.1.4
func (e DeniedError) Error() string
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 Kind ¶ added in v0.1.4
type Kind string
Kind classifies a Tool at the definition level. goai distinguishes the two definition kinds it sends to providers; the dynamic / provider-executed distinctions ai-sdk draws live on the tool *call* (see RawToolCall in parse.go), not on the definition.
const ( // KindFunction is a user-defined function tool (Type==""): InputSchema + // optional Execute, serialized as a function declaration. KindFunction Kind = "function" // KindProviderDefined is a built-in the provider runs server-side // (Type=="provider"): ProviderID + Args, no Execute. KindProviderDefined Kind = "provider" )
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"`
// Denied indicates the call was refused (permission/policy) rather than
// failed. Distinct from IsError so it serializes to execution-denied.
// DeniedReason is the optional human-facing reason.
Denied bool `json:"denied,omitempty"`
DeniedReason string `json:"denied_reason,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"`
// OutputSchema is an optional JSON Schema describing the tool's result.
// It travels with the tool for downstream consumers (MCP structuredContent,
// result validation) but is NOT part of the wire tool definition sent to
// providers like OpenAI, which advertise tool inputs only.
OutputSchema json.RawMessage `json:"outputSchema,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.
func ApplyToolOrder ¶ added in v0.1.4
ApplyToolOrder reorders an already-ordered tool slice so the tools named in toolOrder appear first in that order; tools not named keep their incoming relative order after them. A stable provider request shape lets providers reuse cached request prefixes. Mirrors ai-sdk's toolOrder option.
func (Tool) IsProviderTool ¶ added in v0.1.4
IsProviderTool reports whether the tool is provider-defined (run server-side by the provider rather than via a local Execute function).
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.
type TypedDef ¶
type TypedDef[In, Out any] struct { // contains filtered or unexported fields }
TypedDef builds a Tool from Go types: the input schema is reflected from In, the output schema from Out, and the typed function is wrapped into an ExecuteFunc (decode In, call, encode Out). The resulting tool.Tool is the same value goai's generation calls accept and agentsdk registers — define a tool once, use it everywhere.
func Typed ¶
Typed starts a type-safe tool definition. Build() reflects In→input schema and Out→output schema and wraps the typed Execute.
func (*TypedDef[In, Out]) Description ¶
Description sets the tool description.
func (*TypedDef[In, Out]) InputExample ¶
InputExample appends an example input (the typed value is JSON-encoded).