Call tools (the ReAct loop)¶
Tool calling lets the model decide, mid-conversation, which of your Go functions to invoke. The chat client runs the ReAct (Reason → Act → Observe) loop for you: you define the tools, and the client manages the back-and-forth until the model produces a final text answer.
Tool calling is supported by claude, openai, openai-compatible, azure-openai,
gemini, gemini-vertex, bedrock and vllm. claude-local and codex-local support
it through the MCP bridge, so they need import _ "gitlab.com/phpboyscout/go/chat-mcptools".
agy-local does not support it (SetTools returns an error for any tool).
How the loop works¶
When you call client.Chat(ctx, prompt) with tools registered:
- The model reasons about the prompt and may decide to call a tool.
- If it does, the client invokes your
Handler, captures the result, and injects it back into the conversation. - Steps 1–2 repeat until the model returns a final response, or
Config.MaxStepsis reached (default 20).
Chat returns the final text. A tool error (handler error, or tool-not-found)
is fed back to the model as an error string, so the loop continues rather than
aborting.
Exhausting MaxSteps is a failure, not a truncation: the call returns an
error reading <Provider> reached maximum ReAct steps (20) without a final
answer and no partial text. If you hit it routinely, the task is too big for
one call rather than the cap being too low.
Step 1: define your tools¶
Each chat.Tool has a name, description, a JSON Schema for its parameters, and a
handler. Generate the schema from an exported, tagged parameter struct with
chat.GenerateSchema:
import (
"context"
"encoding/json"
"os"
"gitlab.com/phpboyscout/go/chat"
)
type ReadFileParams struct {
Path string `json:"path" jsonschema_description:"Relative path to the file"`
}
var readFileTool = chat.Tool{
Name: "read_file",
Description: "Read the contents of a file at the given path",
Parameters: chat.GenerateSchema[ReadFileParams](),
Handler: func(ctx context.Context, args json.RawMessage) (any, error) {
var p ReadFileParams
if err := json.Unmarshal(args, &p); err != nil {
return nil, err
}
content, err := os.ReadFile(p.Path)
if err != nil {
return nil, err
}
return string(content), nil
},
}
A handler returns (any, error). A string result is passed back verbatim;
any other value is JSON-marshalled first.
chat.GenerateSchema returns *jsonschema.Schema, which is what
Tool.Parameters and Config.ResponseSchema both take, so nothing needs
asserting. It returned any before v0.8.0, so code carrying a
.(*jsonschema.Schema) assertion no longer compiles and the assertion should
just be deleted.
Every type is written out inline, except one that contains itself, such as a tree
node with a list of nodes. That one goes in $defs and is referenced with $ref.
A provider may limit the references it accepts, so try such a schema against yours.
Three shapes can't be reflected, and overflow the stack: a struct that embeds itself,
one with a field of its own type tagged json:",inline", and a pointer type defined
as a pointer to itself.
What reaches the model¶
The schema is sent whole: its JSON encoding, every keyword included. $defs and
$ref, enum, additionalProperties, minimum and the rest reach the model, from
these releases
(spec 0043):
| Provider | Sent whole from | Sent before that | Parameters nil |
|---|---|---|---|
claude |
chat-anthropic v0.22.0 | properties and required |
Sent as an empty object |
openai, openai-compatible |
chat-openai v0.22.0 | properties and required |
Refused |
azure-openai |
the chat-openai-azure release that requires chat-openai v0.22.0 | properties and required |
Refused |
gemini, gemini-vertex |
chat-gemini v0.21.0 | type, description, properties, required, items and string enums |
No schema sent |
bedrock |
always; the rules below from chat-bedrock v0.9.0 | the whole schema | Sent as an empty object |
vllm |
chat-vllm v0.5.0 | properties and required |
Refused |
An empty required: [] doesn't survive the encoding, and means the same as none.
A number is sent with the digits in that encoding on claude, the OpenAI providers,
gemini, gemini-vertex, bedrock and vllm, from the releases after chat-anthropic
v0.22.2, chat-openai v0.22.1, chat-gemini v0.21.1, chat-bedrock v0.9.1 and chat-vllm
v0.5.1. Struct tags, Go integers and json.Number keep
the number as you wrote it (1.0, or a whole number past 2^53). A Go float doesn't: 1.0
encodes as 1. Nor does a schema read with json.Unmarshal, which turns the numbers in
enum, const and default into floats first, so 12345678901234567890 becomes
12345678901234567000.
A tool's input is always an object, so these rules apply on the API providers:
- A schema with no
typeis sent as"type": "object". So is an empty&jsonschema.Schema{}. - A schema that names anything else is refused by
SetToolsandProposeToolCalls, with an error naming the tool, before any request. That covers atypeinExtras, a root$refinto$defsthat leads to another type, and the schema that encodes asfalse.
claude-local and codex-local refuse nothing at SetTools. The bridge applies the rule when
it publishes the tools for a call, and for now reads only the Type field
(chat-mcptools#3).
Strict modes stay off. additionalProperties: false is passed on as a keyword,
and does not turn on OpenAI's strict function calling.
On vllm, nothing makes the model keep to the schema by default. The adapter leaves tool
choice at auto and strict unset, so validate arguments in the handler, unless the server's
operator started it with --tool-strict-level parameter, which pins arguments to the schema on
a tool parser with structural-tag support. How a model's chat template renders $defs and
$ref is unproved, because the spec's live run didn't include vLLM.
Step 2: register the tools and chat¶
SetTools replaces the client's entire tool set on every call and never merges,
so a stale handler can never linger.
client, err := chat.New(ctx, chat.Settings{Config: chat.Config{
Provider: chat.ProviderClaude,
SystemPrompt: "Use the provided tools to explore before answering.",
MaxSteps: 15, // cap ReAct iterations
}})
if err != nil {
return err
}
if err := client.SetTools([]chat.Tool{readFileTool}); err != nil {
return err
}
answer, err := client.Chat(ctx, "Read go.mod and tell me the module path.")
Handlers are plain closures, so capture any dependency (a config, a DB handle,
an afero.Fs) from the enclosing scope.
Step 3: observe execution¶
Every tool call is logged through the injected *slog.Logger: the call at
INFO, the parameters at DEBUG, and the outcome at INFO/WARN. No extra
wiring is required.
INFO Tool Call tool=read_file
DEBUG Tool Parameters tool=read_file args={"path":"go.mod"}
INFO Tool executed successfully tool=read_file
Parallel tool execution¶
When a provider returns more than one tool call in a single step, they can
run concurrently instead of sequentially, cutting latency for I/O-bound tools.
Opt in with ParallelTools:
cfg := chat.Config{
Provider: chat.ProviderClaude,
ParallelTools: true,
MaxParallelTools: 3, // optional; defaults to 5
}
Behaviour:
- Off by default. Sequential execution unless opted in.
- Activates only when a single step returns more than one call; a lone call always takes the sequential path.
- Results are returned in the same order as the input calls, regardless of completion order.
- Context cancellation propagates to all in-flight tool goroutines.
- Tool errors become error strings in the conversation (same as sequential) and never abort the loop.
- Bounded by
MaxParallelTools(default 5) to prevent goroutine storms.
Thread safety: each handler receives an independent json.RawMessage and
returns an independent result. Parallel execution is safe as long as your
handlers do not share mutable state without synchronisation.
Panics become tool-error content¶
Tool handlers run model-generated, potentially adversarial input. A handler that
panics is recovered and converted to a tool-error string
(Error: tool handler panicked: <value>) fed back to the model as conversation
content (exactly like a returned error) rather than crashing the process.
This holds on both the sequential and parallel paths (in the parallel path a
handler runs in a bare goroutine, where an unrecovered panic would otherwise be
fatal). The recovered value is also logged at Error level. Treat the recover
as a safety net, not a substitute for returning errors explicitly.
Telling the model exactly what failed¶
A handler that returns an error has it shown to the model as Error: <message>.
When the failure is itself something the model should read in a particular form
(a code it can act on, or whether retrying could help), return a
*chat.ToolFailure instead. Its Content is what the model reads, verbatim,
and its Cause stays with your logs:
Handler: func(ctx context.Context, args json.RawMessage) (any, error) {
rows, err := query(ctx, args)
if errors.Is(err, errBusy) {
return nil, &chat.ToolFailure{
Content: `{"failure":{"code":"busy","retryable":true}}`,
Cause: err,
}
}
// ...
},
Either way the call is marked as failed. chat.ToolResult.IsError is set for
every failure, including an unknown tool and a recovered panic. A provider whose
API has an error marker for tool results passes it on, so the model is told the
call failed rather than having to infer it from the text: chat-anthropic from
v0.21.0, chat-gemini from v0.20.0 and chat-bedrock from v0.8.0
(spec 0041).
The OpenAI API has no such marker, so there the text is all the model gets.
On OpenAI, tool calls go through the Responses API¶
From chat-openai v0.21.0, a Chat, StreamChat or ProposeToolCalls that
offers tools under openai is sent to OpenAI's Responses API instead of Chat
Completions. Reasoning models such as the default gpt-6.1-sol refuse function
tools on Chat Completions while reasoning is on, and Responses accepts them.
Nothing changes in how you define tools or read the result:
Config.Effortapplies to tool calls. Left unset, the model reasons at its own default, which on easy prompts can be no reasoning at all.- Reasoning carries within one call, not across turns. Each step of a loop
sees the reasoning from the steps before it. The next
Chatstarts without that reasoning, because the conversation history has no place to keep it. chatopenai.WithSeedcannot be combined with tools. The Responses API has no seed, soSetToolsandProposeToolCallson a seeded client return an error rather than quietly dropping the seed.- A tool step cut off at
Config.MaxTokensis a*chat.TruncatedError. The half-written tool call never runs. - Calls without tools,
Ask,openai-compatibleandazure-openaistay on Chat Completions.
The design is in spec 0042.
Combining tools with structured output¶
Add, Chat, and Ask share one conversation history on a client instance, so
you can let the model explore with tools, then ask for a typed summary:
// Explore with tools enabled
_, err = client.Chat(ctx, "Examine the database package and list what you find.")
// Ask for a structured summary of the same conversation
var report DatabaseReport
err = client.Ask(ctx, "Produce a structured summary of your exploration.", &report)
Related¶
- Stream responses: tool calls are surfaced as stream events too.
- Architecture & the seams: the loop in depth.
- pkg.go.dev reference: the
Tooltype.