{"record":{"id":"a0454e9f05222aa8","repo":"rohitg00/ai-engineering-from-scratch","slug":"tool-use-requires-name-and-object-input","errorCode":null,"errorMessage":"tool_use requires name and object input","messagePattern":"tool_use requires name and object input","errorType":"exception","errorClass":"ProtocolError","httpStatus":null,"severity":"error","filePath":"certifications/claude/lessons/08-messages-api-and-application-lifecycle/code/main.py","lineNumber":120,"sourceCode":"                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)\n        if handler is None:\n            return {\n                \"type\": \"tool_result\",\n                \"tool_use_id\": tool_id,\n                \"content\": f\"Unknown tool: {name}\",\n                \"is_error\": True,\n            }\n        try:\n            value = handler(arguments)\n            return {\n                \"type\": \"tool_result\",\n                \"tool_use_id\": tool_id,\n                \"content\": json.dumps(value, sort_keys=True),\n            }\n        except Exception as exc:  # Tool failures become model-visible results.\n            return {","sourceCodeStart":102,"sourceCodeEnd":138,"githubUrl":"https://github.com/rohitg00/ai-engineering-from-scratch/blob/39ea8a1c6d0b61f071226eff7ede4d4105fed820/certifications/claude/lessons/08-messages-api-and-application-lifecycle/code/main.py#L102-L138","documentation":"Raised by _execute_tool when a model-emitted tool_use content block has a name that is not a string or an input that is not a dict. The Messages API contract requires every tool_use block to carry a string tool name and a JSON object as input; the offline runtime enforces this before dispatching to a handler.","triggerScenarios":"Calling run() with a scripted model response whose tool_use block omits 'name', sets it to null/number, or supplies 'input' as a string/list instead of an object.","commonSituations":"Hand-rolled mock model responses in tests, replaying captured transcripts where input was serialized to a string, or porting from an API version that allowed absent input.","solutions":["Ensure the tool_use block includes a string 'name' matching a registered tool","Pass 'input' as a dict, e.g. {\"query\":\"...\"} not a JSON string","If mocking responses, build blocks via a helper that always sets both fields"],"exampleFix":"// before\n{\"type\":\"tool_use\",\"id\":\"t1\",\"name\":\"search\",\"input\":\"{}\"}\n// after\n{\"type\":\"tool_use\",\"id\":\"t1\",\"name\":\"search\",\"input\":{\"q\":\"x\"}}","handlingStrategy":"validation","validationCode":"def is_valid_tool_use(block):\n    return (\n        isinstance(block, dict)\n        and isinstance(block.get(\"id\"), str) and block[\"id\"]\n        and isinstance(block.get(\"name\"), str)\n        and isinstance(block.get(\"input\"), dict)\n    )","typeGuard":"def is_tool_use(block: object) -> bool:\n    b = block if isinstance(block, dict) else {}\n    return isinstance(b.get(\"name\"), str) and isinstance(b.get(\"input\"), dict)","tryCatchPattern":"try:\n    result = agent.run(...)\nexcept ProtocolError as exc:\n    if \"tool_use requires\" in str(exc):\n        log_and_repair_model_response(exc)","preventionTips":["Build tool_use blocks through one helper that sets id/name/input with correct types","Validate scripted model responses with the same guard before feeding them to run()"],"tags":["messages-api","tool-use","validation","python"],"backgroundTag":"tool-use-input-validation","analyzedSha":"39ea8a1c6d0b61f071226eff7ede4d4105fed820","analyzedAt":"2026-08-26T03:13:46.626Z","schemaVersion":2},"datasetVersion":"2026-08-26T07:17:17.940Z"}