Skip to content

Conversation

@vanducng
Copy link
Contributor

Summary

  • Fix KeyError for 'cost_usd' field by using .get() with fallback to 'total_cost'
  • Handle GeneratorExit exception during async cleanup to prevent unhandled exceptions
  • Add try/except for cancel_scope.cancel() to prevent RuntimeError when cancel scope is already exited

Problem

When using the claude-code-sdk with Claude Code CLI, users encounter:

  1. KeyError: 'cost_usd' when parsing result messages
  2. Unhandled exceptions during asyncio shutdown related to task cancellation

Solution

  1. Use .get() method with fallback values for optional fields
  2. Properly handle cleanup exceptions in the async context manager

Test plan

  • Tested with example scripts that previously failed
  • Verified SDK works without runtime errors
  • Both simple queries and multi-turn conversations work correctly

vanducng and others added 2 commits June 14, 2025 23:51
- Fix KeyError for 'cost_usd' by using .get() with fallback to 'total_cost'
- Handle GeneratorExit exception during async cleanup
- Add try/except for cancel_scope.cancel() to prevent RuntimeError

These changes resolve runtime errors when using the SDK with Claude Code CLI.
@ali-coplanet
Copy link

@ltawfik

@Coplanet
Copy link

any update on this?

@ltawfik
Copy link
Collaborator

ltawfik commented Jun 18, 2025

Hey @vanducng, thanks for the PR!

The async cleanup fixes look great. the cost_usd issue has been merged and fixed in latest release, could you remove those changes and keep just the async fixes? Then we can merge this. We also need commit signing to be able to merge PRs in our org, do you mind creating a new PR with commit signing? thank you

@vanducng
Copy link
Contributor Author

Thanks @ltawfik for reviewing. I noticed that the async was also managed in this PR: https://github.com/anthropics/claude-code-sdk-python/pull/17/files#diff-412e6d9cc43bdd5dc2acd95b97eba9b8d6b84fbe8926a526879b9684bc4234ff

So im closing this PR.

@vanducng vanducng closed this Jun 19, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants