Skip to main content

The Loop: From First Tool Call to Final Verdict

Why This Matters

The loop is where TestPilot becomes an agent: the model decides the next step, your code carries it out. Small mistakes here, such as a missing tool result or no upper limit, turn into endless or silently wrong runs. Write it yourself once, so you understand exactly what the Agent SDK does for you later.

One triage, step by step

  1. You send the failure plus the tool definitions.
  2. The model answers with stop_reason: "tool_use" and one or more tool_use blocks: call get_test_history with { testId: "t-004" }.
  3. Your code runs the tool and sends the result back as a tool_result block, linked by the tool_use_id.
  4. The model asks for read_log. Same again.
  5. The model answers with a final verdict and stop_reason: "end_turn".

The agent loop: your code sends messages and tools, Claude answers with tool_use, your code runs the tool and sends tool_result, until end_turn or a limit

The loop in code

const messages: MessageParam[] = [{ role: "user", content: buildTriageMessage(run, failure) }];

for (let step = 0; step < MAX_STEPS; step++) {
  const reply = await client.messages.create({ model, max_tokens: 2048, system, tools, messages });
  messages.push({ role: "assistant", content: reply.content });

  if (reply.stop_reason === "end_turn") return finalVerdict(reply);
  if (reply.stop_reason !== "tool_use") return notTriaged(reply.stop_reason); // max_tokens, refusal, … (see below)

  const results = [];
  for (const block of reply.content) {
    if (block.type !== "tool_use") continue;
    const output = await runTool(block.name, block.input);
    results.push({ type: "tool_result", tool_use_id: block.id, content: JSON.stringify(output) });
  }
  messages.push({ role: "user", content: results });
}
return limitReached(failure);

Details that matter

  • Answer every tool_use block. The model can ask for several tools at once; each one needs a result with the matching id, in the next user message.
  • Push the assistant message unchanged, including its tool_use blocks. The results refer to them.
  • Unknown tool names get a tool_result with an error, not a crash.

Ending well

A loop needs more than one way to stop:

StopWhy
Final answer (end_turn)The normal case
Maximum number of stepsA model that keeps asking for more is stuck
Time or token budgetOne failure must not eat the whole night
max_tokensThe answer was cut off; treat as an error

Every stop_reason, and what your loop does with it

Your loop decides what to do next from stop_reason, never from the text of the answer:

stop_reasonMeaningWhat the loop does
tool_useThe model wants one or more toolsRun them, send every tool_result, call again
end_turnThe model is doneValidate the verdict and stop
max_tokensCut off at your max_tokens limitDo not trust a half answer; raise the limit or report “not triaged”
stop_sequenceHit one of your stop sequencesExpected only if you set them
pause_turnServer-side tools (such as web search) hit their iteration limit within the turnSend the response back as-is to let it continue
model_context_window_exceededThe conversation filled the model’s context windowTreat it as cut off; trim the context (lessons 56 and 57)
refusalThe model declined to answerDo not retry the same request blindly; read the response’s details, report it, and route to a human

Exam questions like to show code that loops “until the answer contains a verdict” or “until there are no tool calls in the text”. Both are wrong: check stop_reason.

When a limit is hit, TestPilot reports “not triaged: step limit reached after 8 tool calls” with the tools it called, rather than inventing a verdict.

The structured verdict

The final answer still needs to be a validated verdict (lesson 9). The simplest pattern: give the model a submit_verdict tool whose input schema is the verdict schema, and end the loop when it is called. Validate the input with the same triageResultSchema before accepting it.

Exercise

Implement the loop with the read-only tools from lesson 24 (backed by fixture data), a step limit of 8 and a submit_verdict tool. Log every tool call and compare the paths for t-002, t-004 and t-005.