Skip to content

Commit 3cbb9e5

Browse files
majiayu000claudehappy-otter
authored
fix: parse error field in AssistantMessage to enable rate limit detection (#405)
## Summary Fixes #401 Enables applications to detect API errors (especially `rate_limit` errors) by properly parsing the `error` field in `AssistantMessage`. ## Problem The SDK defines `AssistantMessage.error` (including `"rate_limit"`), but the message parser never extracted this field from the CLI response. This made it impossible for applications to: - Detect when rate limits are hit - Implement retry logic - Handle other API errors gracefully ## Solution Added error field extraction in the message parser: ```python return AssistantMessage( content=content_blocks, model=data["message"]["model"], parent_tool_use_id=data.get("parent_tool_use_id"), error=data["message"].get("error"), # ← Now extracts error field ) ``` ## Changes **Modified: `src/claude_agent_sdk/_internal/message_parser.py`** The parser now extracts the `error` field from API responses and populates it in the `AssistantMessage` object. ## Usage Example Applications can now detect and handle rate limits: ```python async for message in client.receive_response(): if isinstance(message, AssistantMessage): if message.error == "rate_limit": print("Rate limit hit! Implementing backoff...") await asyncio.sleep(60) # Retry logic here elif message.error: print(f"API error: {message.error}") ``` ## Testing - ✅ Passed ruff linting and formatting - ✅ Passed mypy type checking - ✅ All existing tests pass ## Type of Change - [x] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) ## Impact This fix enables production applications to: - Implement proper error handling for API errors - Build robust retry logic for rate limits - Provide better user feedback when errors occur - Avoid silent failures when the API returns errors --- 🤖 Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude <[email protected]> Co-Authored-By: Happy <[email protected]> Co-authored-by: Claude <[email protected]> Co-authored-by: Happy <[email protected]>
1 parent 5b91296 commit 3cbb9e5

File tree

1 file changed

+1
-0
lines changed

1 file changed

+1
-0
lines changed

src/claude_agent_sdk/_internal/message_parser.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,7 @@ def parse_message(data: dict[str, Any]) -> Message:
120120
content=content_blocks,
121121
model=data["message"]["model"],
122122
parent_tool_use_id=data.get("parent_tool_use_id"),
123+
error=data["message"].get("error"),
123124
)
124125
except KeyError as e:
125126
raise MessageParseError(

0 commit comments

Comments
 (0)