By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
A support agent told a customer their refund was on the way, and the ticket closed as resolved. Three days later the payment system showed no refund. No refund tool had ever run.
The code had read the first block of the response and sent its text to the user. It never checked stop_reason, the field that says why the model stopped generating. On that turn the model was not answering. It was asking for two tools.
You will meet this bug early. The loop is not a chat window. It is a small state machine, and every turn starts with one question: why did the model stop?
Every assistant response carries a stop_reason. Read it before you read the content. The value tells you which of four things to do next.
| stop_reason | What it means | What your loop does |
|---|---|---|
tool_use | The model wants one or more tools run before it continues | Execute every tool_use block, return every result, loop |
end_turn | The model has finished its answer | Stop and return the content |
max_tokens | Generation hit the output limit and was cut off | Do not act on the content; retry smaller or with more room |
refusal | The model declined the request | Hand off to a person or a fallback, and log it |
You may also see stop_sequence when you set your own stop strings. Treat it as the end of that turn.
Two of these are easy to get wrong. tool_use is not an answer, even when the response also contains friendly text. max_tokens is not a finished turn, even when the text looks complete.
The order matters. The assistant message goes back into the conversation before the results do, and it goes back unchanged. Editing it, or dropping a block you did not understand, breaks the pairing on the next request.
This snippet runs the loop against a scripted stand-in for the model. There is no key and no network. The shape is the shape you will use in production: call, read the stop reason, execute every block, append, send.
def run_agent(goal, call_model, tools, max_steps=6):
messages = [{"role": "user", "content": goal}]
trace = []
for step in range(1, max_steps + 1):
reply = call_model(messages, tools)
stop = reply["stop_reason"]
if stop == "end_turn":
trace.append(f"step {step}: end_turn, stop")
return reply["content"], trace
if stop in ("max_tokens", "refusal"):
trace.append(f"step {step}: {stop}, escalate")
return None, trace
blocks = [b for b in reply["content"] if b["type"] == "tool_use"]
messages.append({"role": "assistant", "content": reply["content"]})
results = []
for block in blocks:
output, is_error = tools[block["name"]](block["input"])
results.append({
"type": "tool_result",
"tool_use_id": block["id"],
"content": output,
"is_error": is_error,
})
messages.append({"role": "user", "content": results})
trace.append(f"step {step}: {len(blocks)} tool_use -> {len(results)} tool_result")
trace.append("step budget exhausted, escalate")
return None, trace
# A scripted model: two tool calls, then a final answer.
SCRIPT = [
{"stop_reason": "tool_use", "content": [
{"type": "tool_use", "id": "tu_1", "name": "get_customer", "input": {"id": "C-88"}},
{"type": "tool_use", "id": "tu_2", "name": "lookup_order", "input": {"id": "A17"}},
]},
{"stop_reason": "end_turn", "content": [
{"type": "text", "text": "Refund of 42.00 issued for order A17."},
]},
]
calls = {"n": 0}
def scripted_model(messages, tools):
reply = SCRIPT[calls["n"]]
calls["n"] += 1
return reply
TOOLS = {
"get_customer": lambda args: ("gold tier", False),
"lookup_order": lambda args: ("delivered, 42.00", False),
}
answer, trace = run_agent("Refund order A17", scripted_model, TOOLS)
print("\n".join(trace))
print("answer:", answer[0]["text"])Three rules keep this loop honest.
tool_result per tool_use_id, in a single user message. A missing result is rejected.is_error and return the message. Dropping a failed call hides the failure from the model.A live loop also needs a budget. Pass max_steps and treat exhaustion as an escalation. If the model keeps asking for tools, the loop stops after six steps and returns nothing rather than pretending the task finished.
Predict first, then check yourself with the snippet.
refusal branch that returns a handoff result instead of None, and decide who receives it.SCRIPT so the first reply has one tool_use block and the second has two. Write the trace you expect before you run it.Key takeaways
stop_reason decides the next move: loop on tool_use, stop on end_turn, escalate on max_tokens and refusal.
Execute every tool_use block in the turn, and return one tool_result per tool_use_id.
Append the assistant message unchanged, then a single user message of results.
A failed tool is a result with is_error, not an omission.
Cap the loop with a step budget; exhaustion is an escalation.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.