Paso 2 de 13 - Unos 40 min
Lab 01 - The turn loop
Time: about 40 minutes. You will: build the loop that lets the model use tools, and make it handle every way a model call can end.
Why
Ask a plain model "how many days until my exam on January 15?" and it will guess today's date. Sometimes it is right. An assistant needs to check, and checking means calling code. The turn loop is the piece that lets the model ask for code to run and then continue with the result. This is tool use: your code defines the tools, the model asks for them, and your code runs them.
Concepts
A turn is a loop, not a call
One user message can need several model calls (how tool use works):
Código del diagrama
flowchart LR
U[User message] --> C[Call the model]
C -->|stop_reason: tool_use| R[Run the requested tools]
R -->|one message with all results| C
C -->|end_turn| D[Done: show the text]
C -->|max_tokens / refusal / context full| E[End the turn safely]Every way a call can end
Every response says why it ended in stop_reason
(Stop reasons and fallback):
stop_reason |
Meaning | What the loop does |
|---|---|---|
end_turn |
The model is finished | Return the text |
tool_use |
The model wants tools | Run them, send results, call again |
pause_turn |
A server-side tool loop paused (Steward has none) | Send the conversation back to continue |
compaction |
The server compacted the conversation and paused (lab 07) | Send the conversation back to continue |
max_tokens |
The answer hit the output limit | Stop; never run tools from it |
refusal |
The model (and any fallback) declined | Stop; never run tools from it |
model_context_window_exceeded |
The answer filled the rest of the context window (cut off) | Stop; lab 07 keeps the context small |
Three rules that keep the conversation valid
- Append the model's content exactly as it came back. The response can hold
thinkingblocks,tool_useblocks, and other blocks besides text. Current models check that earlier turns are sent back unchanged, so never rebuild an assistant message from its text. - Answer every
tool_usewith exactly onetool_result, all in one user message. If the model asks for two tools at once (parallel tool use), both results go back together, in order. Splitting them across messages teaches the model to stop calling tools in parallel. - Never run tools from a cut-off or declined response. A
tool_useat the end of amax_tokensresponse may have half its input. The loop answers it with an error result instead, so the history stays valid for the next turn.
A tool is a contract
export const daysUntil = defineTool({
name: 'days_until',
description:
"Counts the calendar days from today (owner's time zone) until a date, for example an exam " +
'date. Negative when the date is in the past.',
input: z.object({
date: z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/, 'use the YYYY-MM-DD format')
.describe('Target date, YYYY-MM-DD'),
}),
run: ({ date }, context) => {
/* ... */
},
});The same Zod schema does two jobs: it becomes the JSON Schema the model sees (toApiTool, see
Define tools), and it validates the model's input
before run executes (runTool). Invalid input never reaches your code; it becomes an error
result (is_error: true) the model can read and fix
(Handle tool calls).
Build
Read these files in order. Each one is short.
src/core/model.ts- theModelClientinterface. The turn loop depends on this, not on the SDK, which is what makes offline tests possible.src/core/anthropic-model.ts- the real client. Note the request settings:client.beta.messages.stream(...)andfinalMessage(): streaming, so long answers never hit request timeouts, and text appears as it is written.output_config: { effort }: how hard the model thinks (thinking itself is adaptive by default on current models).cache_control: { type: 'ephemeral' }: automatic prompt caching (lab 03 explains it).fallbacks: 'default'with theserver-side-fallback-2026-07-01beta: if the model declines, the API retries on a fallback model inside the same call.eager_input_streaming: trueon each tool: tool input streams as it is generated; the server skips validation, which is why our own Zod validation matters.
src/tools/tool.ts-defineTool,toApiTool, andrunTool(never throws: every failure becomes{ isError: true }).src/tools/time-tools.ts-current_timeanddays_until. Note the round-trip date check: JavaScript happily parses2026-02-30as March 2.src/core/turn-loop.ts-runTurn. Find the three rules in the code; each has a comment.
The heart of the loop:
const response = await input.model.complete(request, { onText, signal });
if (response.content.length > 0) {
await append({ role: 'assistant', content: response.content }); // rule 1
}
switch (response.stop_reason) {
case 'tool_use': {
const batch = await runBatch(input, toolUses); // validate, then run them in parallel
// ('pending' in batch: a call waits for approval, lab 05)
await append({ role: 'user', content: batch.results }); // rule 2: one message
continue;
}
case 'end_turn':
return { text: textOf(response.content), stop: 'end_turn', added, usage };
case 'max_tokens':
case 'refusal': // rule 3: close open tool calls with error results, never run them
// ...
}Run
pnpm steward chat --ephemeralTry:
you> What is today's date?
you> My CCA-F exam is on 2027-01-15. How many days do I have?
you> And how many weeks is that, if I study 5 days a week?You will see [tool] current_time ... done lines as tools run. Exit with /quit and start again:
everything is gone. --ephemeral keeps the conversation in memory only. Lab 02 fixes that.
Break it
- Ask:
How many days until 2026-02-30?The model callsdays_until, gets an error result ("not a real date"), and tells you, because rule 6 inconfig/rules.mdasks it to report failures instead of hiding them. - Set
"maxStepsPerTurn": 1in your local config and ask a question that needs a tool. The turn stops after one model call withstopped: too many steps in one turn. This cap is your protection against a model that keeps calling a failing tool. Set it back to 12.
Check
pnpm lab 01The checkpoint runs the loop against a scripted fake model and checks: tool calls run and their
results come back; parallel calls are answered in one message, in order; bad input and unknown
tools become error results; content (including thinking blocks) is stored unchanged; tools from
a max_tokens response never run; an empty declined response stores nothing; the step cap works;
the history passed in is not changed. It also checks the tools: the JSON Schema sent has type
object and no $schema, and the date tools use the owner's time zone and reject impossible
dates.
Exercises
- Add a
study_plan_weekstool that takes an exam date and study days per week and returns the number of study days left. Write its test first, in the style oftests/labs/01-turn-loop.test.ts. - Print the token usage of each turn after the answer (hint:
result.usage). - The SDK also ships a tool runner
(
client.beta.messages.toolRunner) that runs this loop for you; this lab writes the loop by hand so you see every step. Read its docs and list two things our loop does that you would have to add to it with hooks.
Claude API docs
- How tool use works - the request,
tool_use,tool_resultcycle this loop runs. - Define tools - names, descriptions, and input schemas the model reads.
- Handle tool calls - result blocks and
is_error. - Parallel tool use - why all results go back in one message.
- Stop reasons and fallback - every
stop_reasonand refusal fallbacks. - Streaming - the events behind
stream()andfinalMessage().
Exam connection
CCA-F - Agentic Architecture & Orchestration (the agent loop and stop reasons) and Tool Design & MCP Integration (tool schemas, descriptions, and error results). Practice both on CertLabPro. Related: the NVIDIA-Certified Professional: Agentic AI (NCP-AAI) domain Agent Architecture and Design covers the same loop.
Previous: Lab 00 - Next: Lab 02 - Durable sessions