The two you will see
| stopReason | Means | Do |
|---|---|---|
| tool_use | It decided to call tools. toolCalls is populated. | Run them, append the results, call again. |
| end_turn | It finished. The answer is the content. | Stop. Hand the content to whoever asked. |
const turn = await api.models.turn({ model, messages, tools });
if (turn.stopReason === "tool_use") {
// there is work to do before there is an answer
} else {
return turn.message.content;
}turn = api.models.turn(model=model, messages=messages, tools=tools)
if turn["stopReason"] == "tool_use":
pass # there is work to do before there is an answer
else:
answer = turn["message"]["content"]A turn can carry text and tool calls at once — the model says what it is about to do, then does it. Testing the text first makes your loop stop one step early and lose the work.
When it stopped at the ceiling
A turn can also end because it ran out of room rather than because it was finished. That is not an error — you get a valid response holding an incomplete answer, which is the dangerous case precisely because nothing throws.
// Treat anything that is neither of the two as « did not finish »
const DONE = new Set(["end_turn", "tool_use"]);
if (!DONE.has(turn.stopReason)) {
// Typically the output ceiling. Raise maxOutputTokens, lower thinking,
// or ask for something shorter — but do not use the text as if it were whole.
throw new Error(`the turn did not finish: ${turn.stopReason}`);
}# Treat anything that is neither of the two as « did not finish »
DONE = {"end_turn", "tool_use"}
if turn["stopReason"] not in DONE:
# Typically the output ceiling. Raise max_output_tokens, lower thinking,
# or ask for something shorter — but do not use the text as if it were whole.
raise RuntimeError(f"the turn did not finish: {turn['stopReason']}")The usual cause is maxOutputTokens, and on a thinking model the reasoning is spent from that same ceiling — see thinking.
A loop that terminates
tool_use can repeat. Bound the number of steps, and bound the spend — a loop with neither can run until something else stops it.
const MAX_STEPS = 12;
const MAX_CREDITS = 200;
let spent = 0;
for (let step = 0; step < MAX_STEPS; step += 1) {
const turn = await api.models.turn({ model, messages, tools });
spent += turn.usage.credits;
messages.push(turn.message);
if (turn.stopReason === "end_turn") return turn.message.content;
if (turn.stopReason !== "tool_use") throw new Error(`unfinished: ${turn.stopReason}`);
if (spent > MAX_CREDITS) throw new Error(`budget spent after ${step + 1} steps`);
for (const call of turn.message.toolCalls) {
messages.push({ role: "tool", toolCallId: call.id, name: call.name,
content: String(await run(call.name, call.args)) });
}
}
throw new Error(`no answer after ${MAX_STEPS} steps`);MAX_STEPS = 12
MAX_CREDITS = 200
def solve(messages):
spent = 0
for step in range(MAX_STEPS):
turn = api.models.turn(model=model, messages=messages, tools=tools)
spent += turn["usage"]["credits"]
messages.append(turn["message"])
if turn["stopReason"] == "end_turn":
return turn["message"]["content"]
if turn["stopReason"] != "tool_use":
raise RuntimeError(f"unfinished: {turn['stopReason']}")
if spent > MAX_CREDITS:
raise RuntimeError(f"budget spent after {step + 1} steps")
for call in turn["message"]["toolCalls"]:
messages.append({"role": "tool", "toolCallId": call["id"], "name": call["name"],
"content": str(run(call["name"], call["args"]))})
raise RuntimeError(f"no answer after {MAX_STEPS} steps")The step count catches a loop going in circles. The credit count catches a loop making progress expensively. They fail differently, and a run can hit either.
If that is the loop you were going to write, the agent engine is it — with permissions, budget, retries and a fallback model already in place. See Agent engine.