rohitg00/ai-engineering-from-scratch · error · ProtocolError
maximum turn count exceeded
Error message
maximum turn count {self.max_turns} exceeded What it means
Runaway-loop guard: the conversation consumed all max_turns turns without the model returning end_turn — usually a scripted tool chain that never terminates or a model stuck in a tool loop. The lifecycle raises instead of looping forever, preserving the transcript collected so far.
Solutions
- Raise max_turns if the legitimate tool chain is longer than the budget
- Fix the scripted/model behavior so a turn eventually ends without requesting tools
- Catch ProtocolError and return the partial transcript plus turn count as a degraded result
Defensive patterns
Strategy: fallback
When it happens
Trigger: Thrown at certifications/claude/lessons/08-messages-api-and-application-lifecycle/code/main.py:111 when the library encounters an invalid state.
Common situations: See trigger scenarios.
AI-assisted analysis of rohitg00/ai-engineering-from-scratch@39ea8a1c6d (2026-08-26).
Data as JSON: /api/errors/a8e20f055805b51d.
Report an issue: GitHub.
Appendix: source
Thrown at certifications/claude/lessons/08-messages-api-and-application-lifecycle/code/main.py:111
for turn in range(1, self.max_turns + 1):
response = self.transport.create(messages)
blocks = _validated_blocks(response)
stop_reason = response.get("stop_reason")
# The assistant tool_use block must be retained before tool_result.
messages.append({"role": "assistant", "content": copy.deepcopy(blocks)})
if stop_reason == "end_turn":
return RunResult(_text_from_blocks(blocks), messages, turn)
if stop_reason != "tool_use":
raise ProtocolError(f"unsupported stop_reason: {stop_reason!r}")
tool_results = [self._execute_tool(block) for block in blocks if block["type"] == "tool_use"]
if not tool_results:
raise ProtocolError("stop_reason tool_use had no tool_use block")
messages.append({"role": "user", "content": tool_results})
raise ProtocolError(f"maximum turn count {self.max_turns} exceeded")
def _execute_tool(self, block: dict[str, Any]) -> dict[str, Any]:
tool_id = block.get("id")
name = block.get("name")
arguments = block.get("input")
if not isinstance(tool_id, str) or not tool_id:
raise ProtocolError("tool_use requires a non-empty id")
if not isinstance(name, str) or not isinstance(arguments, dict):
raise ProtocolError("tool_use requires name and object input")
handler = self.tools.get(name)
if handler is None:
return {
"type": "tool_result",
"tool_use_id": tool_id,
"content": f"Unknown tool: {name}",
"is_error": True,
}View on GitHub (pinned to 39ea8a1c6d)