claude-agent-sdk-python icon indicating copy to clipboard operation
claude-agent-sdk-python copied to clipboard

Usage statistics for each step

Open mbt1909432 opened this issue 1 year ago • 4 comments

How to implement usage statistics for each step? The AssistantMessage class doesn't have a usage attribute.

Image Image Image Image

mbt1909432 avatar Oct 22 '25 03:10 mbt1909432

+1. Total usage is only available in ResultMessage. But if there are errors in my workflow, I will never reach ResultMessage and will have no idea of the costs involved.

mrahul16 avatar Oct 22 '25 07:10 mrahul16

claude agent sdk code parsed the event message, you must close the from ._internal.message_parser import parse_message, then looks every event useage.

class ClaudeSDKClient: async def receive_messages(self) -> AsyncIterator[Message]: """Receive all messages from Claude.""" if not self._query: raise CLIConnectionError("Not connected. Call connect() first.")

    from ._internal.message_parser import parse_message

    async for data in self._query.receive_messages():
        yield parse_message(data)

JohnsonXi avatar Oct 24 '25 06:10 JohnsonXi

Workaround: I made a patch that adds .raw field to messages with per-step usage via JSONL correlation.

msg.raw.get('message', {}).get('usage')
# {'input_tokens': 3, 'output_tokens': 77, 'cache_read_input_tokens': ...}

Also gets modelUsage on ResultMessage for per-model breakdown.

Gist: https://gist.github.com/oneryalcin/0f0dc48cdc29dfcbebc4c6dcfe4cbf8f

oneryalcin avatar Jan 12 '26 11:01 oneryalcin

This has been resolved. PR #685 (fc82420, merged in v0.1.49) added the usage field to AssistantMessage, which now captures per-turn usage statistics from the CLI output. You can access per-step usage via msg.usage on any AssistantMessage instance.

Closing as completed.

qing-ant avatar Mar 24 '26 14:03 qing-ant