Skip to main content

07 - AI Agents: Architecture and Implementation Patterns

How to write an agent with tool calling: the loop and its caps, confined tools, orchestration, history and LangGraph, with listings that were actually run.

What do you think about this article?

At a Glance

How to write an agent with tool calling: the loop and its caps, confined tools, orchestration, history and LangGraph, with listings that were actually run.

You have a task that a single question to the model does not solve: to answer "how much does the monitor cost with a 15% discount?" you first have to look up the price and then do the arithmetic, and you do not know in advance how many steps will be needed. An agent is exactly this: a loop in which the model chooses the next step among the tools you declared, your code runs it and hands the result back, until the model says it is done. The model executes nothing; it writes a tool request, and everything that happens afterwards is decided by your code. That is why the quality of an agent depends less on the model than on the loop around it: when it stops, what it can touch, what it remembers.

The method is the series' method: no model was called. Anthropic's SDK (1.8.0) runs with a fake fetch that returns hand-written responses, so the loop code is the real one and the "model" texts are a script. The rest of the listings do not need a model: tools, orchestrators, history trimming and a LangGraph graph whose nodes are functions. For context, see Integrating the OpenAI and Anthropic APIs; for the general theory of agents the AI Agents series starts with OODA, ReAct and tool calling.

The loop: who decides and who executes

Anthropic's documentation on handling tool calls describes the protocol. When the model wants to use a tool, the response has stop_reason equal to tool_use and contains tool_use blocks with an id, the name of the tool and the input. Your code runs the function, then replies with a user message that contains a tool_result block for each tool_use_id, with is_error: true if the execution failed. Two format rules are easy to break: the results must immediately follow the message that requested them, and inside the message the tool_result blocks come before any text.

Listing 1: the agent loop, with a fake fetch following a script (Node 24.11, @anthropic-ai/sdk 1.8.0, run)
import Anthropic from "@anthropic-ai/sdk";

// ---- Script: each scenario is a list of ready-made responses, in order. No model. ----
type Block = { type: "text"; text: string } | { type: "tool_use"; id: string; name: string; input: unknown };
const msg = (stop_reason: string, content: Block[]) => ({
  id: "msg_test", type: "message", role: "assistant", model: "test-model", content,
  stop_reason, stop_sequence: null, usage: { input_tokens: 10, output_tokens: 5 },
});

function clientWithScript(script: ReturnType<typeof msg>[]) {
  let calls = 0;
  const fakeFetch: typeof fetch = async () => Response.json(script[Math.min(calls++, script.length - 1)]);
  const client = new Anthropic({ apiKey: "test", fetch: fakeFetch, maxRetries: 0 });
  return { client, calls: () => calls };
}

// ---- The tools: fixed test data, not a real catalog. ----
const CATALOG: Record<string, number> = { "keyboard": 80, "monitor": 250 };
const tools = {
  find_price: async (i: any) => {
    const p = CATALOG[String(i.product)];
    if (p === undefined) throw new Error(`unknown product: ${i.product}`);
    return String(p);
  },
  apply_discount: async (i: any) => String(Number(i.price) * (1 - Number(i.percent) / 100)),
} as const;
const schemas: Anthropic.Tool[] = [
  { name: "find_price", description: "Price of a catalog product", input_schema: { type: "object", properties: { product: { type: "string" } }, required: ["product"] } },
  { name: "apply_discount", description: "Apply a percentage discount to a price", input_schema: { type: "object", properties: { price: { type: "number" }, percent: { type: "number" } }, required: ["price", "percent"] } },
];

// ---- The loop: the model chooses, the code executes and returns the result. ----
export async function runAgent(client: Anthropic, question: string, maxTurns = 5) {
  const history: Anthropic.MessageParam[] = [{ role: "user", content: question }];
  for (let turn = 1; turn <= maxTurns; turn++) {
    const r = await client.messages.create({ model: "test-model", max_tokens: 1024, tools: schemas, messages: history });
    if (r.stop_reason === "end_turn") {
      const text = r.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("");
      return { outcome: "completed", turns: turn, text };
    }
    if (r.stop_reason !== "tool_use") return { outcome: `stopped: ${r.stop_reason}`, turns: turn, text: "" };

    history.push({ role: "assistant", content: r.content });
    const results: Anthropic.ToolResultBlockParam[] = [];
    for (const b of r.content) {
      if (b.type !== "tool_use") continue;
      const fn = (tools as Record<string, (i: unknown) => Promise<string>>)[b.name];
      try {
        if (!fn) throw new Error(`nonexistent tool: ${b.name}`);
        results.push({ type: "tool_result", tool_use_id: b.id, content: await fn(b.input) });
      } catch (e) {
        results.push({ type: "tool_result", tool_use_id: b.id, content: (e as Error).message, is_error: true });
      }
    }
    history.push({ role: "user", content: results }); // tool_result only, no added text
  }
  return { outcome: "turn limit reached", turns: maxTurns, text: "" };
}

// The loop found in many tutorials: it handles only end_turn and tool_use. With any other stop_reason
// it leaves the history unchanged and repeats the same request until the turn cap.
async function naiveLoop(client: Anthropic, maxTurns: number) {
  const history: Anthropic.MessageParam[] = [{ role: "user", content: "Discounted price?" }];
  for (let turn = 0; turn < maxTurns; turn++) {
    const r = await client.messages.create({ model: "test-model", max_tokens: 1024, messages: history });
    if (r.stop_reason === "end_turn") return "completed";
    // (the tool_use branch would be here; for max_tokens there is no branch)
  }
  return "cap reached with no answer";
}

const use = (id: string, name: string, input: unknown): Block => ({ type: "tool_use", id, name, input });
const scenarios: Record<string, ReturnType<typeof msg>[]> = {
  "two tools and an answer": [
    msg("tool_use", [use("t1", "find_price", { product: "monitor" })]),
    msg("tool_use", [use("t2", "apply_discount", { price: 250, percent: 15 })]),
    msg("end_turn", [{ type: "text", text: "The monitor with a 15% discount costs 212.5." }]),
  ],
  "invented tool": [
    msg("tool_use", [use("t1", "delete_everything", {})]),
    msg("end_turn", [{ type: "text", text: "I can't do that." }]),
  ],
  "truncated answer": [msg("max_tokens", [{ type: "text", text: "The monitor costs" }])],
  "never stops": [msg("tool_use", [use("t1", "find_price", { product: "keyboard" })])],
};

for (const [name, script] of Object.entries(scenarios)) {
  const { client, calls } = clientWithScript(script);
  const r = await runAgent(client, "Discounted price?", 4);
  console.log(`${name.padEnd(26)} -> ${r.outcome}, ${calls()} calls${r.text ? `, "${r.text}"` : ""}`);
}

const naive = clientWithScript(scenarios["truncated answer"]);
console.log(`naive loop, truncated answer -> ${await naiveLoop(naive.client, 4)}, ${naive.calls()} identical calls`);

// Output:
// two tools and an answer    -> completed, 3 calls, "The monitor with a 15% discount costs 212.5."
// invented tool              -> completed, 2 calls, "I can't do that."
// truncated answer           -> stopped: max_tokens, 1 calls
// never stops                -> turn limit reached, 4 calls
// naive loop, truncated answer -> cap reached with no answer, 4 identical calls

The heart is runAgent. At every turn it asks for a response and looks at stop_reason: with end_turn it returns the text; with tool_use it runs the tools and adds to the history the assistant message and the one with the results; with any other value it stops and says so. A tool's errors (a name invented by the model, a nonexistent product) do not bring the loop down: they become a tool_result with is_error, so the model sees the error and can correct itself, as in the "invented tool" scenario. The turn cap (maxTurns) is the last safety net: the "never stops" scenario shows that a model can ask for the same tool forever.

The "truncated answer" scenario is the most common defect of loops written in a hurry. The page on stop reasons lists seven values (end_turn, max_tokens, stop_sequence, tool_use, pause_turn, refusal, model_context_window_exceeded), and a loop that handles two of them with an if silently repeats the same request with the same history: the last line of the output shows four identical calls, that is, four times the cost without a step forward. The SDK also offers an automatism, the Tool Runner, which handles the loop for you; writing the loop by hand is worthwhile when you want to control caps, permissions and logging, as here.

ReAct and tool calling

ReAct (Yao et al., 2022) is the idea of having the model produce reasoning and actions in alternation: the reasoning helps keep track of the plan and handle exceptions, the actions go and fetch information from an external source. In two of the tasks in the abstract the environment is a simple Wikipedia API, and the text of each step had to be interpreted by the program. Native tool calling moves that interpretation inside the API: the tool request arrives already structured, with name and parameters, without having to parse free text with a regular expression. The loop in listing 1 is ReAct without the fragile part.

Tools are the part that can do damage

Everything the model can cause goes through the tools, and the model writes their parameters while also reading text you do not control: the same documentation warns that tool results often carry external content (web pages, incoming mail, uploaded files) to be treated as untrusted, because whoever writes them can insert instructions to hijack the model. Two common tools show the typical defect and the fix.

Listing 2: a calculator without Function() and a confined file reader (Node 24.11, run on Linux)
import { mkdtemp, writeFile, realpath, readFile, symlink, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve, sep } from "node:path";

// 1. Why Function() is not a calculator: the expression the model (or whoever talks to it) writes can reach everything.
//    This test is harmless: it only reads the type of "process".
const fromFunction = Function('"use strict"; return typeof process')();
console.log("Function(): the expression sees process ->", fromFunction);

// 2. A recursive-descent calculator: it accepts numbers, + - * / and parentheses, and nothing else.
export function calculate(expression: string): number {
  const t = expression.replace(/\s+/g, "");
  let i = 0;
  const number = (): number => {
    if (t[i] === "(") { i++; const v = sum(); if (t[i++] !== ")") throw new Error("unclosed parenthesis"); return v; }
    if (t[i] === "-") { i++; return -number(); }
    const m = /^\d+(\.\d+)?/.exec(t.slice(i));
    if (!m) throw new Error(`character not allowed at position ${i}`);
    i += m[0].length;
    return Number(m[0]);
  };
  const product = (): number => {
    let v = number();
    while (t[i] === "*" || t[i] === "/") { const op = t[i++]; const d = number(); v = op === "*" ? v * d : v / d; }
    return v;
  };
  const sum = (): number => {
    let v = product();
    while (t[i] === "+" || t[i] === "-") { const op = t[i++]; const d = product(); v = op === "+" ? v + d : v - d; }
    return v;
  };
  const r = sum();
  if (i !== t.length) throw new Error(`character not allowed at position ${i}`);
  if (!Number.isFinite(r)) throw new Error("result is not finite (division by zero?)");
  return r;
}
for (const e of ["15/100*1250", "2+(3*4)", "process.exit()", "1/0"]) {
  try { console.log(`calculate(${JSON.stringify(e)}) =`, calculate(e)); }
  catch (err) { console.log(`calculate(${JSON.stringify(e)}) rejected:`, (err as Error).message); }
}

// 3. A file reader confined to one folder: the path chosen by the model does not leave the base.
export async function readConfined(base: string, relative: string): Promise<string> {
  const root = await realpath(base);
  const inside = (p: string) => p === root || p.startsWith(root + sep);
  const candidate = resolve(root, relative); // normalizes ".." and accepts absolute paths as they are
  if (!inside(candidate)) throw new Error("path outside the allowed folder");
  const real = await realpath(candidate); // a symbolic link can lead outside: second check
  if (!inside(real)) throw new Error("the link points outside the allowed folder");
  return readFile(real, "utf-8");
}
const folder = await mkdtemp(join(tmpdir(), "agent-"));
await writeFile(join(folder, "note.txt"), "test content");
await symlink("/etc/hostname", join(folder, "shortcut.txt")); // a link that leaves the folder
for (const p of ["note.txt", "../../../etc/hostname", "/etc/hostname", "shortcut.txt"]) {
  try { console.log(`read ${p} ->`, await readConfined(folder, p)); }
  catch (err) { console.log(`read ${p} ->`, (err as Error).message); }
}
await rm(folder, { recursive: true }); // clean up the temporary folder

// Output:
// Function(): the expression sees process -> object
// calculate("15/100*1250") = 187.5
// calculate("2+(3*4)") = 14
// calculate("process.exit()") rejected: character not allowed at position 0
// calculate("1/0") rejected: result is not finite (division by zero?)
// read note.txt -> test content
// read ../../../etc/hostname -> path outside the allowed folder
// read /etc/hostname -> path outside the allowed folder
// read shortcut.txt -> the link points outside the allowed folder

The "safe" calculator in many examples builds an expression and passes it to Function. The first line of the output shows why it is not: inside Function the expression sees process, that is, the whole program. The listing's calculator is instead a recursive-descent parser that accepts numbers, four operations and parentheses: process.exit() is rejected at the first character, and so is 1/0, which would otherwise return Infinity and end up in the model's reasoning as if it were a number.

The file reader applies the same idea to paths: resolve normalizes the path and the inside check rejects everything that leaves the folder, including absolute paths and ../../ sequences. The second check, after realpath, stops symbolic links that point elsewhere: the last line of the output is the case in which the file seems to be inside the folder and its content is not. It works on Linux (it uses /etc/hostname); the same criterion applies elsewhere. For a tool that writes, deletes or spends money, the extra step is a person's approval before execution, not better validation.

Several agents: sequence, parallel, supervisor

When a single loop becomes too big the tasks are split among specialized agents. Three patterns cover almost everything, each with its weak point:

  • Sequence: the output of one agent is the input of the next; the failure of one link stops the chain.
  • Parallel: several agents work on the same input and an aggregator merges the results; you need a maximum time per agent.
  • Supervisor: an agent decides whom to delegate to step by step; you need a cap on decisions.

The choice depends on how well the path is known. If the steps are fixed (analyze, verify, write the report) the sequence is the simplest to understand and to run in tests; if the tasks are independent the parallel reduces the wait; the supervisor costs more and is justified only when the path is not predictable. Every level adds calls to the model, hence cost and noise: start from the sequence and move up only if needed.

Listing 3: the three patterns with agents that are plain functions (Node 24.11, run)
// An "agent" here is an async function: text in, text out. Inside there could be a loop with a model.
type Agent = (input: string) => Promise<string>;
const pause = (ms: number) => new Promise((r) => setTimeout(r, ms));

const analyze: Agent = async (c) => `analysis(${c})`;
const audit: Agent = async (c) => `audit(${c})`;
const summarize: Agent = async (c) => `report(${c})`;
const broken: Agent = async () => { throw new Error("service unreachable"); };
const slow: Agent = async () => { await pause(200); return "never arrived"; };

// Sequential: the output of one is the input of the next.
const sequence = async (agents: Agent[], input: string) => agents.reduce(async (acc, a) => a(await acc), Promise.resolve(input));

// Parallel: each agent has a time limit, and the failure of one does not take down the others (allSettled).
async function parallel(agents: Record<string, Agent>, input: string, timeoutMs: number) {
  const names = Object.keys(agents);
  const outcomes = await Promise.allSettled(names.map((n) => Promise.race([
    agents[n](input),
    pause(timeoutMs).then(() => { throw new Error(`timeout after ${timeoutMs} ms`); }),
  ])));
  return names.map((n, i) => {
    const e = outcomes[i];
    return e.status === "fulfilled" ? `${n}: ${e.value}` : `${n}: ERROR (${(e.reason as Error).message})`;
  });
}

// Hierarchical: a supervisor chooses whom to delegate to. The cap counts EVERY decision, even the wrong ones.
type Decision = { action: "delegate"; agent: string; task: string } | { action: "finish"; answer: string };
async function supervisor(decide: (history: string[]) => Decision, agents: Record<string, Agent>, maxDecisions: number) {
  const history: string[] = [];
  for (let n = 0; n < maxDecisions; n++) {
    const d = decide(history);
    if (d.action === "finish") return `finished after ${n} decisions: ${d.answer}`;
    const agent = agents[d.agent];
    history.push(agent ? `[${d.agent}] ${await agent(d.task)}` : `[error] nonexistent agent: ${d.agent}`);
  }
  return `cap of ${maxDecisions} decisions reached; last entry: ${history.at(-1)}`;
}
// The loop seen in tutorials: on a nonexistent agent it does "continue" WITHOUT counting the turn.
async function naiveSupervisor(decide: (history: string[]) => Decision, agents: Record<string, Agent>, guard: number) {
  const history: string[] = [];
  let turns = 0, decisions = 0;
  while (turns < 15) {
    if (++decisions > guard) return `still running after ${guard} decisions (external guard)`;
    const d = decide(history);
    if (d.action === "finish") return "finished";
    const agent = agents[d.agent];
    if (!agent) { history.push("error"); continue; } // no turns++
    history.push(await agent(d.task)); turns++;
  }
  return "cap of 15 turns";
}

console.log("sequence:", await sequence([analyze, audit, summarize], "diff"));
for (const line of await parallel({ quality: analyze, security: broken, documentation: slow }, "diff", 50)) console.log("parallel ->", line);

const wrong = (): Decision => ({ action: "delegate", agent: "nonexistent", task: "x" });
const twoTurns = (s: string[]): Decision => s.length < 2 ? { action: "delegate", agent: "analyze", task: "diff" } : { action: "finish", answer: s.join(" + ") };
console.log("supervisor:", await supervisor(twoTurns, { analyze }, 6));
console.log("supervisor, nonexistent agent:", await supervisor(wrong, { analyze }, 6));
console.log("naive supervisor, nonexistent agent:", await naiveSupervisor(wrong, { analyze }, 1000));

// Output:
// sequence: report(audit(analysis(diff)))
// parallel -> quality: analysis(diff)
// parallel -> security: ERROR (service unreachable)
// parallel -> documentation: ERROR (timeout after 50 ms)
// supervisor: finished after 2 decisions: [analyze] analysis(diff) + [analyze] analysis(diff)
// supervisor, nonexistent agent: cap of 6 decisions reached; last entry: [error] nonexistent agent: nonexistent
// naive supervisor, nonexistent agent: still running after 1000 decisions (external guard)

In the parallel pattern Promise.allSettled prevents one agent's error from bringing down the others, and the race against a timer gives each a maximum time: in the output "security" fails and "documentation" times out, while "quality" returns its result. The supervisor shows the defect that costs the most. The loop seen in tutorials, on a nonexistent agent, does continue without counting the turn: naiveSupervisor never reaches its cap and I had to stop it with an external guard at 1000 decisions (with a real model that would be 1000 paid calls). The correct version counts every decision, even the wrong one, and stops at 6.

Memory: three different things under the same name

People speak of short-term, long-term and episodic memory, but they are things of a different nature. Short-term is the message history you resend on every call, limited by the context window. Long-term is an external store, normally a vector index queried by similarity (you will find it in Vector databases for web developers), from which you pick a few snippets for each request, as in RAG. Episodic is a special case of store: you record the outcome of past tasks ("tried this, it failed for this reason") and read it back when facing a similar task. All three are text that enters the prompt; only who selects it changes.

The practical problem is already in the short-term one. When the history grows you trim it, and the naive trim ("keep the last N messages") breaks the protocol of listing 1: if the trim separates a tool_use from its tool_result, the next request is rejected (the documentation cites the error "tool_use ids were found without tool_result blocks immediately after").

Listing 4: trimming the history without splitting tool-result pairs (Node 24.11, run)
import type Anthropic from "@anthropic-ai/sdk";
type M = Anthropic.MessageParam;

const blocks = (m: M) => (Array.isArray(m.content) ? m.content : []);

// Documented rule: every tool_use from the assistant must have the tool_result with the same id in the message
// right after it. The "starts with the user" check is instead a cautious choice of this listing.
export function validHistory(history: M[]): string | null {
  if (history.length === 0 || history[0].role !== "user") return "does not start with a user message";
  if (blocks(history[0]).some((b) => b.type === "tool_result")) return "starts with an orphan tool_result";
  for (let i = 0; i < history.length; i++) {
    const used = blocks(history[i]).flatMap((b) => (b.type === "tool_use" ? [b.id] : []));
    if (used.length === 0) continue;
    const after = new Set(blocks(history[i + 1] ?? { role: "user", content: "" }).flatMap((b) => (b.type === "tool_result" ? [b.tool_use_id] : [])));
    if (used.some((id) => !after.has(id))) return `tool_use without tool_result right after (message ${i})`;
  }
  return null;
}

// Trim from the start until at most "cap" messages remain, but always restart from a user message
// that is real text: this way no tool_use / tool_result pair is split.
export function trimHistory(history: M[], cap: number): M[] {
  for (let start = Math.max(0, history.length - cap); start < history.length; start++) {
    const m = history[start];
    if (m.role === "user" && !blocks(m).some((b) => b.type === "tool_result")) return history.slice(start);
  }
  return history.slice(-1); // edge case: keep at least the last message
}

const text = (role: "user" | "assistant", content: string): M => ({ role, content });
const use = (id: string): M => ({ role: "assistant", content: [{ type: "tool_use", id, name: "find_price", input: { product: "monitor" } }] });
const result = (id: string): M => ({ role: "user", content: [{ type: "tool_result", tool_use_id: id, content: "250" }] });

const history: M[] = [
  text("user", "Price of the monitor?"), use("a"), result("a"), text("assistant", "250."),
  text("user", "And with 15% off?"), use("b"), result("b"), text("assistant", "212.5."),
  text("user", "And the keyboard?"), use("c"), result("c"),
];

for (const n of [6, 5]) { // "keep the last n messages"
  const naive = history.slice(-n);
  console.log(`slice(-${n}):           `, naive.length, "messages ->", validHistory(naive) ?? "valid");
}
const good = trimHistory(history, 6);
console.log("trimHistory(…, 6):  ", good.length, "messages ->", validHistory(good) ?? "valid");
console.log("whole history:      ", history.length, "messages ->", validHistory(history) ?? "valid");

// Output:
// slice(-6):            6 messages -> does not start with a user message
// slice(-5):            5 messages -> starts with an orphan tool_result
// trimHistory(…, 6):   3 messages -> valid
// whole history:       11 messages -> valid

validHistory checks the rule in the documentation: every tool_use has its tool_result in the following message. The output shows that keeping the last 6 messages leaves a tool_use at the head, and keeping 5 leaves an orphan tool_result at the head: two different ways of going wrong with the same trim. trimHistory advances to the first user message that is real text and restarts from there, so it keeps 3 messages instead of 6: it loses some context, but the request stays valid. Whoever wants to preserve more information summarizes the discarded messages instead of throwing them away.

LangGraph, when the flow is a graph

LangGraph (its documentation defines it as a low-level orchestration framework for stateful agents) describes the flow as a graph: a shared state, nodes that update it and edges, including conditional ones, that decide the next node. It is useful when you need things that the hand-written loop does not offer, such as state persistence, resuming after an interruption or human approval halfway through. For a simple loop, listing 1 is clearer. In the listing the state is declared with Annotation.Root and its reducers; the form with the channels option found in older examples I did not try with this version.

Listing 5: a graph with a loop and the recursion limit (Node 24.11, @langchain/langgraph 1.7.4, run)
import { Annotation, END, START, StateGraph } from "@langchain/langgraph";

// The graph state: each field declares how node updates are combined.
const AgentState = Annotation.Root({
  steps: Annotation<string[]>({ reducer: (old, added) => old.concat(added), default: () => [] }),
  answer: Annotation<string>({ reducer: (_old, added) => added, default: () => "" }),
});

// Nodes without a model: functions that read the state and return a partial update.
const plan = (s: typeof AgentState.State) =>
  ({ steps: [s.steps.length === 0 ? "choose: find_price" : "choose: respond"] });
const execute = () => ({ steps: ["execute: find_price -> 250"] });
const respond = () => ({ answer: "The monitor costs 250." });

// The conditional edge reads the last step and returns the name of the next node.
const route = (s: typeof AgentState.State) => (s.steps.at(-1) === "choose: find_price" ? "execute" : "respond");

const graph = new StateGraph(AgentState)
  .addNode("plan", plan)
  .addNode("execute", execute)
  .addNode("respond", respond)
  .addEdge(START, "plan")
  .addConditionalEdges("plan", route, ["execute", "respond"])
  .addEdge("execute", "plan") // the loop: after the tool we go back to deciding
  .addEdge("respond", END)
  .compile();

const final = await graph.invoke({});
console.log("steps:", final.steps);
console.log("answer:", final.answer);

// A graph that does not converge: the planner always chooses the tool.
const endless = new StateGraph(AgentState)
  .addNode("plan", () => ({ steps: ["choose: find_price"] }))
  .addNode("execute", execute)
  .addNode("respond", respond)
  .addEdge(START, "plan")
  .addConditionalEdges("plan", route, ["execute", "respond"])
  .addEdge("execute", "plan")
  .addEdge("respond", END)
  .compile();

try {
  await endless.invoke({}, { recursionLimit: 6 });
} catch (e) {
  const err = e as Error;
  console.log("error:", err.name, "-", err.message.split("\n")[0]);
}

// Output:
// steps: [
//   'choose: find_price',
//   'execute: find_price -> 250',
//   'choose: respond'
// ]
// answer: The monitor costs 250.
// error: GraphRecursionError - Recursion limit of 6 reached without hitting a stop condition. You can increase the limit by setting the "recursionLimit" config key.

Each field of AgentState declares how updates are combined: steps accumulates, with a reducer that concatenates, while answer is replaced. The loop is the edge from execute to plan, and the conditional one reads the last step to choose the node. The first graph converges in three steps; the second has a planner that always chooses the tool, and ends with a GraphRecursionError at the limit of 6 that I set. The default limit is 25 in the installed version (I read it in the package's utils/config.js): it is the cap the framework imposes anyway, and when it triggers it tells you that the flow does not converge: better to choose it yourself based on the task.

When to stop an agent

An agent without limits turns a reasoning error into a bill. The useful limits are few, and all of them have to be decided in your code, not in the prompt:

  • Turns: a maximum number of cycles or decisions, counting the wrong ones too.
  • Time and tokens: a cap on duration and consumption for each task.
  • Permissions: tools are listed, parameterized and confined; destructive ones ask for confirmation.
  • Outcome: every stop_reason value other than the expected ones ends the loop with a message.

The four limits compensate for one another: turns protect against the endless loop, but not against the single turn that costs a lot; tokens limit the cost but not the damage of a tool; permissions limit the damage but not the waste. To retry transient call errors (429, 5xx) do not write a mechanism of your own: the SDK already does it, as the article on the APIs explains. If instead the model has to run on your machine, the loop is the same and only the client changes: Local LLMs with Ollama.

What you can do now

You can write the loop of an agent with tool calling and make it stop in every case: complete answer, nonexistent tool, truncated answer, endless loop. You know what makes a tool dangerous and how to confine it, how to coordinate several agents with a cap for each and how to trim the history without breaking the protocol. You can tell when a LangGraph graph is better than the hand-written loop. What these listings do not say is how a real model reasons when faced with an open task: that is measured with your key and your tools. If you want to automate a release pipeline with these patterns, the next step is AI in CI/CD; for orchestration in production see Multi-agent orchestration.

Frequently asked questions

When is an agent better than a simple call?

When the steps are not known in advance or you need external tools. For classifying, translating or summarizing a single call is enough, it costs one request and is easier to evaluate; an agent costs an unpredictable number of them.

Does the model really execute the tools?

No. The model produces a structured request with name and parameters, and your code executes it. That is why permissions, input validation and caps live in your loop and cannot depend on what the model promises.

Do I need LangGraph to write an agent?

No: the loop in listing 1 is a complete agent. LangGraph pays off when you need persistent state, resuming after an interruption or a human approval in the middle, because its infrastructure already provides them.

Before writing an agent it is worth deciding whether the model needs more facts or a different behavior: that is the question of the previous article, fine-tuning or RAG.

Sources

Listings 1, 2, 3, 4 and 5 were run with Node 24.11, each twice with identical output, and compile with TypeScript 7.0.2 (@anthropic-ai/sdk 1.8.0, @langchain/langgraph 1.7.4). In listing 1 the "model" responses are a script; the catalog data are test data. LangGraph's default recursion limit (25) is read in the source of the installed package (utils/config.js). No model was called and no port opened; listing 2 uses a temporary folder and a symbolic link to /etc/hostname, so it assumes Linux.

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects