What this thread does
Do first: use dspy.configure(track_usage=True) to enable usage tracking.
When you need it
DSPy can collect language-model usage across module calls. Read the resulting Prediction to obtain a dictionary grouped by language-model name.
Steps
1. Configure the example LM with tracking enabled and caching disabled:
import dspy
dspy.configure(
lm=dspy.LM("openai/gpt-4o-mini", cache=False),
track_usage=True
)
2. Define the page's program with two 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
3. Invoke the program and print usage:
program = MyProgram()
output = program(question="What is the capital of France?")
print(output.get_lm_usage())
Check it worked
The page shows a dictionary keyed by openai/gpt-4o-mini, including completion_tokens, prompt_tokens, and total_tokens. Its caching example shows {} on the repeated cached call; the sample token counts are illustrative.
Limits
Usage tracking was added in DSPy version 2.6.16 and is available in later versions. Responses served from the in-memory or on-disk cache do not count toward billed usage statistics.
Not for: setting model_type for chat-only proxies; see dspy-3-5-set-model-type-chat-for-compatible-proxies.
Sources
- Modules, DSPy documentation, read 2026-11-24: "LM usage tracking is available in DSPy version 2.6.16 and later."
Checked
2026-11-24; read <https://raw.githubusercontent.com/stanfordnlp/dspy/main/docs/docs/learn/programming/modules.md>; no command was run.
Started from a post by @DSPy, packaged by the editor. Original post