Skip to content

armgit / dspy

Public Imported from GitHub
0

DSPy: The framework for programming—not prompting—language models

Python

Add usage tracking (#8014)

Chen Qian7cdfe988e640
diff --git a/docs/docs/learn/programming/modules.md b/docs/docs/learn/programming/modules.md
index 3275ee0ae..792a89af5 100644
--- a/docs/docs/learn/programming/modules.md
+++ b/docs/docs/learn/programming/modules.md
@@ -244,3 +244,93 @@ class Hop(dspy.Module):
return dspy.Prediction(notes=notes, titles=list(set(titles)))
```
+
+## How do I track LM usage?
+
+!!! note "Version Requirement"
+ LM usage tracking is available in DSPy version 2.6.16 and later.
+
+DSPy provides built-in tracking of language model usage across all module calls. To enable tracking:
+
+```python
+dspy.settings.configure(track_usage=True)
+```
+
+Once enabled, you can access usage statistics from any `dspy.Prediction` object:
+
+```python
+usage = prediction_instance.get_lm_usage()
+```
+
+The usage data is returned as a dictionary that maps each language model name to its usage statistics. Here's a complete example:
+
+```python
+import dspy
+
+# Configure DSPy with tracking enabled
+dspy.settings.configure(
+ lm=dspy.LM("openai/gpt-4o-mini", cache=False),
+ track_usage=True
+)
+
+# Define a simple program that makes multiple LM calls
+class MyProgram(dspy.Module):
+ def __init__(self):
+ self.predict1 = dspy.ChainOfThought("question -> answer")
+ self.predict2 = dspy.ChainOfThought("question, answer -> score")
+
+ def __call__(self, question: str) -> str:
+ answer = self.predict1(question=question)
+ score = self.predict2(question=question, answer=answer)
+ return score
+
+# Run the program and check usage
+program = MyProgram()
+output = program(question="What is the capital of France?")
+print(output.get_lm_usage())
+```
+
+This will output usage statistics like:
+
+```python
+{
+ 'openai/gpt-4o-mini': {
+ 'completion_tokens': 61,
+ 'prompt_tokens': 260,
+ 'total_tokens': 321,
+ 'completion_tokens_details': {
+ 'accepted_prediction_tokens': 0,
+ 'audio_tokens': 0,
+ 'reasoning_tokens': 0,
+ 'rejected_prediction_tokens': 0,
+ 'text_tokens': None
+ },
+ 'prompt_tokens_details': {
+ 'audio_tokens': 0,
+ 'cached_tokens': 0,
+ 'text_tokens': None,
+ 'image_tokens': None
+ }
+ }
+}
+```
+
+When using DSPy's caching features (either in-memory or on-disk via litellm), cached responses won't count toward usage statistics. For example:
+
+```python
+# Enable caching
+dspy.settings.configure(
+ lm=dspy.LM("openai/gpt-4o-mini", cache=True),
+ track_usage=True
+)
+
+program = MyProgram()
+
+# First call - will show usage statistics
+output = program(question="What is the capital of Zambia?")
+print(output.get_lm_usage()) # Shows token usage
+
+# Second call - same question, will use cache
+output = program(question="What is the capital of Zambia?")
+print(output.get_lm_usage()) # Shows empty dict: {}
+```
diff --git a/dspy/__init__.py b/dspy/__init__.py
index 74cad5a39..70e7de708 100644
--- a/dspy/__init__.py
+++ b/dspy/__init__.py
@@ -13,6 +13,7 @@ from dspy.utils.logging_utils import configure_dspy_loggers, disable_logging, en
from dspy.utils.asyncify import asyncify
from dspy.utils.saving import load
from dspy.utils.streaming import streamify
+from dspy.utils.usage_tracker import track_usage
from dspy.dsp.utils.settings import settings
diff --git a/dspy/clients/__init__.py b/dspy/clients/__init__.py
index 19217fb7d..48fa730a9 100644
--- a/dspy/clients/__init__.py
+++ b/dspy/clients/__init__.py
@@ -13,6 +13,14 @@ logger = logging.getLogger(__name__)
DISK_CACHE_DIR = os.environ.get("DSPY_CACHEDIR") or os.path.join(Path.home(), ".dspy_cache")
DISK_CACHE_LIMIT = int(os.environ.get("DSPY_CACHE_LIMIT", 3e10)) # 30 GB default
+
+def _litellm_track_cache_hit_callback(kwargs, completion_response, start_time, end_time):
+ # Access the cache_hit information
+ completion_response.cache_hit = kwargs.get("cache_hit", False)
+
+
+litellm.success_callback = [_litellm_track_cache_hit_callback]
+
try:
# TODO: There's probably value in getting litellm to support FanoutCache and to separate the limit for
# the LM cache from the embeddings cache. Then we can lower the default 30GB limit.
diff --git a/dspy/clients/lm.py b/dspy/clients/lm.py
index adaba55e7..39dcbc0b7 100644
--- a/dspy/clients/lm.py
+++ b/dspy/clients/lm.py
@@ -18,6 +18,7 @@ import dspy
from dspy.clients.openai import OpenAIProvider
from dspy.clients.provider import Provider, TrainingJob
from dspy.clients.utils_finetune import TrainDataFormat
+from dspy.dsp.utils.settings import settings
from dspy.utils.callback import BaseCallback, with_callbacks
from .base_lm import BaseLM
@@ -108,20 +109,24 @@ class LM(BaseLM):
if cache_in_memory:
completion = cached_litellm_completion if self.model_type == "chat" else cached_litellm_text_completion
- return completion(
+ results = completion(
request=dict(model=self.model, messages=messages, **kwargs),
num_retries=self.num_retries,
)
else:
completion = litellm_completion if self.model_type == "chat" else litellm_text_completion
- return completion(
+ results = completion(
request=dict(model=self.model, messages=messages, **kwargs),
num_retries=self.num_retries,
# only leverage LiteLLM cache in this case
cache={"no-cache": not cache, "no-store": not cache},
)
+ if not getattr(results, "cache_hit", False) and dspy.settings.usage_tracker and hasattr(results, "usage"):
+ settings.usage_tracker.add_usage(self.model, dict(results.usage))
+ return results
+
def launch(self, launch_kwargs: Optional[Dict[str, Any]] = None):
self.provider.launch(self, launch_kwargs)
@@ -259,6 +264,12 @@ def request_cache(maxsize: Optional[int] = None):
# If the cache key cannot be computed (e.g. because it contains a value that cannot
# be converted to JSON), bypass the cache and call the target function directly
return func(request, *args, **kwargs)
+ cache_hit = key in func_cached.cache
+ output = func_cached(key, request, *args, **kwargs)
+ if cache_hit and hasattr(output, "usage"):
+ # Clear the usage data when cache is hit, because no LM call is made
+ output.usage = {}
+
return func_cached(key, request, *args, **kwargs)
return wrapper
diff --git a/dspy/dsp/utils/settings.py b/dspy/dsp/utils/settings.py
index 98d96d6ac..fad3cc67f 100644
--- a/dspy/dsp/utils/settings.py
+++ b/dspy/dsp/utils/settings.py
@@ -20,6 +20,8 @@ DEFAULT_CONFIG = dotdict(
async_max_workers=8,
send_stream=None,
disable_history=False,
+ track_usage=False,
+ usage_tracker=None,
)
# Global base configuration and owner tracking
diff --git a/dspy/predict/parallel.py b/dspy/predict/parallel.py
index 9fa74ebe6..0c03ad96c 100644
--- a/dspy/predict/parallel.py
+++ b/dspy/predict/parallel.py
@@ -1,6 +1,5 @@
import threading
-
-from typing import Tuple, List, Any
+from typing import Any, List, Tuple
from dspy.primitives.example import Example
from dspy.utils.parallelizer import ParallelExecutor
diff --git a/dspy/primitives/prediction.py b/dspy/primitives/prediction.py
index 63b74873f..b05b3857c 100644
--- a/dspy/primitives/prediction.py
+++ b/dspy/primitives/prediction.py
@@ -9,6 +9,13 @@ class Prediction(Example):
del self._input_keys
self._completions = None
+ self._lm_usage = None
+
+ def get_lm_usage(self):
+ return self._lm_usage
+
+ def set_lm_usage(self, value):
+ self._lm_usage = value
@classmethod
def from_completions(cls, list_or_dict, signature=None):
@@ -29,7 +36,7 @@ class Prediction(Example):
def __str__(self):
return self.__repr__()
-
+
def __float__(self):
if "score" not in self._store:
raise ValueError("Prediction object does not have a 'score' field to convert to float.")
@@ -41,7 +48,7 @@ class Prediction(Example):
elif isinstance(other, Prediction):
return self.__float__() + float(other)
raise TypeError(f"Unsupported type for addition: {type(other)}")
-
+
def __radd__(self, other):
if isinstance(other, (float, int)):
return other + self.__float__()
@@ -55,7 +62,7 @@ class Prediction(Example):
elif isinstance(other, Prediction):
return self.__float__() / float(other)
raise TypeError(f"Unsupported type for division: {type(other)}")
-
+
def __rtruediv__(self, other):
if isinstance(other, (float, int)):
return other / self.__float__()
@@ -69,21 +76,21 @@ class Prediction(Example):
elif isinstance(other, Prediction):
return self.__float__() < float(other)
raise TypeError(f"Unsupported type for comparison: {type(other)}")
-
+
def __le__(self, other):
if isinstance(other, (float, int)):
return self.__float__() <= other
elif isinstance(other, Prediction):
return self.__float__() <= float(other)
raise TypeError(f"Unsupported type for comparison: {type(other)}")
-
+
def __gt__(self, other):
if isinstance(other, (float, int)):
return self.__float__() > other
elif isinstance(other, Prediction):
return self.__float__() > float(other)
raise TypeError(f"Unsupported type for comparison: {type(other)}")
-
+
def __ge__(self, other):
if isinstance(other, (float, int)):
return self.__float__() >= other
diff --git a/dspy/primitives/program.py b/dspy/primitives/program.py
index 07b5cd4bb..a0592df3b 100644
--- a/dspy/primitives/program.py
+++ b/dspy/primitives/program.py
@@ -1,8 +1,10 @@
import magicattr
+from dspy.dsp.utils.settings import settings
from dspy.predict.parallel import Parallel
from dspy.primitives.module import BaseModule
from dspy.utils.callback import with_callbacks
+from dspy.utils.usage_tracker import track_usage
class ProgramMeta(type):
@@ -19,6 +21,12 @@ class Module(BaseModule, metaclass=ProgramMeta):
@with_callbacks
def __call__(self, *args, **kwargs):
+ if settings.track_usage and settings.usage_tracker is None:
+ with track_usage() as usage_tracker:
+ output = self.forward(*args, **kwargs)
+ output.set_lm_usage(usage_tracker.get_total_tokens())
+ return output
+
return self.forward(*args, **kwargs)
def named_predictors(self):
diff --git a/dspy/utils/parallelizer.py b/dspy/utils/parallelizer.py
index 5541e380a..404aab1dc 100644
--- a/dspy/utils/parallelizer.py
+++ b/dspy/utils/parallelizer.py
@@ -1,13 +1,14 @@
-import sys
-import tqdm
-import signal
+import contextlib
+import copy
import logging
+import signal
+import sys
import threading
-import traceback
import time
-import contextlib
+import traceback
+from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
-from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED
+import tqdm
logger = logging.getLogger(__name__)
@@ -27,7 +28,7 @@ class ParallelExecutor:
Offers isolation between the tasks (dspy.settings) irrespective of whether num_threads == 1 or > 1.
Handles also straggler timeouts.
"""
-
+
self.num_threads = num_threads
self.max_errors = max_errors
self.disable_progress_bar = disable_progress_bar
@@ -59,10 +60,7 @@ class ParallelExecutor:
if self.provide_traceback:
logger.error(f"Error for {item}: {e}\n{traceback.format_exc()}")
else:
- logger.error(
- f"Error for {item}: {e}. "
- "Set `provide_traceback=True` for traceback."
- )
+ logger.error(f"Error for {item}: {e}. " "Set `provide_traceback=True` for traceback.")
return None
return safe_func
@@ -89,6 +87,9 @@ class ParallelExecutor:
original = thread_local_overrides.overrides
thread_local_overrides.overrides = parent_overrides.copy()
+ if parent_overrides.get("usage_tracker"):
+ # Usage tracker needs to be deep copied across threads so that each thread tracks its own usage
+ thread_local_overrides.overrides["usage_tracker"] = copy.deepcopy(parent_overrides["usage_tracker"])
try:
return index, function(item)
@@ -126,9 +127,7 @@ class ParallelExecutor:
submission_counter = 0
for idx, item in enumerate(data):
- f = executor.submit(
- worker, parent_overrides, submission_counter, idx, item
- )
+ f = executor.submit(worker, parent_overrides, submission_counter, idx, item)
futures_map[f] = (submission_counter, idx, item)
futures_set.add(f)
submission_counter += 1
@@ -146,9 +145,7 @@ class ParallelExecutor:
while futures_set and not self.cancel_jobs.is_set():
if all_done():
break
- done, not_done = wait(
- futures_set, timeout=1, return_when=FIRST_COMPLETED
- )
+ done, not_done = wait(futures_set, timeout=1, return_when=FIRST_COMPLETED)
for f in done:
futures_set.remove(f)
try:
diff --git a/dspy/utils/usage_tracker.py b/dspy/utils/usage_tracker.py
new file mode 100644
index 000000000..857b1d021
--- /dev/null
+++ b/dspy/utils/usage_tracker.py
@@ -0,0 +1,69 @@
+"""Usage tracking utilities for DSPy."""
+
+from collections import defaultdict
+from contextlib import contextmanager
+from typing import Any
+
+from dspy.dsp.utils.settings import settings
+
+
+class UsageTracker:
+ """Tracks LM usage data within a context."""
+
+ def __init__(self):
+ # Map of LM name to list of usage entries. For example:
+ # {
+ # "openai/gpt-4o-mini": [
+ # {"prompt_tokens": 100, "completion_tokens": 200},
+ # {"prompt_tokens": 300, "completion_tokens": 400},
+ # ],
+ # }
+ self.usage_data = defaultdict(list)
+
+ def _flatten_usage_entry(self, usage_entry) -> dict[str, dict[str, Any]]:
+ result = dict(usage_entry)
+ if "completion_tokens_details" in result:
+ result["completion_tokens_details"] = dict(result["completion_tokens_details"])
+ if "prompt_tokens_details" in result:
+ result["prompt_tokens_details"] = dict(result["prompt_tokens_details"])
+ return result
+
+ def _merge_usage_entries(self, usage_entry1, usage_entry2) -> dict[str, dict[str, Any]]:
+ if usage_entry1 is None or len(usage_entry1) == 0:
+ return dict(usage_entry2)
+ if usage_entry2 is None or len(usage_entry2) == 0:
+ return dict(usage_entry1)
+
+ result = dict(usage_entry2)
+ for k, v in usage_entry1.items():
+ if k in result:
+ if isinstance(v, dict):
+ result[k] = self._merge_usage_entries(result[k], v)
+ else:
+ result[k] = result[k] or 0
+ result[k] += v if v else 0
+ return result
+
+ def add_usage(self, lm: str, usage_entry: dict):
+ """Add a usage entry to the tracker."""
+ if len(usage_entry) > 0:
+ self.usage_data[lm].append(self._flatten_usage_entry(usage_entry))
+
+ def get_total_tokens(self) -> dict[str, dict[str, Any]]:
+ """Calculate total tokens from all tracked usage."""
+ total_usage_by_lm = {}
+ for lm, usage_entries in self.usage_data.items():
+ total_usage = {}
+ for usage_entry in usage_entries:
+ total_usage = self._merge_usage_entries(total_usage, usage_entry)
+ total_usage_by_lm[lm] = total_usage
+ return total_usage_by_lm
+
+
+@contextmanager
+def track_usage():
+ """Context manager for tracking LM usage."""
+ tracker = UsageTracker()
+
+ with settings.context(usage_tracker=tracker):
+ yield tracker
diff --git a/tests/primitives/test_module.py b/tests/primitives/test_module.py
index 1d458eddb..886213847 100644
--- a/tests/primitives/test_module.py
+++ b/tests/primitives/test_module.py
@@ -3,6 +3,8 @@ import threading
from dspy.utils.dummies import DummyLM
import logging
from unittest.mock import patch
+import pytest
+import os
def test_deepcopy_basic():
@@ -161,3 +163,83 @@ def test_load_with_version_mismatch(tmp_path):
# Clean up: restore original level and remove handler
logger.setLevel(original_level)
logger.removeHandler(handler)
+
+
[email protected](not os.getenv("OPENAI_API_KEY"), reason="Skip the test if OPENAI_API_KEY is not set.")
+def test_single_module_call_with_usage_tracker():
+ dspy.settings.configure(lm=dspy.LM("openai/gpt-4o-mini", cache=False), track_usage=True)
+
+ predict = dspy.ChainOfThought("question -> answer")
+ output = predict(question="What is the capital of France?")
+
+ lm_usage = output.get_lm_usage()
+ assert len(lm_usage) == 1
+ assert lm_usage["openai/gpt-4o-mini"]["prompt_tokens"] > 0
+ assert lm_usage["openai/gpt-4o-mini"]["completion_tokens"] > 0
+ assert lm_usage["openai/gpt-4o-mini"]["total_tokens"] > 0
+
+ # Test no usage being tracked when cache is enabled
+ dspy.settings.configure(lm=dspy.LM("openai/gpt-4o-mini", cache=True), track_usage=True)
+ for _ in range(2):
+ output = predict(question="What is the capital of France?")
+
+ assert len(output.get_lm_usage()) == 0
+
+
[email protected](not os.getenv("OPENAI_API_KEY"), reason="Skip the test if OPENAI_API_KEY is not set.")
+def test_multi_module_call_with_usage_tracker():
+ dspy.settings.configure(lm=dspy.LM("openai/gpt-4o-mini", cache=False), track_usage=True)
+
+ class MyProgram(dspy.Module):
+ def __init__(self):
+ self.predict1 = dspy.ChainOfThought("question -> answer")
+ self.predict2 = dspy.ChainOfThought("question, answer -> score")
+
+ def __call__(self, question: str) -> str:
+ answer = self.predict1(question=question)
+ score = self.predict2(question=question, answer=answer)
+ return score
+
+ program = MyProgram()
+ output = program(question="What is the capital of France?")
+
+ lm_usage = output.get_lm_usage()
+ assert len(lm_usage) == 1
+ assert lm_usage["openai/gpt-4o-mini"]["prompt_tokens"] > 0
+ assert lm_usage["openai/gpt-4o-mini"]["prompt_tokens"] > 0
+ assert lm_usage["openai/gpt-4o-mini"]["completion_tokens"] > 0
+ assert lm_usage["openai/gpt-4o-mini"]["total_tokens"] > 0
+
+
[email protected](not os.getenv("OPENAI_API_KEY"), reason="Skip the test if OPENAI_API_KEY is not set.")
+def test_usage_tracker_in_parallel():
+ class MyProgram(dspy.Module):
+ def __init__(self, lm):
+ self.lm = lm
+ self.predict1 = dspy.ChainOfThought("question -> answer")
+ self.predict2 = dspy.ChainOfThought("question, answer -> score")
+
+ def __call__(self, question: str) -> str:
+ with dspy.settings.context(lm=self.lm):
+ answer = self.predict1(question=question)
+ score = self.predict2(question=question, answer=answer)
+ return score
+
+ dspy.settings.configure(track_usage=True)
+ program1 = MyProgram(lm=dspy.LM("openai/gpt-4o-mini", cache=False))
+ program2 = MyProgram(lm=dspy.LM("openai/gpt-3.5-turbo", cache=False))
+
+ parallelizer = dspy.Parallel()
+
+ results = parallelizer(
+ [
+ (program1, {"question": "What is the meaning of life?"}),
+ (program2, {"question": "why did a chicken cross the kitchen?"}),
+ ]
+ )
+
+ assert results[0].get_lm_usage() is not None
+ assert results[1].get_lm_usage() is not None
+
+ assert results[0].get_lm_usage().keys() == set(["openai/gpt-4o-mini"])
+ assert results[1].get_lm_usage().keys() == set(["openai/gpt-3.5-turbo"])
diff --git a/tests/utils/test_usage_tracker.py b/tests/utils/test_usage_tracker.py
new file mode 100644
index 000000000..a9accef64
--- /dev/null
+++ b/tests/utils/test_usage_tracker.py
@@ -0,0 +1,159 @@
+import pytest
+import dspy
+from unittest.mock import Mock, patch, MagicMock
+from dspy.utils.usage_tracker import UsageTracker, track_usage
+from dspy.utils.dummies import DummyLM
+import os
+
+
+def test_add_usage_entry():
+ """Test adding usage entries to the tracker."""
+ tracker = UsageTracker()
+
+ # Test with a single usage entry
+ usage_entry = {
+ "prompt_tokens": 1117,
+ "completion_tokens": 46,
+ "total_tokens": 1163,
+ "prompt_tokens_details": {"cached_tokens": 0, "audio_tokens": 0},
+ "completion_tokens_details": {
+ "reasoning_tokens": 0,
+ "audio_tokens": 0,
+ "accepted_prediction_tokens": 0,
+ "rejected_prediction_tokens": 0,
+ },
+ }
+
+ tracker.add_usage("gpt-4o-mini", usage_entry)
+ assert len(tracker.usage_data["gpt-4o-mini"]) == 1
+ assert tracker.usage_data["gpt-4o-mini"][0] == usage_entry
+
+
+def test_get_total_tokens():
+ """Test calculating total tokens from usage entries."""
+ tracker = UsageTracker()
+
+ # Add multiple usage entries for the same model
+ usage_entries = [
+ {
+ "prompt_tokens": 1117,
+ "completion_tokens": 46,
+ "total_tokens": 1163,
+ "prompt_tokens_details": {"cached_tokens": 200, "audio_tokens": 50},
+ "completion_tokens_details": {
+ "reasoning_tokens": 20,
+ "audio_tokens": 10,
+ "accepted_prediction_tokens": 16,
+ "rejected_prediction_tokens": 0,
+ },
+ },
+ {
+ "prompt_tokens": 800,
+ "completion_tokens": 100,
+ "total_tokens": 900,
+ "prompt_tokens_details": {"cached_tokens": 300, "audio_tokens": 0},
+ "completion_tokens_details": {
+ "reasoning_tokens": 50,
+ "audio_tokens": 0,
+ "accepted_prediction_tokens": 40,
+ "rejected_prediction_tokens": 10,
+ },
+ },
+ {
+ "prompt_tokens": 500,
+ "completion_tokens": 80,
+ "total_tokens": 580,
+ "prompt_tokens_details": {"cached_tokens": 100, "audio_tokens": 25},
+ "completion_tokens_details": {
+ "reasoning_tokens": 30,
+ "audio_tokens": 15,
+ "accepted_prediction_tokens": 25,
+ "rejected_prediction_tokens": 10,
+ },
+ },
+ ]
+
+ for entry in usage_entries:
+ tracker.add_usage("gpt-4o-mini", entry)
+
+ total_usage = tracker.get_total_tokens()
+ assert "gpt-4o-mini" in total_usage
+ assert total_usage["gpt-4o-mini"]["prompt_tokens"] == 2417 # 1117 + 800 + 500
+ assert total_usage["gpt-4o-mini"]["completion_tokens"] == 226 # 46 + 100 + 80
+ assert total_usage["gpt-4o-mini"]["total_tokens"] == 2643 # 1163 + 900 + 580
+ assert total_usage["gpt-4o-mini"]["prompt_tokens_details"]["cached_tokens"] == 600 # 200 + 300 + 100
+ assert total_usage["gpt-4o-mini"]["prompt_tokens_details"]["audio_tokens"] == 75 # 50 + 0 + 25
+ assert total_usage["gpt-4o-mini"]["completion_tokens_details"]["reasoning_tokens"] == 100 # 20 + 50 + 30
+ assert total_usage["gpt-4o-mini"]["completion_tokens_details"]["audio_tokens"] == 25 # 10 + 0 + 15
+ assert total_usage["gpt-4o-mini"]["completion_tokens_details"]["accepted_prediction_tokens"] == 81 # 16 + 40 + 25
+ assert total_usage["gpt-4o-mini"]["completion_tokens_details"]["rejected_prediction_tokens"] == 20 # 0 + 10 + 10
+
+
+def test_track_usage_with_multiple_models():
+ """Test tracking usage across multiple models."""
+ tracker = UsageTracker()
+
+ # Add usage entries for different models
+ usage_entries = [
+ {
+ "model": "gpt-4o-mini",
+ "usage": {
+ "prompt_tokens": 1117,
+ "completion_tokens": 46,
+ "total_tokens": 1163,
+ "prompt_tokens_details": {"cached_tokens": 0, "audio_tokens": 0},
+ "completion_tokens_details": {
+ "reasoning_tokens": 0,
+ "audio_tokens": 0,
+ "accepted_prediction_tokens": 0,
+ "rejected_prediction_tokens": 0,
+ },
+ },
+ },
+ {
+ "model": "gpt-3.5-turbo",
+ "usage": {
+ "prompt_tokens": 800,
+ "completion_tokens": 100,
+ "total_tokens": 900,
+ "prompt_tokens_details": {"cached_tokens": 0, "audio_tokens": 0},
+ "completion_tokens_details": {
+ "reasoning_tokens": 0,
+ "audio_tokens": 0,
+ "accepted_prediction_tokens": 0,
+ "rejected_prediction_tokens": 0,
+ },
+ },
+ },
+ ]
+
+ for entry in usage_entries:
+ tracker.add_usage(entry["model"], entry["usage"])
+
+ total_usage = tracker.get_total_tokens()
+ assert "gpt-4o-mini" in total_usage
+ assert "gpt-3.5-turbo" in total_usage
+ assert total_usage["gpt-4o-mini"]["total_tokens"] == 1163
+ assert total_usage["gpt-3.5-turbo"]["total_tokens"] == 900
+
+
+ not os.getenv("OPENAI_API_KEY"),
+ reason="Skip the test if OPENAI_API_KEY is not set.",
+)
+def test_track_usage_context_manager():
+ lm = dspy.LM("openai/gpt-4o-mini", cache=False)
+ dspy.settings.configure(lm=lm)
+
+ predict = dspy.ChainOfThought("question -> answer")
+ with track_usage() as tracker:
+ predict(question="What is the capital of France?")
+ predict(question="What is the capital of Italy?")
+
+ assert len(tracker.usage_data) > 0
+ assert len(tracker.usage_data["openai/gpt-4o-mini"]) == 2
+
+ total_usage = tracker.get_total_tokens()
+ assert "openai/gpt-4o-mini" in total_usage
+ assert len(total_usage.keys()) == 1
+ assert isinstance(total_usage["openai/gpt-4o-mini"], dict)