|
| 1 | +"""Activity wrappers for executing LangGraph nodes and tasks.""" |
| 2 | + |
| 3 | +from collections.abc import Awaitable |
| 4 | +from dataclasses import dataclass |
| 5 | +from inspect import iscoroutinefunction, signature |
| 6 | +from typing import Any, Callable |
| 7 | + |
| 8 | +from langgraph.errors import GraphInterrupt |
| 9 | +from langgraph.types import Command, Interrupt |
| 10 | + |
| 11 | +from temporalio import workflow |
| 12 | +from temporalio.contrib.langgraph._langgraph_config import ( |
| 13 | + get_langgraph_config, |
| 14 | + set_langgraph_config, |
| 15 | + strip_runnable_config, |
| 16 | +) |
| 17 | +from temporalio.contrib.langgraph._task_cache import ( |
| 18 | + cache_key, |
| 19 | + cache_lookup, |
| 20 | + cache_put, |
| 21 | +) |
| 22 | + |
| 23 | +# Per-run dedupe so we only warn once when a user passes a Store via |
| 24 | +# graph.compile(store=...) / @entrypoint(store=...). Cleared by |
| 25 | +# LangGraphInterceptor.execute_workflow on workflow exit. |
| 26 | +_warned_store_runs: set[str] = set() |
| 27 | + |
| 28 | + |
| 29 | +def clear_store_warning(run_id: str) -> None: |
| 30 | + """Drop the store-warning dedupe entry for a workflow run.""" |
| 31 | + _warned_store_runs.discard(run_id) |
| 32 | + |
| 33 | + |
| 34 | +@dataclass |
| 35 | +class ActivityInput: |
| 36 | + """Input for a LangGraph activity, containing args, kwargs, and config.""" |
| 37 | + |
| 38 | + args: tuple[Any, ...] |
| 39 | + kwargs: dict[str, Any] |
| 40 | + langgraph_config: dict[str, Any] |
| 41 | + |
| 42 | + |
| 43 | +@dataclass |
| 44 | +class ActivityOutput: |
| 45 | + """Output from an Activity, containing result, command, or interrupts.""" |
| 46 | + |
| 47 | + result: Any = None |
| 48 | + langgraph_command: Any = None |
| 49 | + langgraph_interrupts: tuple[Interrupt] | None = None |
| 50 | + |
| 51 | + |
| 52 | +def wrap_activity( |
| 53 | + func: Callable, |
| 54 | +) -> Callable[[ActivityInput], Awaitable[ActivityOutput]]: |
| 55 | + """Wrap a function as a Temporal activity that handles LangGraph config and interrupts.""" |
| 56 | + # Graph nodes declare `runtime: Runtime[Ctx]` in their signature; tasks |
| 57 | + # don't and instead reach for Runtime via get_runtime(). We re-inject the |
| 58 | + # reconstructed Runtime only when the user function asks. |
| 59 | + accepts_runtime = "runtime" in signature(func).parameters |
| 60 | + |
| 61 | + async def wrapper(input: ActivityInput) -> ActivityOutput: |
| 62 | + runtime = set_langgraph_config(input.langgraph_config) |
| 63 | + kwargs = dict(input.kwargs) |
| 64 | + if accepts_runtime: |
| 65 | + kwargs["runtime"] = runtime |
| 66 | + try: |
| 67 | + if iscoroutinefunction(func): |
| 68 | + result = await func(*input.args, **kwargs) |
| 69 | + else: |
| 70 | + result = func(*input.args, **kwargs) |
| 71 | + if isinstance(result, Command): |
| 72 | + return ActivityOutput(langgraph_command=result) |
| 73 | + return ActivityOutput(result=result) |
| 74 | + except GraphInterrupt as e: |
| 75 | + return ActivityOutput(langgraph_interrupts=e.args[0]) |
| 76 | + |
| 77 | + return wrapper |
| 78 | + |
| 79 | + |
| 80 | +def wrap_execute_activity( |
| 81 | + afunc: Callable[[ActivityInput], Awaitable[ActivityOutput]], |
| 82 | + task_id: str = "", |
| 83 | + **execute_activity_kwargs: Any, |
| 84 | +) -> Callable[..., Any]: |
| 85 | + """Wrap an activity function to be called via workflow.execute_activity with caching.""" |
| 86 | + |
| 87 | + async def wrapper(*args: Any, **kwargs: Any) -> Any: |
| 88 | + # LangGraph may inject a RunnableConfig as the 'config' kwarg. Strip it |
| 89 | + # down to a serializable subset so it can cross the activity boundary; |
| 90 | + # callbacks, stores, etc. aren't serializable. |
| 91 | + if "config" in kwargs: |
| 92 | + kwargs["config"] = strip_runnable_config(kwargs["config"]) |
| 93 | + |
| 94 | + # LangGraph may inject a Runtime as the 'runtime' kwarg. It's |
| 95 | + # reconstructed on the activity side from the serialized langgraph |
| 96 | + # config, so drop the live Runtime from the kwargs that cross the |
| 97 | + # activity boundary (it holds non-serializable stream_writer, store). |
| 98 | + runtime = kwargs.pop("runtime", None) |
| 99 | + run_id = workflow.info().run_id |
| 100 | + if ( |
| 101 | + getattr(runtime, "store", None) is not None |
| 102 | + and run_id not in _warned_store_runs |
| 103 | + ): |
| 104 | + _warned_store_runs.add(run_id) |
| 105 | + workflow.logger.warning( |
| 106 | + "LangGraph Store passed via compile(store=...) / @entrypoint(store=...) " |
| 107 | + "is not accessible inside activity-wrapped nodes and tasks: the Store " |
| 108 | + "object isn't serializable across the activity boundary, and activities " |
| 109 | + "may run on a different worker than the workflow. Use a backend-backed " |
| 110 | + "store (Postgres/Redis) configured on each worker if you need shared " |
| 111 | + "memory, or use workflow state for per-run memory." |
| 112 | + ) |
| 113 | + |
| 114 | + langgraph_config = get_langgraph_config() |
| 115 | + |
| 116 | + # Check task result cache (for continue-as-new deduplication). |
| 117 | + key = ( |
| 118 | + cache_key(task_id, args, kwargs, langgraph_config.get("context")) |
| 119 | + if task_id |
| 120 | + else "" |
| 121 | + ) |
| 122 | + if task_id: |
| 123 | + found, cached = cache_lookup(key) |
| 124 | + if found: |
| 125 | + return cached |
| 126 | + |
| 127 | + input = ActivityInput( |
| 128 | + args=args, kwargs=kwargs, langgraph_config=langgraph_config |
| 129 | + ) |
| 130 | + output = await workflow.execute_activity( |
| 131 | + afunc, input, **execute_activity_kwargs |
| 132 | + ) |
| 133 | + if output.langgraph_interrupts is not None: |
| 134 | + raise GraphInterrupt(output.langgraph_interrupts) |
| 135 | + |
| 136 | + result = output.result |
| 137 | + if output.langgraph_command is not None: |
| 138 | + cmd = output.langgraph_command |
| 139 | + result = Command( |
| 140 | + graph=cmd["graph"], |
| 141 | + update=cmd["update"], |
| 142 | + resume=cmd["resume"], |
| 143 | + goto=cmd["goto"], |
| 144 | + ) |
| 145 | + |
| 146 | + # Store in cache for future continue-as-new cycles. |
| 147 | + if task_id: |
| 148 | + cache_put(key, result) |
| 149 | + |
| 150 | + return result |
| 151 | + |
| 152 | + return wrapper |
0 commit comments