-
Notifications
You must be signed in to change notification settings - Fork 94
Added support for LangSmith tracing across workflows and activities #188
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 all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
6f25d35
Added langchain tracing interceptor. Changed sample to use a child wo…
mfateev 2d2b238
Added parallel execution
mfateev 1e1b058
Updated README
mfateev 7ce68c2
Added run_id to traces.
mfateev 89c2f4d
Fixed imports
mfateev d7c1556
Added t.__enter__ which breaks sandbox
mfateev a0eb654
Fixed sandbox errors by explicitly passing through the __exit__ call.
mfateev 4dc6474
PR feedback
mfateev 7085878
Formatted the files to make linter happy.
mfateev 9f8bd51
All lint errors fixed.
mfateev 7dc7c90
Removed dataclasses from passed_through.
mfateev 427641a
Merge from main. uv.lock regenerated.
mfateev e09cd47
Fixed import sorting to keep lint happy.
mfateev 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
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,181 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from typing import Any, Mapping, Protocol, Type | ||
|
|
||
| from temporalio import activity, api, client, converter, worker, workflow | ||
|
|
||
| with workflow.unsafe.imports_passed_through(): | ||
| from contextlib import contextmanager | ||
|
|
||
| from langsmith import trace, tracing_context | ||
| from langsmith.run_helpers import get_current_run_tree | ||
|
|
||
| # Header key for LangChain context | ||
| LANGCHAIN_CONTEXT_KEY = "langchain-context" | ||
|
|
||
|
|
||
| class _InputWithHeaders(Protocol): | ||
| headers: Mapping[str, api.common.v1.Payload] | ||
|
|
||
|
|
||
| def set_header_from_context( | ||
| input: _InputWithHeaders, payload_converter: converter.PayloadConverter | ||
| ) -> None: | ||
| # Get current LangChain run tree | ||
| run_tree = get_current_run_tree() | ||
| if run_tree: | ||
| headers = run_tree.to_headers() | ||
| input.headers = { | ||
| **input.headers, | ||
| LANGCHAIN_CONTEXT_KEY: payload_converter.to_payload(headers), | ||
| } | ||
|
|
||
|
|
||
| @contextmanager | ||
| def context_from_header( | ||
| input: _InputWithHeaders, payload_converter: converter.PayloadConverter | ||
| ): | ||
| payload = input.headers.get(LANGCHAIN_CONTEXT_KEY) | ||
| if payload: | ||
| run_tree = payload_converter.from_payload(payload, dict) | ||
| # Set the run tree in the current context | ||
| with tracing_context(parent=run_tree): | ||
| yield | ||
| else: | ||
| yield | ||
|
|
||
|
|
||
| class LangChainContextPropagationInterceptor(client.Interceptor, worker.Interceptor): | ||
| """Interceptor that propagates LangChain context through Temporal.""" | ||
|
|
||
| def __init__( | ||
| self, | ||
| payload_converter: converter.PayloadConverter = converter.default().payload_converter, | ||
| ) -> None: | ||
| self._payload_converter = payload_converter | ||
|
|
||
| def intercept_client( | ||
| self, next: client.OutboundInterceptor | ||
| ) -> client.OutboundInterceptor: | ||
| return _LangChainContextPropagationClientOutboundInterceptor( | ||
| next, self._payload_converter | ||
| ) | ||
|
|
||
| def intercept_activity( | ||
| self, next: worker.ActivityInboundInterceptor | ||
| ) -> worker.ActivityInboundInterceptor: | ||
| return _LangChainContextPropagationActivityInboundInterceptor(next) | ||
|
|
||
| def workflow_interceptor_class( | ||
| self, input: worker.WorkflowInterceptorClassInput | ||
| ) -> Type[_LangChainContextPropagationWorkflowInboundInterceptor]: | ||
| return _LangChainContextPropagationWorkflowInboundInterceptor | ||
|
|
||
|
|
||
| class _LangChainContextPropagationClientOutboundInterceptor(client.OutboundInterceptor): | ||
| def __init__( | ||
| self, | ||
| next: client.OutboundInterceptor, | ||
| payload_converter: converter.PayloadConverter, | ||
| ) -> None: | ||
| super().__init__(next) | ||
| self._payload_converter = payload_converter | ||
|
|
||
| async def start_workflow( | ||
| self, input: client.StartWorkflowInput | ||
| ) -> client.WorkflowHandle[Any, Any]: | ||
| with trace(name=f"start_workflow:{input.workflow}"): | ||
| set_header_from_context(input, self._payload_converter) | ||
| return await super().start_workflow(input) | ||
|
|
||
|
|
||
| class _LangChainContextPropagationActivityInboundInterceptor( | ||
| worker.ActivityInboundInterceptor | ||
| ): | ||
| async def execute_activity(self, input: worker.ExecuteActivityInput) -> Any: | ||
| if isinstance(input.fn, str): | ||
| name = input.fn | ||
| elif callable(input.fn): | ||
| defn = activity._Definition.from_callable(input.fn) | ||
| name = ( | ||
| defn.name if defn is not None and defn.name is not None else "unknown" | ||
| ) | ||
| else: | ||
| name = "unknown" | ||
|
|
||
| with context_from_header(input, activity.payload_converter()): | ||
| with trace(name=f"execute_activity:{name}"): | ||
| return await self.next.execute_activity(input) | ||
|
|
||
|
|
||
| class _LangChainContextPropagationWorkflowInboundInterceptor( | ||
| worker.WorkflowInboundInterceptor | ||
| ): | ||
| def init(self, outbound: worker.WorkflowOutboundInterceptor) -> None: | ||
| self.next.init( | ||
| _LangChainContextPropagationWorkflowOutboundInterceptor(outbound) | ||
| ) | ||
|
|
||
| async def execute_workflow(self, input: worker.ExecuteWorkflowInput) -> Any: | ||
| if isinstance(input.run_fn, str): | ||
| name = input.run_fn | ||
| elif callable(input.run_fn): | ||
| defn = workflow._Definition.from_run_fn(input.run_fn) | ||
| name = ( | ||
| defn.name if defn is not None and defn.name is not None else "unknown" | ||
| ) | ||
| else: | ||
| name = "unknown" | ||
|
|
||
| with context_from_header(input, workflow.payload_converter()): | ||
| # This is a sandbox friendly way to write | ||
| # with trace(...): | ||
| # return await self.next.execute_workflow(input) | ||
| with workflow.unsafe.sandbox_unrestricted(): | ||
| t = trace( | ||
| name=f"execute_workflow:{name}", run_id=workflow.info().run_id | ||
| ) | ||
| with workflow.unsafe.imports_passed_through(): | ||
| t.__enter__() | ||
| try: | ||
| return await self.next.execute_workflow(input) | ||
| finally: | ||
| with workflow.unsafe.sandbox_unrestricted(): | ||
| # Cannot use __aexit__ because it's internally uses | ||
| # loop.run_in_executor which is not available in the sandbox | ||
| t.__exit__() | ||
|
|
||
|
|
||
| class _LangChainContextPropagationWorkflowOutboundInterceptor( | ||
| worker.WorkflowOutboundInterceptor | ||
| ): | ||
| def start_activity( | ||
| self, input: worker.StartActivityInput | ||
| ) -> workflow.ActivityHandle: | ||
| with workflow.unsafe.sandbox_unrestricted(): | ||
| t = trace(name=f"start_activity:{input.activity}", run_id=workflow.uuid4()) | ||
| with workflow.unsafe.imports_passed_through(): | ||
| t.__enter__() | ||
| try: | ||
| set_header_from_context(input, workflow.payload_converter()) | ||
| return self.next.start_activity(input) | ||
| finally: | ||
| with workflow.unsafe.sandbox_unrestricted(): | ||
| t.__exit__() | ||
|
|
||
| async def start_child_workflow( | ||
| self, input: worker.StartChildWorkflowInput | ||
| ) -> workflow.ChildWorkflowHandle: | ||
| with workflow.unsafe.sandbox_unrestricted(): | ||
| t = trace( | ||
| name=f"start_child_workflow:{input.workflow}", run_id=workflow.uuid4() | ||
| ) | ||
| with workflow.unsafe.imports_passed_through(): | ||
| t.__enter__() | ||
|
|
||
| try: | ||
| set_header_from_context(input, workflow.payload_converter()) | ||
| return await self.next.start_child_workflow(input) | ||
| finally: | ||
| with workflow.unsafe.sandbox_unrestricted(): | ||
| t.__exit__() |
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
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
Oops, something went wrong.
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.
I see we never really had tests for the
langchainsample, so don't have to add as part of this, but we should probably make an issue to add them at some point. We've found cases where these integration-type examples become stale or stop working with new dependency versions and there are no tests to confirm that.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.
I'm not sure how a local test would help, as they don't have an embeddable version of Langsmith.
Uh oh!
There was an error while loading. Please reload this page.
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.
That is unfortunate. Ideally we'd test the same way they encourage users to test using the in-memory representations or mocks they suggest. But we do often not test integrations in this repo.