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
- You send the failure plus the tool definitions.
- The model answers with
stop_reason: "tool_use"and one or moretool_useblocks: callget_test_historywith{ testId: "t-004" }. - Your code runs the tool and sends the result back as a
tool_resultblock, linked by thetool_use_id. - The model asks for
read_log. Same again. - The model answers with a final verdict and
stop_reason: "end_turn".
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_useblock. 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_useblocks. The results refer to them. - Unknown tool names get a
tool_resultwith an error, not a crash.
Ending well
A loop needs more than one way to stop:
| Stop | Why |
|---|---|
Final answer (end_turn) | The normal case |
| Maximum number of steps | A model that keeps asking for more is stuck |
| Time or token budget | One failure must not eat the whole night |
max_tokens | The 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_reason | Meaning | What the loop does |
|---|---|---|
tool_use | The model wants one or more tools | Run them, send every tool_result, call again |
end_turn | The model is done | Validate the verdict and stop |
max_tokens | Cut off at your max_tokens limit | Do not trust a half answer; raise the limit or report “not triaged” |
stop_sequence | Hit one of your stop sequences | Expected only if you set them |
pause_turn | Server-side tools (such as web search) hit their iteration limit within the turn | Send the response back as-is to let it continue |
model_context_window_exceeded | The conversation filled the model’s context window | Treat it as cut off; trim the context (lessons 56 and 57) |
refusal | The model declined to answer | Do 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.