-
Notifications
You must be signed in to change notification settings - Fork 106
LangGraph plugin samples #289
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
Open
DABH
wants to merge
15
commits into
temporalio:main
Choose a base branch
from
DABH:langgraph-samples
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
149803f
Add LangGraph plugin samples
DABH 8a260c6
Remove explicit langchain deps from langgraph group to avoid conflict
DABH 042a51f
Declare langchain and langgraph as conflicting dependency groups
DABH 3e7f91b
Fix import sorting and formatting
DABH 0505fd1
Update dependencies and lint config (temporarily - waiting for SDK PR…
DABH ee781cd
Add hello_world samples, per-sample READMEs, tests, __init__ docstrin…
DABH e2832bb
Address review: consistent v2 API, unique thread_id, SDK prereq note
DABH f3fb15c
Remove SDK prereq note - PR won't merge until plugin is released
DABH 67d1310
Add LangSmith tracing sample (Graph API + Functional API)
DABH dedf931
Update all samples to match SDK PR #1448 API
DABH a5e3871
Merge branch 'main' into langgraph-samples
DABH 9c06edd
Update LangGraph samples to current sdk-python main API
DABH 85a2ab1
CI: install protoc for building temporalio from sdk-python git source
DABH 876892f
Skip LangGraph functional API + interrupt tests on Python < 3.11
DABH f1a305e
Address review feedback on LangGraph samples
DABH 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,73 @@ | ||
| # LangGraph Plugin Samples | ||
|
|
||
| These samples demonstrate the [Temporal LangGraph plugin](https://github.com/temporalio/sdk-python/pull/1448), which runs LangGraph workflows as durable Temporal workflows. Each LangGraph graph node (Graph API) or `@task` (Functional API) executes as a Temporal activity with automatic retries, timeouts, and crash recovery. | ||
|
|
||
| Samples are organized by API style: | ||
|
|
||
| - **Graph API** (`graph_api/`) -- Define workflows as `StateGraph` with nodes and edges. | ||
| - **Functional API** (`functional_api/`) -- Define workflows with `@task` and `@entrypoint` decorators for an imperative programming style. | ||
|
|
||
| ## Samples | ||
|
|
||
| | Sample | Graph API | Functional API | Description | | ||
| |--------|:---------:|:--------------:|-------------| | ||
| | **Hello World** | [graph_api/hello_world](graph_api/hello_world) | [functional_api/hello_world](functional_api/hello_world) | Minimal sample -- single node/task that processes a query string. Start here. | | ||
| | **Human-in-the-loop** | [graph_api/human_in_the_loop](graph_api/human_in_the_loop) | [functional_api/human_in_the_loop](functional_api/human_in_the_loop) | Chatbot that uses `interrupt()` to pause for human approval, Temporal signals to receive feedback, and queries to expose the pending draft. | | ||
| | **Continue-as-new** | [graph_api/continue_as_new](graph_api/continue_as_new) | [functional_api/continue_as_new](functional_api/continue_as_new) | Multi-stage data pipeline that uses `continue-as-new` with task result caching so previously-completed stages are not re-executed. | | ||
| | **ReAct Agent** | [graph_api/react_agent](graph_api/react_agent) | [functional_api/react_agent](functional_api/react_agent) | Tool-calling agent loop. Graph API uses conditional edges; Functional API uses a `while` loop. | | ||
| | **Control Flow** | -- | [functional_api/control_flow](functional_api/control_flow) | Demonstrates parallel task execution, `for` loops, and `if/else` branching -- patterns that are natural in the Functional API. | | ||
|
DABH marked this conversation as resolved.
|
||
| | **LangSmith Tracing** | [graph_api/langsmith_tracing](graph_api/langsmith_tracing) | [functional_api/langsmith_tracing](functional_api/langsmith_tracing) | Combines `LangGraphPlugin` with Temporal's `LangSmithPlugin` for durable execution + full observability of LLM calls. Requires API keys. | | ||
|
|
||
| ## Prerequisites | ||
|
|
||
| 1. Install dependencies: | ||
|
|
||
| ```bash | ||
| uv sync --group langgraph | ||
| ``` | ||
|
|
||
|
DABH marked this conversation as resolved.
|
||
| 2. Start a [Temporal dev server](https://docs.temporal.io/cli#start-dev-server): | ||
|
|
||
| ```bash | ||
| temporal server start-dev | ||
| ``` | ||
|
|
||
| ## Running a Sample | ||
|
|
||
| Most samples have two scripts -- start the Worker first, then the Workflow starter in a separate terminal. | ||
|
|
||
| ```bash | ||
| # Terminal 1: start the Worker | ||
| uv run langgraph_plugin/<api>/<sample>/run_worker.py | ||
|
|
||
| # Terminal 2: start the Workflow | ||
| uv run langgraph_plugin/<api>/<sample>/run_workflow.py | ||
| ``` | ||
|
|
||
| For example, to run the Graph API human-in-the-loop chatbot: | ||
|
|
||
| ```bash | ||
| # Terminal 1 | ||
| uv run langgraph_plugin/graph_api/human_in_the_loop/run_worker.py | ||
|
|
||
| # Terminal 2 | ||
| uv run langgraph_plugin/graph_api/human_in_the_loop/run_workflow.py | ||
| ``` | ||
|
|
||
| The LangSmith Tracing samples bundle the Worker and Workflow execution into a single `main.py`: | ||
|
|
||
| ```bash | ||
| uv run langgraph_plugin/<api>/langsmith_tracing/main.py | ||
| ``` | ||
|
|
||
| ## Key Features Demonstrated | ||
|
|
||
| - **Durable execution** -- Every graph node / `@task` runs as a Temporal activity with configurable timeouts and retry policies. | ||
| - **Human-in-the-loop** -- LangGraph's `interrupt()` pauses the graph; Temporal signals deliver human input; queries expose pending state to UIs. | ||
| - **Continue-as-new with caching** -- `cache()` captures completed task results; passing the cache to the next execution avoids re-running them. | ||
| - **Conditional routing** -- Graph API's `add_conditional_edges` and Functional API's native `if/else`/`while` for agent loops. | ||
| - **Parallel execution** -- Functional API launches multiple tasks concurrently by creating futures before awaiting them. | ||
|
|
||
| ## Related | ||
|
|
||
| - [SDK PR: LangGraph plugin](https://github.com/temporalio/sdk-python/pull/1448) | ||
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 @@ | ||
| """Temporal LangGraph plugin samples.""" |
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 @@ | ||
| """LangGraph Functional API samples using @task and @entrypoint.""" |
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,36 @@ | ||
| # Continue-as-New with Caching (Functional API) | ||
|
|
||
| Demonstrates combining Temporal's continue-as-new with LangGraph's task result caching to avoid re-executing completed `@task` functions across workflow boundaries. | ||
|
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. It's actually OUR task result caching, right? |
||
|
|
||
| ## What This Sample Demonstrates | ||
|
|
||
| - Task result caching across continue-as-new boundaries with `cache()` | ||
| - Restoring cached results with `entrypoint(name, cache=...)` | ||
| - Each `@task` executes exactly once despite multiple workflow invocations | ||
|
|
||
| ## How It Works | ||
|
|
||
| 1. Three tasks run sequentially: `double` (x2) -> `add_50` (+50) -> `triple` (x3). | ||
| 2. After the first invocation, the workflow continues-as-new with the cache. | ||
| 3. On subsequent invocations, all tasks return cached results instantly. | ||
| 4. Input 10 -> 20 -> 70 -> 210. | ||
|
|
||
| ## Running the Sample | ||
|
|
||
| Prerequisites: `uv sync --group langgraph` and a running Temporal dev server (`temporal server start-dev`). | ||
|
|
||
| ```bash | ||
| # Terminal 1 | ||
| uv run langgraph_plugin/functional_api/continue_as_new/run_worker.py | ||
|
|
||
| # Terminal 2 | ||
| uv run langgraph_plugin/functional_api/continue_as_new/run_workflow.py | ||
| ``` | ||
|
|
||
| ## Files | ||
|
|
||
| | File | Description | | ||
| |------|-------------| | ||
| | `workflow.py` | `@task` functions, `@entrypoint`, `PipelineInput`, and `PipelineFunctionalWorkflow` | | ||
| | `run_worker.py` | Registers tasks and entrypoint with `LangGraphPlugin`, starts Worker | | ||
| | `run_workflow.py` | Executes the pipeline Workflow and prints the result | | ||
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 @@ | ||
| """Continue-as-new pipeline with task result caching.""" |
37 changes: 37 additions & 0 deletions
37
langgraph_plugin/functional_api/continue_as_new/run_worker.py
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,37 @@ | ||
| """Worker for the continue-as-new pipeline (Functional API).""" | ||
|
|
||
| import asyncio | ||
| import os | ||
|
|
||
| from temporalio.client import Client | ||
| from temporalio.contrib.langgraph import LangGraphPlugin | ||
| from temporalio.worker import Worker | ||
|
|
||
| from langgraph_plugin.functional_api.continue_as_new.workflow import ( | ||
| PipelineFunctionalWorkflow, | ||
| activity_options, | ||
| all_tasks, | ||
| pipeline_entrypoint, | ||
| ) | ||
|
|
||
|
|
||
| async def main() -> None: | ||
| client = await Client.connect(os.environ.get("TEMPORAL_ADDRESS", "localhost:7233")) | ||
| plugin = LangGraphPlugin( | ||
| entrypoints={"pipeline": pipeline_entrypoint}, | ||
| tasks=all_tasks, | ||
| activity_options=activity_options, | ||
| ) | ||
|
|
||
| worker = Worker( | ||
| client, | ||
| task_queue="langgraph-pipeline-functional", | ||
| workflows=[PipelineFunctionalWorkflow], | ||
| plugins=[plugin], | ||
| ) | ||
| print("Worker started. Ctrl+C to exit.") | ||
| await worker.run() | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| asyncio.run(main()) |
31 changes: 31 additions & 0 deletions
31
langgraph_plugin/functional_api/continue_as_new/run_workflow.py
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,31 @@ | ||
| """Start the continue-as-new pipeline workflow (Functional API).""" | ||
|
|
||
| import asyncio | ||
| import os | ||
| from datetime import timedelta | ||
|
|
||
| from temporalio.client import Client | ||
|
|
||
| from langgraph_plugin.functional_api.continue_as_new.workflow import ( | ||
| PipelineFunctionalWorkflow, | ||
| PipelineInput, | ||
| ) | ||
|
|
||
|
|
||
| async def main() -> None: | ||
| client = await Client.connect(os.environ.get("TEMPORAL_ADDRESS", "localhost:7233")) | ||
|
|
||
| result = await client.execute_workflow( | ||
| PipelineFunctionalWorkflow.run, | ||
| PipelineInput(data=10), | ||
| id="pipeline-functional-workflow", | ||
| task_queue="langgraph-pipeline-functional", | ||
| execution_timeout=timedelta(seconds=60), | ||
| ) | ||
|
|
||
| # 10*2=20 -> 20+50=70 -> 70*3=210 | ||
| print(f"Pipeline result: {result}") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| asyncio.run(main()) |
84 changes: 84 additions & 0 deletions
84
langgraph_plugin/functional_api/continue_as_new/workflow.py
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,84 @@ | ||
| """Continue-as-new with caching using the LangGraph Functional API with Temporal. | ||
|
|
||
| Demonstrates Temporal's continue-as-new with LangGraph's task result caching | ||
| to avoid re-executing completed @task functions across workflow boundaries. | ||
| """ | ||
|
|
||
| from dataclasses import dataclass | ||
| from datetime import timedelta | ||
| from typing import Any | ||
|
|
||
| from langgraph.func import entrypoint, task | ||
| from temporalio import workflow | ||
| from temporalio.contrib.langgraph import cache | ||
| from temporalio.contrib.langgraph import entrypoint as temporal_entrypoint | ||
|
|
||
|
|
||
| @task | ||
| def double(data: int) -> int: | ||
| """Stage 1: double the input.""" | ||
| return data * 2 | ||
|
|
||
|
|
||
| @task | ||
| def add_50(data: int) -> int: | ||
| """Stage 2: add 50.""" | ||
| return data + 50 | ||
|
|
||
|
|
||
| @task | ||
| def triple(data: int) -> int: | ||
| """Stage 3: triple the result.""" | ||
| return data * 3 | ||
|
|
||
|
|
||
| @entrypoint() | ||
| async def pipeline_entrypoint(data: int) -> dict: | ||
| """Run the 3-stage pipeline: double -> add_50 -> triple.""" | ||
| doubled = await double(data) | ||
| plus_50 = await add_50(doubled) | ||
| tripled = await triple(plus_50) | ||
| return {"result": tripled} | ||
|
|
||
|
|
||
| all_tasks: list[Any] = [double, add_50, triple] | ||
|
|
||
| activity_options = { | ||
| t.func.__name__: { | ||
| "execute_in": "activity", | ||
| "start_to_close_timeout": timedelta(seconds=30), | ||
| } | ||
| for t in all_tasks | ||
| } | ||
|
|
||
|
|
||
| @dataclass | ||
| class PipelineInput: | ||
| data: int | ||
| cache: dict[str, Any] | None = None | ||
| phase: int = 1 | ||
|
|
||
|
|
||
| @workflow.defn | ||
| class PipelineFunctionalWorkflow: | ||
| """Runs the pipeline, continuing-as-new after each phase. | ||
|
|
||
| Input 10: 10*2=20 -> 20+50=70 -> 70*3=210 | ||
| Each task executes once; phases 2 and 3 use cached results. | ||
| """ | ||
|
|
||
| @workflow.run | ||
| async def run(self, input_data: PipelineInput) -> dict[str, Any]: | ||
| app = temporal_entrypoint("pipeline", cache=input_data.cache) | ||
| result = await app.ainvoke(input_data.data) | ||
|
|
||
| if input_data.phase < 3: | ||
| workflow.continue_as_new( | ||
| PipelineInput( | ||
| data=input_data.data, | ||
| cache=cache(), | ||
| phase=input_data.phase + 1, | ||
| ) | ||
| ) | ||
|
|
||
| return result | ||
|
DABH marked this conversation as resolved.
|
||
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,37 @@ | ||
| # Control Flow (Functional API) | ||
|
|
||
| Demonstrates the Functional API's strength for complex control flow: parallel execution, sequential loops, and conditional branching — all as natural Python code. | ||
|
|
||
| ## What This Sample Demonstrates | ||
|
|
||
| - **Parallel execution**: launching multiple tasks concurrently by creating futures before awaiting | ||
| - **For loops**: processing items sequentially with `for item in items` | ||
| - **If/else branching**: routing items based on classification results | ||
| - Why the Functional API is ideal for programmatic composition patterns | ||
|
|
||
| ## How It Works | ||
|
|
||
| 1. A batch of items is validated **in parallel** — all `validate_item` tasks launch concurrently. | ||
| 2. Valid items are processed **sequentially** in a for loop. | ||
| 3. Each item is classified, then routed via **if/else** to `process_urgent` or `process_normal`. | ||
| 4. Results are aggregated with a `summarize` task. | ||
|
|
||
| ## Running the Sample | ||
|
|
||
| Prerequisites: `uv sync --group langgraph` and a running Temporal dev server (`temporal server start-dev`). | ||
|
|
||
| ```bash | ||
| # Terminal 1 | ||
| uv run langgraph_plugin/functional_api/control_flow/run_worker.py | ||
|
|
||
| # Terminal 2 | ||
| uv run langgraph_plugin/functional_api/control_flow/run_workflow.py | ||
| ``` | ||
|
|
||
| ## Files | ||
|
|
||
| | File | Description | | ||
| |------|-------------| | ||
| | `workflow.py` | `@task` functions (validate, classify, process, summarize), `@entrypoint`, and `ControlFlowWorkflow` | | ||
| | `run_worker.py` | Registers tasks and entrypoint with `LangGraphPlugin`, starts worker | | ||
| | `run_workflow.py` | Sends a batch of items and prints processing results | |
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 @@ | ||
| """Control flow: parallel execution, for loops, and if/else branching.""" |
37 changes: 37 additions & 0 deletions
37
langgraph_plugin/functional_api/control_flow/run_worker.py
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,37 @@ | ||
| """Worker for the control flow pipeline (Functional API).""" | ||
|
|
||
| import asyncio | ||
| import os | ||
|
|
||
| from temporalio.client import Client | ||
| from temporalio.contrib.langgraph import LangGraphPlugin | ||
| from temporalio.worker import Worker | ||
|
|
||
| from langgraph_plugin.functional_api.control_flow.workflow import ( | ||
| ControlFlowWorkflow, | ||
| activity_options, | ||
| all_tasks, | ||
| control_flow_pipeline, | ||
| ) | ||
|
|
||
|
|
||
| async def main() -> None: | ||
| client = await Client.connect(os.environ.get("TEMPORAL_ADDRESS", "localhost:7233")) | ||
| plugin = LangGraphPlugin( | ||
| entrypoints={"control-flow": control_flow_pipeline}, | ||
| tasks=all_tasks, | ||
| activity_options=activity_options, | ||
| ) | ||
|
|
||
| worker = Worker( | ||
| client, | ||
| task_queue="langgraph-control-flow", | ||
| workflows=[ControlFlowWorkflow], | ||
| plugins=[plugin], | ||
| ) | ||
| print("Worker started. Ctrl+C to exit.") | ||
| await worker.run() | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| asyncio.run(main()) |
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.
Can we just leave this step? I assume we'll need to constantly add and remove it as we write new plugins + samples.