Skip to content

Conversation

LakshmiPriyaSujith
Copy link
Contributor

@LakshmiPriyaSujith LakshmiPriyaSujith commented Jun 30, 2025

  • I have added tests that cover my changes.
  • If adding a new instrumentation or changing an existing one, I've added screenshots from some observability platform showing the change.
  • PR name follows conventional commits format: feat(instrumentation): ... or fix(instrumentation): ....
  • (If applicable) I have updated the documentation accordingly.

This PR introduces an alternative approach for calculating token usage with Langchain. The current instrumentation processes LLM responses differently to set span attributes and record token usage metrics via a histogram. We encountered cases where the llm_output attribute used to derive token usage metrics, was missing from the LLM response. The new implementation includes a fallback mechanism that computes token usage following the logic used to populate span attributes for token usage.

image


Important

Introduces a fallback mechanism for token usage calculation and model name extraction in Langchain instrumentation when llm_output is missing.

  • Behavior:
    • Adds fallback mechanism in _set_chat_response() to calculate token usage when llm_output is missing.
    • Records token usage metrics using token_histogram in _set_chat_response().
    • Extracts model name using _extract_model_name_from_response_metadata() if not present in llm_output.
  • Functions:
    • Adds _extract_model_name_from_response_metadata() to extract model name from response metadata.
    • Modifies _set_chat_response() to include token_histogram, record_token_usage, and model_name parameters.
  • Misc:
    • Updates on_llm_end() to use new token usage calculation and model name extraction logic.

This description was created by Ellipsis for bed4136. You can customize this summary. It will automatically update as commits are pushed.

Summary by CodeRabbit

  • New Features

    • Improved model name detection for language model responses, including fallback extraction from response metadata.
    • Enhanced usage metrics reporting with additional context such as token histograms and model names.
  • Bug Fixes

    • Ensured metrics are correctly recorded even when language model output is missing.
  • Tests

    • Added tests to validate metric collection and edge case handling for missing outputs.
    • Refactored metric validation into reusable helper functions for improved test clarity.

@LakshmiPriyaSujith LakshmiPriyaSujith changed the title Alternate method to calculate token usage feat(instrumentation): Alternate method to calculate token usage Jun 30, 2025
@LakshmiPriyaSujith LakshmiPriyaSujith changed the title feat(instrumentation): Alternate method to calculate token usage feat(langchain-instrumentation): Alternate method to calculate token usage Jun 30, 2025
adharshctr
adharshctr approved these changes Jul 2, 2025
@LakshmiPriyaSujith LakshmiPriyaSujith marked this pull request as ready for review July 3, 2025 04:09
Copy link
Contributor

@ellipsis-dev ellipsis-dev bot left a comment

Choose a reason for hiding this comment

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

Important

Looks good to me! 👍

Reviewed everything up to bed4136 in 1 minute and 52 seconds. Click for details.
  • Reviewed 72 lines of code in 1 files
  • Skipped 0 files when reviewing.
  • Skipped posting 4 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. packages/opentelemetry-instrumentation-langchain/opentelemetry/instrumentation/langchain/callback_handler.py:207
  • Draft comment:
    In _extract_model_name_from_response_metadata, consider assigning the result of generation.message.response_metadata.get('model_name') to a variable to avoid calling get() twice.
  • Reason this comment was not posted:
    Decided after close inspection that this draft comment was likely wrong and/or not actionable: usefulness confidence = 20% vs. threshold = 50% The suggestion is valid - calling get() twice is slightly inefficient. However, this is a very minor optimization that would have negligible performance impact. The code is also more readable in its current form since it clearly shows what's being checked and returned. The change would require introducing a new variable just to save one dictionary lookup. Am I being too dismissive of small optimizations? In a high-performance system, every small inefficiency can add up. While micro-optimizations can matter at scale, this particular case is not in a hot path and the overhead of an extra dictionary lookup is trivial compared to the network/API calls involved in LLM operations. The comment should be deleted. While technically correct, the suggested change would make the code more verbose for a negligible performance benefit.
2. packages/opentelemetry-instrumentation-langchain/opentelemetry/instrumentation/langchain/callback_handler.py:219
  • Draft comment:
    Document the new parameters (token_histogram, record_token_usage, model_name) in _set_chat_response for clarity and future maintenance.
  • Reason this comment was not posted:
    Decided after close inspection that this draft comment was likely wrong and/or not actionable: usefulness confidence = 10% vs. threshold = 50% Documentation can be helpful, but we need to consider if this comment meets our criteria. The parameters have fairly clear purposes from their names and usage. token_histogram is for recording metrics, record_token_usage is a flag for whether to record tokens, and model_name is used as a label. The function is internal (starts with _) which typically means detailed docs aren't required. The parameter names are quite self-explanatory and the function is internal. Documentation might be redundant here. However, record_token_usage's relationship with token_usage being None is a bit subtle. While there is some subtle logic, the parameter names and usage are clear enough for an internal function. Adding documentation would not substantially improve code quality or maintainability. The comment should be deleted. The parameters are sufficiently self-documenting for an internal function, and requesting documentation does not meet our bar for required code changes.
3. packages/opentelemetry-instrumentation-langchain/opentelemetry/instrumentation/langchain/callback_handler.py:704
  • Draft comment:
    When checking for token_usage, an empty dict (which is falsy) might be passed through. Consider normalizing token_usage (e.g., using token_usage = token_usage or None) so that the fallback mechanism (record_token_usage) triggers correctly if token_usage is empty.
  • Reason this comment was not posted:
    Comment was on unchanged code.
4. packages/opentelemetry-instrumentation-langchain/opentelemetry/instrumentation/langchain/callback_handler.py:755
  • Draft comment:
    Update the _set_chat_response call to ensure fallback token usage recording is applied only when appropriate. Verify that passing 'token_usage is None' correctly handles cases where token_usage might be empty rather than None.
  • Reason this comment was not posted:
    Comment did not seem useful. Confidence is useful = 0% <= threshold 50% The comment is asking the author to verify the handling of 'token_usage is None', which is not allowed as per the rules. It is not making a specific code suggestion or asking for a test to be written. It is more of a request for confirmation, which is not permitted.

Workflow ID: wflow_rITvd9hvpQKqpGrB

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

Copy link

@madhutadiparthi4ibm madhutadiparthi4ibm left a comment

Choose a reason for hiding this comment

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

LGTM

@nirga nirga changed the title feat(langchain-instrumentation): Alternate method to calculate token usage fix(langchain): Alternate method to calculate token usage Jul 3, 2025
Copy link
Member

@nirga nirga left a comment

Choose a reason for hiding this comment

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

Thanks @LakshmiPriyaSujith! Can you add a test for this? (similar to metrics tests we have in other packages)

@LakshmiPriyaSujith
Copy link
Contributor Author

Thanks @LakshmiPriyaSujith! Can you add a test for this? (similar to metrics tests we have in other packages)

Hi @nirga, I have added the test. Could you please review?

@LakshmiPriyaSujith LakshmiPriyaSujith requested a review from nirga July 8, 2025 04:00
Copy link
Member

@nirga nirga left a comment

Choose a reason for hiding this comment

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

Thanks @LakshmiPriyaSujith and sorry for the delay here!

@nirga
Copy link
Member

nirga commented Jul 14, 2025

@LakshmiPriyaSujith can you rebase this?

@LakshmiPriyaSujith
Copy link
Contributor Author

Hi @nirga I have updated the branch. Could you please help merge the PR?

Copy link

coderabbitai bot commented Jul 20, 2025

Walkthrough

The changes introduce a fallback mechanism for extracting the model name from LLM responses, update metric recording logic to include additional attributes and conditions, and add comprehensive tests—including a new test cassette—to ensure metrics are correctly reported even when the LLM output is None. Helper functions for metric validation are also introduced.

Changes

File(s) Change Summary
.../opentelemetry/instrumentation/langchain/callback_handler.py Enhanced on_llm_end to use a fallback for model name extraction and updated metric reporting with extra arguments.
.../opentelemetry/instrumentation/langchain/span_utils.py Updated set_chat_response_usage signature and logic; added extract_model_name_from_response_metadata function.
.../tests/metrics/cassettes/test_langchain_metrics/test_llm_chain_metrics_with_none_llm_output.yaml Added a new test cassette simulating an OpenAI API chat completion with a None LLM output.
.../tests/metrics/test_langchain_metrics.py Added helper functions for metric validation and a new test for handling None LLM output in metrics collection.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant LLMChain
    participant CallbackHandler
    participant SpanUtils

    User->>LLMChain: Run chain
    LLMChain->>CallbackHandler: on_llm_end(response)
    CallbackHandler->>SpanUtils: set_chat_response_usage(span, response, histogram, record_token_usage, model_name)
    SpanUtils->>SpanUtils: Extract token counts & model name (with fallback)
    SpanUtils->>SpanUtils: Record metrics if applicable
Loading

Poem

In the warren of code, a new path unfurled,
Where model names hide, their secrets are twirled.
Metrics now sparkle, even when output is none,
Rabbits rejoice—test coverage won!
With histograms hopping and helpers in tow,
This patch makes our metrics garden grow.
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a750944 and 08babce.

📒 Files selected for processing (4)
  • packages/opentelemetry-instrumentation-langchain/opentelemetry/instrumentation/langchain/callback_handler.py (3 hunks)
  • packages/opentelemetry-instrumentation-langchain/opentelemetry/instrumentation/langchain/span_utils.py (3 hunks)
  • packages/opentelemetry-instrumentation-langchain/tests/metrics/cassettes/test_langchain_metrics/test_llm_chain_metrics_with_none_llm_output.yaml (1 hunks)
  • packages/opentelemetry-instrumentation-langchain/tests/metrics/test_langchain_metrics.py (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
packages/opentelemetry-instrumentation-langchain/opentelemetry/instrumentation/langchain/callback_handler.py (1)
packages/opentelemetry-instrumentation-langchain/opentelemetry/instrumentation/langchain/span_utils.py (2)
  • extract_model_name_from_response_metadata (360-369)
  • set_chat_response_usage (275-357)
packages/opentelemetry-instrumentation-langchain/opentelemetry/instrumentation/langchain/span_utils.py (1)
packages/opentelemetry-semantic-conventions-ai/opentelemetry/semconv_ai/__init__.py (1)
  • SpanAttributes (36-229)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Cursor BugBot
🔇 Additional comments (11)
packages/opentelemetry-instrumentation-langchain/opentelemetry/instrumentation/langchain/callback_handler.py (3)

37-37: Import addition looks good.

The import of extract_model_name_from_response_metadata is properly placed and necessary for the fallback model name extraction functionality.


450-451: Fallback model name extraction implemented correctly.

The logic appropriately calls the fallback function only when model_name is None, providing robust handling for cases where llm_output is missing from the LLM response.


500-500: Enhanced function call correctly integrates fallback mechanism.

The updated call to set_chat_response_usage properly passes the additional parameters including the token histogram, the boolean flag indicating missing token usage data, and the resolved model name from the fallback logic.

packages/opentelemetry-instrumentation-langchain/tests/metrics/cassettes/test_langchain_metrics/test_llm_chain_metrics_with_none_llm_output.yaml (1)

1-104: Test cassette properly configured for the new test case.

The VCR cassette correctly records the OpenAI chat completions API interaction needed to support the test_llm_chain_metrics_with_none_llm_output test case. The request/response structure is properly formatted and will enable consistent test replay.

packages/opentelemetry-instrumentation-langchain/opentelemetry/instrumentation/langchain/span_utils.py (4)

18-18: Import addition is appropriate.

The Histogram import is necessary for the new token usage recording functionality and is properly placed with other OpenTelemetry imports.


275-281: Function signature enhancement is well-designed.

The additional parameters (token_histogram, record_token_usage, model_name) are appropriately typed and named, clearly supporting the enhanced token usage recording functionality.


338-357: Token usage recording implementation follows best practices.

The conditional histogram recording correctly:

  • Only records when record_token_usage is True
  • Separates input and output tokens for granular metrics
  • Uses appropriate semantic convention attributes
  • Prevents recording zero token values

360-369: Helper function implementation is robust and efficient.

The extract_model_name_from_response_metadata function correctly:

  • Uses safe attribute access with getattr
  • Implements early return for efficiency (addressing previous review feedback)
  • Provides appropriate fallback to "unknown"
  • Properly traverses the nested LLMResult structure
packages/opentelemetry-instrumentation-langchain/tests/metrics/test_langchain_metrics.py (3)

1-1: Import addition is necessary for the new test functionality.

The patch import from unittest.mock is required for mocking the LLM's _generate method in the new test case.


120-156: Helper functions improve test maintainability.

The extracted helper functions (verify_token_metrics, verify_duration_metrics, verify_langchain_metrics) effectively reduce code duplication and encapsulate common assertion patterns, making the test suite more maintainable.


159-181: New test case provides excellent coverage for the fallback mechanism.

The test effectively validates the edge case handling when llm_output is None by:

  • Using proper mocking to simulate the condition
  • Verifying that both token usage and duration metrics are still recorded
  • Including descriptive assertions and documentation
  • Leveraging the new helper functions for clean verification logic
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@nirga nirga changed the title fix(langchain): Alternate method to calculate token usage fix(langchain): report token usage histogram Jul 20, 2025
@nirga nirga merged commit 1fe6257 into traceloop:main Jul 20, 2025
11 checks passed
nina-kollman pushed a commit that referenced this pull request Aug 11, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants