Skip to content

fix(sdk): accept null usage in litellm, mistral, cohere, and sarvam parsers - #2029

Open
yqecea wants to merge 1 commit into
openlit:mainfrom
yqecea:fix-null-usage-parsers
Open

yqecea wants to merge 1 commit into
openlit:mainfrom
yqecea:fix-null-usage-parsers

Conversation

@yqecea

@yqecea yqecea commented Nov 28, 2026 •

Copy link
Copy Markdown

Summary

The litellm, mistral, cohere, and sarvam instrumentations crash with AttributeError: 'NoneType' object has no attribute 'get' when a provider response carries "usage": null, marking the span ERROR and dropping all response telemetry. This is the same defect reported for Azure AI Inference in #2023 and AI21 in #2022: response_dict.get("usage", {}) does not help when the usage key is present with a None value, which gateways and provider outages emit in the wild for this OpenAI-shaped response contract.

Changes

  • litellm, mistral, cohere, sarvam: parse usage with response_dict.get("usage") or {} in the chat and embedding response paths, matching the pattern already used in the OpenAI instrumentation.
  • New offline regression tests in tests/test_null_usage.py feed "usage": None responses to all four chat parsers.

Red/green verified: all four tests fail on main with the exact AttributeError above and pass with the fix. Groq and the litellm streaming path were checked and are already guarded (isinstance / truthiness checks), so they are untouched. AI21 and Azure AI Inference are intentionally excluded since #2024/#2026 already cover them.

Test plan

  • pytest tests/test_null_usage.py — 4/4 pass (4/4 fail without the fix)

Summary by Sourcery

Handle null usage payloads across supported provider response parsers without interrupting instrumentation.

Bug Fixes:

  • Prevent LiteLLM, Mistral, Cohere, and Sarvam parsers from failing when provider responses contain null usage data, preserving response telemetry and successful spans.

Tests:

  • Add regression coverage for null usage responses across the four affected chat parsers.

@yqecea
yqecea requested review from a team and ishanjainn as code owners November 28, 2026 11:11
@yqecea
yqecea deployed to release-notes November 28, 2026 11:11 — with GitHub Actions Active
@sourcery-ai

sourcery-ai Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Implementation

Treat missing and null usage payloads as empty mappings in the Cohere chat response parser.

  • sdk/python/src/openlit/instrumentation/cohere/utils.py L660

Treat missing and null usage payloads as empty mappings in LiteLLM chat and embedding response parsers.

  • sdk/python/src/openlit/instrumentation/litellm/utils.py L805, L878

Treat missing and null usage payloads as empty mappings in Mistral chat and embedding response parsers.

  • sdk/python/src/openlit/instrumentation/mistral/utils.py L713-714, L734, L869

Treat missing and null usage payloads as empty mappings in the Sarvam chat response parser.

  • sdk/python/src/openlit/instrumentation/sarvam/utils.py L624

Tests

Add regression tests confirming all four chat parsers accept responses with null usage.

  • sdk/python/tests/test_null_usage.py L1-106

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Handle null usage in four provider response parsers

🐞 Bug fix 🧪 Tests 🕐 10-20 Minutes

Grey Divider

AI Description

• Prevent null usage fields from crashing LiteLLM, Mistral, Cohere, and Sarvam response parsing.
• Default missing usage data to zero tokens so response telemetry can still be recorded.
• Add offline regression tests for all four chat parsers.
Merge Risk 🟢 Low

Blast radius 🟢 Low 💥 1 capability

  • 1 affected end-to-end capability after fault-specific containment; implementation boundaries do not widen its functional scope.
  • All changed functions transform provider responses into the SDK's common chat or embedding telemetry path; the provider-specific files are adapter hops for the same bounded outcome, not independent stored or user-facing capabilities.
  • The parsers populate token and response fields before common telemetry logic consumes them.
Sources

sdk/python/src/openlit/instrumentation/litellm/utils.py[805-808]

    usage = response_dict.get("usage") or {}
    # Handle token usage including reasoning tokens and cached tokens
    scope._input_tokens = usage.get("prompt_tokens", 0)
    scope._output_tokens = usage.get("completion_tokens", 0)

sdk/python/src/openlit/instrumentation/mistral/utils.py[713-714]

    scope._input_tokens = (response_dict.get("usage") or {}).get("prompt_tokens", 0)
    scope._output_tokens = (response_dict.get("usage") or {}).get("completion_tokens", 0)
Behavioral complexity 🟢 Low 🧩 Straightforward

  • Before, a present null usage value was passed to .get and could abort response instrumentation; after, falsy usage values become an empty mapping and token fields default to zero.
  • The new correctness condition is limited to preserving parser completion for absent or null usage while retaining normal usage extraction; existing common telemetry, cost, and wrapper paths are unchanged.
  • No new state machine, concurrency, compatibility protocol, or cross-capability invariant is introduced.
Sources

sdk/python/src/openlit/instrumentation/litellm/utils.py[805-808]

    usage = response_dict.get("usage") or {}
    # Handle token usage including reasoning tokens and cached tokens
    scope._input_tokens = usage.get("prompt_tokens", 0)
    scope._output_tokens = usage.get("completion_tokens", 0)

sdk/python/src/openlit/instrumentation/mistral/utils.py[713-714]

    scope._input_tokens = (response_dict.get("usage") or {}).get("prompt_tokens", 0)
    scope._output_tokens = (response_dict.get("usage") or {}).get("completion_tokens", 0)
Potential damage 🟡 Medium 🩹 Recoverable

  • If response telemetry processing regresses, affected spans may be marked errored and usage/cost telemetry may be missing or zeroed while the provider response is still returned.
  • The wrapper's exception path records fallback error metrics, but it does not recreate the lost detailed telemetry.
  • A code fix restores future telemetry; already missed spans cannot be reconstructed.
  • Business importance uses the required equal-importance baseline.
  • Future telemetry resumes after correcting the parser; previously dropped detailed span and usage data is not recoverable from these paths.
Assessed commit 3fa8c6d
Diagram

graph TD
  A["Provider response"] --> B["Response parsers"] --> C["Null-safe usage"] --> D["Token counts"] --> E["Spans and metrics"]
Loading
High-Level Assessment

The localized fallback matches the existing OpenAI parser pattern and addresses the failure without introducing a shared abstraction for a simple check. The new tests cover chat responses; embedding paths also changed but have no new regression tests.

Files changed (5) +114 / -8

Bug fix (4) +8 / -8
utils.pyHandle null usage in Cohere chat responses +1/-1

Handle null usage in Cohere chat responses

• Defaults null usage to an empty mapping before reading billed units and cache tokens, preventing an attribute error during chat telemetry processing.

sdk/python/src/openlit/instrumentation/cohere/utils.py

utils.pyHandle null usage in LiteLLM chat and embedding responses +2/-2

Handle null usage in LiteLLM chat and embedding responses

• Uses an empty mapping when chat or embedding usage is null, allowing token extraction to fall back to zero.

sdk/python/src/openlit/instrumentation/litellm/utils.py

utils.pyHandle null usage in Mistral chat and embedding responses +4/-4

Handle null usage in Mistral chat and embedding responses

• Guards chat token and cache-detail extraction, plus embedding input-token extraction, against null usage.

sdk/python/src/openlit/instrumentation/mistral/utils.py

utils.pyHandle null usage in Sarvam chat cache-token extraction +1/-1

Handle null usage in Sarvam chat cache-token extraction

• Defaults null usage to an empty mapping before reading token details. The existing conditional extraction already skips primary token counts when usage is null.

sdk/python/src/openlit/instrumentation/sarvam/utils.py

Tests (1) +106 / -0
test_null_usage.pyAdd null-usage chat regression tests +106/-0

Add null-usage chat regression tests

• Adds offline responses with null usage and checks that each of the four chat parsers completes without raising. The tests do not cover embedding parsing or assert span attributes.

sdk/python/tests/test_null_usage.py

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0)

Grey Divider

Great, no issues found!

Qodo reviewed your code and found no material issues that require review

Grey Divider

Tip of the day
💡 Did you know, you can turn these tips off under Display > Comment parts

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 3 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="sdk/python/src/openlit/instrumentation/cohere/utils.py" line_range="660" />
<code_context>
     scope._response_id = response_dict.get("id")
     scope._response_model = request_model
-    usage = response_dict.get("usage", {})
+    usage = response_dict.get("usage") or {}
     billed = usage.get("billed_units", {})
     # Handle token usage including reasoning tokens and cached tokens
</code_context>
<issue_to_address>
**Null usage aborts Cohere streams**

When a Cohere streaming `message-end` event has `delta.usage` set to null, `process_chunk` receives `None` for `usage`, so `usage.get("billed_units", {})` raises `AttributeError`; the stream wrapper rethrows it, interrupts iteration, and marks the span ERROR.

Normalize `delta.get("usage")` to an empty mapping before accessing its fields.

Also at `sdk/python/src/openlit/instrumentation/cohere/utils.py:661`.
</issue_to_address>

### Comment 2
<location path="sdk/python/tests/test_null_usage.py" line_range="106" />
<code_context>
+def test_litellm_chat_null_usage_does_not_crash():
+    from openlit.instrumentation.litellm.utils import process_chat_response
+
+    _run(process_chat_response, dict(OPENAI_SHAPED_RESPONSE))
+
+
</code_context>
<issue_to_address>
**Sarvam regression test passes unchanged**

When the Sarvam null-usage test runs, `process_chat_response` skips token extraction when `usage` is falsey, and its subsequent fallback is already null-safe, so this test passes on both the pre-PR and changed code and does not verify a Sarvam regression fix.

Remove Sarvam from the claimed regression cases or replace it with a scenario that fails before the change and assert the intended behavior.
</issue_to_address>

### Comment 3
<location path="sdk/python/tests/test_null_usage.py" line_range="88" />
<code_context>
+def test_litellm_chat_null_usage_does_not_crash():
+    from openlit.instrumentation.litellm.utils import process_chat_response
+
+    _run(process_chat_response, dict(OPENAI_SHAPED_RESPONSE))
+
+
</code_context>
<issue_to_address>
**No-op parsers pass the tests**

When a parser silently skips response processing instead of raising, a parser that returns without processing the response completes each bare `_run(...)` call, so all four tests pass even though no response telemetry is recorded.

Assert that the response is processed successfully and that the span records the expected telemetry.

Also at `sdk/python/tests/test_null_usage.py:94`, `sdk/python/tests/test_null_usage.py:100`, `sdk/python/tests/test_null_usage.py:106`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 3 findings to address first, and a null usage field is now treated as an empty object, so the parser records zero token usage and continues emitting response telemetry instead of raising an exception. If zero is misleading, those exported metrics may remain in the monitoring backend after a revert, though the effect is bounded to responses with null usage.

Blocking findings: sdk/python/src/openlit/instrumentation/cohere/utils.py:660, sdk/python/tests/test_null_usage.py:106, sdk/python/tests/test_null_usage.py:88


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

scope._response_id = response_dict.get("id")
scope._response_model = request_model
usage = response_dict.get("usage", {})
usage = response_dict.get("usage") or {}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Null usage aborts Cohere streams

When a Cohere streaming message-end event has delta.usage set to null, process_chunk receives None for usage, so usage.get("billed_units", {}) raises AttributeError; the stream wrapper rethrows it, interrupts iteration, and marks the span ERROR.

Normalize delta.get("usage") to an empty mapping before accessing its fields.

Also at sdk/python/src/openlit/instrumentation/cohere/utils.py:661.

Prompt for AI agents
In `sdk/python/src/openlit/instrumentation/cohere/utils.py` at line 660:

**Null usage aborts Cohere streams**

When a Cohere streaming `message-end` event has `delta.usage` set to null, `process_chunk` receives `None` for `usage`, so `usage.get("billed_units", {})` raises `AttributeError`; the stream wrapper rethrows it, interrupts iteration, and marks the span ERROR.

Normalize `delta.get("usage")` to an empty mapping before accessing its fields.

Also at `sdk/python/src/openlit/instrumentation/cohere/utils.py:661`.

def test_sarvam_chat_null_usage_does_not_crash():
from openlit.instrumentation.sarvam.utils import process_chat_response

_run(process_chat_response, dict(OPENAI_SHAPED_RESPONSE))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Sarvam regression test passes unchanged

When the Sarvam null-usage test runs, process_chat_response skips token extraction when usage is falsey, and its subsequent fallback is already null-safe, so this test passes on both the pre-PR and changed code and does not verify a Sarvam regression fix.

Remove Sarvam from the claimed regression cases or replace it with a scenario that fails before the change and assert the intended behavior.

Prompt for AI agents
In `sdk/python/tests/test_null_usage.py` at line 106:

**Sarvam regression test passes unchanged**

When the Sarvam null-usage test runs, `process_chat_response` skips token extraction when `usage` is falsey, and its subsequent fallback is already null-safe, so this test passes on both the pre-PR and changed code and does not verify a Sarvam regression fix.

Remove Sarvam from the claimed regression cases or replace it with a scenario that fails before the change and assert the intended behavior.

def test_litellm_chat_null_usage_does_not_crash():
from openlit.instrumentation.litellm.utils import process_chat_response

_run(process_chat_response, dict(OPENAI_SHAPED_RESPONSE))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · No-op parsers pass the tests

When a parser silently skips response processing instead of raising, a parser that returns without processing the response completes each bare _run(...) call, so all four tests pass even though no response telemetry is recorded.

Assert that the response is processed successfully and that the span records the expected telemetry.

Also at sdk/python/tests/test_null_usage.py:94, sdk/python/tests/test_null_usage.py:100, sdk/python/tests/test_null_usage.py:106.

Prompt for AI agents
In `sdk/python/tests/test_null_usage.py` at line 88:

**No-op parsers pass the tests**

When a parser silently skips response processing instead of raising, a parser that returns without processing the response completes each bare `_run(...)` call, so all four tests pass even though no response telemetry is recorded.

Assert that the response is processed successfully and that the span records the expected telemetry.

Also at `sdk/python/tests/test_null_usage.py:94`, `sdk/python/tests/test_null_usage.py:100`, `sdk/python/tests/test_null_usage.py:106`.

This branch was successfully deployed

1 active deployment
release-notes — 3fa8c6dc Deployed Nov 28, 2026 by yqecea via Normalize / Conventional title #922
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants