Register and share your invite link to earn from video plays and referrals.

cv usk
@cv_usk
AI / Software Research Notes AI Agent, LLMOps, MLOps, Software Architecture ๆŠ•็จฟใฏๅ€‹ไบบใฎๆ„่ฆ‹ใงใ™ใ€‚
Joined May 2026
286 Following    469 Followers
# Useful but Little-Known Features of Claude Agent SDK ๐ŸŒ Do you really know how much your agent runs cost? Detailed tracking makes it visible! Claude Agent SDK provides granular token usage and cost breakdowns for every query. ๐Ÿ“Œ Title: Detailed Cost and Usage Tracking ๐Ÿ”— URL: ๐Ÿงฉ Overview `ResultMessage` includes `total_cost_usd` (estimated cost), `usage` (token breakdown), and `num_turns` (turn count), available on all result subtypes including errors. Additionally, `model_usage` (Python) / `modelUsage` (TypeScript) provides per-model cost and token breakdowns. When parallel tool calls occur, messages share the same ID with duplicate usage data, so ID-based deduplication is essential for accurate counting. ๐Ÿ›  How to Use ```python # Python - Get total cost for a query from claude_agent_sdk import query, ResultMessage async for message in query(prompt="Summarize this project"): if isinstance(message, ResultMessage): print(f"Total cost: ${ or 0}") # Per-model breakdown if message.model_usage: for model, usage in message.model_usage.items(): print(f" {model}: ${usage['costUSD']:.4f}") print(f" Input tokens: {usage['inputTokens']}") print(f" Cache read: {usage['cacheReadInputTokens']}") ``` ```typescript // TypeScript - Accumulate costs across multiple queries import { query } from "@anthropic-ai/claude-agent-sdk"; let totalSpend = 0; for (const prompt of prompts) { for await (const message of query({ prompt })) { if (message.type === "result") { totalSpend += // Per-model breakdown for (const [model, usage] of Object.entries(message.modelUsage)) { console.log(`${model}: $${usage.costUSD.toFixed(4)}`); } } } } console.log(`Total: $${totalSpend.toFixed(4)}`); ``` ๐Ÿ— Integration into Production Systems - Send `total_cost_usd` to monitoring systems for real-time cost trend visualization - Analyze per-model costs via `model_usage` to optimize subagent cost allocation - Calls that `resume` the same session already include the session's earlier spend (Claude Code v2.1.277 and later), so read the latest result rather than summing, which double-counts; implement summation logic only for independent calls that share no session - Errors still incur costs, so always record costs from failed `ResultMessage` instances too ๐Ÿ’ก Use Cases ๐Ÿ’ฐ Report per-user usage costs in multi-tenant environments ๐Ÿ“Š Analyze per-model cost breakdowns to find optimal model configurations ๐Ÿ” Monitor cache token ratios (`cache_read_input_tokens`) to measure prompt caching effectiveness โš ๏ธ Caveats - `total_cost_usd` is a client-side estimate and may differ from actual billing. Use the Usage and Cost API for authoritative billing data - Parallel tool calls produce duplicate messages with the same ID; deduplicate by ID to avoid inflated token counts - Setting `ENABLE_PROMPT_CACHING_1H` enables 1-hour TTL caching but increases write costs โœจ No cost optimization without cost visibility. Start by integrating tracking to understand your agent's spending patterns! #ClaudeAgentSDK# #AIAgent#
Show more