-
Notifications
You must be signed in to change notification settings - Fork 824
fix(langchain): changed dictionary access from spans[run_id] to spans.get(run_id) #3403
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 3 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
27213ef
Changed dictionary access from spans[run_id] to spans.get(run_id) to …
shivampatel-bwater 5afa753
Remove verbose comments
shivampatel-bwater 383ed2a
Add tests for external run_id handling
shivampatel-bwater f45add1
fix linter and remove test
shivampatel-bwater 55c5f40
Merge branch 'main' into shivampatel/fix-key-issue
Shivamp629 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
138 changes: 138 additions & 0 deletions
138
packages/opentelemetry-instrumentation-langchain/tests/test_external_run_id.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,138 @@ | ||
| """Tests for handling external run_ids from systems like LangSmith.""" | ||
|
|
||
| import logging | ||
| from unittest.mock import MagicMock, Mock, patch | ||
| from uuid import uuid4 | ||
|
|
||
| import pytest | ||
| from opentelemetry.instrumentation.langchain.callback_handler import ( | ||
| TraceloopCallbackHandler, | ||
| ) | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def callback_handler(tracer_provider): | ||
| """Create a TraceloopCallbackHandler instance.""" | ||
| return TraceloopCallbackHandler(tracer_provider=tracer_provider) | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def mock_run_manager(): | ||
| """Create a mock run manager with an external run_id.""" | ||
| manager = Mock() | ||
| manager.run_id = uuid4() | ||
| return manager | ||
|
|
||
|
|
||
| def test_external_run_id_no_keyerror( | ||
| callback_handler, mock_run_manager, instrument_legacy, caplog | ||
| ): | ||
| """Test that external run_ids (e.g., from LangSmith) don't cause KeyError.""" | ||
| from opentelemetry.instrumentation.langchain import _OpenAITracingWrapper | ||
|
|
||
| # Create the wrapper | ||
| wrapper = _OpenAITracingWrapper(callback_handler) | ||
|
|
||
| # Mock the wrapped function | ||
| mock_wrapped = Mock(return_value="test_result") | ||
|
|
||
| # Ensure the run_id is NOT in the spans dictionary | ||
| # (simulating an external system like LangSmith creating the run_id) | ||
| assert mock_run_manager.run_id not in callback_handler.spans | ||
|
|
||
| # Create kwargs with the external run_manager | ||
| kwargs = { | ||
| "run_manager": mock_run_manager, | ||
| "extra_headers": {}, | ||
| } | ||
|
|
||
| # Capture debug logs | ||
| with caplog.at_level(logging.DEBUG): | ||
| # Call the wrapper - should NOT raise KeyError | ||
| result = wrapper(mock_wrapped, None, [], kwargs) | ||
|
|
||
| # Verify the function was called successfully | ||
| assert result == "test_result" | ||
| mock_wrapped.assert_called_once() | ||
|
|
||
| # Verify debug log was generated | ||
| assert any( | ||
| "No span found for run_id" in record.message | ||
| and "skipping header injection" in record.message | ||
| for record in caplog.records | ||
| ) | ||
|
|
||
| # Verify extra_headers were not modified since there's no span | ||
| # (the original empty dict should still be there) | ||
| assert "traceparent" not in kwargs["extra_headers"] | ||
|
|
||
|
|
||
| def test_internal_run_id_injects_headers( | ||
| callback_handler, mock_run_manager, instrument_legacy | ||
| ): | ||
| """Test that internal run_ids (created by OTEL) get headers injected.""" | ||
| from opentelemetry.instrumentation.langchain import _OpenAITracingWrapper | ||
| from opentelemetry.sdk.trace import TracerProvider | ||
| from opentelemetry.trace import SpanKind | ||
|
|
||
| # Create a real span and add it to the callback handler's spans | ||
| tracer = TracerProvider().get_tracer(__name__) | ||
| span = tracer.start_span("test_span", kind=SpanKind.CLIENT) | ||
|
|
||
| # Create a span holder (mimicking what the callback handler does) | ||
| span_holder = Mock() | ||
| span_holder.span = span | ||
|
|
||
| # Add the span to the callback handler's spans dictionary | ||
| callback_handler.spans[mock_run_manager.run_id] = span_holder | ||
|
|
||
| # Create the wrapper | ||
| wrapper = _OpenAITracingWrapper(callback_handler) | ||
|
|
||
| # Mock the wrapped function | ||
| mock_wrapped = Mock(return_value="test_result") | ||
|
|
||
| # Create kwargs with the internal run_manager | ||
| kwargs = { | ||
| "run_manager": mock_run_manager, | ||
| "extra_headers": {}, | ||
| } | ||
|
|
||
| # Call the wrapper | ||
| result = wrapper(mock_wrapped, None, [], kwargs) | ||
|
|
||
| # Verify the function was called successfully | ||
| assert result == "test_result" | ||
| mock_wrapped.assert_called_once() | ||
|
|
||
| # Verify headers were injected (traceparent should exist) | ||
| assert "traceparent" in kwargs["extra_headers"] | ||
| assert kwargs["extra_headers"]["traceparent"] # Should have a value | ||
|
|
||
| # Clean up | ||
| span.end() | ||
|
|
||
|
|
||
| def test_no_run_manager_continues_normally(callback_handler, instrument_legacy): | ||
| """Test that missing run_manager doesn't cause issues.""" | ||
| from opentelemetry.instrumentation.langchain import _OpenAITracingWrapper | ||
|
|
||
| # Create the wrapper | ||
| wrapper = _OpenAITracingWrapper(callback_handler) | ||
|
|
||
| # Mock the wrapped function | ||
| mock_wrapped = Mock(return_value="test_result") | ||
|
|
||
| # Create kwargs without run_manager | ||
| kwargs = {"extra_headers": {}} | ||
|
|
||
| # Call the wrapper - should work fine | ||
| result = wrapper(mock_wrapped, None, [], kwargs) | ||
|
|
||
| # Verify the function was called successfully | ||
| assert result == "test_result" | ||
| mock_wrapped.assert_called_once() | ||
|
|
||
| # Verify no headers were injected | ||
| assert "traceparent" not in kwargs["extra_headers"] | ||
|
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
please remove this - it's not testing anything