temporalio-langgraph 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,25 @@
1
+ """LangGraph plugin for Temporal SDK.
2
+
3
+ .. warning::
4
+ This package is experimental and may change in future versions.
5
+ Use with caution in production environments.
6
+
7
+ This plugin runs `LangGraph <https://github.com/langchain-ai/langgraph>`_ nodes
8
+ and tasks as Temporal Activities, giving your AI agent workflows durable
9
+ execution, automatic retries, and timeouts. It supports both the LangGraph Graph
10
+ API (``StateGraph``) and Functional API (``@entrypoint`` / ``@task``).
11
+ """
12
+
13
+ from temporalio.langgraph._plugin import (
14
+ LangGraphPlugin,
15
+ cache,
16
+ entrypoint,
17
+ graph,
18
+ )
19
+
20
+ __all__ = [
21
+ "LangGraphPlugin",
22
+ "cache",
23
+ "entrypoint",
24
+ "graph",
25
+ ]
@@ -0,0 +1,188 @@
1
+ """Activity wrappers for executing LangGraph nodes and tasks."""
2
+
3
+ import asyncio
4
+ from collections.abc import Awaitable
5
+ from dataclasses import dataclass
6
+ from datetime import timedelta
7
+ from inspect import iscoroutinefunction, signature
8
+ from typing import Any, Callable
9
+
10
+ from langgraph.errors import GraphInterrupt
11
+ from langgraph.types import Command, Interrupt
12
+
13
+ from temporalio import workflow
14
+ from temporalio.contrib.workflow_streams import WorkflowStreamClient
15
+ from temporalio.langgraph._langgraph_config import (
16
+ get_langgraph_config,
17
+ set_langgraph_config,
18
+ strip_runnable_config,
19
+ )
20
+ from temporalio.langgraph._task_cache import (
21
+ cache_key,
22
+ cache_lookup,
23
+ cache_put,
24
+ )
25
+
26
+ # Per-run dedupe so we only warn once when a user passes a Store via
27
+ # graph.compile(store=...) / @entrypoint(store=...). Cleared by
28
+ # LangGraphInterceptor.execute_workflow on workflow exit.
29
+ _warned_store_runs: set[str] = set()
30
+
31
+
32
+ def clear_store_warning(run_id: str) -> None:
33
+ """Drop the store-warning dedupe entry for a workflow run."""
34
+ _warned_store_runs.discard(run_id)
35
+
36
+
37
+ @dataclass
38
+ class ActivityInput:
39
+ """Input for a LangGraph activity, containing args, kwargs, and config."""
40
+
41
+ args: tuple[Any, ...]
42
+ kwargs: dict[str, Any]
43
+ langgraph_config: dict[str, Any]
44
+
45
+
46
+ @dataclass
47
+ class ActivityOutput:
48
+ """Output from an Activity, containing result, command, or interrupts."""
49
+
50
+ result: Any = None
51
+ langgraph_command: Any = None
52
+ langgraph_interrupts: tuple[Interrupt] | None = None
53
+
54
+
55
+ def wrap_activity(
56
+ func: Callable,
57
+ *,
58
+ streaming_topic: str | None = None,
59
+ streaming_batch_interval: timedelta = timedelta(milliseconds=100),
60
+ ) -> Callable[[ActivityInput], Awaitable[ActivityOutput]]:
61
+ """Wrap a function as a Temporal activity that handles LangGraph config and interrupts."""
62
+ accepts_runtime = "runtime" in signature(func).parameters
63
+
64
+ async def wrapper(input: ActivityInput) -> ActivityOutput:
65
+ async def run(stream_writer: Callable[[Any], None] | None) -> ActivityOutput:
66
+ # Sync funcs run on a thread (so the loop keeps flushing the
67
+ # stream client mid-execution); marshal writer calls back to
68
+ # the loop thread because the client's flush event is an
69
+ # asyncio.Event and isn't safe to set off-thread.
70
+ effective_writer = stream_writer
71
+ if not iscoroutinefunction(func) and stream_writer is not None:
72
+ loop = asyncio.get_running_loop()
73
+ inner_writer = stream_writer
74
+
75
+ def thread_safe_writer(value: Any) -> None:
76
+ loop.call_soon_threadsafe(inner_writer, value)
77
+
78
+ effective_writer = thread_safe_writer
79
+
80
+ runtime = set_langgraph_config(
81
+ input.langgraph_config, stream_writer=effective_writer
82
+ )
83
+ kwargs = dict(input.kwargs)
84
+ if accepts_runtime:
85
+ kwargs["runtime"] = runtime
86
+
87
+ try:
88
+ if iscoroutinefunction(func):
89
+ result = await func(*input.args, **kwargs)
90
+ else:
91
+ result = await asyncio.to_thread(func, *input.args, **kwargs)
92
+ if isinstance(result, Command):
93
+ return ActivityOutput(langgraph_command=result)
94
+ return ActivityOutput(result=result)
95
+ except GraphInterrupt as e:
96
+ return ActivityOutput(langgraph_interrupts=e.args[0])
97
+
98
+ if streaming_topic is None:
99
+ return await run(stream_writer=None)
100
+ async with WorkflowStreamClient.from_within_activity(
101
+ batch_interval=streaming_batch_interval,
102
+ ) as client:
103
+ topic = client.topic(streaming_topic)
104
+ return await run(stream_writer=topic.publish)
105
+
106
+ return wrapper
107
+
108
+
109
+ def wrap_execute_activity(
110
+ afunc: Callable[[ActivityInput], Awaitable[ActivityOutput]],
111
+ task_id: str = "",
112
+ summary_fn: Callable[[tuple[Any, ...], dict[str, Any]], str | None] | None = None,
113
+ **execute_activity_kwargs: Any,
114
+ ) -> Callable[..., Any]:
115
+ """Wrap an activity function to be called via workflow.execute_activity with caching."""
116
+
117
+ async def wrapper(*args: Any, **kwargs: Any) -> Any:
118
+ # LangGraph may inject a RunnableConfig as the 'config' kwarg. Strip it
119
+ # down to a serializable subset so it can cross the activity boundary;
120
+ # callbacks, stores, etc. aren't serializable.
121
+ if "config" in kwargs:
122
+ kwargs["config"] = strip_runnable_config(kwargs["config"])
123
+
124
+ # LangGraph may inject a Runtime as the 'runtime' kwarg. It's
125
+ # reconstructed on the activity side from the serialized langgraph
126
+ # config, so drop the live Runtime from the kwargs that cross the
127
+ # activity boundary (it holds non-serializable stream_writer, store).
128
+ runtime = kwargs.pop("runtime", None)
129
+ run_id = workflow.info().run_id
130
+ if (
131
+ getattr(runtime, "store", None) is not None
132
+ and run_id not in _warned_store_runs
133
+ ):
134
+ _warned_store_runs.add(run_id)
135
+ workflow.logger.warning(
136
+ "LangGraph Store passed via compile(store=...) / @entrypoint(store=...) "
137
+ "is not accessible inside activity-wrapped nodes and tasks: the Store "
138
+ "object isn't serializable across the activity boundary, and activities "
139
+ "may run on a different worker than the workflow. Use a backend-backed "
140
+ "store (Postgres/Redis) configured on each worker if you need shared "
141
+ "memory, or use workflow state for per-run memory."
142
+ )
143
+
144
+ langgraph_config = get_langgraph_config()
145
+
146
+ # Check task result cache (for continue-as-new deduplication).
147
+ key = (
148
+ cache_key(task_id, args, kwargs, langgraph_config.get("context"))
149
+ if task_id
150
+ else ""
151
+ )
152
+ if task_id:
153
+ found, cached = cache_lookup(key)
154
+ if found:
155
+ return cached
156
+
157
+ input = ActivityInput(
158
+ args=args, kwargs=kwargs, langgraph_config=langgraph_config
159
+ )
160
+ # Compute a dynamic activity summary (if configured) on the schedule
161
+ # path only; a cache hit above returns before reaching here, so no
162
+ # activity is scheduled and no summary is needed.
163
+ call_kwargs = dict(execute_activity_kwargs)
164
+ if summary_fn is not None:
165
+ summary = summary_fn(args, kwargs)
166
+ if summary:
167
+ call_kwargs["summary"] = summary
168
+ output = await workflow.execute_activity(afunc, input, **call_kwargs)
169
+ if output.langgraph_interrupts is not None:
170
+ raise GraphInterrupt(output.langgraph_interrupts)
171
+
172
+ result = output.result
173
+ if output.langgraph_command is not None:
174
+ cmd = output.langgraph_command
175
+ result = Command(
176
+ graph=cmd["graph"],
177
+ update=cmd["update"],
178
+ resume=cmd["resume"],
179
+ goto=cmd["goto"],
180
+ )
181
+
182
+ # Store in cache for future continue-as-new cycles.
183
+ if task_id:
184
+ cache_put(key, result)
185
+
186
+ return result
187
+
188
+ return wrapper
@@ -0,0 +1,77 @@
1
+ """Workflow interceptor that scopes LangGraph graphs/entrypoints to the workflow run."""
2
+
3
+ # pyright: reportMissingTypeStubs=false
4
+
5
+ from __future__ import annotations
6
+
7
+ from typing import Any
8
+
9
+ from langgraph.graph import StateGraph
10
+ from langgraph.pregel import Pregel
11
+
12
+ from temporalio import workflow
13
+ from temporalio.contrib.workflow_streams._stream import _PUBLISH_SIGNAL
14
+ from temporalio.langgraph._activity import clear_store_warning
15
+ from temporalio.worker import (
16
+ ExecuteWorkflowInput,
17
+ Interceptor,
18
+ WorkflowInboundInterceptor,
19
+ WorkflowInterceptorClassInput,
20
+ WorkflowOutboundInterceptor,
21
+ )
22
+
23
+ _workflow_graphs: dict[str, dict[str, StateGraph[Any, Any, Any, Any]]] = {}
24
+ _workflow_entrypoints: dict[str, dict[str, Pregel[Any, Any, Any, Any]]] = {}
25
+
26
+
27
+ class LangGraphInterceptor(Interceptor):
28
+ """Interceptor that registers a workflow's graphs and entrypoints for the run."""
29
+
30
+ def __init__(
31
+ self,
32
+ graphs: dict[str, StateGraph[Any, Any, Any, Any]],
33
+ entrypoints: dict[str, Pregel[Any, Any, Any, Any]],
34
+ streaming_topic: str | None = None,
35
+ ) -> None:
36
+ """Initialize with the graphs and entrypoints to scope to each workflow run."""
37
+ self._graphs = graphs
38
+ self._entrypoints = entrypoints
39
+ self._streaming_topic = streaming_topic
40
+
41
+ def workflow_interceptor_class(
42
+ self, input: WorkflowInterceptorClassInput
43
+ ) -> type[WorkflowInboundInterceptor]:
44
+ """Return the inbound interceptor class used to scope graphs per run."""
45
+ graphs = self._graphs
46
+ entrypoints = self._entrypoints
47
+ streaming_topic = self._streaming_topic
48
+
49
+ class Inbound(WorkflowInboundInterceptor):
50
+ def init(self, outbound: WorkflowOutboundInterceptor) -> None:
51
+ run_id = outbound.info().run_id
52
+ _workflow_graphs[run_id] = graphs
53
+ _workflow_entrypoints[run_id] = entrypoints
54
+ super().init(outbound)
55
+
56
+ async def execute_workflow(self, input: ExecuteWorkflowInput) -> Any:
57
+ if (
58
+ streaming_topic is not None
59
+ and workflow.get_signal_handler(_PUBLISH_SIGNAL) is None
60
+ ):
61
+ raise RuntimeError(
62
+ f"LangGraphPlugin was configured with "
63
+ f"streaming_topic={streaming_topic!r}, but workflow "
64
+ f"{workflow.info().workflow_type!r} did not register a "
65
+ f"WorkflowStream. Construct WorkflowStream() in the "
66
+ f"workflow's @workflow.init (i.e. __init__) method so "
67
+ f"streaming activities can publish to it."
68
+ )
69
+ try:
70
+ return await self.next.execute_workflow(input)
71
+ finally:
72
+ run_id = workflow.info().run_id
73
+ _workflow_graphs.pop(run_id, None)
74
+ _workflow_entrypoints.pop(run_id, None)
75
+ clear_store_warning(run_id)
76
+
77
+ return Inbound
@@ -0,0 +1,164 @@
1
+ """LangGraph configuration management for Temporal workflows."""
2
+
3
+ # pyright: reportMissingTypeStubs=false
4
+
5
+ import dataclasses
6
+ from typing import Any, Callable
7
+
8
+ from langchain_core.runnables.config import var_child_runnable_config
9
+ from langgraph._internal._constants import (
10
+ CONFIG_KEY_CHECKPOINT_ID,
11
+ CONFIG_KEY_CHECKPOINT_MAP,
12
+ CONFIG_KEY_CHECKPOINT_NS,
13
+ CONFIG_KEY_DURABILITY,
14
+ CONFIG_KEY_RESUMING,
15
+ CONFIG_KEY_RUNTIME,
16
+ CONFIG_KEY_SCRATCHPAD,
17
+ CONFIG_KEY_SEND,
18
+ CONFIG_KEY_TASK_ID,
19
+ CONFIG_KEY_THREAD_ID,
20
+ )
21
+ from langgraph._internal._scratchpad import PregelScratchpad
22
+ from langgraph.graph.state import RunnableConfig
23
+ from langgraph.pregel._algo import LazyAtomicCounter
24
+ from langgraph.runtime import ExecutionInfo, Runtime
25
+
26
+
27
+ def strip_runnable_config(config: RunnableConfig | None) -> RunnableConfig:
28
+ """Return a serializable subset of a RunnableConfig.
29
+
30
+ LangGraph injects the active RunnableConfig into user functions as a
31
+ config kwarg. The full object holds non-serializable things (callbacks,
32
+ checkpointer/store/cache handles, pregel send/read callables) that can't
33
+ cross an activity boundary, so we keep only primitive fields and the
34
+ serializable subset of configurable.
35
+ """
36
+ orig = config or {}
37
+ configurable = orig.get("configurable") or {}
38
+
39
+ result: RunnableConfig = {
40
+ "tags": list(orig.get("tags") or []),
41
+ "metadata": dict(orig.get("metadata") or {}),
42
+ }
43
+ if run_name := orig.get("run_name"):
44
+ result["run_name"] = run_name
45
+ if run_id := orig.get("run_id"):
46
+ result["run_id"] = run_id
47
+ if (recursion_limit := orig.get("recursion_limit")) is not None:
48
+ result["recursion_limit"] = recursion_limit
49
+
50
+ stripped_configurable: dict[str, Any] = {
51
+ key: configurable[key]
52
+ for key in (
53
+ CONFIG_KEY_CHECKPOINT_NS,
54
+ CONFIG_KEY_CHECKPOINT_ID,
55
+ CONFIG_KEY_CHECKPOINT_MAP,
56
+ CONFIG_KEY_THREAD_ID,
57
+ CONFIG_KEY_TASK_ID,
58
+ CONFIG_KEY_RESUMING,
59
+ CONFIG_KEY_DURABILITY,
60
+ )
61
+ if key in configurable
62
+ }
63
+ if stripped_configurable:
64
+ result["configurable"] = stripped_configurable
65
+ return result
66
+
67
+
68
+ def get_langgraph_config() -> dict[str, Any]:
69
+ """Get the current LangGraph runnable config as a serializable dict."""
70
+ config = var_child_runnable_config.get()
71
+ configurable = (config or {}).get("configurable") or {}
72
+ scratchpad = configurable.get(CONFIG_KEY_SCRATCHPAD)
73
+ runtime = configurable.get(CONFIG_KEY_RUNTIME)
74
+ execution_info = getattr(runtime, "execution_info", None)
75
+
76
+ stripped = strip_runnable_config(config)
77
+ return {
78
+ **stripped,
79
+ "configurable": {
80
+ **(stripped.get("configurable") or {}),
81
+ CONFIG_KEY_SCRATCHPAD: {
82
+ "step": getattr(scratchpad, "step", 0),
83
+ "stop": getattr(scratchpad, "stop", 0),
84
+ "resume": list(getattr(scratchpad, "resume", [])),
85
+ "null_resume": scratchpad.get_null_resume() if scratchpad else None,
86
+ },
87
+ },
88
+ "context": getattr(runtime, "context", None),
89
+ "previous": getattr(runtime, "previous", None),
90
+ "execution_info": (
91
+ dataclasses.asdict(execution_info) if execution_info else None
92
+ ),
93
+ }
94
+
95
+
96
+ def set_langgraph_config(
97
+ config: dict[str, Any],
98
+ *,
99
+ stream_writer: Callable[[Any], None] | None = None,
100
+ ) -> Runtime:
101
+ """Restore a LangGraph runnable config from a serialized dict.
102
+
103
+ Returns the reconstructed Runtime so callers can re-inject it into the
104
+ user function's kwargs without needing to know the configurable layout.
105
+ """
106
+ configurable = config.get("configurable") or {}
107
+ scratchpad = configurable.get(CONFIG_KEY_SCRATCHPAD) or {}
108
+ null_resume_box = [scratchpad.get("null_resume")]
109
+
110
+ def get_null_resume(consume: bool = False) -> Any:
111
+ val = null_resume_box[0]
112
+ if consume and val is not None:
113
+ null_resume_box[0] = None
114
+ return val
115
+
116
+ execution_info_dict = config.get("execution_info")
117
+ runtime = Runtime(
118
+ context=config.get("context"),
119
+ stream_writer=stream_writer or (lambda _: None),
120
+ previous=config.get("previous"),
121
+ execution_info=(
122
+ ExecutionInfo(**execution_info_dict) if execution_info_dict else None
123
+ ),
124
+ )
125
+
126
+ restored_configurable: dict[str, Any] = {
127
+ key: configurable[key]
128
+ for key in (
129
+ CONFIG_KEY_CHECKPOINT_NS,
130
+ CONFIG_KEY_CHECKPOINT_ID,
131
+ CONFIG_KEY_CHECKPOINT_MAP,
132
+ CONFIG_KEY_THREAD_ID,
133
+ CONFIG_KEY_TASK_ID,
134
+ CONFIG_KEY_RESUMING,
135
+ CONFIG_KEY_DURABILITY,
136
+ )
137
+ if key in configurable
138
+ }
139
+ restored_configurable[CONFIG_KEY_SCRATCHPAD] = PregelScratchpad(
140
+ step=scratchpad.get("step", 0),
141
+ stop=scratchpad.get("stop", 0),
142
+ call_counter=LazyAtomicCounter(),
143
+ interrupt_counter=LazyAtomicCounter(),
144
+ get_null_resume=get_null_resume,
145
+ resume=list(scratchpad.get("resume", [])),
146
+ subgraph_counter=LazyAtomicCounter(),
147
+ )
148
+ restored_configurable[CONFIG_KEY_SEND] = lambda _: None
149
+ restored_configurable[CONFIG_KEY_RUNTIME] = runtime
150
+
151
+ runnable_config: RunnableConfig = {"configurable": restored_configurable}
152
+ if tags := config.get("tags"):
153
+ runnable_config["tags"] = tags
154
+ if metadata := config.get("metadata"):
155
+ runnable_config["metadata"] = metadata
156
+ if run_name := config.get("run_name"):
157
+ runnable_config["run_name"] = run_name
158
+ if run_id := config.get("run_id"):
159
+ runnable_config["run_id"] = run_id
160
+ if (recursion_limit := config.get("recursion_limit")) is not None:
161
+ runnable_config["recursion_limit"] = recursion_limit
162
+
163
+ var_child_runnable_config.set(runnable_config)
164
+ return runtime