|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from typing import Any, Mapping, Protocol, Type |
| 4 | + |
| 5 | +from temporalio import activity, api, client, converter, worker, workflow |
| 6 | + |
| 7 | +with workflow.unsafe.imports_passed_through(): |
| 8 | + from contextlib import contextmanager |
| 9 | + |
| 10 | + from langsmith import trace, tracing_context |
| 11 | + from langsmith.run_helpers import get_current_run_tree |
| 12 | + |
| 13 | +# Header key for LangChain context |
| 14 | +LANGCHAIN_CONTEXT_KEY = "langchain-context" |
| 15 | + |
| 16 | + |
| 17 | +class _InputWithHeaders(Protocol): |
| 18 | + headers: Mapping[str, api.common.v1.Payload] |
| 19 | + |
| 20 | + |
| 21 | +def set_header_from_context( |
| 22 | + input: _InputWithHeaders, payload_converter: converter.PayloadConverter |
| 23 | +) -> None: |
| 24 | + # Get current LangChain run tree |
| 25 | + run_tree = get_current_run_tree() |
| 26 | + if run_tree: |
| 27 | + headers = run_tree.to_headers() |
| 28 | + input.headers = { |
| 29 | + **input.headers, |
| 30 | + LANGCHAIN_CONTEXT_KEY: payload_converter.to_payload(headers), |
| 31 | + } |
| 32 | + |
| 33 | + |
| 34 | +@contextmanager |
| 35 | +def context_from_header( |
| 36 | + input: _InputWithHeaders, payload_converter: converter.PayloadConverter |
| 37 | +): |
| 38 | + payload = input.headers.get(LANGCHAIN_CONTEXT_KEY) |
| 39 | + if payload: |
| 40 | + run_tree = payload_converter.from_payload(payload, dict) |
| 41 | + # Set the run tree in the current context |
| 42 | + with tracing_context(parent=run_tree): |
| 43 | + yield |
| 44 | + else: |
| 45 | + yield |
| 46 | + |
| 47 | + |
| 48 | +class LangChainContextPropagationInterceptor(client.Interceptor, worker.Interceptor): |
| 49 | + """Interceptor that propagates LangChain context through Temporal.""" |
| 50 | + |
| 51 | + def __init__( |
| 52 | + self, |
| 53 | + payload_converter: converter.PayloadConverter = converter.default().payload_converter, |
| 54 | + ) -> None: |
| 55 | + self._payload_converter = payload_converter |
| 56 | + |
| 57 | + def intercept_client( |
| 58 | + self, next: client.OutboundInterceptor |
| 59 | + ) -> client.OutboundInterceptor: |
| 60 | + return _LangChainContextPropagationClientOutboundInterceptor( |
| 61 | + next, self._payload_converter |
| 62 | + ) |
| 63 | + |
| 64 | + def intercept_activity( |
| 65 | + self, next: worker.ActivityInboundInterceptor |
| 66 | + ) -> worker.ActivityInboundInterceptor: |
| 67 | + return _LangChainContextPropagationActivityInboundInterceptor(next) |
| 68 | + |
| 69 | + def workflow_interceptor_class( |
| 70 | + self, input: worker.WorkflowInterceptorClassInput |
| 71 | + ) -> Type[_LangChainContextPropagationWorkflowInboundInterceptor]: |
| 72 | + return _LangChainContextPropagationWorkflowInboundInterceptor |
| 73 | + |
| 74 | + |
| 75 | +class _LangChainContextPropagationClientOutboundInterceptor(client.OutboundInterceptor): |
| 76 | + def __init__( |
| 77 | + self, |
| 78 | + next: client.OutboundInterceptor, |
| 79 | + payload_converter: converter.PayloadConverter, |
| 80 | + ) -> None: |
| 81 | + super().__init__(next) |
| 82 | + self._payload_converter = payload_converter |
| 83 | + |
| 84 | + async def start_workflow( |
| 85 | + self, input: client.StartWorkflowInput |
| 86 | + ) -> client.WorkflowHandle[Any, Any]: |
| 87 | + with trace(name=f"start_workflow:{input.workflow}"): |
| 88 | + set_header_from_context(input, self._payload_converter) |
| 89 | + return await super().start_workflow(input) |
| 90 | + |
| 91 | + |
| 92 | +class _LangChainContextPropagationActivityInboundInterceptor( |
| 93 | + worker.ActivityInboundInterceptor |
| 94 | +): |
| 95 | + async def execute_activity(self, input: worker.ExecuteActivityInput) -> Any: |
| 96 | + if isinstance(input.fn, str): |
| 97 | + name = input.fn |
| 98 | + elif callable(input.fn): |
| 99 | + defn = activity._Definition.from_callable(input.fn) |
| 100 | + name = ( |
| 101 | + defn.name if defn is not None and defn.name is not None else "unknown" |
| 102 | + ) |
| 103 | + else: |
| 104 | + name = "unknown" |
| 105 | + |
| 106 | + with context_from_header(input, activity.payload_converter()): |
| 107 | + with trace(name=f"execute_activity:{name}"): |
| 108 | + return await self.next.execute_activity(input) |
| 109 | + |
| 110 | + |
| 111 | +class _LangChainContextPropagationWorkflowInboundInterceptor( |
| 112 | + worker.WorkflowInboundInterceptor |
| 113 | +): |
| 114 | + def init(self, outbound: worker.WorkflowOutboundInterceptor) -> None: |
| 115 | + self.next.init( |
| 116 | + _LangChainContextPropagationWorkflowOutboundInterceptor(outbound) |
| 117 | + ) |
| 118 | + |
| 119 | + async def execute_workflow(self, input: worker.ExecuteWorkflowInput) -> Any: |
| 120 | + if isinstance(input.run_fn, str): |
| 121 | + name = input.run_fn |
| 122 | + elif callable(input.run_fn): |
| 123 | + defn = workflow._Definition.from_run_fn(input.run_fn) |
| 124 | + name = ( |
| 125 | + defn.name if defn is not None and defn.name is not None else "unknown" |
| 126 | + ) |
| 127 | + else: |
| 128 | + name = "unknown" |
| 129 | + |
| 130 | + with context_from_header(input, workflow.payload_converter()): |
| 131 | + # This is a sandbox friendly way to write |
| 132 | + # with trace(...): |
| 133 | + # return await self.next.execute_workflow(input) |
| 134 | + with workflow.unsafe.sandbox_unrestricted(): |
| 135 | + t = trace( |
| 136 | + name=f"execute_workflow:{name}", run_id=workflow.info().run_id |
| 137 | + ) |
| 138 | + with workflow.unsafe.imports_passed_through(): |
| 139 | + t.__enter__() |
| 140 | + try: |
| 141 | + return await self.next.execute_workflow(input) |
| 142 | + finally: |
| 143 | + with workflow.unsafe.sandbox_unrestricted(): |
| 144 | + # Cannot use __aexit__ because it's internally uses |
| 145 | + # loop.run_in_executor which is not available in the sandbox |
| 146 | + t.__exit__() |
| 147 | + |
| 148 | + |
| 149 | +class _LangChainContextPropagationWorkflowOutboundInterceptor( |
| 150 | + worker.WorkflowOutboundInterceptor |
| 151 | +): |
| 152 | + def start_activity( |
| 153 | + self, input: worker.StartActivityInput |
| 154 | + ) -> workflow.ActivityHandle: |
| 155 | + with workflow.unsafe.sandbox_unrestricted(): |
| 156 | + t = trace(name=f"start_activity:{input.activity}", run_id=workflow.uuid4()) |
| 157 | + with workflow.unsafe.imports_passed_through(): |
| 158 | + t.__enter__() |
| 159 | + try: |
| 160 | + set_header_from_context(input, workflow.payload_converter()) |
| 161 | + return self.next.start_activity(input) |
| 162 | + finally: |
| 163 | + with workflow.unsafe.sandbox_unrestricted(): |
| 164 | + t.__exit__() |
| 165 | + |
| 166 | + async def start_child_workflow( |
| 167 | + self, input: worker.StartChildWorkflowInput |
| 168 | + ) -> workflow.ChildWorkflowHandle: |
| 169 | + with workflow.unsafe.sandbox_unrestricted(): |
| 170 | + t = trace( |
| 171 | + name=f"start_child_workflow:{input.workflow}", run_id=workflow.uuid4() |
| 172 | + ) |
| 173 | + with workflow.unsafe.imports_passed_through(): |
| 174 | + t.__enter__() |
| 175 | + |
| 176 | + try: |
| 177 | + set_header_from_context(input, workflow.payload_converter()) |
| 178 | + return await self.next.start_child_workflow(input) |
| 179 | + finally: |
| 180 | + with workflow.unsafe.sandbox_unrestricted(): |
| 181 | + t.__exit__() |
0 commit comments