tools

package
v0.43.0 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2026 License: Apache-2.0 Imports: 12 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 tools defines the Tool interface and extension utilities.

It includes:

  • Tool contract and typed parameter schema
  • Concurrent-safe registry
  • Middleware composition (`Chain`) for logging, timing, timeout, and rate limits

Package tools defines the Tool interface and a thread-safe Registry for managing agent tools.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrUser flags errors caused by bad user/caller input.
	ErrUser = errors.New("tools: user error")

	// ErrTransient flags transient failures that may succeed on retry.
	ErrTransient = errors.New("tools: transient error")

	// ErrPermanent flags non-recoverable downstream failures.
	ErrPermanent = errors.New("tools: permanent error")

	// ErrTimeout flags a deadline the framework itself imposed — a tool-call
	// budget, a query timeout, a poll ceiling. It is deliberately distinct
	// from context.DeadlineExceeded, which any enclosing context also
	// produces: a layer that sets its own deadline needs to know whether the
	// deadline that fired was *its own* before reporting one. Attach it with
	// DeadlineCause and test with TimedOut.
	ErrTimeout = errors.New("tools: deadline exceeded")
)

Error classification sentinels. Tool authors wrap their real error with one of these to let the agent loop and clients distinguish the failure category:

  • ErrUser — the caller supplied bad input; show the message to the user, do not retry.
  • ErrTransient — transient downstream failure (rate limit, 5xx, network timeout); retrying later may succeed.
  • ErrPermanent — non-recoverable downstream failure (bad config, permanent 4xx from an external API); retries will keep failing.

Wrap pattern:

return tools.Result{}, fmt.Errorf("rate limited: %w", tools.ErrTransient)

The loop surfaces the classification on the error stream event so clients can render differently (toast for ErrUser, retry banner for ErrTransient, hard fail for ErrPermanent). errors.Is against the sentinels is the match mechanism; use ClassifyError to get the sentinel directly from an arbitrary error.

Functions

func ClassifyError

func ClassifyError(err error) error

ClassifyError returns the classification sentinel that err unwraps to, or nil when err matches none of them. Consumers use this for concise branching in error handlers:

switch tools.ClassifyError(err) {
case tools.ErrUser:      // show to user, don't retry
case tools.ErrTransient: // maybe retry with backoff
case tools.ErrPermanent: // give up
default:                 // unknown — default conservative handling
}

Passing nil returns nil.

func DeadlineCause added in v0.43.0

func DeadlineCause(what string, d time.Duration) error

DeadlineCause builds the cause value to hand to context.WithTimeoutCause, naming the budget that will have elapsed. what should read as the thing being bounded ("tool call", "sql query"), not the tool's name.

ctx, cancel := context.WithTimeoutCause(ctx, d, tools.DeadlineCause("sql query", d))

The returned error satisfies errors.Is(err, ErrTimeout) and carries the duration in its message, so a model-facing report can name the budget without the reporting site holding it.

func RegisterFunc

func RegisterFunc[T any](reg Registerer, name, description string, fn func(ctx context.Context, args T) (Result, error), opts ...FuncToolOpts)

RegisterFunc registers a tool built from a strongly-typed function, dropping the per-tool struct/Descriptor/Execute boilerplate. The parameter schema is generated via SchemaFor[T] unless FuncToolOpts.Schema overrides it; argsJSON arriving from the LLM is unmarshalled into T before fn runs.

Example:

type LookupArgs struct {
    UserID string `json:"user_id" description:"the user to look up"`
}

tools.RegisterFunc(reg, "lookup_user", "Look up a user by ID",
    func(ctx context.Context, a LookupArgs) (tools.Result, error) {
        return tools.Text("found " + a.UserID), nil
    })

Compared with the struct-and-methods form (~40 LOC), the typed-fn form is one declaration + the function body. The trade-off is that adopters who need to customize Descriptor flags pass FuncToolOpts.

The reg parameter accepts anything implementing Registerer — that's the in-tree *Registry as well as adopter wrappers like builder.GlobalCatalog. The interface keeps the call site readable when the same tools register into both the agent registry and the catalog: pass either pointer directly.

func ReportProgress

func ReportProgress(ctx context.Context, msg string)

ReportProgress emits a progress message if a reporting function was injected into ctx by WithProgressFunc. It is a no-op when called outside an agent loop (e.g. in tests that do not set up the reporting function).

Call this inside Execute to emit status updates while a long-running operation is in progress:

tools.ReportProgress(ctx, "Polling operation (30s elapsed)…")

func TimedOut added in v0.43.0

func TimedOut(ctx context.Context) bool

TimedOut reports whether ctx is done because a deadline set with DeadlineCause elapsed. It answers "was it *my* deadline?" — an enclosing context that expires or is cancelled first leaves its own cause in place, so this returns false and the caller correctly reports cancellation instead of claiming its own timeout fired.

Prefer this over comparing ctx.Err() to context.DeadlineExceeded, which cannot tell the two apart.

func ToolCallIDFromContext

func ToolCallIDFromContext(ctx context.Context) string

ToolCallIDFromContext returns the correlation ID set by WithToolCallID, or "" when called outside an agent loop.

func WithProgressFunc

func WithProgressFunc(ctx context.Context, f func(msg string)) context.Context

WithProgressFunc injects a progress-reporting callback into ctx. The agent loop calls this before invoking Execute so that long-running tools can emit "tool_progress" stream events without knowing about the streaming layer.

The returned context should be passed directly to tool.Execute.

func WithToolCallID

func WithToolCallID(ctx context.Context, id string) context.Context

WithToolCallID injects a per-Execute correlation ID into ctx. The agent loop generates one ID per tool dispatch (separate from the LLM-issued tool-call ID, which is not always unique across providers — Gemini reuses tool names). Middleware that logs tool I/O reads the ID via ToolCallIDFromContext to pair entry and exit lines reliably even when SpeculativeTools=true interleaves parallel calls.

Types

type Degradation added in v0.38.0

type Degradation struct {
	Reason     string
	Artifacts  []string
	Unreliable []string
}

Degradation marks a tool call that half-succeeded: the expensive, durable part of the work landed but the derived bookkeeping did not. A tool that writes a file and then fails to update its index is the canonical case — returning an error would invite a retry that duplicates the write, and returning a clean Result would hide the inconsistency.

A tool raises one by returning a normal (non-error) Result with this field set. The loop appends a short partial-success note to the text the model sees, and rolls every degradation of the turn into a terminal DegradedEvent for the host.

Reason is a one-line human summary. Artifacts names what did land and must not be discarded or redone; Unreliable names the state a subsequent run should treat as suspect and repair. Both are opaque identifiers chosen by the tool (paths, IDs, table names).

type Embedder

type Embedder interface {
	Embed(ctx context.Context, texts []string) ([][]float32, error)
}

Embedder produces fixed-size vector representations of text.

Implementations live in pkg/llm/openai and pkg/llm/gemini (each exports an Embedder backed by that vendor's embeddings API). A single Embed call should accept a batch and return one vector per input, in order. All returned vectors must share the same dimensionality.

type FuncToolOpts

type FuncToolOpts struct {
	RequiresConfirmation bool
	Cacheable            bool
	Inline               bool
	Display              ToolDisplay

	// Schema, when non-nil, replaces the reflected SchemaFor[T] output.
	// Reflection reads enum values from struct tags, which are
	// compile-time constants — so a tool whose valid parameter values are
	// only known at runtime (names discovered from disk, IDs read from a
	// database) cannot express them any other way.
	//
	// T still decodes argsJSON, so the override must stay structurally
	// compatible with T: a property the override declares but T lacks is
	// dropped silently on unmarshal.
	Schema *ToolSchema
}

FuncToolOpts tunes the ToolDescriptor that RegisterFunc builds. The zero value gives a sensible default — non-confirmation, non-cacheable, non-inline, default Display. Override individual fields when a tool needs caching, HITL approval, or custom UI hints.

type LoggingOption

type LoggingOption func(*loggingConfig)

LoggingOption customizes WithLogging. Use the With* helpers below.

func WithArgsTruncation

func WithArgsTruncation(maxBytes int) LoggingOption

WithArgsTruncation caps the args string included on the entry log line at maxBytes; longer args are replaced with their prefix plus a length marker. 0 (default) disables truncation. Use to keep log lines bounded when tools accept large blobs (image data URIs, multi-KB SQL, etc).

func WithContextExtractor

func WithContextExtractor(fn func(context.Context) []slog.Attr) LoggingOption

WithContextExtractor lets adopters surface ctx-scoped values (trace_id, user_id, request tags) on every tool log line without writing a custom slog.Handler bridge. The extractor runs on every Execute and its attrs are appended to the entry/exit log records. nil extractors are a no-op.

tools.WithLogging(logger,
    tools.WithContextExtractor(func(ctx context.Context) []slog.Attr {
        return []slog.Attr{
            slog.String("trace_id", trace.SpanContextFromContext(ctx).TraceID().String()),
            slog.String("user_id", auth.UserIDFromContext(ctx)),
        }
    }),
)

func WithSuccessLevel

func WithSuccessLevel(level slog.Level) LoggingOption

WithSuccessLevel sets the slog level for the entry ("tool call") and successful exit ("tool ok") log lines. Errors always log at slog.LevelError regardless. Default is slog.LevelInfo. Demote to slog.LevelDebug in production to keep error visibility while silencing healthy traffic:

tools.WithLogging(prodLogger, tools.WithSuccessLevel(slog.LevelDebug))

type MediaPart

type MediaPart struct {
	MIMEType string
	Data     []byte
	Text     string
}

MediaPart is a leaf-package multi-modal output unit. Tools that emit images or files populate this; the agent loop adapts to history.MediaPart at the boundary. Kept inline so pkg/tools stays a leaf package (no upward dep on pkg/history).

type Middleware

type Middleware func(next Tool) Tool

Middleware wraps a Tool to add cross-cutting behaviour (logging, timing, rate limiting…). Pattern: each Middleware receives the next Tool in the chain and returns a decorated Tool.

func WithLogging

func WithLogging(logger *slog.Logger, opts ...LoggingOption) Middleware

WithLogging logs each tool call and result via slog. The tool-call correlation ID set by the agent loop (see ToolCallIDFromContext) is included on entry and exit so log scrapers can pair them reliably even when SpeculativeTools=true interleaves parallel calls.

reg.Register(tools.Chain(myTool, tools.WithLogging(slog.Default())))

Pair with WithContextExtractor to surface trace IDs, tenant tags, etc.

func WithRateLimit

func WithRateLimit(rps float64) Middleware

WithRateLimit throttles tool execution to at most rps calls per second. Excess calls are delayed (not dropped) and respect context cancellation. Each application of this middleware creates an independent rate limiter, so applying it separately to each tool gives per-tool limits.

func WithSchemaValidation

func WithSchemaValidation() Middleware

WithSchemaValidation validates argsJSON against the tool's ToolDescriptor.Parameters before delegating to Execute. It implements a practical subset of JSON Schema: JSON well-formedness, object-type check, required-property check, and per-property primitive-type check (string / number / integer / boolean / array / object). Unknown properties are accepted (draft-07 default). No enum, pattern, minimum, additionalProperties, $ref, or nested property recursion beyond the top level.

Tools whose Descriptor().Parameters is a zero value (no type, no properties, no required) are passed through unchanged.

The schema is captured once per wrap so Descriptor() is not re-read on every call.

func WithTimeout

func WithTimeout(d time.Duration) Middleware

WithTimeout wraps each Execute call with a per-call deadline. The parent context's deadline, if shorter, still takes precedence.

A failure caused by this middleware's own deadline is wrapped so the error names the elapsed budget and satisfies errors.Is(err, ErrTimeout). An outer deadline or a cancellation is left untouched: the tool did not exceed *its* budget, and reporting otherwise would misattribute a turn the caller cut short. The wrapped error still unwraps to whatever the tool returned, so existing context.DeadlineExceeded matches keep working.

func WithTiming

func WithTiming(onDone func(toolName string, d time.Duration, err error)) Middleware

WithTiming calls onDone with the tool name, wall-clock duration, and error after each Execute call. Zero external dependencies — wire to any metrics system:

tools.WithTiming(func(name string, d time.Duration, err error) {
    prometheus.ObserveToolLatency(name, d.Seconds())
})

type Registerer

type Registerer interface {
	Register(t Tool)
}

Registerer is the small surface RegisterFunc needs from a tool container. *Registry implements it; adopter-side wrappers like builder.GlobalCatalog implement it too because they expose the same Register(Tool) shape. Using an interface here lets RegisterFunc target either without the caller bridging.

type Registry

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

Registry manages the available tools for an agent. Safe for concurrent use.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates an empty tool registry.

func (*Registry) All

func (r *Registry) All() []Tool

All returns every registered tool in deterministic alphabetical order. Debug wrapping is applied when enabled.

func (*Registry) Clone

func (r *Registry) Clone() *Registry

Clone returns a shallow copy of the registry with the same tools, debug flag, and logger. Changes to the clone do not affect the original.

func (*Registry) EnableDebug

func (r *Registry) EnableDebug(logger *slog.Logger)

EnableDebug turns on per-call logging for every tool in this registry. Pass nil to use slog.Default(). Calls are idempotent — calling again swaps the logger.

reg.EnableDebug(nil)                          // use default logger
reg.EnableDebug(slog.New(slog.NewJSONHandler(os.Stdout, nil)))

func (*Registry) Get

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

Get retrieves a tool by name. Returns false if not found. When debug mode is enabled the tool is transparently wrapped with WithLogging.

func (*Registry) Len

func (r *Registry) Len() int

Len returns the number of registered tools. Cheap branch for hot-path gates that only need to know "how many" — avoids the sort+slice+copy cost of All.

func (*Registry) Register

func (r *Registry) Register(t Tool)

Register adds a tool to the registry. Overwrites any existing tool with the same name.

type Result

type Result struct {
	Text       string
	Structured any
	Parts      []MediaPart
	Degraded   *Degradation
}

Result is the return value of Tool.Execute.

Text is what flows back to the LLM as the tool_result content — the only field that round-trips to the model. Tools that only return text populate Text alone (use Text() for a one-liner).

Structured is an optional typed payload delivered to the agent loop's OnToolResult hook so post-execution mutators can work with fields instead of substring-replacing markdown. Nil when the tool has nothing structured to surface.

Parts is optional multi-modal output for providers that accept non-text tool results. Empty when the tool returns text only.

Degraded is set by a tool that half-succeeded — see Degradation. Nil for the overwhelming majority of calls; the loop pays one nil check.

func Text

func Text(s string) Result

Text is a convenience constructor for text-only results:

return tools.Text("ok"), nil

func (Result) String added in v0.38.0

func (r Result) String() string

String returns the result's model-facing text, so a Result formats sensibly with %s / %q / %v instead of dumping a struct with a raw pointer in it.

Load-bearing beyond convenience: without a String method, `go vet`'s printf check rejects `%s`/`%q` on a Result because of the *Degradation field, and that failure lands in adopters' builds — including callers who never touch the degradation feature. Do not remove it without re-checking `go vet` in a module that only consumes this package.

Deliberately renders Text alone. Structured, Parts, and Degraded are separate channels with their own consumers; folding them in here would make a debug line's output depend on which of them a tool happened to populate.

type Selector

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

Selector performs dynamic tool selection: given a natural-language query it returns the top-K tools from a Registry ranked by cosine similarity between the query embedding and each tool's pre-computed description embedding.

A selector is built once per Registry; tool embeddings are computed eagerly on construction so request-path cost is one Embed(query) + O(N) cosine.

Register new tools on the underlying Registry after construction by calling Refresh(ctx) to re-embed.

func NewSelector

func NewSelector(ctx context.Context, registry *Registry, embedder Embedder, topK int, opts ...SelectorOption) (*Selector, error)

NewSelector builds a Selector over registry with the given embedder. topK is the number of tools to return from Select (pinned tools are added on top and do not count toward the limit). Embeds every tool description immediately.

topK <= 0 disables ranking: Select returns all tools (useful as a test hook or to opt out at runtime without nil-checking).

func (*Selector) Refresh

func (s *Selector) Refresh(ctx context.Context) error

Refresh re-embeds all tool descriptions currently in the registry. Call after Register-ing new tools on the underlying registry.

func (*Selector) Select

func (s *Selector) Select(ctx context.Context, query string) ([]Tool, error)

Select returns the top-K tools most relevant to query, plus any pinned tools. If query is empty or topK <= 0 the full tool list is returned. The result preserves Registry's alphabetical ordering for determinism.

Never returns an error solely because a tool was added/removed after construction — tools not in the embedding set are simply skipped. Call Refresh to pick them up for future Select calls.

func (*Selector) SelectRegistry

func (s *Selector) SelectRegistry(ctx context.Context, query string) (*Registry, error)

SelectRegistry is a convenience that returns a fresh Registry populated with the tools Select would return. The returned Registry is safe to pass to an LLMProvider that expects *tools.Registry (e.g. AgentLoop's LLM field).

type SelectorOption

type SelectorOption func(*Selector)

SelectorOption configures a Selector at construction time.

func WithPinned

func WithPinned(names ...string) SelectorOption

WithPinned marks tool names that must always be included in Select results, regardless of similarity score. Useful for tools the agent should never be denied (e.g. "ask_user", "final_answer").

type Tool

type Tool interface {
	Descriptor() ToolDescriptor
	Execute(ctx context.Context, argsJSON string) (Result, error)
}

Tool is the minimal interface every agent tool must satisfy.

Descriptor returns the static metadata block — name, description, parameters schema, capability flags. Wrappers preserve every capability flag trivially because Descriptor is one accessor returning a value struct (no method-set interface dance).

Execute runs the tool with the given JSON arguments and returns a Result. Errors are returned alongside the zero Result so the loop can format the failure as a tool-error message.

func Chain

func Chain(t Tool, mws ...Middleware) Tool

Chain applies middlewares to t in declaration order: the first middleware is the outermost wrapper (called first on Execute). Equivalent to A(B(C(t))) for Chain(t, A, B, C).

type ToolDescriptor

type ToolDescriptor struct {
	Name                 string
	Description          string
	Parameters           ToolSchema
	RequiresConfirmation bool
	// Cacheable is true when the tool's results are deterministic and safe
	// for the agent loop to cache by (name, argsJSON). Tools that hit live
	// data (prices, time, remote APIs without idempotency) leave this false.
	Cacheable bool
	// Inline is true when the tool's text output should be streamed to the
	// frontend as a content event in addition to being fed back to the LLM
	// as a tool result. Used by image/video tools whose result is a markdown
	// URL the FE needs to render directly.
	Inline bool
	// Display carries UI-facing metadata (label, description, category, icon
	// hint). Use DefaultDisplay(name, description) for tools without special
	// UI treatment.
	Display ToolDisplay
}

ToolDescriptor carries the static metadata of a Tool. Returned by Tool.Descriptor() — every capability flag the loop reads lives here so wrappers preserve them for free (the previous design used opt-in method-set interfaces that dropped silently on wrap).

type ToolDisplay

type ToolDisplay struct {
	// Label is a short human-readable name shown above/beside the tool
	// invocation in the UI — e.g. "Looking up game" for a find_game tool.
	// When empty, clients typically fall back to Tool.Name().
	Label string

	// Description is a longer user-facing description, may differ from
	// Tool.Description (which is model-facing). When empty, clients may
	// fall back to Tool.Description() or omit entirely.
	Description string

	// Category is a logical grouping key — "search", "io", "control",
	// "memory", etc. Clients use this to group tool calls visually or
	// to apply category-level styling. Free-form; no enum enforced.
	Category string

	// IconHint is a string key clients map to their own icon registry
	// — e.g. "magnifier" or "database". Not an icon URL; just a hint
	// that lets the library stay render-agnostic.
	IconHint string
}

ToolDisplay carries UI-facing metadata for a tool — friendly label, user-facing description, logical category, and an icon hint. Clients rendering tool calls in a chat UI read Display() on every Tool to drive consistent labeling without having to hard-code per-tool friendly names.

Zero-value fields let the client fall back to whatever default it prefers (typically Name() and Description() from the Tool itself). DefaultDisplay is a one-liner for tools that don't want to invent separate UI copy.

func DefaultDisplay

func DefaultDisplay(name, description string) ToolDisplay

DefaultDisplay returns a ToolDisplay with Label and Description populated from the given name and description. Tools that don't want to invent separate UI copy can return this directly from their Display() method:

func (t *MyTool) Display() tools.ToolDisplay {
    return tools.DefaultDisplay(t.Name(), t.Description())
}

type ToolSchema

type ToolSchema struct {
	Type       string         `json:"type"`                 // typically "object"
	Properties map[string]any `json:"properties,omitempty"` // parameter definitions
	Required   []string       `json:"required,omitempty"`   // required parameter names
}

ToolSchema defines the JSON Schema for a tool's parameters. It maps directly to the OpenAI/Anthropic function calling schema format.

func SchemaFor

func SchemaFor[T any]() ToolSchema

SchemaFor derives a ToolSchema from a Go struct type using reflection. It removes the boilerplate of hand-writing map[string]any literals for every tool's parameter schema.

Supported field types

  • string → "string"
  • bool → "boolean"
  • all int / uint variants → "integer"
  • float32, float64 → "number"
  • slice / array of a supported element type → "array" with items
  • struct → nested "object"
  • pointer to any of the above → same type, optional

Supported struct tags

  • `json:"name"` property name (defaults to the Go field name)
  • `json:"-"` skip this field
  • `json:",omitempty"` mark the field optional
  • `description:"..."` human-readable description sent to the LLM
  • `enum:"a,b,c"` restrict the field to a fixed set of values
  • `required:"true"`/`"false"` force the required state, overriding omitempty

A field is required by default; it becomes optional when the field type is a pointer, the json tag carries `omitempty`, or the `required` tag is explicitly set to "false".

Example

type SearchArgs struct {
    Query string `json:"query" description:"The search query"`
    Topic string `json:"topic,omitempty" description:"Search category" enum:"general,news"`
    Days  int    `json:"days,omitempty" description:"Limit results to the last N days"`
}

func (t *SearchTool) ParametersSchema() tools.ToolSchema {
    return tools.SchemaFor[SearchArgs]()
}

SchemaFor panics when T is not a struct type or when a field has an unsupported type. This is deliberate: schemas are built at startup, so a panic surfaces misuse immediately instead of silently dropping fields the LLM would then fail to populate.

Directories

Path Synopsis
Package toolsfake provides a configurable tools.Tool fake for agent tests.
Package toolsfake provides a configurable tools.Tool fake for agent tests.

Jump to

Keyboard shortcuts

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