Suryanand/ Bootcamp
suryanand.com ↗Let's talk
← AgentsAI guideBeginner#agents#react#tool-use#function-calling
Frame · ai-engineering / agents / 03-react-and-tool-use-loops.mdGuide 027 / 103

ReAct and the tool-use loop

ReAct (short for "reasoning and acting") is the idea underneath almost every agent you will build. The 2022 paper by Yao and colleagues showed that letting a model alternate between thinking out loud and taking actions, then reading the observations, beat both reasoning-only and acting-only approaches on question answering and interactive tasks. Today you rarely write ReAct prompts by hand, because native tool calling bakes the pattern into the API, but the mental model is still the right one.

Why it matters

Before ReAct, you had two camps. Chain-of-thought prompting let models reason, but they reasoned over stale internal knowledge and hallucinated facts. Action-only agents could look things up, but they had no explicit plan and wandered. ReAct combined them: the reasoning trace decides what to look up next, and the observations ground the reasoning in real data.

Understanding this loop helps you debug. When an agent fails, it is almost always one of three things: it reasoned badly about what to do next, it called a tool with bad input, or the tool returned something unhelpful. Tracing the thought, action and observation at each step tells you which.

How it works

The original ReAct format was plain text: the model wrote Thought:, then Action: search[query], the harness parsed it, ran the tool, and appended Observation: before calling the model again. Modern APIs replace the brittle text parsing with structured tool calls:

  • You declare tools with a JSON Schema for their inputs.
  • The model returns a tool_use block (Anthropic) or a function call item (OpenAI) with arguments that match the schema.
  • You execute the tool and send back a tool_result tied to the call's ID.
  • The model may emit visible text or extended thinking before the call, which plays the role of the old Thought: line.
Rendering diagram…

Models can also request several tools in one turn (parallel tool calls). Your harness should run independent calls concurrently and return all results in the next message.

Tool design is prompt engineering

Anthropic's advice is to put as much effort into the agent-computer interface (ACI) as you would into a human-facing UI. In my experience this is where most quality gains hide:

  • Name and describe tools from the model's point of view. Say what the tool does, when to use it, and when not to use it, especially if two tools overlap.
  • Include example inputs and edge cases in the description.
  • Make mistakes hard ("poka-yoke"). Anthropic found that requiring absolute file paths removed a whole class of errors from relative paths. Use enums instead of free text where you can.
  • Return useful errors. "Order ID must look like A-1234" lets the model self-correct. A stack trace does not.
  • Keep outputs tight. Paginate, truncate and summarise large results. Every token you return is context the model has to carry for the rest of the run.
  • Fewer, higher-level tools beat many thin wrappers. A schedule_meeting tool is easier to use correctly than separate list_calendars, find_free_slot and create_event calls.

Reference architecture

Inside the harness, a tool call goes through more than just "run the function":

Rendering diagram…

Validation, policy and truncation are where you protect both the system and the context window.

Code

The Anthropic TypeScript SDK's tool runner implements the loop for you, including schema validation with Zod. Here is a small research agent with two tools and a bounded number of iterations.

import Anthropic from "@anthropic-ai/sdk";
import { betaZodTool } from "@anthropic-ai/sdk/helpers/beta/zod";
import { z } from "zod";

const client = new Anthropic();

const searchDocs = betaZodTool({
  name: "search_docs",
  description:
    "Full-text search over the internal handbook. Use for policy questions. " +
    "Returns up to 5 snippets with their page IDs. Do not use for people lookups.",
  inputSchema: z.object({
    query: z.string().describe("Keywords, e.g. 'parental leave UK'"),
  }),
  run: async ({ query }) => {
    // Replace with a real search call
    return JSON.stringify([{ pageId: "hr-12", snippet: `Results for ${query}` }]);
  },
});

const readPage = betaZodTool({
  name: "read_page",
  description: "Fetch the full text of a handbook page by the ID returned from search_docs.",
  inputSchema: z.object({ pageId: z.string().regex(/^[a-z]+-\d+$/) }),
  run: async ({ pageId }) => `Full text of ${pageId} ...`,
});

const runner = client.beta.messages.toolRunner({
  model: "claude-opus-5-5",
  max_tokens: 2048,
  max_iterations: 6,
  tools: [searchDocs, readPage],
  messages: [{ role: "user", content: "How many weeks of parental leave do UK staff get?" }],
});

for await (const message of runner) {
  for (const block of message.content) {
    if (block.type === "tool_use") console.log("action:", block.name, block.input);
    if (block.type === "text") console.log("text:", block.text);
  }
}

Iterating over the runner lets you log each thought and action as it happens, which is exactly the ReAct trace you want in your observability tool. If you need approvals or custom routing per call, drop down to the manual loop.

Trade-offs and pitfalls

  • Looping on the same action. A model that keeps calling search with near-identical queries is stuck. Detect repeated calls and either inject a hint or stop.
  • Context bloat. Each observation stays in the conversation. Long runs need truncation, result clearing or summarisation (see the memory doc in this track).
  • Too many tools. Large tool lists cost tokens on every call and make selection harder. Group tools, load them on demand, or split work across specialised agents.
  • Overlapping tools. If two tools could plausibly answer the same question, the model will pick inconsistently. Merge them or make the boundary explicit.
  • Hidden reasoning is not an audit log. Visible "thoughts" help debugging, but the model's stated reason is not guaranteed to be its real reason. Log actions and observations as the source of truth.
  • Treat observations as untrusted. A fetched web page that says "ignore previous instructions" is a prompt injection, not an instruction.

Checklist

  • Each tool has a description that says when to use it and when not to.
  • Inputs use strict schemas, enums and formats that make wrong calls hard.
  • Tool errors return actionable messages to the model.
  • Tool outputs are paginated or truncated to a known size.
  • Parallel tool calls run concurrently and return together.
  • The loop caps iterations and detects repeated identical calls.
  • Every thought, action and observation is captured in traces.

Further reading

Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.