tool

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: Apache-2.0 Imports: 17 Imported by: 4 modules, 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 typed, provider-neutral tool contract used by the agent runtime.

A Tool describes itself with a Spec and executes a Call. Constructors in this package generate JSON Schema from Go input types and validate model arguments before a handler observes them.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrIDRequired is returned when creating a tool without a name.
	ErrIDRequired = fmt.Errorf("tool: id is required")
	// ErrExecuteRequired is returned when creating a tool without a handler.
	ErrExecuteRequired = fmt.Errorf("tool: execute function is required")
	// ErrInvalidSchema is returned when a tool's parameter schema cannot be
	// built or is not a JSON object.
	ErrInvalidSchema = fmt.Errorf("tool: invalid schema")
	// ErrInvalidInput is returned when tool input cannot be decoded or does
	// not satisfy the tool schema.
	ErrInvalidInput = fmt.Errorf("tool: invalid input")
	// ErrOutputEncode is returned when a tool output cannot be encoded.
	ErrOutputEncode = fmt.Errorf("tool: cannot encode output")
)

Functions

func Definition

func Definition(t Tool) llm.ToolDefinition

Definition converts a tool into the provider-neutral definition sent to a model. Nil and typed-nil tools produce an empty definition.

func Definitions

func Definitions(tools []Tool) []llm.ToolDefinition

Definitions converts tools into model definitions, skipping nil entries.

func GenerateSchema

func GenerateSchema[T any](opts ...SchemaOption) (map[string]any, error)

GenerateSchema generates a JSON Schema map for T and reports unsupported types instead of silently emitting an incorrect schema.

func GenerateSchemaFromType

func GenerateSchemaFromType(t reflect.Type, opts ...SchemaOption) (map[string]any, error)

GenerateSchemaFromType generates a JSON Schema map for a given reflect.Type and reports unsupported types.

func IsNilTool

func IsNilTool(t Tool) bool

IsNilTool reports whether t is nil or wraps a typed nil implementation.

func Validate

func Validate(schema map[string]any, input []byte) error

Validate checks input against the dependency-free JSON Schema subset used by generated tool schemas.

Supported keywords: type, properties, required, additionalProperties, items, enum, const, minimum, maximum, exclusiveMinimum, exclusiveMaximum, minLength, maxLength, pattern, minItems, maxItems, anyOf, oneOf, and allOf. Unknown keywords are ignored so provider-specific annotations (description, title, default, format) do not reject valid input.

Types

type Annotations

type Annotations struct {
	// ReadOnly means the tool does not mutate state.
	ReadOnly bool
	// Destructive means the tool may delete or overwrite data.
	Destructive bool
	// Idempotent means repeating the same call has the same effect.
	Idempotent bool
	// OpenWorld means the tool interacts with an unbounded external system.
	OpenWorld bool
}

Annotations describes a tool's side effects.

type BaseTool

type BaseTool[In any, Out any] struct {
	// contains filtered or unexported fields
}

BaseTool is the generic, typed implementation of Tool.

func MustNew

func MustNew[In any, Out any](cfg Config[In, Out]) *BaseTool[In, Out]

MustNew creates a tool or panics on invalid configuration.

func New

func New[In any, Out any](cfg Config[In, Out]) (*BaseTool[In, Out], error)

New creates a typed tool. It fails on missing configuration, unsupported input types, or an invalid custom schema.

func (*BaseTool[In, Out]) Description

func (t *BaseTool[In, Out]) Description() string

Description returns the tool description.

func (*BaseTool[In, Out]) Execute

func (t *BaseTool[In, Out]) Execute(ctx context.Context, call Call) (Result, error)

Execute validates and decodes the call arguments, invokes the handler, and normalizes the output.

func (*BaseTool[In, Out]) ID

func (t *BaseTool[In, Out]) ID() string

ID returns the tool name.

func (*BaseTool[In, Out]) Parameters

func (t *BaseTool[In, Out]) Parameters() map[string]any

Parameters returns a copy of the input schema.

func (*BaseTool[In, Out]) Spec

func (t *BaseTool[In, Out]) Spec() Spec

Spec returns a copy of the tool specification.

type Call

type Call struct {
	// ID is the unique call identifier. The runner guarantees it is non-empty
	// and unique within a run.
	ID string
	// Index is the canonical part index within the assistant message. Tool
	// call parts may follow text and reasoning parts, so it is not necessarily
	// the call's position among the calls.
	Index int
	// Name is the requested tool name.
	Name string
	// Kind classifies the execution path. Empty means function.
	Kind llm.ToolKind
	// Arguments is the validated JSON input.
	Arguments json.RawMessage
	// IdempotencyKey is stable across retries of the same call when the runner
	// can derive one.
	IdempotencyKey string
}

Call is one model-requested tool invocation.

type Config

type Config[In any, Out any] struct {
	// ID is the unique tool name. Required.
	ID string
	// Description explains the tool.
	Description string
	// Parameters overrides the generated JSON Schema. If nil, a schema is
	// generated from In.
	Parameters map[string]any
	// SchemaOptions configures generated schemas.
	SchemaOptions []SchemaOption
	// Annotations describes side effects.
	Annotations Annotations
	// ExecutionMode declares the tool's scheduling preference. The zero value
	// is parallel. The runner currently executes calls sequentially.
	ExecutionMode ExecutionMode
	// Strict marks the schema as strict for providers that support it.
	Strict bool
	// Execute is the typed handler. Required.
	Execute ExecuteFunc[In, Out]
}

Config configures a typed tool.

type ExecuteFunc

type ExecuteFunc[In any, Out any] func(ctx context.Context, input In) (Out, error)

ExecuteFunc is the typed execution function of a tool.

type ExecutionMode

type ExecutionMode string

ExecutionMode is a tool's scheduling preference.

The runner currently executes every call sequentially, so the mode is advisory metadata for schedulers that can parallelize safely.

const (
	// ExecutionParallel marks a tool as safe to run alongside other calls from
	// the same assistant message.
	ExecutionParallel ExecutionMode = "parallel"
	// ExecutionSequential requires a scheduler to finish this call before
	// starting the next one.
	ExecutionSequential ExecutionMode = "sequential"
)

type Result

type Result struct {
	// Content contains the message parts returned by the tool (text, images, audio, video, documents).
	Content []llm.Part `json:"content"`
	// Data contains optional structured result data for programmatic consumption.
	Data any `json:"data,omitempty"`
}

Result represents the execution output of a tool, supporting both textual and rich multipart components.

func NewFileResult

func NewFileResult(text string, part llm.Part) Result

NewFileResult creates a tool result with optional text and a file part.

func (Result) Parts

func (r Result) Parts() ([]llm.Part, error)

Parts returns the content to deliver to the model. If Content is empty and Data is set, Data is encoded as a JSON text part.

func (Result) Text

func (r Result) Text() string

Text returns the aggregated textual output of all text parts in the result.

type SchemaOption

type SchemaOption func(*schemaConfig)

SchemaOption configures schema generation options.

func WithStrictSchema

func WithStrictSchema(strict bool) SchemaOption

WithStrictSchema configures the generator for strict JSON schema providers. It sets additionalProperties to false on objects and requires every field.

type Spec

type Spec struct {
	// Name is the unique tool name exposed to the model.
	Name string
	// Description explains what the tool does and when to use it.
	Description string
	// InputSchema is the JSON Schema for the tool input.
	InputSchema map[string]any
	// Annotations describes side effects.
	Annotations Annotations
	// ExecutionMode declares the tool's scheduling preference.
	ExecutionMode ExecutionMode
	// Strict asks the provider to enforce the input schema exactly.
	Strict bool
}

Spec is the immutable description of a tool.

type Tool

type Tool interface {
	// Spec returns the tool description.
	Spec() Spec
	// Execute runs the tool. Implementations must honor ctx.
	Execute(ctx context.Context, call Call) (Result, error)
}

Tool is an executable capability.

type Validator

type Validator interface {
	Validate() error
}

Validator is an optional interface for input types that validate themselves after JSON decoding and schema validation.

Jump to

Keyboard shortcuts

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