Skip to content

fix(ai21): accept null usage in chat and RAG parsers - #2026

Merged
AmanAgarwal041 merged 1 commit into
openlit:mainfrom
feiiiiii5:feiiiiii5/1126-D280
Nov 29, 2026
Merged

AmanAgarwal041 merged 1 commit into
openlit:mainfrom
feiiiiii5:feiiiiii5/1126-D280

Conversation

@feiiiiii5

@feiiiiii5 feiiiiii5 commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Issue number: #2022

Change description:

process_chat_response and process_chat_rag_response called .get() on response_dict.get("usage", {}); explicit JSON null returned None and raised AttributeError, marking the span ERROR. Changed both sites to get("usage") or {}; valid-usage behavior is untouched.

Checklist

  • PR title follows Conventional Commit format.
  • I have reviewed the contributing guidelines
  • Have you checked to ensure there aren't other open Pull Requests for the same change?
  • I have performed a self-review of this change
  • Changes have been tested
  • Changes are documented (no API change)

Acknowledgment

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of the project license.

Verification

New null-usage tests across chat/chat_rag and sync/async wrappers: base-red 4 failed / 1 passed (StatusCode.ERROR instead of OK); with fix 5/5 passed. Related stream-lifecycle module 16/16 passed. ast.parse clean; ruff findings on the source file are pre-existing.

No live provider calls, network, or credentials — all responses are synthetic dicts.

Summary by Sourcery

Prevent null AI21 usage fields from causing response parsing failures and incomplete telemetry.

Bug Fixes:

  • Handle AI21 chat and RAG responses with null usage data without marking otherwise successful spans as errors.

Tests:

  • Add synchronous and asynchronous regression coverage for null usage handling while preserving valid token usage reporting.

@feiiiiii5
feiiiiii5 requested review from a team and ishanjainn as code owners November 26, 2026 05:14
@feiiiiii5
feiiiiii5 deployed to release-notes November 26, 2026 05:14 — with GitHub Actions Active
@sourcery-ai

sourcery-ai Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Implementation

Treat null usage values as empty dictionaries in both chat and RAG response parsers so token extraction does not fail.

  • sdk/python/src/openlit/instrumentation/ai21/utils.py L667, L906

Tests

Add sync and async regression tests for null usage in chat and RAG responses, plus a valid-usage behavior check.

  • sdk/python/tests/test_ai21_null_usage.py L1-176

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 26, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

fix(ai21): accept null usage in chat and RAG responses

🐞 Bug fix 🧪 Tests 🕐 10-20 Minutes

Grey Divider

AI Description

• Treat null AI21 usage as empty in chat and RAG parsing, preventing false error spans.
• Cover sync and async wrappers, including preservation of valid chat token counts.
Merge Risk 🟡 Medium

Blast radius 🟡 Medium 💥 2 capabilities

  • 2 affected capabilities within one bounded functional scope: ai21_completion_telemetry.
  • The changed chat processor feeds the AI21 chat wrapper and produces the span attributes and metrics for one chat-completion integration.
  • Async chat uses the same processor, so it is the same bounded end-to-end telemetry capability rather than an independent scope.
  • The changed RAG processor feeds the AI21 RAG wrapper and produces telemetry for the RAG completion operation.
  • It shares the bounded AI21 completion telemetry integration with chat, while representing a distinct useful operation and response-processing outcome.
Sources

sdk/python/src/openlit/instrumentation/ai21/utils.py[667-667]

    usage = response_dict.get("usage") or {}

sdk/python/src/openlit/instrumentation/ai21/utils.py[906-906]

    usage = response_dict.get("usage") or {}
Behavioral complexity 🟢 Low 🧩 Straightforward

  • Before, a missing usage key received an empty dictionary but an explicit null remained null.
  • After, both missing and explicit null usage values become an empty dictionary, while a valid mapping is preserved.
  • The new correctness condition is limited to safe normalization before existing token and cache-field lookups; no new ordering, state, compatibility protocol, or algorithm is introduced.
Sources

sdk/python/src/openlit/instrumentation/ai21/utils.py[667-667]

    usage = response_dict.get("usage") or {}

sdk/python/src/openlit/instrumentation/ai21/utils.py[906-906]

    usage = response_dict.get("usage") or {}
Potential damage 🟡 Medium 🩹 Recoverable

  • If this capability regresses for an explicit null usage payload, instrumentation can raise while processing the response, causing failed or incomplete telemetry and missing token attributes.
  • The underlying AI21 response is already returned by the wrapper, so the model completion is not lost.
  • Reverting restores the prior code path; no persistent application state or external business effect requires repair.
  • Reverting the instrumentation code restores processing.
  • Existing spans that failed or lost attributes are not automatically reconstructed, but the completion response itself remains available to the caller.
Assessed commit f86eca5
Diagram

graph TD
  Wrappers["Sync and async wrappers"] --> Chat["Chat parser"] --> Usage["Null-safe usage"] --> Span["Telemetry span"]
  Wrappers --> Rag["RAG parser"] --> Usage
Loading
High-Level Assessment

Keep the localized fallback in the two shared parsers: it fixes both sync and async paths without changing valid usage handling. A separate normalization abstraction would add complexity for these two reads.

Files changed (2) +178 / -2

Bug fix (1) +2 / -2
utils.pyHandle null usage in chat and RAG response parsers +2/-2

Handle null usage in chat and RAG response parsers

• Both parsers now substitute an empty dictionary when response usage is null or absent, avoiding an AttributeError while reading token details. Valid usage dictionaries retain their existing behavior.

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

Tests (1) +176 / -0
test_ai21_null_usage.pyAdd AI21 null-usage wrapper regression tests +176/-0

Add AI21 null-usage wrapper regression tests

• Synthetic responses exercise sync and async chat and RAG wrappers, asserting successful spans and preserved output. A valid-usage chat test verifies that reported token counts remain intact.

sdk/python/tests/test_ai21_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 tweak Display settings with a live preview to see your comment before it ships

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 1 issue

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

## Individual Comments

### Comment 1
<location path="sdk/python/src/openlit/instrumentation/ai21/utils.py" line_range="667" />
<code_context>
     scope._response_model = response_dict.get("model") or request_model
     # Handle token usage including reasoning tokens and cached tokens
-    usage = response_dict.get("usage", {})
+    usage = response_dict.get("usage") or {}
     scope._input_tokens = usage.get("prompt_tokens", 0)
     scope._output_tokens = usage.get("completion_tokens", 0)
</code_context>
<issue_to_address>
**Unavailable usage is recorded as zero**

When AI21 returns `usage: null` for a response that consumed tokens, `process_chat_response` defaults missing prompt and completion counts to zero, and `common_chat_logic` treats those attributes as present instead of estimating from the response; the span therefore records zero tokens and cost for a real completion. The RAG path likewise records unavailable cache counts as zero, so callers see false usage data.

When usage is unavailable, estimate token counts from the request and completion (and represent unavailable cache counts distinctly where possible) instead of recording them as zero.

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

Sourcery assessment

Needs a human reviewer. 1 finding to address first, and if the fallback is wrong, affected calls will produce spans with zero token counts instead of preserving the prior failed-span behavior. Those exported telemetry records cannot be changed by reverting, though the impact is bounded to the affected calls.

Blocking findings: sdk/python/src/openlit/instrumentation/ai21/utils.py:667


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

scope._response_model = response_dict.get("model") or request_model
# Handle token usage including reasoning tokens and cached tokens
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 · Unavailable usage is recorded as zero

When AI21 returns usage: null for a response that consumed tokens, process_chat_response defaults missing prompt and completion counts to zero, and common_chat_logic treats those attributes as present instead of estimating from the response; the span therefore records zero tokens and cost for a real completion. The RAG path likewise records unavailable cache counts as zero, so callers see false usage data.

When usage is unavailable, estimate token counts from the request and completion (and represent unavailable cache counts distinctly where possible) instead of recording them as zero.

Also at sdk/python/src/openlit/instrumentation/ai21/utils.py:906.

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

**Unavailable usage is recorded as zero**

When AI21 returns `usage: null` for a response that consumed tokens, `process_chat_response` defaults missing prompt and completion counts to zero, and `common_chat_logic` treats those attributes as present instead of estimating from the response; the span therefore records zero tokens and cost for a real completion. The RAG path likewise records unavailable cache counts as zero, so callers see false usage data.

When usage is unavailable, estimate token counts from the request and completion (and represent unavailable cache counts distinctly where possible) instead of recording them as zero.

Also at `sdk/python/src/openlit/instrumentation/ai21/utils.py:906`.

@AmanAgarwal041
AmanAgarwal041 merged commit ed356a5 into openlit:main Nov 29, 2026
14 checks passed
@github-actions

Copy link
Copy Markdown

Merged PR summary

  • Python SDK · Fixes — Handle null AI21 usage in chat and RAG response parsing so successful spans are not marked as errors while valid token usage remains unchanged.

Generated from the merged PR description and bounded, component-scoped file evidence. Release preparation reuses this validated summary.

This branch was successfully deployed

1 active deployment
release-notes — f86eca57 Deployed Nov 29, 2026 by AmanAgarwal041 via Summarize / Merged pull request #351
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