DSPy: The framework for programming—not prompting—language models
Python
Proposed fix of Issue #10064, rolling up nested cost trackers to the parent on closing (#10065)
Ariel Pérezbb8ba59c0c6d
diff --git a/dspy/utils/usage_tracker.py b/dspy/utils/usage_tracker.pyindex e724e1de0..dcc72e637 100644--- a/dspy/utils/usage_tracker.py+++ b/dspy/utils/usage_tracker.py@@ -32,21 +32,37 @@ class UsageTracker:result[key] = valuereturn result+ @staticmethod+ def _is_summable(value: Any) -> bool:+ """Whether a usage value is a count that can be added across entries.++ `bool` is excluded even though it is an `int` subclass: providers report flags+ (such as OpenRouter's `is_byok`) alongside token counts, and summing those would+ turn a flag into a meaningless tally.+ """+ return isinstance(value, (int, float)) and not isinstance(value, bool)+def _merge_usage_entries(self, usage_entry1: dict[str, Any] | None, usage_entry2: dict[str, Any] | None) -> dict[str, Any]:if usage_entry1 is None or len(usage_entry1) == 0:- return dict(usage_entry2)+ return dict(usage_entry2 or {})if usage_entry2 is None or len(usage_entry2) == 0:- return dict(usage_entry1)+ return dict(usage_entry1 or {})- result = dict(usage_entry2)- for k, v in usage_entry1.items():+ result = dict(usage_entry1)+ for k, v in usage_entry2.items():current_v = result.get(k)if isinstance(v, dict) or isinstance(current_v, dict):result[k] = self._merge_usage_entries(current_v, v)- elif current_v is not None or v is not None:- result[k] = (current_v or 0) + (v or 0)+ elif current_v is None:+ if v is not None:+ result[k] = v+ elif self._is_summable(current_v) and self._is_summable(v):+ result[k] = current_v + v+ # Otherwise keep `current_v` as-is. `usage` is not guaranteed to hold only+ # counts: both litellm's `Usage` and dspy's `LMUsage` allow extra fields, so+ # whatever a provider reports flows through verbatim.return resultdef add_usage(self, lm: str, usage_entry: dict[str, Any]) -> None:@@ -67,8 +83,18 @@ class UsageTracker:@contextmanagerdef track_usage() -> Generator[UsageTracker, None, None]:- """Context manager for tracking LM usage."""+ """Context manager for tracking LM usage.++ When nested, the child will roll-up recorded usage into the parent upon exit.+ Note that usage added after the scope exit will not be recorded in the parent.+ """tracker = UsageTracker()+ parent = settings.usage_trackerwith settings.context(usage_tracker=tracker):- yield tracker+ try:+ yield tracker+ finally:+ if parent is not None:+ for lm, entries in tracker.usage_data.items():+ parent.usage_data[lm].extend(entries)diff --git a/tests/utils/test_usage_tracker.py b/tests/utils/test_usage_tracker.pyindex af303ba12..46e934a8c 100644--- a/tests/utils/test_usage_tracker.py+++ b/tests/utils/test_usage_tracker.py@@ -1,5 +1,7 @@+import asynciofrom unittest import mock+import pytestfrom pydantic import BaseModelimport dspy@@ -392,3 +394,165 @@ def test_parallel_executor_with_usage_tracker():# Parent tracker should remain unchanged (workers have independent copies)assert len(parent_tracker.usage_data) == 0+++def test_non_numeric_usage_values_are_not_accumulated():+ """Non-count fields a provider reports in `usage` are kept, not concatenated or tallied."""+ tracker = UsageTracker()+ tracker.add_usage(+ "openai/gpt-4o-mini",+ {+ "prompt_tokens": 10,+ "completion_tokens": 2,+ "service_tier": "standard",+ "inference_geo": "us",+ "iterations": None,+ "is_byok": False,+ },+ )+ tracker.add_usage(+ "openai/gpt-4o-mini",+ {+ "prompt_tokens": 10,+ "completion_tokens": 2,+ "service_tier": "flex",+ "inference_geo": "us",+ "iterations": None,+ "is_byok": False,+ },+ )++ assert tracker.get_total_tokens()["openai/gpt-4o-mini"] == {+ "prompt_tokens": 20,+ "completion_tokens": 4,+ "service_tier": "standard", # Keeps first+ "inference_geo": "us", # Keeps value+ "iterations": None, # Keeps value+ "is_byok": False, # Keeps bool as-is+ }+++def test_non_numeric_usage_value_present_in_only_some_entries():+ """A field only some calls report must not raise when merged with the entries missing it."""+ tracker = UsageTracker()+ tracker.add_usage("openai/gpt-4o-mini", {"prompt_tokens": 10, "service_tier": "standard"})+ tracker.add_usage("openai/gpt-4o-mini", {"prompt_tokens": 10})++ assert tracker.get_total_tokens()["openai/gpt-4o-mini"] == {+ "prompt_tokens": 20,+ "service_tier": "standard",+ }+++def test_nested_usage_trackers_roll_up():+ """Test that nested usage trackers still reflect usage on the parent."""++ with track_usage() as orchestrator_cost:+ orchestrator_cost.add_usage(+ "openai/gpt-4o-mini",+ {+ "prompt_tokens": 100,+ "completion_tokens": 10,+ "total_tokens": 110,+ },+ )+ with track_usage() as subagent_cost:+ subagent_cost.add_usage(+ "openai/gpt-4o-mini",+ {+ "prompt_tokens": 1000,+ "completion_tokens": 100,+ "total_tokens": 1100,+ },+ )+ orchestrator_cost.add_usage(+ "openai/gpt-4o-mini",+ {+ "prompt_tokens": 10,+ "completion_tokens": 1,+ "total_tokens": 11,+ },+ )++ total_prompt_tokens = 1110+ total_completion_tokens = 111+ total_tokens = total_prompt_tokens + total_completion_tokens+ assert orchestrator_cost.get_total_tokens()["openai/gpt-4o-mini"] == {+ "prompt_tokens": total_prompt_tokens,+ "completion_tokens": total_completion_tokens,+ "total_tokens": total_tokens,+ }+++def test_nested_usage_trackers_roll_up_despite_errors():+ """Test that nested usage trackers still reflect usage on the parent even when child raises."""++ def erroring_subagent():+ with track_usage() as subagent_cost:+ subagent_cost.add_usage(+ "openai/gpt-4o-mini",+ {+ "prompt_tokens": 1000,+ "completion_tokens": 100,+ "total_tokens": 1100,+ },+ )+ raise RuntimeError("!")++ with track_usage() as orchestrator_cost:+ orchestrator_cost.add_usage(+ "openai/gpt-4o-mini",+ {+ "prompt_tokens": 100,+ "completion_tokens": 10,+ "total_tokens": 110,+ },+ )+ try:+ erroring_subagent()+ except RuntimeError:+ pass++ total_prompt_tokens = 1100+ total_completion_tokens = 110+ total_tokens = total_prompt_tokens + total_completion_tokens+ assert orchestrator_cost.get_total_tokens()["openai/gpt-4o-mini"] == {+ "prompt_tokens": total_prompt_tokens,+ "completion_tokens": total_completion_tokens,+ "total_tokens": total_tokens,+ }+++async def test_nested_usage_trackers_support_async_work():+ """Test that nested usage trackers work well with asyncio.gather."""++ async def llm_call():+ dspy.settings.usage_tracker.add_usage(+ "openai/gpt-4o-mini",+ {+ "prompt_tokens": 10,+ "completion_tokens": 1,+ "total_tokens": 11,+ },+ )++ async def subagent():+ with track_usage():+ await llm_call()++ with track_usage() as orchestrator_cost:+ tasks = [+ asyncio.create_task(subagent())+ for _ in range(5)+ ]+ await asyncio.gather(*tasks)++ total_prompt_tokens = 10 * 5+ total_completion_tokens = 1 * 5+ total_tokens = total_prompt_tokens + total_completion_tokens+ assert orchestrator_cost.get_total_tokens()["openai/gpt-4o-mini"] == {+ "prompt_tokens": total_prompt_tokens,+ "completion_tokens": total_completion_tokens,+ "total_tokens": total_tokens,+ }