Skip to content

Conversation

@dinmukhamedm
Copy link
Collaborator

@dinmukhamedm dinmukhamedm commented Jul 30, 2025

Fixes the following:

  • Tools are not recorded at all in streaming mode
  • Tools are not recorded as a separate block in input assistant (historic previous responses) messages
  • 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.

Important

Fixes tool usage recording issues in Anthropic instrumentation for both streaming and non-streaming modes, with added tests for verification.

  • Behavior:
    • Fixes tool usage not being recorded in streaming mode in event_emitter.py and streaming.py.
    • Ensures tools are recorded as separate blocks in assistant messages in span_utils.py.
  • Tests:
    • Adds tests in test_messages.py to verify tool usage recording in various scenarios, including legacy and streaming modes.
    • Adds test cassettes for different tool usage scenarios, such as test_anthropic_tools_history_legacy.yaml and test_anthropic_tools_streaming_with_events_with_content.yaml.

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

Summary by CodeRabbit

  • New Features

    • Enhanced support for tool usage blocks in Anthropic message and streaming responses, allowing detailed tracking and recording of tool calls and their parameters.
  • Bug Fixes

    • Improved handling of streaming events and tool usage, ensuring accurate event emission and attribute recording for various message types.
  • Tests

    • Added comprehensive tests and test data for Anthropic message and streaming scenarios involving tool usage, increasing coverage and robustness.
    • Centralized tool definitions in tests to reduce duplication and improve maintainability.
@coderabbitai
Copy link

coderabbitai bot commented Jul 30, 2025

Walkthrough

The changes introduce enhanced support for Anthropic tool usage events within OpenTelemetry instrumentation. Internal logic is updated to distinguish and process tool use blocks and streaming tool calls, with structured attributes and JSON parsing. The test suite is expanded with new scenarios and shared tool definitions, and multiple test cassettes are added for comprehensive coverage.

Changes

Cohort / File(s) Change Summary
Event Emitter Tool Use Handling
packages/opentelemetry-instrumentation-anthropic/opentelemetry/instrumentation/anthropic/event_emitter.py
Updates emit_streaming_response_events to distinguish "tool_use" messages, constructing ToolCall objects with parsed JSON arguments and emitting them as structured events.
Span Attribute and Streaming Tool Use Support
packages/opentelemetry-instrumentation-anthropic/opentelemetry/instrumentation/anthropic/span_utils.py
Refactors prompt and streaming response processing to separately record tool use blocks, set structured tool call attributes, and improve type safety and error handling for span attributes.
Streaming Response Tool Use Parsing
packages/opentelemetry-instrumentation-anthropic/opentelemetry/instrumentation/anthropic/streaming.py
Enhances _process_response_item to handle "tool_use" content blocks and "input_json_delta" events, collecting tool call information incrementally during streaming.
Test Suite Refactor and Expansion
packages/opentelemetry-instrumentation-anthropic/tests/test_messages.py
Refactors to use a shared TOOLS definition, adds multiple new tests for tool usage (history and streaming, with/without content), and validates span, log, and metric outputs for tool call scenarios.
Test Cassettes: Tool Use Scenarios
packages/opentelemetry-instrumentation-anthropic/tests/cassettes/test_messages/test_anthropic_tools_history_legacy.yaml,
.../test_anthropic_tools_history_with_events_with_content.yaml,
.../test_anthropic_tools_history_with_events_with_no_content.yaml,
.../test_anthropic_tools_streaming_legacy.yaml,
.../test_anthropic_tools_streaming_with_events_with_content.yaml,
.../test_anthropic_tools_streaming_with_events_with_no_content.yaml
Adds new YAML cassettes capturing Anthropic API interactions for tool usage in both history and streaming modes, covering scenarios with and without content.

Sequence Diagram(s)

sequenceDiagram participant User participant Instrumentation participant AnthropicAPI User->>Instrumentation: Send message with tool usage Instrumentation->>AnthropicAPI: Forward message (with tools) AnthropicAPI-->>Instrumentation: Streaming response events loop For each event Instrumentation->>Instrumentation: Parse event alt event.type == "tool_use" Instrumentation->>Instrumentation: Parse JSON input, create ToolCall Instrumentation->>Instrumentation: Emit ChoiceEvent with tool_calls else event.type != "tool_use" Instrumentation->>Instrumentation: Emit ChoiceEvent with message content end end Instrumentation-->>User: Emit structured events and span attributes 
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Suggested reviewers

  • nirga

Poem

A rabbit hops through code so bright,
Tool calls parsed with keen insight.
Streaming blocks and spans align,
With structured logs, the tests entwine.
Anthropic’s tools now clearly seen—
In YAML fields and Python green!
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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 generate unit tests to generate unit tests for 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.
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 81dcefa in 2 minutes and 21 seconds. Click for details.
  • Reviewed 2471 lines of code in 10 files
  • Skipped 0 files when reviewing.
  • Skipped posting 8 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-anthropic/tests/test_messages.py:2454
  • Draft comment:
    Consider using a partial or subset dictionary comparison in assert_message_in_logs rather than full equality. This would reduce brittleness if the log body includes extra keys in the future.
  • Reason this comment was not posted:
    Comment was not on a location in the diff, so it can't be submitted as a review comment.
2. packages/opentelemetry-instrumentation-anthropic/tests/test_messages.py:115
  • Draft comment:
    Multiple tests assert hardcoded response IDs (e.g. 'msg_01TPXhkPo8jy6yQMrMhjpiAE'). Consider documenting or dynamically verifying these values to reduce fragility if cassette responses change.
  • Reason this comment was not posted:
    Comment was not on a location in the diff, so it can't be submitted as a review comment.
3. packages/opentelemetry-instrumentation-anthropic/tests/test_messages.py:85
  • Draft comment:
    Instead of catching a generic Exception when calling messages.create() with an 'unknown_parameter', consider using pytest.raises with a specific exception type. This makes the intended failure mode explicit.
  • Reason this comment was not posted:
    Comment was not on a location in the diff, so it can't be submitted as a review comment.
4. packages/opentelemetry-instrumentation-anthropic/tests/test_messages.py:1890
  • Draft comment:
    The expected user message log is asserted as an empty dictionary ({}). It would help to document why an empty body is expected in this case to clarify the behavior when there is no content.
  • Reason this comment was not posted:
    Comment did not seem useful. Confidence is useful = 0% <= threshold 50% The comment is asking the PR author to document why an empty dictionary is expected, which falls under asking for clarification or confirmation of intention. This violates the rule against asking the author to explain or confirm their intention.
5. packages/opentelemetry-instrumentation-anthropic/opentelemetry/instrumentation/anthropic/span_utils.py:186
  • Draft comment:
    Typo: 'Antrhopic' should be spelled as 'Anthropic'.
  • Reason this comment was not posted:
    Comment was on unchanged code.
6. packages/opentelemetry-instrumentation-anthropic/tests/cassettes/test_messages/test_anthropic_tools_history_with_events_with_no_content.yaml:5
  • Draft comment:
    Typographical note: The string "I''ll help you get the weather and current time in San Francisco." contains a double apostrophe (I''ll). Please confirm if this is intentional or if it should be a single apostrophe (I'll).
  • Reason this comment was not posted:
    Comment looked like it was already resolved.
7. packages/opentelemetry-instrumentation-anthropic/tests/test_messages.py:1456
  • Draft comment:
    There's a typographical error in the comment on this line. It currently reads "Validate the tool messages input vent" — likely it was meant to be "Validate the tool messages input event".
  • Reason this comment was not posted:
    Comment was on unchanged code.
8. packages/opentelemetry-instrumentation-anthropic/tests/test_messages.py:2266
  • Draft comment:
    Typo: In the comment "Validate the tool messages input vent", "vent" should be corrected to "event".
  • 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% While the comment correctly identifies a typo, it's a very minor issue in a test file comment. Test file comments are internal documentation and don't affect functionality. The rules state to only keep comments that require clear code changes, and to not make comments that are obvious or unimportant. A typo in a test comment is not a significant issue that requires immediate attention. The typo could theoretically cause confusion for future developers reading the test. Documentation clarity has some value. While documentation clarity has value, this is an extremely minor typo that doesn't meaningfully impact understanding - "vent" vs "event" in this context is obvious from context. The cost of the PR review comment outweighs the minor benefit. Delete the comment. The typo is too minor of an issue to warrant a PR comment, especially in test file documentation.

Workflow ID: wflow_aF7XfQnljGTgD9sk

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

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🔭 Outside diff range comments (1)
packages/opentelemetry-instrumentation-anthropic/opentelemetry/instrumentation/anthropic/event_emitter.py (1)

131-164: Add error handling for JSON parsing of tool arguments.

The tool call parsing logic is well-structured, but the json.loads() call on Line 138 could raise a JSONDecodeError if the input contains malformed JSON.

Apply this diff to add proper error handling:

- "arguments": json.loads(message.get("input", '{}')), + "arguments": self._safe_parse_json(message.get("input", '{}')),

And add this helper method:

def _safe_parse_json(self, json_str): try: return json.loads(json_str) except (json.JSONDecodeError, TypeError): logger.warning("Failed to parse tool call arguments as JSON: %s", json_str) return {}
🧹 Nitpick comments (1)
packages/opentelemetry-instrumentation-anthropic/tests/test_messages.py (1)

1646-1651: Consider using contextlib.suppress for cleaner exception handling.

The static analysis tool correctly identifies that contextlib.suppress(Exception) would be cleaner than try-except-pass blocks.

+from contextlib import suppress + # Then replace patterns like: -try: - anthropic_client.messages.create( - unknown_parameter="unknown", - ) -except Exception: - pass +with suppress(Exception): + anthropic_client.messages.create( + unknown_parameter="unknown", + )

Also applies to: 1806-1811, 1909-1914, 1988-1993, 2120-2125, 2233-2238

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 168236a and 81dcefa.

📒 Files selected for processing (10)
  • packages/opentelemetry-instrumentation-anthropic/opentelemetry/instrumentation/anthropic/event_emitter.py (3 hunks)
  • packages/opentelemetry-instrumentation-anthropic/opentelemetry/instrumentation/anthropic/span_utils.py (3 hunks)
  • packages/opentelemetry-instrumentation-anthropic/opentelemetry/instrumentation/anthropic/streaming.py (1 hunks)
  • packages/opentelemetry-instrumentation-anthropic/tests/cassettes/test_messages/test_anthropic_tools_history_legacy.yaml (1 hunks)
  • packages/opentelemetry-instrumentation-anthropic/tests/cassettes/test_messages/test_anthropic_tools_history_with_events_with_content.yaml (1 hunks)
  • packages/opentelemetry-instrumentation-anthropic/tests/cassettes/test_messages/test_anthropic_tools_history_with_events_with_no_content.yaml (1 hunks)
  • packages/opentelemetry-instrumentation-anthropic/tests/cassettes/test_messages/test_anthropic_tools_streaming_legacy.yaml (1 hunks)
  • packages/opentelemetry-instrumentation-anthropic/tests/cassettes/test_messages/test_anthropic_tools_streaming_with_events_with_content.yaml (1 hunks)
  • packages/opentelemetry-instrumentation-anthropic/tests/cassettes/test_messages/test_anthropic_tools_streaming_with_events_with_no_content.yaml (1 hunks)
  • packages/opentelemetry-instrumentation-anthropic/tests/test_messages.py (6 hunks)
🧰 Additional context used
🪛 Ruff (0.12.2)
packages/opentelemetry-instrumentation-anthropic/tests/test_messages.py

1646-1651: Use contextlib.suppress(Exception) instead of try-except-pass

Replace with contextlib.suppress(Exception)

(SIM105)


1806-1811: Use contextlib.suppress(Exception) instead of try-except-pass

Replace with contextlib.suppress(Exception)

(SIM105)


1909-1914: Use contextlib.suppress(Exception) instead of try-except-pass

Replace with contextlib.suppress(Exception)

(SIM105)


1988-1993: Use contextlib.suppress(Exception) instead of try-except-pass

Replace with contextlib.suppress(Exception)

(SIM105)


2120-2125: Use contextlib.suppress(Exception) instead of try-except-pass

Replace with contextlib.suppress(Exception)

(SIM105)


2233-2238: Use contextlib.suppress(Exception) instead of try-except-pass

Replace with contextlib.suppress(Exception)

(SIM105)

⏰ 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). (2)
  • GitHub Check: Lint
  • GitHub Check: Build Packages (3.11)
🔇 Additional comments (15)
packages/opentelemetry-instrumentation-anthropic/tests/cassettes/test_messages/test_anthropic_tools_history_with_events_with_no_content.yaml (1)

1-121: LGTM! Test cassette properly captures tool interaction scenario.

This test cassette accurately records the HTTP interaction for testing tool usage with no initial content, providing good test coverage for the instrumentation changes.

packages/opentelemetry-instrumentation-anthropic/opentelemetry/instrumentation/anthropic/streaming.py (2)

43-46: LGTM! Proper initialization of tool use events.

The code correctly initializes tool use content blocks with the necessary fields (id, name, and empty input string) to support incremental tool input construction during streaming.


53-54: LGTM! Correct handling of incremental JSON input.

The addition of input_json_delta handling properly accumulates partial JSON data for tool inputs during streaming, which is essential for the tool parsing fixes mentioned in the PR objectives.

packages/opentelemetry-instrumentation-anthropic/tests/cassettes/test_messages/test_anthropic_tools_history_with_events_with_content.yaml (1)

1-121: LGTM! Test cassette provides comprehensive tool interaction coverage.

This cassette complements the test suite by covering tool usage scenarios with content, ensuring thorough testing of the enhanced tool parsing logic.

packages/opentelemetry-instrumentation-anthropic/tests/cassettes/test_messages/test_anthropic_tools_history_legacy.yaml (1)

1-116: LGTM! Legacy compatibility test coverage is valuable.

This cassette ensures that the tool parsing enhancements maintain backward compatibility with legacy tool usage formats, which is crucial for the robustness of the changes.

packages/opentelemetry-instrumentation-anthropic/opentelemetry/instrumentation/anthropic/event_emitter.py (1)

3-3: LGTM! JSON import needed for tool argument parsing.

The addition of the json import is necessary for parsing tool call arguments in the streaming response events.

packages/opentelemetry-instrumentation-anthropic/tests/cassettes/test_messages/test_anthropic_tools_streaming_with_events_with_content.yaml (1)

1-304: LGTM! Test cassette file looks complete.

This test cassette properly captures the streaming interaction with Anthropic's API including tool usage for weather and time queries. The recorded response includes all necessary streaming events and metadata.

packages/opentelemetry-instrumentation-anthropic/tests/cassettes/test_messages/test_anthropic_tools_streaming_with_events_with_no_content.yaml (1)

1-335: LGTM! Test cassette properly captures the "no content" streaming scenario.

This cassette complements the previous one by testing the edge case where tool inputs initially contain no content and are incrementally built through streaming deltas.

packages/opentelemetry-instrumentation-anthropic/tests/cassettes/test_messages/test_anthropic_tools_streaming_legacy.yaml (1)

1-300: LGTM! Legacy streaming cassette ensures backward compatibility.

This cassette properly captures the legacy streaming format interactions, which is important for maintaining compatibility with older Anthropic API integrations.

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

115-135: Good separation of tool use blocks from content.

The logic correctly separates tool use blocks from other content blocks when processing messages. This ensures tool calls are recorded with proper attributes while maintaining the regular content flow.


136-152: Tool call attributes are properly structured.

The implementation correctly records tool call details including ID, name, and JSON-serialized arguments under the appropriate span attribute paths.


188-189: Good defensive check for text attribute existence.

Adding hasattr(content, "text") prevents potential AttributeError when processing content blocks that may not have a text attribute.


270-299: Improved streaming response handling with explicit event type processing.

The refactored code is cleaner and more maintainable:

  • Explicit index management for completions
  • Proper handling of thinking events as separate completions
  • Clear distinction between tool_use events and regular text events

The removal of the try-except block makes the code flow more predictable.

packages/opentelemetry-instrumentation-anthropic/tests/test_messages.py (2)

33-68: Excellent refactoring - centralizing tool definitions improves maintainability.

Moving tool definitions to a global TOOLS list eliminates duplication across tests and ensures consistency. This makes it easier to update tool schemas in one place.


1605-2312: Comprehensive test coverage for tool usage scenarios.

The new tests thoroughly cover:

  • Tool usage with legacy attributes
  • Streaming tool calls with events
  • Multi-turn conversations with tool results
  • Both synchronous and asynchronous operations

Each test properly verifies span attributes, metrics, and event logs for tool-related interactions.

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 @dinmukhamedm!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants