Provider responses with no usage object are recorded as zero tokens, not unknown

Author: qaisermehdi3-coderCreated Sep 23, 2026Updated Oct 1, 2026
Labelsbugpydanty:bugp:2-highneeds-maintainer-actionattention-pinged

Initial Checks

Description

Follow-up to #8551, as @DouweM suggested there. @tonydzi's probe scripts from that thread: https://gist.github.com/tonydzi/9a33c0a605549258fe376175fa07b023 https://gist.github.com/tonydzi/1992ce6cf95340ea000e67cdb33a4600

When a provider returns no usage object, the model's _map_usage returns an empty RequestUsage(), so the request is recorded as 0 tokens. A request where the provider sent nothing and one that really cost 0 look identical (tonydzi measured A == B on 2.48.0). The total looks complete and reads low, and nothing errors.

Scoping, from reading main at 5a2e2d9. I have not run these, so treat them as places to check:

1. Which providers. Same if usage is None: return RequestUsage() in openai.py _map_usage (chat, chunks and Responses share it), groq.py, mistral.py, huggingface.py, cohere.py. google.py _metadata_as_usage and anthropic.py _map_usage return existing_usage or RequestUsage() on streaming paths; the anthropic one looks deliberate (the Bedrock metrics chunk duplicates usage). I did not check bedrock.py.

2. Where to carry it. A marker can't go in that None branch as is. The openai, groq, mistral and huggingface streams call _map_usage on every chunk and add the results (e.g. openai.py self._usage += chunk_usage). With include_usage=True, which pydantic-ai sets, every chunk except the last has usage=None, so a per-call marker would count once per chunk and flag streams that did report usage. It needs deciding once per response: at the end of a stream, did any chunk carry usage.

3. Usage limits. request_limit is counted by pydantic-ai, so it is fine. But input/output/total token limits are checked against RunUsage after each response (check_tokens in usage.py). A response recorded as 0 tokens never counts toward them, so a run can exceed a token limit without raising.

4. Cost. Likely the same shape: a response recorded as 0 tokens would price at 0, and cost_limit would not see it. I have not traced the price path end to end, so worth checking.

Minimal, Reproducible Example

python
# See @tonydzi's probe in #8551 (case A: provider sent no usage object, case B: genuine zero; A == B on 2.48.0):
# https://gist.github.com/tonydzi/1992ce6cf95340ea000e67cdb33a4600

Logfire Trace

No response

Python, Pydantic AI & LLM client version

  • Python: n/a (not run by me)
  • Pydantic AI: read on main at 5a2e2d9; tonydzi's probe ran on 2.48.0
  • LLM provider SDK: n/a