tool

package
v0.2.6 Latest Latest
Warning

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

Go to latest
Published: Dec 19, 2025 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package tool provides tool infrastructure for the gains library.

This package includes:

  • Registry and Handler types for tool management
  • Function binding with automatic schema generation from struct tags
  • Built-in tools for common operations (file, HTTP, search)
  • Client tools wrapping gains client capabilities (image, embedding, chat)

Basic Usage

Define tool arguments as a struct with tags, then use Bind or BindTo:

type WeatherArgs struct {
    Location string `json:"location" desc:"City name" required:"true"`
    Unit     string `json:"unit" desc:"Temperature unit" enum:"celsius,fahrenheit"`
}

// Create tool and handler
t, h := tool.MustBind("get_weather", "Get current weather",
    func(ctx context.Context, args WeatherArgs) (string, error) {
        return fmt.Sprintf(`{"temp": 72, "location": %q}`, args.Location), nil
    })

// Register to a registry
registry := tool.NewRegistry()
registry.MustRegister(t, h)

Supported Struct Tags

The following tags are supported for schema generation:

json:"name"      - Property name (required for inclusion)
desc:"text"      - Description for the model
required:"true"  - Mark field as required
enum:"a,b,c"     - Allowed values (comma-separated)
min:"0"          - Minimum value (numbers)
max:"100"        - Maximum value (numbers)
minLength:"1"    - Minimum string length
maxLength:"100"  - Maximum string length
pattern:"regex"  - String pattern
default:"value"  - Default value
minItems:"1"     - Minimum array items
maxItems:"10"    - Maximum array items

Built-in Tools

The package provides several built-in tools:

File Tools:

  • read_file: Read file contents
  • write_file: Write content to a file
  • list_directory: List directory contents

HTTP Tool:

  • http_request: Make HTTP requests

Search Tool:

  • search_files: Search for patterns in files

Client Tools (require gains client):

  • generate_image: Generate images from text
  • embed_text: Generate text embeddings
  • ask_assistant: Make LLM calls (sub-agent pattern)

Using Built-in Tools

registry := tool.NewRegistry()

// Register file tools with restrictions
tool.RegisterAll(registry, tool.FileTools(
    tool.WithBasePath("/workspace"),
    tool.WithAllowedExtensions(".go", ".md"),
))

// Register all standard tools
tool.RegisterAll(registry, tool.AllTools(client,
    tool.WithFileOptions(tool.WithBasePath("/workspace")),
    tool.WithHTTPOptions(tool.WithAllowedHosts("api.example.com")),
))

Tool Sets

Pre-configured tool collections are available:

  • FileTools(): read, write, list directory
  • WebTools(): HTTP requests
  • SearchTools(): file search
  • ClientTools(): image, embedding, chat (requires client)
  • StandardTools(): file, HTTP, search (no client required)
  • AllTools(): all tools including client tools

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BindTo

func BindTo[T any](r *Registry, name, description string, fn TypedHandler[T]) error

BindTo creates a tool from a typed function and registers it directly to a Registry. This is a convenience function combining Bind and Registry.Register.

Example:

type SearchArgs struct {
    Query string `json:"query" desc:"Search query" required:"true"`
    Limit int    `json:"limit" desc:"Max results" min:"1" max:"100"`
}

err := tool.BindTo(registry, "search", "Search the web",
    func(ctx context.Context, args SearchArgs) (string, error) {
        return doSearch(args.Query, args.Limit), nil
    })

func MustBindTo

func MustBindTo[T any](r *Registry, name, description string, fn TypedHandler[T])

MustBindTo is like BindTo but panics on error.

func MustRegisterAll

func MustRegisterAll(r *Registry, pairs []ToolPair)

MustRegisterAll is like RegisterAll but panics on error.

func MustRegisterFunc

func MustRegisterFunc[T any](r *Registry, name, description string, fn TypedHandler[T])

MustRegisterFunc is like RegisterFunc but panics on error.

func MustSchemaFor

func MustSchemaFor[T any]() json.RawMessage

MustSchemaFor is like SchemaFor but panics on error. This is a convenience re-export of gains.MustSchemaFor.

func RegisterAll

func RegisterAll(r *Registry, pairs []ToolPair) error

RegisterAll registers all tool pairs to a registry. Returns the first error encountered, or nil if all registrations succeed.

func RegisterFunc

func RegisterFunc[T any](r *Registry, name, description string, fn TypedHandler[T]) error

RegisterFunc registers a tool with a typed handler that automatically unmarshals the arguments JSON into the specified type T.

Example:

type SearchArgs struct {
    Query string `json:"query" desc:"Search query" required:"true"`
}

tool.RegisterFunc(registry, "search", "Search the web",
    func(ctx context.Context, args SearchArgs) (string, error) {
        return doSearch(args.Query), nil
    },
)

func SchemaFor

func SchemaFor[T any]() (json.RawMessage, error)

SchemaFor generates a JSON schema from a struct type T. This is a convenience re-export of gains.SchemaFor. See gains.SchemaFor for full documentation.

Types

type AllToolsOption

type AllToolsOption func(*allToolsConfig)

AllToolsOption configures the AllTools function.

func WithClientOptions

func WithClientOptions(opts ...ClientToolsOption) AllToolsOption

WithClientOptions sets options for client tools in AllTools.

func WithFileOptions

func WithFileOptions(opts ...FileToolOption) AllToolsOption

WithFileOptions sets options for file tools in AllTools.

func WithHTTPOptions

func WithHTTPOptions(opts ...HTTPToolOption) AllToolsOption

WithHTTPOptions sets options for HTTP tool in AllTools.

func WithSearchOptions

func WithSearchOptions(opts ...SearchToolOption) AllToolsOption

WithSearchOptions sets options for search tool in AllTools.

type ChatToolOption

type ChatToolOption func(*chatToolConfig)

ChatToolOption configures the chat tool.

func WithChatDefaults

func WithChatDefaults(opts ...ai.Option) ChatToolOption

WithChatDefaults sets default options for chat requests.

func WithChatName

func WithChatName(name string) ChatToolOption

WithChatName sets a custom name for the chat tool. Default is "ask_assistant".

func WithSystemPrompt

func WithSystemPrompt(prompt string) ChatToolOption

WithSystemPrompt sets a system prompt for the chat tool.

type ClientToolsOption

type ClientToolsOption func(*clientToolsConfig)

ClientToolsOption configures the ClientTools function.

func WithChatToolOptions

func WithChatToolOptions(opts ...ChatToolOption) ClientToolsOption

WithChatToolOptions sets options for the chat tool in ClientTools.

func WithEmbeddingToolOptions

func WithEmbeddingToolOptions(opts ...EmbeddingToolOption) ClientToolsOption

WithEmbeddingToolOptions sets options for the embedding tool in ClientTools.

func WithImageToolOptions

func WithImageToolOptions(opts ...ImageToolOption) ClientToolsOption

WithImageToolOptions sets options for the image tool in ClientTools.

type EmbeddingClient

type EmbeddingClient interface {
	Embed(ctx context.Context, texts []string, opts ...ai.EmbeddingOption) (*ai.EmbeddingResponse, error)
}

EmbeddingClient is the interface for embedding capabilities.

type EmbeddingToolOption

type EmbeddingToolOption func(*embeddingToolConfig)

EmbeddingToolOption configures the embedding tool.

func WithEmbeddingDefaults

func WithEmbeddingDefaults(opts ...ai.EmbeddingOption) EmbeddingToolOption

WithEmbeddingDefaults sets default options for embedding generation.

func WithEmbeddingName

func WithEmbeddingName(name string) EmbeddingToolOption

WithEmbeddingName sets a custom name for the embedding tool. Default is "embed_text".

type ErrClientTool

type ErrClientTool struct {
	Name string
}

ErrClientTool is returned when Execute is called on a client-side tool. Client tools should be executed by the frontend, not the backend.

func (*ErrClientTool) Error

func (e *ErrClientTool) Error() string

Error returns a formatted error message indicating this is a client tool.

type ErrToolAlreadyRegistered

type ErrToolAlreadyRegistered struct {
	Name string
}

ErrToolAlreadyRegistered is returned when registering a tool with a duplicate name.

func (*ErrToolAlreadyRegistered) Error

func (e *ErrToolAlreadyRegistered) Error() string

Error returns a formatted error message including the duplicate tool name.

type ErrToolExecution

type ErrToolExecution struct {
	Name string
	Err  error
}

ErrToolExecution wraps errors from tool handler execution.

func (*ErrToolExecution) Error

func (e *ErrToolExecution) Error() string

Error returns a formatted error message including the tool name and cause.

func (*ErrToolExecution) Unwrap

func (e *ErrToolExecution) Unwrap() error

Unwrap returns the underlying error for use with errors.Is and errors.As.

type ErrToolNotFound

type ErrToolNotFound struct {
	Name string
}

ErrToolNotFound is returned when a tool call references an unregistered tool.

func (*ErrToolNotFound) Error

func (e *ErrToolNotFound) Error() string

Error returns a formatted error message including the tool name.

type FileToolOption

type FileToolOption func(*fileToolConfig)

FileToolOption configures file tools.

func WithAllowedExtensions

func WithAllowedExtensions(exts ...string) FileToolOption

WithAllowedExtensions restricts file operations to specific file extensions.

func WithBasePath

func WithBasePath(path string) FileToolOption

WithBasePath restricts file operations to a specific directory. All paths will be resolved relative to this base path.

func WithMaxFileSize

func WithMaxFileSize(bytes int64) FileToolOption

WithMaxFileSize sets the maximum file size for read/write operations. Default is 10MB.

type HTTPToolOption

type HTTPToolOption func(*httpToolConfig)

HTTPToolOption configures the HTTP tool.

func WithAllowedHosts

func WithAllowedHosts(hosts ...string) HTTPToolOption

WithAllowedHosts restricts requests to specific hosts only.

func WithBlockedHosts

func WithBlockedHosts(hosts ...string) HTTPToolOption

WithBlockedHosts blocks requests to specific hosts.

func WithHTTPClient

func WithHTTPClient(c *http.Client) HTTPToolOption

WithHTTPClient sets a custom HTTP client.

func WithHTTPTimeout

func WithHTTPTimeout(d time.Duration) HTTPToolOption

WithHTTPTimeout sets the request timeout. Default is 30 seconds.

func WithMaxResponseSize

func WithMaxResponseSize(bytes int64) HTTPToolOption

WithMaxResponseSize sets the maximum response body size. Default is 1MB.

type Handler

type Handler func(ctx context.Context, call ai.ToolCall) (string, error)

Handler is a function that executes a tool call and returns a result. The context supports cancellation and timeout. The call contains the tool name, ID, and arguments as a JSON string. Returns the result content string, or an error if execution failed.

func Bind

func Bind[T any](name, description string, fn TypedHandler[T]) (ai.Tool, Handler, error)

Bind creates a Tool and Handler from a typed function. The JSON schema for tool parameters is automatically generated from struct tags on type T.

Example:

type TranslateArgs struct {
    Text string `json:"text" desc:"Text to translate" required:"true"`
    From string `json:"from" desc:"Source language" required:"true"`
    To   string `json:"to" desc:"Target language" required:"true"`
}

t, h := tool.Bind("translate", "Translate text between languages",
    func(ctx context.Context, args TranslateArgs) (string, error) {
        // implementation
        return translated, nil
    })

func MustBind

func MustBind[T any](name, description string, fn TypedHandler[T]) (ai.Tool, Handler)

MustBind is like Bind but panics on error. This is useful for initialization code where errors should be fatal.

func NewChatTool

func NewChatTool(c chat.Client, opts ...ChatToolOption) (ai.Tool, Handler)

NewChatTool creates a tool that makes LLM calls (sub-agent pattern). This allows an agent to delegate tasks to another LLM call.

func NewEditFileTool

func NewEditFileTool(opts ...FileToolOption) (ai.Tool, Handler)

NewEditFileTool creates a tool for editing file contents. Supports string replacement and line operations (insert, delete, replace).

func NewEmbeddingTool

func NewEmbeddingTool(c EmbeddingClient, opts ...EmbeddingToolOption) (ai.Tool, Handler)

NewEmbeddingTool creates a tool for generating text embeddings. The tool accepts an array of texts and returns their embedding vectors.

func NewHTTPTool

func NewHTTPTool(opts ...HTTPToolOption) (ai.Tool, Handler)

NewHTTPTool creates a tool for making HTTP requests.

func NewImageTool

func NewImageTool(c ImageClient, opts ...ImageToolOption) (ai.Tool, Handler)

NewImageTool creates a tool for generating images. The tool accepts a prompt and optional size, quality, and style parameters.

func NewListDirTool

func NewListDirTool(opts ...FileToolOption) (ai.Tool, Handler)

NewListDirTool creates a tool for listing directory contents.

func NewReadFileTool

func NewReadFileTool(opts ...FileToolOption) (ai.Tool, Handler)

NewReadFileTool creates a tool for reading file contents.

func NewSearchTool

func NewSearchTool(opts ...SearchToolOption) (ai.Tool, Handler)

NewSearchTool creates a tool for searching file contents with regex.

func NewWriteFileTool

func NewWriteFileTool(opts ...FileToolOption) (ai.Tool, Handler)

NewWriteFileTool creates a tool for writing file contents.

type ImageClient

type ImageClient interface {
	GenerateImage(ctx context.Context, prompt string, opts ...ai.ImageOption) (*ai.ImageResponse, error)
}

ImageClient is the interface for image generation capabilities.

type ImageToolOption

type ImageToolOption func(*imageToolConfig)

ImageToolOption configures the image generation tool.

func WithImageDefaults

func WithImageDefaults(opts ...ai.ImageOption) ImageToolOption

WithImageDefaults sets default options for image generation.

func WithImageName

func WithImageName(name string) ImageToolOption

WithImageName sets a custom name for the image tool. Default is "generate_image".

type Registration

type Registration struct {
	Tool    ai.Tool
	Handler Handler
}

Registration holds a tool and its handler for fluent registration.

func Func

func Func[T any](name, description string, fn TypedHandler[T]) Registration

Func creates a Registration with automatic schema generation from the typed handler. Panics if schema generation fails.

Example:

registry := tool.NewRegistry().Add(
    tool.Func("weather", "Get weather", func(ctx context.Context, args WeatherArgs) (string, error) {
        return getWeather(args.Location), nil
    }),
    tool.Func("search", "Search web", searchHandler),
)

func WithHandler

func WithHandler(name, description string, schema json.RawMessage, h Handler) Registration

WithHandler creates a Registration from a Handler and schema. Use this when you have a pre-built Handler implementation.

func WithTool

func WithTool(t ai.Tool, h Handler) Registration

WithTool creates a Registration from an existing Tool and Handler. Use this when you have pre-built tool definitions.

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry manages registered tools and their handlers. It is safe for concurrent use.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates an empty tool registry.

func (*Registry) Add

func (r *Registry) Add(regs ...Registration) *Registry

Add registers one or more tools to the registry. Panics if any tool is already registered. Returns the registry for fluent chaining.

Example:

registry := tool.NewRegistry().Add(
    tool.Func("weather", "Get weather", weatherFn),
    tool.Func("search", "Search web", searchFn),
    tool.Func("calc", "Calculate", calcFn),
)

func (*Registry) ClientToolNames

func (r *Registry) ClientToolNames() []string

ClientToolNames returns the names of all registered client tools.

func (*Registry) Execute

func (r *Registry) Execute(ctx context.Context, call ai.ToolCall) (ai.ToolResult, error)

Execute runs the handler for a tool call and returns a ToolResult. If the tool is not found, returns ErrToolNotFound. If the tool is a client-side tool, returns ErrClientTool. If the handler returns an error, the error is captured in ToolResult.IsError and the error message is returned as the content (allowing the model to recover).

func (*Registry) Get

func (r *Registry) Get(name string) (Handler, bool)

Get retrieves a handler by tool name. Returns the handler and true if found, or nil and false if not found.

func (*Registry) GetTool

func (r *Registry) GetTool(name string) (ai.Tool, bool)

GetTool retrieves a tool definition by name. Returns the tool and true if found, or empty tool and false if not found.

func (*Registry) IsClientTool

func (r *Registry) IsClientTool(name string) bool

IsClientTool returns true if the named tool is a client-side tool.

func (*Registry) Len

func (r *Registry) Len() int

Len returns the number of registered tools.

func (*Registry) MustRegister

func (r *Registry) MustRegister(tool ai.Tool, handler Handler)

MustRegister is like Register but panics on error.

func (*Registry) Names

func (r *Registry) Names() []string

Names returns the names of all registered tools.

func (*Registry) Register

func (r *Registry) Register(tool ai.Tool, handler Handler) error

Register adds a tool with its handler to the registry. Returns an error if a tool with the same name is already registered.

func (*Registry) RegisterClientTool

func (r *Registry) RegisterClientTool(tool ai.Tool) error

RegisterClientTool registers a tool definition without a handler. Client tools are executed by the frontend/client, not the backend. When the agent encounters a call to a client tool, it emits events but does not execute locally.

func (*Registry) RegisterClientTools

func (r *Registry) RegisterClientTools(tools []ai.Tool) error

RegisterClientTools registers multiple client tool definitions.

func (*Registry) Tools

func (r *Registry) Tools() []ai.Tool

Tools returns all registered tool definitions. This is used to pass the tools to the ChatProvider.

func (*Registry) Unregister

func (r *Registry) Unregister(name string)

Unregister removes a tool from the registry. It is a no-op if the tool is not registered.

type SearchToolOption

type SearchToolOption func(*searchToolConfig)

SearchToolOption configures the search tool.

func WithExcludePatterns

func WithExcludePatterns(patterns ...string) SearchToolOption

WithExcludePatterns sets glob patterns for files to exclude.

func WithIncludePatterns

func WithIncludePatterns(patterns ...string) SearchToolOption

WithIncludePatterns sets glob patterns for files to include.

func WithMaxResults

func WithMaxResults(n int) SearchToolOption

WithMaxResults limits the number of search results. Default is 100.

func WithSearchPath

func WithSearchPath(path string) SearchToolOption

WithSearchPath sets the base path for searches.

type ToolPair

type ToolPair struct {
	Tool    ai.Tool
	Handler Handler
}

ToolPair holds a tool definition and its handler for easy registration.

func AllTools

func AllTools(c *client.Client, opts ...AllToolsOption) []ToolPair

AllTools returns all standard tools: file, HTTP, search, and client tools. Pass nil for the client parameter to exclude client-specific tools.

func ClientTools

func ClientTools(c *client.Client, opts ...ClientToolsOption) []ToolPair

ClientTools returns tools for image, embedding, and chat capabilities. Only tools for supported features are returned.

func FileTools

func FileTools(opts ...FileToolOption) []ToolPair

FileTools returns read, write, edit, and list directory tools.

func SearchTools

func SearchTools(opts ...SearchToolOption) []ToolPair

SearchTools returns the search tool.

func StandardTools

func StandardTools(opts ...AllToolsOption) []ToolPair

StandardTools returns non-client tools: file, HTTP, and search tools. Use this when you don't need image, embedding, or chat tools.

func WebTools

func WebTools(opts ...HTTPToolOption) []ToolPair

WebTools returns the HTTP request tool.

type TypedHandler

type TypedHandler[T any] func(ctx context.Context, args T) (string, error)

TypedHandler is a function that executes a tool call with typed arguments. The args parameter is automatically unmarshaled from the tool call's JSON arguments.

Jump to

Keyboard shortcuts

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