File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1414log , result = agent .run ("Analyze the dataset and create a visualization" )
1515print (result )
1616
17- # Access usage metrics — _usage_metrics accumulates across all runs
18- total_cost = sum (u .cost for u in agent ._usage_metrics if u .cost is not None )
19- total_input = sum (u .input_tokens for u in agent ._usage_metrics if u .input_tokens is not None )
20- total_output = sum (u .output_tokens for u in agent ._usage_metrics if u .output_tokens is not None )
17+ # Access usage metrics — agent.usage_metrics accumulates across all runs.
18+ # Note: cost may be None for providers that do not return it in streaming events (e.g. Anthropic).
19+ total_cost = sum (u .cost for u in agent .usage_metrics if u .cost is not None )
20+ total_input = sum (u .input_tokens for u in agent .usage_metrics if u .input_tokens is not None )
21+ total_output = sum (u .output_tokens for u in agent .usage_metrics if u .output_tokens is not None )
22+ total_cache_creation = sum (u .cache_creation_tokens for u in agent .usage_metrics if u .cache_creation_tokens is not None )
23+ total_cache_read = sum (u .cache_read_tokens for u in agent .usage_metrics if u .cache_read_tokens is not None )
2124print (f"\n Usage Metrics:" )
22- print (f"Input tokens: { total_input } " )
23- print (f"Output tokens: { total_output } " )
24- print (f"Total cost: ${ total_cost :.4f} " )
25+ print (f"Input tokens: { total_input } " )
26+ print (f"Output tokens: { total_output } " )
27+ print (f"Cache creation tokens:{ total_cache_creation } " )
28+ print (f"Cache read tokens: { total_cache_read } " )
29+ print (f"Total cost: ${ total_cost :.4f} (may not reflect actual expense for streaming)" )
Original file line number Diff line number Diff line change 6161 print (f"Agent error: { e } " )
6262
6363# ── 5. Lifetime vs per-run usage tracking ─────────────────────────────────────
64- # agent._usage_metrics accumulates across ALL runs on this instance.
64+ # agent.usage_metrics accumulates across ALL runs on this instance.
6565# max_cost is checked against only the CURRENT run's metrics.
6666
6767agent5 = BaseAgent (llm = "claude-sonnet-4-20250514" )
7070log_a , _ = agent5 .run ("What is DNA?" )
7171log_b , _ = agent5 .run ("What is RNA?" ) # new run; budget resets
7272
73- total_cost = sum (u .cost for u in agent5 ._usage_metrics if u .cost is not None )
73+ total_cost = sum (u .cost for u in agent5 .usage_metrics if u .cost is not None )
7474print (f"Lifetime cost across both runs: ${ total_cost :.4f} " )
7575
7676# ── 6. Configure via environment variables ────────────────────────────────────
You can’t perform that action at this time.
0 commit comments