Get an API key
api.models

turn · stop reasons

turn.stopReason

Why the model stopped. It is the field your loop branches on, and the one that tells a finished answer from a truncated one.

tool_use · end_turnbranch on it, not on the text
Using Python?

Switch any code block to Python: the choice applies to every page. Python SDK guide and resource reference.

The two you will see

stopReasonMeansDo
tool_useIt decided to call tools. toolCalls is populated.Run them, append the results, call again.
end_turnIt 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"]
Branch on stopReason, never on whether toolCalls is empty

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")
Both bounds earn their place

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.