-
Notifications
You must be signed in to change notification settings - Fork 955
fix(langchain): ensure llm spans are created for sync cases #3201
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
nirga
merged 3 commits into
traceloop:main
from
ronensc:droidnxs/fix-langchain-missing-llm-spans
Jul 30, 2025
Merged
Changes from all commits
Commits
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
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 |
|---|---|---|
|
|
@@ -5,6 +5,8 @@ | |
|
|
||
| from langchain_core.callbacks import ( | ||
| BaseCallbackHandler, | ||
| CallbackManager, | ||
| AsyncCallbackManager, | ||
| ) | ||
| from langchain_core.messages import ( | ||
| AIMessage, | ||
|
|
@@ -85,19 +87,6 @@ def _extract_class_name_from_serialized(serialized: Optional[dict[str, Any]]) -> | |
| return "" | ||
|
|
||
|
|
||
| def _message_type_to_role(message_type: str) -> str: | ||
| if message_type == "human": | ||
| return "user" | ||
| elif message_type == "system": | ||
| return "system" | ||
| elif message_type == "ai": | ||
| return "assistant" | ||
| elif message_type == "tool": | ||
| return "tool" | ||
| else: | ||
| return "unknown" | ||
|
Comment on lines
-88
to
-98
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I removed this function from this file, as it was moved to |
||
|
|
||
|
|
||
| def _sanitize_metadata_value(value: Any) -> Any: | ||
| """Convert metadata values to OpenTelemetry-compatible types.""" | ||
| if value is None: | ||
|
|
@@ -163,6 +152,7 @@ def __init__( | |
| self.token_histogram = token_histogram | ||
| self.spans: dict[UUID, SpanHolder] = {} | ||
| self.run_inline = True | ||
| self._callback_manager: CallbackManager | AsyncCallbackManager = None | ||
|
|
||
| @staticmethod | ||
| def _get_name_from_callback( | ||
|
|
@@ -192,6 +182,9 @@ def _end_span(self, span: Span, run_id: UUID) -> None: | |
| if child_span.end_time is None: # avoid warning on ended spans | ||
| child_span.end() | ||
| span.end() | ||
| token = self.spans[run_id].token | ||
| if token: | ||
| context_api.detach(token) | ||
|
|
||
| def _create_span( | ||
| self, | ||
|
|
@@ -230,13 +223,17 @@ def _create_span( | |
| else: | ||
| span = self.tracer.start_span(span_name, kind=kind) | ||
|
|
||
| token = None | ||
| # TODO: make this unconditional once attach/detach works properly with async callbacks. | ||
| # Currently, it doesn't work due to this - https://github.com/langchain-ai/langchain/issues/31398 | ||
| # As a sidenote, OTel Python users also report similar issues - | ||
| # https://github.com/open-telemetry/opentelemetry-python/issues/2606 | ||
| if self._callback_manager and not self._callback_manager.is_async: | ||
| token = context_api.attach(set_span_in_context(span)) | ||
|
|
||
| _set_span_attribute(span, SpanAttributes.TRACELOOP_WORKFLOW_NAME, workflow_name) | ||
| _set_span_attribute(span, SpanAttributes.TRACELOOP_ENTITY_PATH, entity_path) | ||
|
|
||
| token = context_api.attach( | ||
| context_api.set_value(SUPPRESS_LANGUAGE_MODEL_INSTRUMENTATION_KEY, True) | ||
| ) | ||
|
|
||
| self.spans[run_id] = SpanHolder( | ||
| span, token, None, [], workflow_name, entity_name, entity_path | ||
| ) | ||
|
|
@@ -300,6 +297,16 @@ def _create_llm_span( | |
| _set_span_attribute(span, SpanAttributes.LLM_SYSTEM, vendor) | ||
| _set_span_attribute(span, SpanAttributes.LLM_REQUEST_TYPE, request_type.value) | ||
|
|
||
| # we already have an LLM span by this point, | ||
| # so skip any downstream instrumentation from here | ||
| token = context_api.attach( | ||
| context_api.set_value(SUPPRESS_LANGUAGE_MODEL_INSTRUMENTATION_KEY, True) | ||
| ) | ||
|
|
||
| self.spans[run_id] = SpanHolder( | ||
| span, token, None, [], workflow_name, None, entity_path | ||
| ) | ||
|
|
||
| return span | ||
|
|
||
| @dont_throw | ||
|
|
@@ -464,7 +471,7 @@ def on_llm_end( | |
| "model_name" | ||
| ) or response.llm_output.get("model_id") | ||
| if model_name is not None: | ||
| _set_span_attribute(span, SpanAttributes.LLM_RESPONSE_MODEL, model_name) | ||
| _set_span_attribute(span, SpanAttributes.LLM_RESPONSE_MODEL, model_name or "unknown") | ||
|
|
||
| if self.spans[run_id].request_model is None: | ||
| _set_span_attribute( | ||
|
|
||
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.
In _OpenAITracingWrapper.call, a new suppression context is attached via context_api.attach(). Consider whether this token should be explicitly detached after the wrapped call to avoid any context leakage. The fallback looks intentional, but ensuring cleanup may prevent potential side effects.