{"record":{"id":"e52b13881d0b10af","repo":"rohitg00/ai-engineering-from-scratch","slug":"unsupported-stop-reason-stop-reason-r","errorCode":null,"errorMessage":"unsupported stop_reason: {stop_reason!r}","messagePattern":"unsupported stop_reason: (.+?)","errorType":"exception","errorClass":"ProtocolError","httpStatus":null,"severity":"error","filePath":"certifications/claude/lessons/08-messages-api-and-application-lifecycle/code/main.py","lineNumber":104,"sourceCode":"    def run(self, user_text: str) -> RunResult:\n        if not user_text.strip():\n            raise ValueError(\"user_text must not be empty\")\n        messages: list[dict[str, Any]] = [\n            {\"role\": \"user\", \"content\": [{\"type\": \"text\", \"text\": user_text}]}\n        ]\n\n        for turn in range(1, self.max_turns + 1):\n            response = self.transport.create(messages)\n            blocks = _validated_blocks(response)\n            stop_reason = response.get(\"stop_reason\")\n\n            # The assistant tool_use block must be retained before tool_result.\n            messages.append({\"role\": \"assistant\", \"content\": copy.deepcopy(blocks)})\n\n            if stop_reason == \"end_turn\":\n                return RunResult(_text_from_blocks(blocks), messages, turn)\n            if stop_reason != \"tool_use\":\n                raise ProtocolError(f\"unsupported stop_reason: {stop_reason!r}\")\n\n            tool_results = [self._execute_tool(block) for block in blocks if block[\"type\"] == \"tool_use\"]\n            if not tool_results:\n                raise ProtocolError(\"stop_reason tool_use had no tool_use block\")\n            messages.append({\"role\": \"user\", \"content\": tool_results})\n\n        raise ProtocolError(f\"maximum turn count {self.max_turns} exceeded\")\n\n    def _execute_tool(self, block: dict[str, Any]) -> dict[str, Any]:\n        tool_id = block.get(\"id\")\n        name = block.get(\"name\")\n        arguments = block.get(\"input\")\n        if not isinstance(tool_id, str) or not tool_id:\n            raise ProtocolError(\"tool_use requires a non-empty id\")\n        if not isinstance(name, str) or not isinstance(arguments, dict):\n            raise ProtocolError(\"tool_use requires name and object input\")\n\n        handler = self.tools.get(name)","sourceCodeStart":86,"sourceCodeEnd":122,"githubUrl":"https://github.com/rohitg00/ai-engineering-from-scratch/blob/39ea8a1c6d0b61f071226eff7ede4d4105fed820/certifications/claude/lessons/08-messages-api-and-application-lifecycle/code/main.py#L86-L122","documentation":"Protocol assertion inside the turn loop: the response's stop_reason is neither 'end_turn' nor 'tool_use' (e.g. 'max_tokens', 'stop_sequence', or missing). The lifecycle implements only those two transitions, so it raises ProtocolError rather than guessing how to continue.","triggerScenarios":"Thrown at certifications/claude/lessons/08-messages-api-and-application-lifecycle/code/main.py:104 when the library encounters an invalid state.","commonSituations":"See trigger scenarios.","solutions":["Script responses to end with stop_reason 'end_turn' after the tool round-trips","Handle additional stop reasons explicitly (e.g. surface 'max_tokens' truncation to the caller)","Log the offending response payload when the assertion fires to speed fixture repair"],"exampleFix":null,"handlingStrategy":"validation","validationCode":null,"typeGuard":null,"tryCatchPattern":null,"preventionTips":[],"tags":[],"backgroundTag":null,"analyzedSha":"39ea8a1c6d0b61f071226eff7ede4d4105fed820","analyzedAt":"2026-08-26T03:13:46.626Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}