An agent is a program that receives a goal instead of a plan. We have already drawn the line between that and a chatbot — a chatbot’s product is the conversation; an agent’s product is the completed task — so this piece takes the distinction as settled and goes straight to the code.

Everything below is Node and TypeScript: the loop, the tools it calls, where its state sits between passes, and what happens when the process holding it dies mid-run.

Writing the loop takes an afternoon. Deciding what the model is not allowed to decide takes the rest of the project.

Somebody Has To Choose The Next Step

There is one structural difference between an agent and the systems we described in workflow engines, and it is not intelligence — it is who chose the order. In an engine, a developer enumerated the states and the legal transitions before anything ran, and the engine executes that map faithfully under failure. In an agent, the model picks the next step at runtime, from a set of tools, based on what it just saw.

That single delta cuts both ways. You gain the ability to handle cases nobody enumerated in advance. You lose the guarantee that the next step is one you anticipated — and with it, every property the engine used to hand you for free.

So the useful frame is not “the model does the work”. It is a negotiation over the next step, and the sections below are ordered by who wins each round: the model, your code, or a person.

What One Pass Has To Carry

Start with the state, because the loop is a function over it.

// src/agent/state.ts
import type Anthropic from "@anthropic-ai/sdk";

export type RunState = {
  runId: string;
  goal: string;
  /** The only thing the model ever sees. Grows by two entries per pass. */
  messages: Anthropic.MessageParam[];
  /** Never in the prompt. */
  stepsRemaining: number;
  /** Fingerprints of calls already made, for loop detection. */
  seenCalls: Set<string>;
  status: "running" | "done" | "budget_exhausted" | "stalled";
};

The split that matters is between the fields the model can see and the fields it cannot. messages is its entire world — the prompt is rebuilt from this array on every pass. stepsRemaining and seenCalls are deliberately absent from it, because a budget the model can read is a budget it can argue with.

Thirty Lines Is The Whole Agent

// src/agent/loop.ts
export async function runAgent(state: RunState): Promise<RunState> {
  while (state.status === "running") {
    if (state.stepsRemaining <= 0) {
      state.status = "budget_exhausted";
      break;
    }
    state.stepsRemaining -= 1;

    const reply = await client.messages.create({
      model: process.env.AGENT_MODEL!,
      max_tokens: 4096,
      system: "You resolve billing cases. Use tools; never guess an order id.",
      tools: toolSpecs,
      messages: state.messages,
    });

    state.messages.push({ role: "assistant", content: reply.content });

    if (reply.stop_reason !== "tool_use") {
      state.status = "done";
      break;
    }

    const results: Anthropic.ToolResultBlockParam[] = [];
    for (const block of reply.content) {
      if (block.type !== "tool_use") continue;
      results.push(await runTool(block));
    }
    state.messages.push({ role: "user", content: results });
  }
  return state;
}

Plan is the messages.create call, act is runTool, observe is pushing the results back onto the transcript, and adjust is the next iteration reading them. There is no fifth thing.

Two details carry more weight than they look:

  • Append the assistant’s whole content array, not its text. Reduce it to a string and the tool_use blocks vanish; the next request then carries results for calls the transcript no longer contains, and the API rejects it.
  • Every tool result goes back in a single user message. One assistant turn can request several calls at once, and splitting the replies across separate messages teaches the model to stop asking for them in parallel — which quietly doubles the number of passes.

Note also the only place the model gets to end the run: a stop_reason other than tool_use. That is its single termination privilege, and on its own it is not enough.

One pass of an agent loop drawn above the checkpoint rail it writes: Plan and Adjust are decided by the model, Act and Observe by your code, an invalid tool call is rejected back into Observe rather than thrown, and after a crash the run resumes from the last committed checkpoint rather than from the failed pass or the beginning
The loop is the easy half. The rail underneath it is what makes a run survivable.

The Model Invents Its Arguments

This is the part most implementations get wrong, and the mechanism is worth stating bluntly. The model does not fetch an order id from your database and pass it to your tool. It reads a transcript, infers what an order id looks like, and emits a string of that shape. Here is what actually arrives:

{
  "type": "tool_use",
  "id": "toolu_01A09q90qw90lq917835lq9",
  "name": "issue_refund",
  "input": {
    "orderId": "ord_7f3a9c21b0d4",
    "amountCents": 4999,
    "reason": "duplicate_charge"
  }
}

Every value under input was produced by the model. Nothing guarantees the order exists, that the amount matches it, or that reason is one of yours — which is why the SDK types that field unknown and hands you the problem. The description is a prompt; the schema is a contract; only one is enforced.

// src/agent/tools.ts
import { z } from "zod";
import type Anthropic from "@anthropic-ai/sdk";

const IssueRefund = z.object({
  orderId: z.string().regex(/^ord_[a-z0-9]{12}$/),
  amountCents: z.number().int().positive().max(50_000),
  reason: z.enum(["duplicate_charge", "not_delivered", "damaged"]),
});

export const registry = {
  issue_refund: {
    spec: {
      name: "issue_refund",
      description: "Refund a settled order. Only for orders already marked paid; " +
        "amounts are in cents and may not exceed the order total.",
      input_schema: z.toJSONSchema(IssueRefund) as Anthropic.Tool["input_schema"],
    },
    schema: IssueRefund,
    run: async (args: unknown) => refundOrder(IssueRefund.parse(args)),
  },
};

Generate the JSON Schema from the Zod object rather than writing it twice. Two hand-maintained descriptions of one shape drift within a month, and always in the same direction: the schema the model reads gets updated, the one that validates does not.

The constraints are not decoration. The ceiling is there because “refund the full amount” is a sentence the model can produce carrying a number it reconstructed from context. The regex is there so a malformed id fails at your boundary with a message the model can act on, not three layers down in a database driver.

A Rejection Is A Result, Not A Crash

export async function runTool(
  call: Anthropic.ToolUseBlock,
): Promise<Anthropic.ToolResultBlockParam> {
  const reject = (content: string): Anthropic.ToolResultBlockParam => ({
    type: "tool_result", tool_use_id: call.id, is_error: true, content,
  });

  const tool = registry[call.name];
  if (!tool) return reject(`No tool named ${call.name}. Have: ${Object.keys(registry).join(", ")}.`);

  const parsed = tool.schema.safeParse(call.input);
  if (!parsed.success) {
    return reject("Rejected: " + parsed.error.issues
      .map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; "));
  }

  try {
    return { type: "tool_result", tool_use_id: call.id, content: await tool.run(parsed.data) };
  } catch (e) {
    return reject(e instanceof Error ? e.message : "Tool failed.");
  }
}

Nothing in that function throws into the loop. An unknown tool name, invalid arguments and a handler that blew up all become tool_result blocks carrying is_error. The model reads them on the next pass and corrects — precisely what the observe step is for.

A thrown exception ends the run and discards everything the model had worked out. A returned error is one more thing to observe. An agent told “orderId: must match /^ord_/” will go and look the id up; an agent handed a 500 will not.

So write those messages as prompts, because that is what they are: say what was wrong and what would be right. Never paste raw exception text — stack traces and internal ids are noise the model will try to reason about, and they land permanently in your stored transcript.

Nothing Ends A Run But A Number You Wrote

The loop has three exits: the model stops calling tools, the budget runs out, or the process dies. Only the first is a decision, and it belongs to the model — which is why an agent without a step limit is an outage waiting for traffic.

The budget catches the runaway. It does not catch the more common failure, which is not infinite at all: the agent calls the same read three times because the answer was not what it wanted, then gives up having spent a whole budget on one lookup.

export function guardRepeats(
  state: RunState,
  call: Anthropic.ToolUseBlock,
): Anthropic.ToolResultBlockParam | null {
  const fingerprint = `${call.name}:${JSON.stringify(call.input)}`;
  if (!state.seenCalls.has(fingerprint)) {
    state.seenCalls.add(fingerprint);
    return null; // not seen before — let it run
  }
  return {
    type: "tool_result",
    tool_use_id: call.id,
    is_error: true,
    content: "You already made this exact call and got a result. Change the arguments, " +
      "use a different tool, or say you cannot proceed.",
  };
}

Fingerprint the call, and when it repeats, return that fact instead of the result. Telling the model it is going in circles gives it somewhere else to go — better than looping or dying.

Cost and latency fall out of the same structure. Every pass resends the whole transcript, and the transcript grows on every pass, so total input volume rises with the square of the step count — which makes the step budget a cost control before it is a safety control. The second lever is tool output: a tool that returns an entire table pays for that table again on every subsequent pass. Cap what tools return, or write the payload to storage and hand back a handle.

What A Graph Buys That A While Loop Cannot

Everything so far is a while loop, and for a bounded agent with four tools that is the right answer. Reaching for a framework before you have felt the problem it solves costs a dependency, a mental model, and the ability to read your own control flow at a glance. Very few agents fail in production for want of a graph.

LangGraph earns its place when you want the routing back. Instead of “the model calls tools until it stops”, you declare nodes, and you declare the edges between them — including the conditional ones, which are your functions and not the model’s.

import { StateSchema, StateGraph, MessagesValue, ReducedValue,
         MemorySaver, START, END } from "@langchain/langgraph";
import { z } from "zod";

const CaseState = new StateSchema({
  messages: MessagesValue,                                     // the transcript
  steps: new ReducedValue(z.number().default(0), { reducer: (a, b) => a + b }),
  refundCents: z.number().default(0),
});

function route(state: { steps: number; refundCents: number }) {
  if (state.steps >= 12) return END;              // the budget, as an edge
  if (state.refundCents > 20_000) return "approve";
  return "act";
}
export const graph = new StateGraph(CaseState)
  .addNode("plan", plan)        // one model call
  .addNode("act", act)          // run the tools it asked for
  .addNode("approve", approve)  // stop and wait for a person
  .addEdge(START, "plan")
  .addConditionalEdges("plan", route, ["act", "approve", END])
  .addEdge("act", "plan")
  .addEdge("approve", "plan")
  .compile({ checkpointer: new MemorySaver() });

The conditional edge is the entire point. The model still chooses which tool to call inside act; route decides whether the run goes to approval, back to planning, or to END. That decision is now a small piece of testable code with no model anywhere in it.

A version note, because most LangGraph.js material you will find declares state with Annotation.Root: that still works and is still exported. The current form is StateSchema with Zod field schemas plus the prebuilt values — MessagesValue for a transcript, ReducedValue where a field accumulates instead of overwriting. Reducers are why state is declared rather than merely typed: plan returns steps: 1 and the reducer adds it to the total.

Where The State Object Lands Between Passes

Compiling with a checkpointer changes exactly one thing, and it is the thing that matters: after every node, the graph writes the whole state to storage, keyed by a thread id.

const config = { configurable: { thread_id: caseId } };

await graph.invoke({ messages: [], steps: 0 }, config);

// Later, in a different process:
const snapshot = await graph.getState(config);
const waiting = snapshot.tasks.flatMap((t) => t.interrupts);

The thread_id is the identity of the run. Invoke with the same one tomorrow and the graph continues where it stopped; invoke with a new one and you get a fresh run over the same graph. That is how one piece of code serves both a long-lived case and a batch job.

MemorySaver lives in the process and dies with it, which makes it precisely wrong for the problem it appears to solve. LangGraph publishes durable checkpointers as separate packages backed by SQLite and Postgres; anything that must survive a deploy needs one of those, or your own implementation of the interface.

The Run That Died At Step Seven

Now the scenario worth designing for. A long run reaches pass seven — six tool calls done, two of them writes — and the pod is evicted mid-deploy. With state in a local variable that run is gone, and the only recovery is to start again from pass one, redoing six calls that already had effects.

With a checkpointer, restarting the process and invoking the same thread_id resumes from the last committed checkpoint. Look again at where the arrow in the figure starts: checkpoint six, not the failed pass and not the beginning.

What that does not buy you is a guarantee that the tool at pass seven ran exactly once, because a call that timed out may well have committed on the other side. So every tool that writes needs an idempotency key, exactly as it would in any other distributed system — and this is where the agent loop meets the boring machinery. Retries with backoff, dead-letter queues, compensating actions when a committed step must be undone: all of that is the subject of the workflow-engines piece, and we will not re-derive it here. The useful point is that an agent loop still needs every bit of it underneath: the graph decides what happens next, not what happens when the thing it decided fails halfway through.

Scratchpad, Thread, And The Thing That Is Not Memory

“Memory” is one word covering three unrelated mechanisms, and conflating them is how agents end up expensive and wrong at the same time.

LayerWhat it holdsWhere it livesWhat it costs
ScratchpadValues one node writes for another inside a single runState fields on the run; gone when the run endsPrompt space, only if you expose it to the model
Thread stateThe transcript, plus anything that must still be true next runThe checkpointer, keyed by thread idGrows without limit unless you prune it; every pass pays for its size
KnowledgeFacts that were true before this run and outlive itA store you query — search index, vector index, or the source systemA retrieval step per use, and the ranking quality of what you queried

The distinction that saves you is between conversation state and knowledge. Conversation state records what was said and done in this thread. Knowledge is a set of facts that were true before the thread started and will be true after it ends.

Put knowledge in thread state and every fact the agent ever learned rides along in every prompt of every pass, forever, whether this run needs it or not. Put conversation state in a vector store and you retrieve the third-most-similar thing the user said in March instead of what they said two minutes ago. Retrieval is a system in its own right with its own architecture, and the agent should be its client, not its owner.

When The Next Step Is Not Yours To Take

Some steps should not be automated yet, and a graph makes that a state rather than a special case.

import { interrupt, Command } from "@langchain/langgraph";

async function approve(state: { refundCents: number }) {
  const decision = interrupt({           // graph stops here; state is already saved
    kind: "refund_approval",
    amountCents: state.refundCents,
  }) as "approve" | "reject";
  return { messages: [new AIMessage(`human said ${decision}`)] };
}

// From the approvals queue, hours later, in another process:
await graph.invoke(new Command({ resume: "approve" }), config);

interrupt() stops the graph and parks its payload on the thread. Because the checkpointer already holds the state, a paused run is just a row in a table — render it in a queue, leave it overnight, resume it from another process. getState hands you the pending interrupts, and new Command({ resume }) sends the answer back.

One behaviour will bite you if nobody warned you: on resume, the node runs again from the top. Everything above the interrupt() call executes a second time; everything below it executes once. So put the side-effect-free work — reading state, composing the approval payload — above the call, and the writes below it. We checked this against the current release rather than trusting the mental model — a counter above interrupt() increments twice.

Showing The Work While It Is Still Running

An agent that returns nothing for the length of eight tool calls is indistinguishable from one that has hung.

for await (const chunk of await graph.stream(
  { messages: [], steps: 0 },
  { ...config, streamMode: "updates" },
)) {
  const [node] = Object.keys(chunk);
  if (node === "__interrupt__") ui.awaitingApproval(chunk);
  else ui.progress(labelFor(node));   // "Checking the order", "Issuing the refund"
}

Each chunk is keyed by the node that produced it, so surfacing progress means mapping node names onto sentences a person should read. When the run pauses, a chunk keyed __interrupt__ arrives — the cue to switch the interface from working to waiting on you. Resist streaming the raw tool arguments themselves: they are model output, they can contain anything, and they are the part of the run most likely to be wrong.

Observability is the same data written somewhere durable. One row per tool call — run id, thread id, pass number, tool name, arguments as given, whether validation passed, and what you returned — reconstructs any run afterwards. That table is how you answer “why did it refund that order” three weeks later, and it stays readable long after the transcript does not.

Where Else The Loop Could Live

LangGraph is one answer, not the answer, and for plenty of work it is more machinery than the problem deserves. The honest comparison is by what each option takes off your hands and what it leaves.

OptionReach for it whenIt stops helping when
A plain while loopA handful of tools, the run fits in one request, and you want to read your own control flowYou need to pause for a person, resume after a crash, or route on anything richer than “did it call a tool”
Vercel AI SDKYou want the loop, provider-neutral tool calling and streaming, this weekThe run has to outlive the process — there is no saved state to resume from
LangGraphRouting is a real decision, runs are long, and pause-and-resume is a feature rather than an accidentThe graph has three nodes and one edge, and you are maintaining a framework to express an if
MastraYou want an opinionated TypeScript project shape — agents, tools, workflows and memory pre-wiredYour architecture is already settled and the opinions fight it
Durable executionDurability, retries and run history are the hard requirement and the agent logic is simpleThe complexity is the routing rather than the recovery — the engine will replay a loop it understands nothing about

The AI SDK is the one most teams should try first. Its generateText runs the tool loop for you once you give it a stopping condition:

import { generateText, stepCountIs, tool } from "ai";
import { z } from "zod";

const { text, steps } = await generateText({
  model,
  prompt: goal,
  stopWhen: stepCountIs(8),          // the step budget, as one argument
  tools: {
    issue_refund: tool({
      description: "Refund a settled order.",
      inputSchema: z.object({
        orderId: z.string(),
        amountCents: z.number().int().positive().max(50_000),
      }),
      execute: async (args) => refundOrder(args),
    }),
  },
});

Two names there have moved, which matters because most tutorials predate the change: the tool’s schema field was parameters and is now inputSchema, and the loop bound was a maxSteps number and is now a stopWhen condition, of which stepCountIs is the obvious one. Validation is still yours, though — everything the schema does not say remains unchecked.

That leaves the axis worth deciding on. If the agent runs inside one request and the worst case is the user clicking again, a plain loop or the AI SDK is enough. If a run spans minutes, touches systems that move money, or has to stop and wait for a person, the state needs somewhere to land — a graph with a durable checkpointer, or the loop wrapped in a durable-execution engine such as Temporal or Inngest, where each pass becomes a step the platform will replay.


The pattern under all of it: an agent is only as good as the decisions you refused to delegate. The model picks the tool. Your schema decides whether the call is real, your budget decides whether there is another pass, your checkpointer decides where the run resumes, and a person decides the handful of things nobody should automate yet. Get those four right and the loop in the middle can stay thirty lines.

If you are building AI agents on Node and have reached the point where the demo works but the second week of production does not, we are glad to read your loop with you.

Frequently Asked Questions

Do I need a framework like LangGraph to build an AI agent in Node.js?

Not at first. A bounded agent with a handful of tools is about thirty lines of TypeScript: a while loop that calls the model, runs the requested tools, appends results to the transcript and stops on a step budget. LangGraph earns its place when routing is a real decision, runs are long, and pausing for a person or resuming after a crash is a feature.

How do I stop an AI agent from looping forever?

Give it a step budget the model cannot see, because otherwise only the model's own decision to stop calling tools ends a run. Also fingerprint each tool call and, when an identical call repeats, return an error telling the model it already made that call. Since every pass resends a growing transcript, the step budget doubles as a cost control.

How should an AI agent handle invalid tool arguments?

Validate every argument against a schema, for example with Zod, and return failures as tool results marked as errors rather than throwing. The model invents its arguments from context, so nothing guarantees an order exists or an amount is valid. A returned error explaining what was wrong lets the model correct itself on the next pass; a thrown exception ends the run.

How do you make an AI agent survive a crash or deploy in the middle of a run?

Persist state after every step with a durable checkpointer keyed by a thread ID, so invoking the same thread after a restart resumes from the last committed checkpoint rather than from the beginning. LangGraph's in-memory saver dies with the process, so anything that must survive a deploy needs a durable SQLite or Postgres checkpointer, or your own. Every tool that writes also needs an idempotency key, because a timed-out call may already have committed.

What is the difference between agent memory and a knowledge base?

Conversation state records what was said and done in one thread, while knowledge is facts that were true before the thread started and remain true after it ends. Keep thread state in the checkpointer and knowledge in a store you query, such as a search or vector index. Mixing them up makes agents expensive, because every learned fact rides along in every prompt.

Sources