Skip to content

Commit 18e5899

Browse files
committed
Fix KeyError: 'cost_usd' for Max subscription users
This fix addresses issue anthropics#2 where Max subscription users encounter a KeyError when the API response doesn't include the 'cost_usd' field. Changes: - Modified ResultMessage dataclass to make cost_usd and total_cost_usd optional (float | None) - Updated client.py to use .get() with None default for cost-related fields - Maintains backward compatibility for users with cost data This ensures the SDK works for all subscription types, including Max subscriptions that don't have access to cost information. By: Unclecode <https://github.com/unclecode>
1 parent 54bff2e commit 18e5899

3 files changed

Lines changed: 30 additions & 4 deletions

File tree

‎src/claude_code_sdk/_internal/client.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,15 +84,16 @@ def _parse_message(self, data: dict[str, Any]) -> Message | None:
8484

8585
case "result":
8686
# Map total_cost to total_cost_usd for consistency
87+
# Handle missing cost_usd for Max subscription users
8788
return ResultMessage(
8889
subtype=data["subtype"],
89-
cost_usd=data["cost_usd"],
90+
cost_usd=data.get("cost_usd", None),
9091
duration_ms=data["duration_ms"],
9192
duration_api_ms=data["duration_api_ms"],
9293
is_error=data["is_error"],
9394
num_turns=data["num_turns"],
9495
session_id=data["session_id"],
95-
total_cost_usd=data["total_cost"],
96+
total_cost_usd=data.get("total_cost", None),
9697
usage=data.get("usage"),
9798
result=data.get("result"),
9899
)

‎src/claude_code_sdk/types.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,13 +75,13 @@ class ResultMessage:
7575
"""Result message with cost and usage information."""
7676

7777
subtype: str
78-
cost_usd: float
78+
cost_usd: float | None
7979
duration_ms: int
8080
duration_api_ms: int
8181
is_error: bool
8282
num_turns: int
8383
session_id: str
84-
total_cost_usd: float
84+
total_cost_usd: float | None
8585
usage: dict[str, Any] | None = None
8686
result: str | None = None
8787

‎test_fix.py‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#!/usr/bin/env python3
2+
"""Test script to verify the cost_usd fix works."""
3+
4+
import anyio
5+
from claude_code_sdk import process_query, ClaudeCodeOptions
6+
7+
async def main():
8+
"""Test the SDK with a simple query."""
9+
print("Testing claude-code-sdk with cost_usd fix...")
10+
11+
try:
12+
# Simple test query
13+
async for message in process_query(
14+
"What is 2+2?",
15+
ClaudeCodeOptions()
16+
):
17+
print(f"Message type: {type(message).__name__}")
18+
print(f"Message: {message}")
19+
print("-" * 40)
20+
except Exception as e:
21+
print(f"Error: {type(e).__name__}: {e}")
22+
raise
23+
24+
if __name__ == "__main__":
25+
anyio.run(main)

0 commit comments

Comments
 (0)