Merge branch 'main' into v1
@@ -9,21 +9,12 @@ hide:
|
||||
|
||||
# Use MCP
|
||||
|
||||
[Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) is an open protocol that standardizes how applications provide tools and context to language models. LangGraph agents can use tools defined on MCP servers through the `langchain-mcp-adapters` library.
|
||||
|
||||

|
||||
|
||||
Install the `langchain-mcp-adapters` library to use MCP tools in LangGraph:
|
||||
|
||||
```bash
|
||||
pip install langchain-mcp-adapters
|
||||
```
|
||||
The Model Context Protocol (MCP) is an open protocol that standardizes how applications provide tools and context to language models. LangGraph agents can use tools defined on MCP servers through the `langchain-mcp-adapters` library.
|
||||
|
||||
## Use MCP tools
|
||||
|
||||
The `langchain-mcp-adapters` package enables agents to use tools defined across one or more MCP servers.
|
||||
|
||||
|
||||
=== "In an agent"
|
||||
|
||||
```python title="Agent using tools defined on MCP servers"
|
||||
|
||||
@@ -30,7 +30,7 @@ LangGraph includes several capabilities essential for building robust, productio
|
||||
- [**Memory integration**](../how-tos/memory/add-memory.md): Native support for *short-term* (session-based) and *long-term* (persistent across sessions) memory, enabling stateful behaviors in chatbots and assistants.
|
||||
- [**Human-in-the-loop control**](../concepts/human_in_the_loop.md): Execution can pause *indefinitely* to await human feedback—unlike websocket-based solutions limited to real-time interaction. This enables asynchronous approval, correction, or intervention at any point in the workflow.
|
||||
- [**Streaming support**](../how-tos/streaming.md): Real-time streaming of agent state, model tokens, tool outputs, or combined streams.
|
||||
- [**Deployment tooling**](./deployment.md): Includes infrastructure-free deployment tools. [**LangGraph Platform**](https://langchain-ai.github.io/langgraph/concepts/langgraph_platform/) supports testing, debugging, and deployment.
|
||||
- [**Deployment tooling**](../tutorials/langgraph-platform/local-server.md): Includes infrastructure-free deployment tools. [**LangGraph Platform**](https://langchain-ai.github.io/langgraph/concepts/langgraph_platform/) supports testing, debugging, and deployment.
|
||||
- **[Studio](https://langchain-ai.github.io/langgraph/concepts/langgraph_studio/)**: A visual IDE for inspecting and debugging workflows.
|
||||
- Supports multiple [**deployment options**](https://langchain-ai.github.io/langgraph/concepts/deployment_options.md) for production.
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ You can use a prebuilt chat UI for interacting with any LangGraph agent through
|
||||
|
||||
## Run agent in UI
|
||||
|
||||
First, set up LangGraph API server [locally](./deployment.md#launch-langgraph-server-locally) or deploy your agent on [LangGraph Platform](https://langchain-ai.github.io/langgraph/cloud/quick_start/).
|
||||
First, set up LangGraph API server [locally](../tutorials/langgraph-platform/local-server.md) or deploy your agent on [LangGraph Platform](https://langchain-ai.github.io/langgraph/cloud/quick_start/).
|
||||
|
||||
Then, navigate to [Agent Chat UI](https://agentchat.vercel.app), or clone the repository and [run the dev server locally](https://github.com/langchain-ai/agent-chat-ui?tab=readme-ov-file#setup):
|
||||
|
||||
@@ -25,7 +25,7 @@ Then, navigate to [Agent Chat UI](https://agentchat.vercel.app), or clone the re
|
||||
|
||||
## Add human-in-the-loop
|
||||
|
||||
Agent Chat UI has full support for [human-in-the-loop](../concepts/human_in_the_loop.md) workflows. To try it out, replace the agent code in `src/agent/graph.py` (from the [deployment](./deployment.md) guide) with this [agent implementation](../how-tos/human_in_the_loop/add-human-in-the-loop.md#add-interrupts-to-any-tool):
|
||||
Agent Chat UI has full support for [human-in-the-loop](../concepts/human_in_the_loop.md) workflows. To try it out, replace the agent code in `src/agent/graph.py` (from the [deployment](../tutorials/langgraph-platform/local-server.md) guide) with this [agent implementation](../how-tos/human_in_the_loop/add-human-in-the-loop.md#add-interrupts-to-any-tool):
|
||||
|
||||
<video controls src="../assets/interrupt-chat-ui.mp4" type="video/mp4"></video>
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
# API Reference
|
||||
# LangGraph Server API Reference
|
||||
|
||||
The LangGraph Platform API reference is available with each deployment at the `/docs` URL path (e.g. `http://localhost:8124/docs`).
|
||||
The LangGraph Server API reference is available within each deployment at the `/docs` endpoint (e.g. `http://localhost:8124/docs`).
|
||||
|
||||
Click <a href="/langgraph/cloud/reference/api/api_ref.html" target="_blank">here</a> to view the API reference.
|
||||
|
||||
## Authentication
|
||||
|
||||
For deployments to LangGraph Platform, authentication is required. Pass the `X-Api-Key` header with each request to the LangGraph Platform API. The value of the header should be set to a valid LangSmith API key for the organization where the API is deployed.
|
||||
For deployments to LangGraph Platform, authentication is required. Pass the `X-Api-Key` header with each request to the LangGraph Server. The value of the header should be set to a valid LangSmith API key for the organization where the LangGraph Server is deployed.
|
||||
|
||||
Example `curl` command:
|
||||
```shell
|
||||
@@ -18,5 +18,5 @@ curl --request POST \
|
||||
"metadata": {},
|
||||
"limit": 10,
|
||||
"offset": 0
|
||||
}'
|
||||
}'
|
||||
```
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
# LangGraph Control Plane API Reference
|
||||
|
||||
The LangGraph Control Plane API is used to programmatically create and manage LangGraph Server deployments. For example, the APIs can be orchestrated to create custom CI/CD workflows.
|
||||
|
||||
Click <a href="https://api.host.langchain.com/docs" target="_blank">here</a> to view the API reference.
|
||||
|
||||
## Host
|
||||
|
||||
LangGraph Control Plane hosts for Cloud SaaS data regions:
|
||||
|
||||
| US | EU |
|
||||
|----|----|
|
||||
| `https://api.host.langchain.com` | `https://eu.api.host.langchain.com` |
|
||||
|
||||
**Note**: Self-hosted deployments of LangGraph Platform will have a custom host for the LangGraph Control Plane.
|
||||
|
||||
## Authentication
|
||||
|
||||
To authenticate with the LangGraph Control Plane API, set the `X-Api-Key` header to a valid LangSmith API key.
|
||||
|
||||
Example `curl` command:
|
||||
```shell
|
||||
curl --request GET \
|
||||
--url http://localhost:8124/v2/deployments \
|
||||
--header 'X-Api-Key: LANGSMITH_API_KEY'
|
||||
```
|
||||
|
||||
## Versioning
|
||||
|
||||
Each endpoint path is prefixed with a version (e.g. `v1`, `v2`).
|
||||
|
||||
## Quick Start
|
||||
|
||||
1. Call `POST /v2/deployments` to create a new Deployment. The response body contains the Deployment ID (`id`) and the ID of the latest (and first) revision (`latest_revision_id`).
|
||||
1. Call `GET /v2/deployments/{deployment_id}` to retrieve the Deployment. Set `deployment_id` in the URL to the value of Deployment ID (`id`).
|
||||
1. Poll for revision `status` until `status` is `DEPLOYED` by calling `GET /v2/deployments/{deployment_id}/revisions/{latest_revision_id}`.
|
||||
1. Call `PATCH /v2/deployments/{deployment_id}` to update the deployment.
|
||||
|
||||
## Example Code
|
||||
Below is example Python code that demonstrates how to orchestrate the LangGraph Control Plane APIs to create a deployment, update the deployment, and delete the deployment.
|
||||
```python
|
||||
import os
|
||||
import time
|
||||
|
||||
import requests
|
||||
from dotenv import load_dotenv
|
||||
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# required environment variables
|
||||
CONTROL_PLANE_HOST = os.getenv("CONTROL_PLANE_HOST")
|
||||
LANGSMITH_API_KEY = os.getenv("LANGSMITH_API_KEY")
|
||||
INTEGRATION_ID = os.getenv("INTEGRATION_ID")
|
||||
MAX_WAIT_TIME = 1800 # 30 mins
|
||||
|
||||
|
||||
def get_headers() -> dict:
|
||||
"""Return common headers for requests to LangGraph Control Plane API."""
|
||||
return {
|
||||
"X-Api-Key": LANGSMITH_API_KEY,
|
||||
}
|
||||
|
||||
|
||||
def create_deployment() -> str:
|
||||
"""Create deployment. Return deployment ID."""
|
||||
headers = get_headers()
|
||||
headers["Content-Type"] = "application/json"
|
||||
|
||||
deployment_name = "my_deployment"
|
||||
|
||||
request_body = {
|
||||
"name": deployment_name,
|
||||
"source": "github",
|
||||
"source_config": {
|
||||
"integration_id": INTEGRATION_ID,
|
||||
"repo_url": "https://github.com/langchain-ai/langgraph-example",
|
||||
"deployment_type": "dev",
|
||||
"build_on_push": False,
|
||||
"custom_url": None,
|
||||
"resource_spec": None,
|
||||
},
|
||||
"source_revision_config": {
|
||||
"repo_ref": "main",
|
||||
"langgraph_config_path": "langgraph.json",
|
||||
"image_uri": None,
|
||||
},
|
||||
"secrets": [
|
||||
{
|
||||
"name": "OPENAI_API_KEY",
|
||||
"value": "test_openai_api_key",
|
||||
},
|
||||
{
|
||||
"name": "ANTHROPIC_API_KEY",
|
||||
"value": "test_anthropic_api_key",
|
||||
},
|
||||
{
|
||||
"name": "TAVILY_API_KEY",
|
||||
"value": "test_tavily_api_key",
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
response = requests.post(
|
||||
url=f"{CONTROL_PLANE_HOST}/v2/deployments",
|
||||
headers=headers,
|
||||
json=request_body,
|
||||
)
|
||||
|
||||
if response.status_code != 201:
|
||||
raise Exception(f"Failed to create deployment: {response.text}")
|
||||
|
||||
deployment_id = response.json()["id"]
|
||||
print(f"Created deployment {deployment_name} ({deployment_id})")
|
||||
return deployment_id
|
||||
|
||||
|
||||
def get_deployment(deployment_id: str) -> dict:
|
||||
"""Get deployment."""
|
||||
response = requests.get(
|
||||
url=f"{CONTROL_PLANE_HOST}/v2/deployments/{deployment_id}",
|
||||
headers=get_headers(),
|
||||
)
|
||||
|
||||
if response.status_code != 200:
|
||||
raise Exception(f"Failed to get deployment ID {deployment_id}: {response.text}")
|
||||
|
||||
return response.json()
|
||||
|
||||
|
||||
def list_revisions(deployment_id: str) -> list[dict]:
|
||||
"""List revisions.
|
||||
|
||||
Return list is sorted by created_at in descending order (latest first).
|
||||
"""
|
||||
response = requests.get(
|
||||
url=f"{CONTROL_PLANE_HOST}/v2/deployments/{deployment_id}/revisions",
|
||||
headers=get_headers(),
|
||||
)
|
||||
|
||||
if response.status_code != 200:
|
||||
raise Exception(
|
||||
f"Failed to list revisions for deployment ID {deployment_id}: {response.text}"
|
||||
)
|
||||
|
||||
return response.json()
|
||||
|
||||
|
||||
def get_revision(
|
||||
deployment_id: str,
|
||||
revision_id: str,
|
||||
) -> dict:
|
||||
"""Get revision."""
|
||||
response = requests.get(
|
||||
url=f"{CONTROL_PLANE_HOST}/v2/deployments/{deployment_id}/revisions/{revision_id}",
|
||||
headers=get_headers(),
|
||||
)
|
||||
|
||||
if response.status_code != 200:
|
||||
raise Exception(f"Failed to get revision ID {revision_id}: {response.text}")
|
||||
|
||||
return response.json()
|
||||
|
||||
|
||||
def patch_deployment(deployment_id: str) -> None:
|
||||
"""Patch deployment."""
|
||||
headers = get_headers()
|
||||
headers["Content-Type"] = "application/json"
|
||||
|
||||
response = requests.patch(
|
||||
url=f"{CONTROL_PLANE_HOST}/v2/deployments/{deployment_id}",
|
||||
headers=headers,
|
||||
json={
|
||||
"source_config": {
|
||||
"build_on_push": True,
|
||||
},
|
||||
"source_revision_config": {
|
||||
"repo_ref": "main",
|
||||
"langgraph_config_path": "langgraph.json",
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
if response.status_code != 200:
|
||||
raise Exception(f"Failed to patch deployment: {response.text}")
|
||||
|
||||
print(f"Patched deployment ID {deployment_id}")
|
||||
|
||||
|
||||
def wait_for_deployment(deployment_id: str, revision_id: str) -> None:
|
||||
"""Wait for revision status to be DEPLOYED."""
|
||||
start_time = time.time()
|
||||
revision, status = None, None
|
||||
while time.time() - start_time < MAX_WAIT_TIME:
|
||||
revision = get_revision(deployment_id, revision_id)
|
||||
status = revision["status"]
|
||||
if status == "DEPLOYED":
|
||||
break
|
||||
elif "FAILED" in status:
|
||||
raise Exception(f"Revision ID {revision_id} failed: {revision}")
|
||||
|
||||
print(f"Waiting for revision ID {revision_id} to be DEPLOYED...")
|
||||
time.sleep(60)
|
||||
|
||||
if status != "DEPLOYED":
|
||||
raise Exception(
|
||||
f"Timeout waiting for revision ID {revision_id} to be DEPLOYED: {revision}"
|
||||
)
|
||||
|
||||
|
||||
def delete_deployment(deployment_id: str) -> None:
|
||||
"""Delete deployment."""
|
||||
response = requests.delete(
|
||||
url=f"{CONTROL_PLANE_HOST}/v2/deployments/{deployment_id}",
|
||||
headers=get_headers(),
|
||||
)
|
||||
|
||||
if response.status_code != 204:
|
||||
raise Exception(
|
||||
f"Failed to delete deployment ID {deployment_id}: {response.text}"
|
||||
)
|
||||
|
||||
print(f"Deployment ID {deployment_id} deleted")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# create deployment and get the latest revision
|
||||
deployment_id = create_deployment()
|
||||
revisions = list_revisions(deployment_id)
|
||||
latest_revision = revisions["resources"][0]
|
||||
latest_revision_id = latest_revision["id"]
|
||||
|
||||
# wait for latest revision to be DEPLOYED
|
||||
wait_for_deployment(deployment_id, latest_revision_id)
|
||||
|
||||
# patch the deployment and get the latest revision
|
||||
patch_deployment(deployment_id)
|
||||
revisions = list_revisions(deployment_id)
|
||||
latest_revision = revisions["resources"][0]
|
||||
latest_revision_id = latest_revision["id"]
|
||||
|
||||
# wait for latest revision to be DEPLOYED
|
||||
wait_for_deployment(deployment_id, latest_revision_id)
|
||||
|
||||
# delete the deployment
|
||||
delete_deployment(deployment_id)
|
||||
```
|
||||
@@ -53,7 +53,7 @@ The LangGraph CLI requires a JSON configuration file that follows this [schema](
|
||||
| <span style="white-space: nowrap;">`pip_installer`</span> | _(Added in v0.3)_ Optional. Python package installer selector. It can be set to `"auto"`, `"pip"`, or `"uv"`. From version 0.3 onward the default strategy is to run `uv pip`, which typically delivers faster builds while remaining a drop-in replacement. In the uncommon situation where `uv` cannot handle your dependency graph or the structure of your `pyproject.toml`, specify `"pip"` here to revert to the earlier behaviour. |
|
||||
| <span style="white-space: nowrap;">`dockerfile_lines`</span> | Array of additional lines to add to Dockerfile following the import from parent image. |
|
||||
| <span style="white-space: nowrap;">`checkpointer`</span> | Configuration for the checkpointer. Contains a `ttl` field which is an object with the following keys: <ul><li>`strategy`: How to handle expired checkpoints (e.g., `"delete"`).</li><li>`sweep_interval_minutes`: How often to check for expired checkpoints (integer).</li><li>`default_ttl`: Default time-to-live for checkpoints in **minutes** (integer). Defines how long checkpoints are kept before the specified strategy is applied.</li></ul> |
|
||||
| <span style="white-space: nowrap;">`http`</span> | HTTP server configuration with the following fields: <ul><li>`app`: Path to custom Starlette/FastAPI app (e.g., `"./src/agent/webapp.py:app"`). See [custom routes guide](../../how-tos/http/custom_routes.md).</li><li>`disable_assistants`: Disable `/assistants` routes</li><li>`disable_threads`: Disable `/threads` routes</li><li>`disable_runs`: Disable `/runs` routes</li><li>`disable_store`: Disable `/store` routes</li><li>`disable_meta`: Disable `/ok`, `/info`, `/metrics`, and `/docs` routes</li><li>`disable_mcp`: Disable `/mcp` routes</li><li>`cors`: CORS configuration with fields for `allow_origins`, `allow_methods`, `allow_headers`, etc.</li><li>`configurable_headers`: Define which request headers to exclude or include as a run's configurable values.</li></ul> |
|
||||
| <span style="white-space: nowrap;">`http`</span> | HTTP server configuration with the following fields: <ul><li>`app`: Path to custom Starlette/FastAPI app (e.g., `"./src/agent/webapp.py:app"`). See [custom routes guide](../../how-tos/http/custom_routes.md).</li><li>`cors`: CORS configuration with fields for `allow_origins`, `allow_methods`, `allow_headers`, etc.</li><li>`configurable_headers`: Define which request headers to exclude or include as a run's configurable values.</li><li>`disable_assistants`: Disable `/assistants` routes</li><li>`disable_mcp`: Disable `/mcp` routes</li><li>`disable_meta`: Disable `/ok`, `/info`, `/metrics`, and `/docs` routes</li><li>`disable_runs`: Disable `/runs` routes</li><li>`disable_store`: Disable `/store` routes</li><li>`disable_threads`: Disable `/threads` routes</li><li>`disable_ui`: Disable `/ui` routes</li><li>`disable_webhooks`: Disable webhooks calls on run completion in all routes</li><li>`mount_prefix`: Prefix for mounted routes (e.g., "/my-deployment/api")</li></ul> |
|
||||
|
||||
=== "JS"
|
||||
|
||||
|
||||
@@ -97,7 +97,7 @@ Parallel processing is vital for efficient multi-agent systems and complex tasks
|
||||
- Implementation of map-reduce-like operations
|
||||
- Efficient handling of independent subtasks
|
||||
|
||||
For practical implementation, see our [map-reduce tutorial](../how-tos/graph-api.ipynb#map-reduce-and-the-send-api)
|
||||
For practical implementation, see our [map-reduce tutorial](../how-tos/graph-api.md#map-reduce-and-the-send-api)
|
||||
|
||||
### Subgraphs
|
||||
|
||||
@@ -107,7 +107,7 @@ For practical implementation, see our [map-reduce tutorial](../how-tos/graph-api
|
||||
- Hierarchical organization of agent teams
|
||||
- Controlled communication between agents and the main system
|
||||
|
||||
Subgraphs communicate with the parent graph through overlapping keys in the state schema. This enables flexible, modular agent design. For implementation details, refer to our [subgraph how-to guide](../how-tos/subgraph.ipynb).
|
||||
Subgraphs communicate with the parent graph through overlapping keys in the state schema. This enables flexible, modular agent design. For implementation details, refer to our [subgraph how-to guide](../how-tos/subgraph.md).
|
||||
|
||||
### Reflection
|
||||
|
||||
|
||||
@@ -143,6 +143,54 @@ The returned user information is available:
|
||||
In many of our tutorials, we will just show the "authorization" parameter to be concise, but you can opt to accept more information as needed
|
||||
to implement your custom authentication scheme.
|
||||
|
||||
### Agent authentication
|
||||
|
||||
Custom authentication permits delegated access. The values you return in `@auth.authenticate` are added to the run context, giving agents user-scoped credentials lets them access resources on the user’s behalf.
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
%% Actors
|
||||
participant ClientApp as Client
|
||||
participant AuthProv as Auth Provider
|
||||
participant LangGraph as LangGraph Backend
|
||||
participant SecretStore as Secret Store
|
||||
participant ExternalService as External Service
|
||||
|
||||
%% Platform login / AuthN
|
||||
ClientApp ->> AuthProv: 1. Login (username / password)
|
||||
AuthProv -->> ClientApp: 2. Return token
|
||||
ClientApp ->> LangGraph: 3. Request with token
|
||||
|
||||
Note over LangGraph: 4. Validate token (@auth.authenticate)
|
||||
LangGraph -->> AuthProv: 5. Fetch user info
|
||||
AuthProv -->> LangGraph: 6. Confirm validity
|
||||
|
||||
%% Fetch user tokens from secret store
|
||||
LangGraph ->> SecretStore: 6a. Fetch user tokens
|
||||
SecretStore -->> LangGraph: 6b. Return tokens
|
||||
|
||||
Note over LangGraph: 7. Apply access control (@auth.on.*)
|
||||
|
||||
%% External Service round-trip
|
||||
LangGraph ->> ExternalService: 8. Call external service (with header)
|
||||
Note over ExternalService: 9. External service validates header and executes action
|
||||
ExternalService -->> LangGraph: 10. Service response
|
||||
|
||||
%% Return to caller
|
||||
LangGraph -->> ClientApp: 11. Return resources
|
||||
```
|
||||
|
||||
After authentication, the platform creates a special configuration object that is passed to your graph and all nodes via the configurable context.
|
||||
This object contains information about the current user, including any custom fields you return from your [`@auth.authenticate`](../cloud/reference/sdk/python_sdk_ref.md#langgraph_sdk.auth.Auth.authenticate) handler.
|
||||
|
||||
To enable an agent to act on behalf of the user, use [custom authentication middleware](../how-tos/auth/custom_auth.md). This will allow the agent to interact with external systems like MCP servers, external databases, and even other agents on behalf of the user.
|
||||
|
||||
For more information, see the [Use custom auth](../how-tos/auth/custom_auth.md#enable-agent-authentication) guide.
|
||||
|
||||
### Agent authentication with MCP
|
||||
|
||||
For information on how to authenticate an agent to an MCP server, see the [MCP conceptual guide](../concepts/mcp.md).
|
||||
|
||||
## Authorization
|
||||
|
||||
After authentication, LangGraph calls your [`@auth.on`](../cloud/reference/sdk/python_sdk_ref.md#langgraph_sdk.auth.Auth.on) handlers to control access to specific resources (e.g., threads, assistants, crons). These handlers can:
|
||||
|
||||
@@ -26,7 +26,7 @@ The Control Plane UI is embedded in [LangSmith](https://docs.smith.langchain.com
|
||||
|
||||
## Control Plane API
|
||||
|
||||
This section describes data model of the control plane API. The API is used to create, update, and delete deployments. However, they are not publicly accessible.
|
||||
This section describes the data model of the control plane API. The API is used to create, update, and delete deployments. See the [control plane API reference](../cloud/reference/api/api_ref_control_plane.md) for more details.
|
||||
|
||||
### Deployment
|
||||
|
||||
@@ -34,11 +34,7 @@ A deployment is an instance of a LangGraph Server. A single deployment can have
|
||||
|
||||
### Revision
|
||||
|
||||
A revision is an iteration of a deployment. When a new deployment is created, an initial revision is automatically created. To deploy code changes or update environment variables for a deployment, a new revision must be created.
|
||||
|
||||
### Environment Variable
|
||||
|
||||
Environment variables are set for a deployment. All environment variables are stored as secrets (i.e. saved in a secrets store).
|
||||
A revision is an iteration of a deployment. When a new deployment is created, an initial revision is automatically created. To deploy code changes or update secrets for a deployment, a new revision must be created.
|
||||
|
||||
## Control Plane Features
|
||||
|
||||
@@ -50,21 +46,40 @@ For simplicity, the control plane offers two deployment types with different res
|
||||
|
||||
| **Deployment Type** | **CPU/Memory** | **Scaling** | **Database** |
|
||||
|---------------------|-----------------|---------------------|----------------------------------------------------------------------------------|
|
||||
| Development | 1 CPU, 1 GB RAM | Up to 1 container | 10 GB disk, no backups |
|
||||
| Production | 2 CPU, 2 GB RAM | Up to 10 containers | Autoscaling disk, automatic backups, highly available (multi-zone configuration) |
|
||||
| Development | 1 CPU, 1 GB RAM | Up to 1 replica | 10 GB disk, no backups |
|
||||
| Production | 2 CPU, 2 GB RAM | Up to 10 replicas | Autoscaling disk, automatic backups, highly available (multi-zone configuration) |
|
||||
|
||||
CPU and memory resources are per container.
|
||||
CPU and memory resources are per replica.
|
||||
|
||||
!!! warning "Immutable Deployment Type"
|
||||
|
||||
Once a deployment is created, the deployment type cannot be changed.
|
||||
|
||||
!!! info "Resource Customization"
|
||||
For `Production` type deployments, resources can be manually increased on a case-by-case basis depending on use case and capacity constraints. Contact support@langchain.dev to request an increase in resources.
|
||||
!!! info "Self-Hosted Deployment"
|
||||
Resources for [Self-Hosted Data Plane](../concepts/langgraph_self_hosted_data_plane.md) and [Self-Hosted Control Plane](../concepts/langgraph_self_hosted_control_plane.md) deployments can be fully customized. Deployment types are only applicable for [Cloud SaaS](../concepts/langgraph_cloud.md) deployments.
|
||||
|
||||
For `Development` types deployments, database disk size can be manually increased on a case-by-case basis depending on use case and capacity constraints. For most use cases, [TTLs](../how-tos/ttl/configure_ttl.md) should be configured to manage disk usage. Contact support@langchain.dev to request an increase in resources.
|
||||
#### Production
|
||||
|
||||
Resources for [Self-Hosted Data Plane](../concepts/langgraph_self_hosted_data_plane.md) and [Self-Hosted Control Plane](../concepts/langgraph_self_hosted_control_plane.md) deployments can be fully customized.
|
||||
`Production` type deployments are suitable for "production" workloads. For example, select `Production` for customer-facing applications in the critical path.
|
||||
|
||||
Resources for `Production` type deployments can be manually increased on a case-by-case basis depending on use case and capacity constraints. Contact support@langchain.dev to request an increase in resources.
|
||||
|
||||
#### Development
|
||||
|
||||
`Development` type deployments are suitable development and testing. For example, select `Development` for internal testing environments. `Development` type deployments are not suitable for "production" workloads.
|
||||
|
||||
!!! danger "Preemptible Compute Infrastructure"
|
||||
`Development` type deployments (API server, queue server, and database) are provisioned on preemptible compute infrastructure. This means the compute infrastructure **may be terminated at any time without notice**. This may result in intermittent...
|
||||
|
||||
- Redis connection timeouts/errors
|
||||
- Postgres connection timeouts/errors
|
||||
- Failed or retrying background runs
|
||||
|
||||
This behavior is expected. Preemptible compute infrastructure **significantly reduces the cost to provision a `Development` type deployment**. By design, LangGraph Server is fault-tolerant. The implementation will automatically attempt to recover from Redis/Postgres connection errors and retry failed background runs.
|
||||
|
||||
`Production` type deployments are provisioned on durable compute infrastructure, not preemptible compute infrastructure.
|
||||
|
||||
Database disk size for `Development` type deployments can be manually increased on a case-by-case basis depending on use case and capacity constraints. For most use cases, [TTLs](../how-tos/ttl/configure_ttl.md) should be configured to manage disk usage. Contact support@langchain.dev to request an increase in resources.
|
||||
|
||||
### Database Provisioning
|
||||
|
||||
|
||||
@@ -45,9 +45,9 @@ The first thing you do when you define a graph is define the `State` of the grap
|
||||
|
||||
### Schema
|
||||
|
||||
The main documented way to specify the schema of a graph is by using `TypedDict`. However, we also support [using a Pydantic BaseModel](../how-tos/graph-api.ipynb#use-pydantic-models-for-graph-state) as your graph state to add **default values** and additional data validation.
|
||||
The main documented way to specify the schema of a graph is by using `TypedDict`. However, we also support [using a Pydantic BaseModel](../how-tos/graph-api.md#use-pydantic-models-for-graph-state) as your graph state to add **default values** and additional data validation.
|
||||
|
||||
By default, the graph will have the same input and output schemas. If you want to change this, you can also specify explicit input and output schemas directly. This is useful when you have a lot of keys, and some are explicitly for input and others for output. See the [guide here](../how-tos/graph-api.ipynb#define-input-and-output-schemas) for how to use.
|
||||
By default, the graph will have the same input and output schemas. If you want to change this, you can also specify explicit input and output schemas directly. This is useful when you have a lot of keys, and some are explicitly for input and others for output. See the [guide here](../how-tos/graph-api.md#define-input-and-output-schemas) for how to use.
|
||||
|
||||
#### Multiple schemas
|
||||
|
||||
@@ -56,9 +56,9 @@ Typically, all graph nodes communicate with a single schema. This means that the
|
||||
- Internal nodes can pass information that is not required in the graph's input / output.
|
||||
- We may also want to use different input / output schemas for the graph. The output might, for example, only contain a single relevant output key.
|
||||
|
||||
It is possible to have nodes write to private state channels inside the graph for internal node communication. We can simply define a private schema, `PrivateState`. See [this guide](../how-tos/graph-api.ipynb#pass-private-state-between-nodes) for more detail.
|
||||
It is possible to have nodes write to private state channels inside the graph for internal node communication. We can simply define a private schema, `PrivateState`. See [this guide](../how-tos/graph-api.md#pass-private-state-between-nodes) for more detail.
|
||||
|
||||
It is also possible to define explicit input and output schemas for a graph. In these cases, we define an "internal" schema that contains _all_ keys relevant to graph operations. But, we also define `input` and `output` schemas that are sub-sets of the "internal" schema to constrain the input and output of the graph. See [this guide](../how-tos/graph-api.ipynb#define-input-and-output-schemas) for more detail.
|
||||
It is also possible to define explicit input and output schemas for a graph. In these cases, we define an "internal" schema that contains _all_ keys relevant to graph operations. But, we also define `input` and `output` schemas that are sub-sets of the "internal" schema to constrain the input and output of the graph. See [this guide](../how-tos/graph-api.md#define-input-and-output-schemas) for more detail.
|
||||
|
||||
Let's look at an example:
|
||||
|
||||
@@ -406,7 +406,7 @@ def my_node(state: State) -> Command[Literal["my_other_node"]]:
|
||||
|
||||
When returning `Command` in your node functions, you must add return type annotations with the list of node names the node is routing to, e.g. `Command[Literal["my_other_node"]]`. This is necessary for the graph rendering and tells LangGraph that `my_node` can navigate to `my_other_node`.
|
||||
|
||||
Check out this [how-to guide](../how-tos/graph-api.ipynb#combine-control-flow-and-state-updates-with-command) for an end-to-end example of how to use `Command`.
|
||||
Check out this [how-to guide](../how-tos/graph-api.md#combine-control-flow-and-state-updates-with-command) for an end-to-end example of how to use `Command`.
|
||||
|
||||
### When should I use Command instead of conditional edges?
|
||||
|
||||
@@ -433,17 +433,17 @@ def my_node(state: State) -> Command[Literal["other_subgraph"]]:
|
||||
|
||||
!!! important "State updates with `Command.PARENT`"
|
||||
|
||||
When you send updates from a subgraph node to a parent graph node for a key that's shared by both parent and subgraph [state schemas](#schema), you **must** define a [reducer](#reducers) for the key you're updating in the parent graph state. See this [example](../how-tos/graph-api.ipynb#navigate-to-a-node-in-a-parent-graph).
|
||||
When you send updates from a subgraph node to a parent graph node for a key that's shared by both parent and subgraph [state schemas](#schema), you **must** define a [reducer](#reducers) for the key you're updating in the parent graph state. See this [example](../how-tos/graph-api.md#navigate-to-a-node-in-a-parent-graph).
|
||||
|
||||
This is particularly useful when implementing [multi-agent handoffs](./multi_agent.md#handoffs).
|
||||
|
||||
Check out [this guide](../how-tos/graph-api.ipynb#navigate-to-a-node-in-a-parent-graph) for detail.
|
||||
Check out [this guide](../how-tos/graph-api.md#navigate-to-a-node-in-a-parent-graph) for detail.
|
||||
|
||||
### Using inside tools
|
||||
|
||||
A common use case is updating graph state from inside a tool. For example, in a customer support application you might want to look up customer information based on their account number or ID in the beginning of the conversation.
|
||||
|
||||
Refer to [this guide](../how-tos/graph-api.ipynb#use-inside-tools) for detail.
|
||||
Refer to [this guide](../how-tos/graph-api.md#use-inside-tools) for detail.
|
||||
|
||||
### Human-in-the-loop
|
||||
|
||||
@@ -489,7 +489,7 @@ def node_a(state, config):
|
||||
...
|
||||
```
|
||||
|
||||
See [this guide](../how-tos/graph-api.ipynb#add-runtime-configuration) for a full breakdown on configuration.
|
||||
See [this guide](../how-tos/graph-api.md#add-runtime-configuration) for a full breakdown on configuration.
|
||||
|
||||
### Recursion Limit
|
||||
|
||||
@@ -503,4 +503,4 @@ Read [this how-to](https://langchain-ai.github.io/langgraph/how-tos/recursion-li
|
||||
|
||||
## Visualization
|
||||
|
||||
It's often nice to be able to visualize graphs, especially as they get more complex. LangGraph comes with several built-in ways to visualize graphs. See [this how-to guide](../how-tos/graph-api.ipynb#visualize-your-graph) for more info.
|
||||
It's often nice to be able to visualize graphs, especially as they get more complex. LangGraph comes with several built-in ways to visualize graphs. See [this how-to guide](../how-tos/graph-api.md#visualize-your-graph) for more info.
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# MCP
|
||||
|
||||
[Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) is an open protocol that standardizes how applications provide tools and context to language models. LangGraph agents can use tools defined on MCP servers through the `langchain-mcp-adapters` library.
|
||||
|
||||

|
||||
|
||||
Install the `langchain-mcp-adapters` library to use MCP tools in LangGraph:
|
||||
|
||||
```bash
|
||||
pip install langchain-mcp-adapters
|
||||
```
|
||||
|
||||
## Authenticate to an MCP server
|
||||
|
||||
You can set up [custom authentication middleware](../how-tos/auth/custom_auth.md) to authenticate a user with an MCP server to get access to user-scoped tools within your LangGraph Platform deployment.
|
||||
|
||||
!!! note
|
||||
Custom authentication is a LangGraph Platform feature.
|
||||
|
||||
An example architecture for this flow:
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
%% Actors
|
||||
participant ClientApp as Client
|
||||
participant AuthProv as Auth Provider
|
||||
participant LangGraph as LangGraph Backend
|
||||
participant SecretStore as Secret Store
|
||||
participant MCPServer as MCP Server
|
||||
|
||||
%% Platform login / AuthN
|
||||
ClientApp ->> AuthProv: 1. Login (username / password)
|
||||
AuthProv -->> ClientApp: 2. Return token
|
||||
ClientApp ->> LangGraph: 3. Request with token
|
||||
|
||||
Note over LangGraph: 4. Validate token (@auth.authenticate)
|
||||
LangGraph -->> AuthProv: 5. Fetch user info
|
||||
AuthProv -->> LangGraph: 6. Confirm validity
|
||||
|
||||
%% Fetch user tokens from secret store
|
||||
LangGraph ->> SecretStore: 6a. Fetch user tokens
|
||||
SecretStore -->> LangGraph: 6b. Return tokens
|
||||
|
||||
Note over LangGraph: 7. Apply access control (@auth.on.*)
|
||||
|
||||
%% MCP round-trip
|
||||
Note over LangGraph: 8. Build MCP client with user token
|
||||
LangGraph ->> MCPServer: 9. Call MCP tool (with header)
|
||||
Note over MCPServer: 10. MCP validates header and runs tool
|
||||
MCPServer -->> LangGraph: 11. Tool response
|
||||
|
||||
%% Return to caller
|
||||
LangGraph -->> ClientApp: 12. Return resources / tool output
|
||||
```
|
||||
|
||||
For more information, see [MCP endpoint in LangGraph Server](../concepts/server-mcp.md#use-user-scoped-mcp-tools-in-your-deployment).
|
||||
|
||||
@@ -166,7 +166,7 @@ network = builder.compile()
|
||||
|
||||
### Supervisor
|
||||
|
||||
In this architecture, we define agents as nodes and add a supervisor node (LLM) that decides which agent nodes should be called next. We use [`Command`](./low_level.md#command) to route execution to the appropriate agent node based on supervisor's decision. This architecture also lends itself well to running multiple agents in parallel or using [map-reduce](../how-tos/graph-api.ipynb#map-reduce-and-the-send-api) pattern.
|
||||
In this architecture, we define agents as nodes and add a supervisor node (LLM) that decides which agent nodes should be called next. We use [`Command`](./low_level.md#command) to route execution to the appropriate agent node based on supervisor's decision. This architecture also lends itself well to running multiple agents in parallel or using [map-reduce](../how-tos/graph-api.md#map-reduce-and-the-send-api) pattern.
|
||||
|
||||
```python
|
||||
from typing import Literal
|
||||
@@ -414,5 +414,5 @@ There are two high-level approaches to achieve that:
|
||||
|
||||
An agent might need to have a different state schema from the rest of the agents. For example, a search agent might only need to keep track of queries and retrieved documents. There are two ways to achieve this in LangGraph:
|
||||
|
||||
- Define [subgraph](./subgraphs.md) agents with a separate state schema. If there are no shared state keys (channels) between the subgraph and the parent graph, it’s important to [add input / output transformations](../how-tos/subgraph.ipynb#different-state-schemas) so that the parent graph knows how to communicate with the subgraphs.
|
||||
- Define agent node functions with a [private input state schema](../how-tos/graph-api.ipynb/#pass-private-state-between-nodes) that is distinct from the overall graph state schema. This allows passing information that is only needed for executing that particular agent.
|
||||
- Define [subgraph](./subgraphs.md) agents with a separate state schema. If there are no shared state keys (channels) between the subgraph and the parent graph, it’s important to [add input / output transformations](../how-tos/subgraph.md#different-state-schemas) so that the parent graph knows how to communicate with the subgraphs.
|
||||
- Define agent node functions with a [private input state schema](../how-tos/graph-api.md/#pass-private-state-between-nodes) that is distinct from the overall graph state schema. This allows passing information that is only needed for executing that particular agent.
|
||||
|
||||
@@ -8,8 +8,7 @@ hide:
|
||||
|
||||
# MCP endpoint in LangGraph Server
|
||||
|
||||
The **Model Context Protocol (MCP)** is an open protocol for describing tools and data sources in a model-agnostic format, enabling LLMs to discover
|
||||
and use them via a structured API.
|
||||
The [Model Context Protocol (MCP)](./mcp.md) is an open protocol for describing tools and data sources in a model-agnostic format, enabling LLMs to discover and use them via a structured API.
|
||||
|
||||
[LangGraph Server](./langgraph_server.md) implements MCP using the [Streamable HTTP transport](https://spec.modelcontextprotocol.io/specification/2025-03-26/basic/transports/#streamable-http). This allows LangGraph **agents** to be exposed as **MCP tools**, making them usable with any MCP-compliant client supporting Streamable HTTP.
|
||||
|
||||
@@ -28,79 +27,6 @@ Install them with:
|
||||
pip install "langgraph-api>=0.2.3" "langgraph-sdk>=0.1.61"
|
||||
```
|
||||
|
||||
## Exposing an agent as MCP tool
|
||||
|
||||
|
||||
When deployed, your agent will appear as a tool in the MCP endpoint
|
||||
with this configuration:
|
||||
|
||||
- **Tool name**: The agent's name.
|
||||
- **Tool description**: The agent's description.
|
||||
- **Tool input schema**: The agent's input schema.
|
||||
|
||||
### Setting name and description
|
||||
|
||||
You can set the name and description of your agent in `langgraph.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"graphs": {
|
||||
"my_agent": {
|
||||
"path": "./my_agent/agent.py:graph",
|
||||
"description": "A description of what the agent does"
|
||||
}
|
||||
},
|
||||
"env": ".env"
|
||||
}
|
||||
```
|
||||
|
||||
After deployment, you can update the name and description using the LangGraph SDK.
|
||||
|
||||
### Schema
|
||||
|
||||
Define clear, minimal input and output schemas to avoid exposing unnecessary internal complexity to the LLM.
|
||||
|
||||
The default [MessagesState](./low_level.md#messagesstate) uses `AnyMessage`, which supports many message types but is too general for direct LLM exposure.
|
||||
|
||||
Instead, define **custom agents or workflows** that use explicitly typed input and output structures.
|
||||
|
||||
For example, a workflow answering documentation questions might look like this:
|
||||
|
||||
```python
|
||||
from langgraph.graph import StateGraph, START, END
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
# Define input schema
|
||||
class InputState(TypedDict):
|
||||
question: str
|
||||
|
||||
# Define output schema
|
||||
class OutputState(TypedDict):
|
||||
answer: str
|
||||
|
||||
# Combine input and output
|
||||
class OverallState(InputState, OutputState):
|
||||
pass
|
||||
|
||||
# Define the processing node
|
||||
def answer_node(state: InputState):
|
||||
# Replace with actual logic and do something useful
|
||||
return {"answer": "bye", "question": state["question"]}
|
||||
|
||||
# Build the graph with explicit schemas
|
||||
builder = StateGraph(OverallState, input_schema=InputState, output_schema=OutputState)
|
||||
builder.add_node(answer_node)
|
||||
builder.add_edge(START, "answer_node")
|
||||
builder.add_edge("answer_node", END)
|
||||
graph = builder.compile()
|
||||
|
||||
# Run the graph
|
||||
print(graph.invoke({"question": "hi"}))
|
||||
```
|
||||
|
||||
For more details, see the [low-level concepts guide](https://langchain-ai.github.io/langgraph/concepts/low_level/#state).
|
||||
|
||||
|
||||
## Usage overview
|
||||
|
||||
To enable MCP:
|
||||
@@ -201,6 +127,109 @@ Use an MCP-compliant client to connect to the LangGraph server. The following ex
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
## Expose an agent as MCP tool
|
||||
|
||||
When deployed, your agent will appear as a tool in the MCP endpoint
|
||||
with this configuration:
|
||||
|
||||
- **Tool name**: The agent's name.
|
||||
- **Tool description**: The agent's description.
|
||||
- **Tool input schema**: The agent's input schema.
|
||||
|
||||
### Setting name and description
|
||||
|
||||
You can set the name and description of your agent in `langgraph.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"graphs": {
|
||||
"my_agent": {
|
||||
"path": "./my_agent/agent.py:graph",
|
||||
"description": "A description of what the agent does"
|
||||
}
|
||||
},
|
||||
"env": ".env"
|
||||
}
|
||||
```
|
||||
|
||||
After deployment, you can update the name and description using the LangGraph SDK.
|
||||
|
||||
### Schema
|
||||
|
||||
Define clear, minimal input and output schemas to avoid exposing unnecessary internal complexity to the LLM.
|
||||
|
||||
The default [MessagesState](./low_level.md#messagesstate) uses `AnyMessage`, which supports many message types but is too general for direct LLM exposure.
|
||||
|
||||
Instead, define **custom agents or workflows** that use explicitly typed input and output structures.
|
||||
|
||||
For example, a workflow answering documentation questions might look like this:
|
||||
|
||||
```python
|
||||
from langgraph.graph import StateGraph, START, END
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
# Define input schema
|
||||
class InputState(TypedDict):
|
||||
question: str
|
||||
|
||||
# Define output schema
|
||||
class OutputState(TypedDict):
|
||||
answer: str
|
||||
|
||||
# Combine input and output
|
||||
class OverallState(InputState, OutputState):
|
||||
pass
|
||||
|
||||
# Define the processing node
|
||||
def answer_node(state: InputState):
|
||||
# Replace with actual logic and do something useful
|
||||
return {"answer": "bye", "question": state["question"]}
|
||||
|
||||
# Build the graph with explicit schemas
|
||||
builder = StateGraph(OverallState, input_schema=InputState, output_schema=OutputState)
|
||||
builder.add_node(answer_node)
|
||||
builder.add_edge(START, "answer_node")
|
||||
builder.add_edge("answer_node", END)
|
||||
graph = builder.compile()
|
||||
|
||||
# Run the graph
|
||||
print(graph.invoke({"question": "hi"}))
|
||||
```
|
||||
|
||||
For more details, see the [low-level concepts guide](https://langchain-ai.github.io/langgraph/concepts/low_level/#state).
|
||||
|
||||
## Use user-scoped MCP tools in your deployment
|
||||
|
||||
!!! tip "Prerequisites"
|
||||
|
||||
You have added your own [custom auth middleware](https://langchain-ai.github.io/langgraph/how-tos/auth/custom_auth/) that populates the `langgraph_auth_user` object, making it accessible through configurable context for every node in your graph.
|
||||
|
||||
To make user-scoped tools available to your LangGraph Platform deployment, start with implementing a snippet like the following:
|
||||
|
||||
```python
|
||||
from langchain_mcp_adapters.client import MultiServerMCPClient
|
||||
|
||||
def get_mcp_tools_node(state, config):
|
||||
user = config["configurable"].get("langgraph_auth_user")
|
||||
# e.g., user["github_token"], user["email"], etc.
|
||||
|
||||
client = MultiServerMCPClient({
|
||||
"github": {
|
||||
"transport": "streamable_http", # (1)
|
||||
"url": "https://my-github-mcp-server/mcp", # (2)
|
||||
"headers": {
|
||||
"Authorization": f"Bearer {user['github_token']}"
|
||||
}
|
||||
}
|
||||
})
|
||||
tools = await client.get_tools() # (3)
|
||||
return {"tools": tools}
|
||||
|
||||
```
|
||||
|
||||
1. MCP only supports adding headers to requests made to `streamable_http` and `sse` `transport` servers.
|
||||
2. Your MCP server URL.
|
||||
3. Get available tools from your MCP server.
|
||||
|
||||
## Session behavior
|
||||
|
||||
@@ -210,7 +239,7 @@ The current LangGraph MCP implementation does not support sessions. Each `/mcp`
|
||||
|
||||
The `/mcp` endpoint uses the same authentication as the rest of the LangGraph API. Refer to the [authentication guide](./auth.md) for setup details.
|
||||
|
||||
## Disabling MCP
|
||||
## Disable MCP
|
||||
|
||||
To disable the MCP endpoint, set `disable_mcp` to `true` in your `langgraph.json` configuration file:
|
||||
|
||||
@@ -222,4 +251,4 @@ To disable the MCP endpoint, set `disable_mcp` to `true` in your `langgraph.json
|
||||
}
|
||||
```
|
||||
|
||||
This will prevent the server from exposing the `/mcp` endpoint.
|
||||
This will prevent the server from exposing the `/mcp` endpoint.
|
||||
|
||||
@@ -12,7 +12,7 @@ Some reasons for using subgraphs are:
|
||||
|
||||
The main question when adding subgraphs is how the parent graph and subgraph communicate, i.e. how they pass the [state](./low_level.md#state) between each other during the graph execution. There are two scenarios:
|
||||
|
||||
* parent and subgraph have **shared state keys** in their state [schemas](./low_level.md#state). In this case, you can [include the subgraph as a node in the parent graph](../how-tos/subgraph.ipynb#shared-state-schemas)
|
||||
* parent and subgraph have **shared state keys** in their state [schemas](./low_level.md#state). In this case, you can [include the subgraph as a node in the parent graph](../how-tos/subgraph.md#shared-state-schemas)
|
||||
|
||||
```python
|
||||
from langgraph.graph import StateGraph, MessagesState, START
|
||||
@@ -40,7 +40,7 @@ The main question when adding subgraphs is how the parent graph and subgraph com
|
||||
graph.invoke({"messages": [{"role": "user", "content": "hi!"}]})
|
||||
```
|
||||
|
||||
* parent graph and subgraph have **different schemas** (no shared state keys in their state [schemas](./low_level.md#state)). In this case, you have to [call the subgraph from inside a node in the parent graph](../how-tos/subgraph.ipynb#different-state-schemas): this is useful when the parent graph and the subgraph have different state schemas and you need to transform state before or after calling the subgraph
|
||||
* parent graph and subgraph have **different schemas** (no shared state keys in their state [schemas](./low_level.md#state)). In this case, you have to [call the subgraph from inside a node in the parent graph](../how-tos/subgraph.md#different-state-schemas): this is useful when the parent graph and the subgraph have different state schemas and you need to transform state before or after calling the subgraph
|
||||
|
||||
```python
|
||||
from typing_extensions import TypedDict, Annotated
|
||||
|
||||
|
After Width: | Height: | Size: 3.9 KiB |
|
After Width: | Height: | Size: 147 KiB |
|
After Width: | Height: | Size: 7.0 KiB |
|
After Width: | Height: | Size: 9.5 KiB |
|
After Width: | Height: | Size: 9.9 KiB |
|
After Width: | Height: | Size: 7.2 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 7.5 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 7.7 KiB |
@@ -1,138 +1,147 @@
|
||||
# Add custom authentication
|
||||
|
||||
!!! tip "Prerequisites"
|
||||
|
||||
This guide assumes familiarity with the following concepts:
|
||||
|
||||
* [**Authentication & Access Control**](../../concepts/auth.md)
|
||||
* [**LangGraph Platform**](../../concepts/langgraph_platform.md)
|
||||
|
||||
For a more guided walkthrough, see [**setting up custom authentication**](../../tutorials/auth/getting_started.md) tutorial.
|
||||
|
||||
???+ note "Support by deployment type"
|
||||
|
||||
Custom auth is supported for all deployments in the **managed LangGraph Platform**, as well as **Enterprise** self-hosted plans. It is not supported for **Lite** self-hosted plans.
|
||||
|
||||
This guide shows how to add custom authentication to your LangGraph Platform application. This guide applies to both LangGraph Platform and self-hosted deployments. It does not apply to isolated usage of the LangGraph open source library in your own custom server.
|
||||
|
||||
## 1. Implement authentication
|
||||
!!! note
|
||||
|
||||
Custom auth is supported for all **managed LangGraph Platform** deployments, as well as **Enterprise** self-hosted plans. It is not supported for **Lite** self-hosted plans.
|
||||
|
||||
## Add custom authentication to your deployment
|
||||
|
||||
To leverage custom authentication and access user-level metadata in your deployments, set up custom authentication to automatically populate the `config["configurable"]["langgraph_auth_user"]` object through a custom authentication handler. You can then access this object in your graph with the `langgraph_auth_user` key to [allow an agent to perform authenticated actions on behalf of the user](#enable-agent-authentication).
|
||||
|
||||
1. Implement authentication:
|
||||
|
||||
!!! note
|
||||
|
||||
Without a custom `@auth.authenticate` handler, LangGraph sees only the API-key owner (usually the developer), so requests aren’t scoped to individual end-users. To propagate custom tokens, you must implement your own handler.
|
||||
|
||||
```python
|
||||
from langgraph_sdk import Auth
|
||||
import requests
|
||||
|
||||
auth = Auth()
|
||||
|
||||
def is_valid_key(api_key: str) -> bool:
|
||||
is_valid = # your API key validation logic
|
||||
return is_valid
|
||||
|
||||
@auth.authenticate # (1)!
|
||||
async def authenticate(headers: dict) -> Auth.types.MinimalUserDict:
|
||||
api_key = headers.get("x-api-key")
|
||||
if not api_key or not is_valid_key(api_key):
|
||||
raise Auth.exceptions.HTTPException(status_code=401, detail="Invalid API key")
|
||||
|
||||
# Fetch user-specific tokens from your secret store
|
||||
user_tokens = await fetch_user_tokens(api_key)
|
||||
|
||||
return { # (2)!
|
||||
"identity": api_key, # fetch user ID from LangSmith
|
||||
"github_token" : user_tokens.github_token
|
||||
"jira_token" : user_tokens.jira_token
|
||||
# ... custom fields/secrets here
|
||||
}
|
||||
```
|
||||
|
||||
1. This handler receives the request (headers, etc.), validates the user, and returns a dictionary with at least an identity field.
|
||||
2. You can add any custom fields you want (e.g., OAuth tokens, roles, org IDs, etc.).
|
||||
|
||||
2. In your `langgraph.json`, add the path to your auth file:
|
||||
|
||||
```json hl_lines="7-9"
|
||||
{
|
||||
"dependencies": ["."],
|
||||
"graphs": {
|
||||
"agent": "./agent.py:graph"
|
||||
},
|
||||
"env": ".env",
|
||||
"auth": {
|
||||
"path": "./auth.py:my_auth"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
3. Once you've set up authentication in your server, requests must include the required authorization information based on your chosen scheme. Assuming you are using JWT token authentication, you could access your deployments using any of the following methods:
|
||||
|
||||
=== "Python Client"
|
||||
|
||||
```python
|
||||
from langgraph_sdk import get_client
|
||||
|
||||
my_token = "your-token" # In practice, you would generate a signed token with your auth provider
|
||||
client = get_client(
|
||||
url="http://localhost:2024",
|
||||
headers={"Authorization": f"Bearer {my_token}"}
|
||||
)
|
||||
threads = await client.threads.search()
|
||||
```
|
||||
|
||||
=== "Python RemoteGraph"
|
||||
|
||||
```python
|
||||
from langgraph.pregel.remote import RemoteGraph
|
||||
|
||||
my_token = "your-token" # In practice, you would generate a signed token with your auth provider
|
||||
remote_graph = RemoteGraph(
|
||||
"agent",
|
||||
url="http://localhost:2024",
|
||||
headers={"Authorization": f"Bearer {my_token}"}
|
||||
)
|
||||
threads = await remote_graph.ainvoke(...)
|
||||
```
|
||||
|
||||
=== "JavaScript Client"
|
||||
|
||||
```javascript
|
||||
import { Client } from "@langchain/langgraph-sdk";
|
||||
|
||||
const my_token = "your-token"; // In practice, you would generate a signed token with your auth provider
|
||||
const client = new Client({
|
||||
apiUrl: "http://localhost:2024",
|
||||
defaultHeaders: { Authorization: `Bearer ${my_token}` },
|
||||
});
|
||||
const threads = await client.threads.search();
|
||||
```
|
||||
|
||||
=== "JavaScript RemoteGraph"
|
||||
|
||||
```javascript
|
||||
import { RemoteGraph } from "@langchain/langgraph/remote";
|
||||
|
||||
const my_token = "your-token"; // In practice, you would generate a signed token with your auth provider
|
||||
const remoteGraph = new RemoteGraph({
|
||||
graphId: "agent",
|
||||
url: "http://localhost:2024",
|
||||
headers: { Authorization: `Bearer ${my_token}` },
|
||||
});
|
||||
const threads = await remoteGraph.invoke(...);
|
||||
```
|
||||
|
||||
=== "CURL"
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer ${your-token}" http://localhost:2024/threads
|
||||
```
|
||||
|
||||
## Enable agent authentication
|
||||
|
||||
After [authentication](#add-custom-authentication-to-your-deployment), the platform creates a special configuration object (`config`) that is passed to LangGraph Platform deployment. This object contains information about the current user, including any custom fields you return from your `@auth.authenticate` handler.
|
||||
|
||||
To allow an agent to perform authenticated actions on behalf of the user, access this object in your graph with the `langgraph_auth_user` key:
|
||||
|
||||
```python
|
||||
from langgraph_sdk import Auth
|
||||
|
||||
my_auth = Auth()
|
||||
|
||||
@my_auth.authenticate
|
||||
async def authenticate(authorization: str) -> str:
|
||||
token = authorization.split(" ", 1)[-1] # "Bearer <token>"
|
||||
try:
|
||||
# Verify token with your auth provider
|
||||
user_id = await verify_token(token)
|
||||
return user_id
|
||||
except Exception:
|
||||
raise Auth.exceptions.HTTPException(
|
||||
status_code=401,
|
||||
detail="Invalid token"
|
||||
)
|
||||
|
||||
# Add authorization rules to actually control access to resources
|
||||
@my_auth.on
|
||||
async def add_owner(
|
||||
ctx: Auth.types.AuthContext,
|
||||
value: dict,
|
||||
):
|
||||
"""Add owner to resource metadata and filter by owner."""
|
||||
filters = {"owner": ctx.user.identity}
|
||||
metadata = value.setdefault("metadata", {})
|
||||
metadata.update(filters)
|
||||
return filters
|
||||
|
||||
# Assumes you organize information in store like (user_id, resource_type, resource_id)
|
||||
@my_auth.on.store()
|
||||
async def authorize_store(ctx: Auth.types.AuthContext, value: dict):
|
||||
namespace: tuple = value["namespace"]
|
||||
assert namespace[0] == ctx.user.identity, "Not authorized"
|
||||
|
||||
def my_node(state, config):
|
||||
user_config = config["configurable"].get("langgraph_auth_user")
|
||||
# token was resolved during the @auth.authenticate function
|
||||
token = user_config.get("github_token","")
|
||||
...
|
||||
```
|
||||
|
||||
## 2. Update configuration
|
||||
!!! note
|
||||
Fetch user credentials from a secure secret store. Storing secrets in graph state is not recommended.
|
||||
|
||||
In your `langgraph.json`, add the path to your auth file:
|
||||
## Learn more
|
||||
|
||||
```json hl_lines="7-9"
|
||||
{
|
||||
"dependencies": ["."],
|
||||
"graphs": {
|
||||
"agent": "./agent.py:graph"
|
||||
},
|
||||
"env": ".env",
|
||||
"auth": {
|
||||
"path": "./auth.py:my_auth"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 3. Connect from the client
|
||||
|
||||
Once you've set up authentication in your server, requests must include the required authorization information based on your chosen scheme.
|
||||
Assuming you are using JWT token authentication, you could access your deployments using any of the following methods:
|
||||
|
||||
=== "Python Client"
|
||||
|
||||
```python
|
||||
from langgraph_sdk import get_client
|
||||
|
||||
my_token = "your-token" # In practice, you would generate a signed token with your auth provider
|
||||
client = get_client(
|
||||
url="http://localhost:2024",
|
||||
headers={"Authorization": f"Bearer {my_token}"}
|
||||
)
|
||||
threads = await client.threads.search()
|
||||
```
|
||||
|
||||
=== "Python RemoteGraph"
|
||||
|
||||
```python
|
||||
from langgraph.pregel.remote import RemoteGraph
|
||||
|
||||
my_token = "your-token" # In practice, you would generate a signed token with your auth provider
|
||||
remote_graph = RemoteGraph(
|
||||
"agent",
|
||||
url="http://localhost:2024",
|
||||
headers={"Authorization": f"Bearer {my_token}"}
|
||||
)
|
||||
threads = await remote_graph.ainvoke(...)
|
||||
```
|
||||
|
||||
=== "JavaScript Client"
|
||||
|
||||
```javascript
|
||||
import { Client } from "@langchain/langgraph-sdk";
|
||||
|
||||
const my_token = "your-token"; // In practice, you would generate a signed token with your auth provider
|
||||
const client = new Client({
|
||||
apiUrl: "http://localhost:2024",
|
||||
defaultHeaders: { Authorization: `Bearer ${my_token}` },
|
||||
});
|
||||
const threads = await client.threads.search();
|
||||
```
|
||||
|
||||
=== "JavaScript RemoteGraph"
|
||||
|
||||
```javascript
|
||||
import { RemoteGraph } from "@langchain/langgraph/remote";
|
||||
|
||||
const my_token = "your-token"; // In practice, you would generate a signed token with your auth provider
|
||||
const remoteGraph = new RemoteGraph({
|
||||
graphId: "agent",
|
||||
url: "http://localhost:2024",
|
||||
headers: { Authorization: `Bearer ${my_token}` },
|
||||
});
|
||||
const threads = await remoteGraph.invoke(...);
|
||||
```
|
||||
|
||||
=== "CURL"
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer ${your-token}" http://localhost:2024/threads
|
||||
```
|
||||
* [Authentication & Access Control](../../concepts/auth.md)
|
||||
* [LangGraph Platform](../../concepts/langgraph_platform.md)
|
||||
* [Setting up custom authentication tutorial](../../tutorials/auth/getting_started.md)
|
||||
|
||||
@@ -0,0 +1,580 @@
|
||||
# Build multi-agent systems
|
||||
|
||||
A single agent might struggle if it needs to specialize in multiple domains or manage many tools. To tackle this, you can break your agent into smaller, independent agents and composing them into a [multi-agent system](../concepts/multi_agent.md).
|
||||
|
||||
In multi-agent systems, agents need to communicate between each other. They do so via [handoffs](#handoffs) — a primitive that describes which agent to hand control to and the payload to send to that agent.
|
||||
|
||||
This guide covers the following:
|
||||
|
||||
* implementing [handoffs](#handoffs) between agents
|
||||
* using handoffs and the prebuilt [agent](../agents/agents.md) to [build a custom multi-agent system](#build-a-multi-agent-system)
|
||||
|
||||
To get started with building multi-agent systems, check out LangGraph [prebuilt implementations](#prebuilt-implementations) of two of the most popular multi-agent architectures — [supervisor](../agents/multi-agent.md#supervisor) and [swarm](../agents/multi-agent.md#swarm).
|
||||
|
||||
## Handoffs
|
||||
|
||||
To set up communication between the agents in a multi-agent system you can use [**handoffs**](../concepts/multi_agent.md#handoffs) — a pattern where one agent *hands off* control to another. Handoffs allow you to specify:
|
||||
|
||||
- **destination**: target agent to navigate to (e.g., name of the LangGraph node to go to)
|
||||
- **payload**: information to pass to that agent (e.g., state update)
|
||||
|
||||
### Create handoffs
|
||||
|
||||
To implement handoffs, you can return `Command` objects from your agent nodes or tools:
|
||||
|
||||
```python
|
||||
from typing import Annotated
|
||||
from langchain_core.tools import tool, InjectedToolCallId
|
||||
from langgraph.prebuilt import create_react_agent, InjectedState
|
||||
from langgraph.graph import StateGraph, START, MessagesState
|
||||
from langgraph.types import Command
|
||||
|
||||
def create_handoff_tool(*, agent_name: str, description: str | None = None):
|
||||
name = f"transfer_to_{agent_name}"
|
||||
description = description or f"Transfer to {agent_name}"
|
||||
|
||||
@tool(name, description=description)
|
||||
def handoff_tool(
|
||||
# highlight-next-line
|
||||
state: Annotated[MessagesState, InjectedState], # (1)!
|
||||
# highlight-next-line
|
||||
tool_call_id: Annotated[str, InjectedToolCallId],
|
||||
) -> Command:
|
||||
tool_message = {
|
||||
"role": "tool",
|
||||
"content": f"Successfully transferred to {agent_name}",
|
||||
"name": name,
|
||||
"tool_call_id": tool_call_id,
|
||||
}
|
||||
return Command( # (2)!
|
||||
# highlight-next-line
|
||||
goto=agent_name, # (3)!
|
||||
# highlight-next-line
|
||||
update={"messages": state["messages"] + [tool_message]}, # (4)!
|
||||
# highlight-next-line
|
||||
graph=Command.PARENT, # (5)!
|
||||
)
|
||||
return handoff_tool
|
||||
```
|
||||
|
||||
1. Access the [state](../concepts/low_level.md#state) of the agent that is calling the handoff tool using the [InjectedState][langgraph.prebuilt.InjectedState] annotation.
|
||||
2. The `Command` primitive allows specifying a state update and a node transition as a single operation, making it useful for implementing handoffs.
|
||||
3. Name of the agent or node to hand off to.
|
||||
4. Take the agent's messages and **add** them to the parent's **state** as part of the handoff. The next agent will see the parent state.
|
||||
5. Indicate to LangGraph that we need to navigate to agent node in a **parent** multi-agent graph.
|
||||
|
||||
!!! tip
|
||||
|
||||
If you want to use tools that return `Command`, you can either use prebuilt [`create_react_agent`][langgraph.prebuilt.chat_agent_executor.create_react_agent] / [`ToolNode`][langgraph.prebuilt.tool_node.ToolNode] components, or implement your own tool-executing node that collects `Command` objects returned by the tools and returns a list of them, e.g.:
|
||||
|
||||
```python
|
||||
def call_tools(state):
|
||||
...
|
||||
commands = [tools_by_name[tool_call["name"]].invoke(tool_call) for tool_call in tool_calls]
|
||||
return commands
|
||||
```
|
||||
|
||||
!!! Important
|
||||
|
||||
This handoff implementation assumes that:
|
||||
|
||||
- each agent receives overall message history (across all agents) in the multi-agent system as its input. If you want more control over agent inputs, see [this section](#control-agent-inputs)
|
||||
- each agent outputs its internal messages history to the overall message history of the multi-agent system. If you want more control over **how agent outputs are added**, wrap the agent in a separate node function:
|
||||
|
||||
```python
|
||||
def call_hotel_assistant(state):
|
||||
# return agent's final response,
|
||||
# excluding inner monologue
|
||||
response = hotel_assistant.invoke(state)
|
||||
# highlight-next-line
|
||||
return {"messages": response["messages"][-1]}
|
||||
```
|
||||
|
||||
### Control agent inputs
|
||||
|
||||
You can use the [`Send()`][langgraph.types.Send] primitive to directly send data to the worker agents during the handoff. For example, you can request that the calling agent populate a task description for the next agent:
|
||||
|
||||
```python
|
||||
|
||||
from typing import Annotated
|
||||
from langchain_core.tools import tool, InjectedToolCallId
|
||||
from langgraph.prebuilt import InjectedState
|
||||
from langgraph.graph import StateGraph, START, MessagesState
|
||||
# highlight-next-line
|
||||
from langgraph.types import Command, Send
|
||||
|
||||
def create_task_description_handoff_tool(
|
||||
*, agent_name: str, description: str | None = None
|
||||
):
|
||||
name = f"transfer_to_{agent_name}"
|
||||
description = description or f"Ask {agent_name} for help."
|
||||
|
||||
@tool(name, description=description)
|
||||
def handoff_tool(
|
||||
# this is populated by the calling agent
|
||||
task_description: Annotated[
|
||||
str,
|
||||
"Description of what the next agent should do, including all of the relevant context.",
|
||||
],
|
||||
# these parameters are ignored by the LLM
|
||||
state: Annotated[MessagesState, InjectedState],
|
||||
) -> Command:
|
||||
task_description_message = {"role": "user", "content": task_description}
|
||||
agent_input = {**state, "messages": [task_description_message]}
|
||||
return Command(
|
||||
# highlight-next-line
|
||||
goto=[Send(agent_name, agent_input)],
|
||||
graph=Command.PARENT,
|
||||
)
|
||||
|
||||
return handoff_tool
|
||||
```
|
||||
|
||||
See the multi-agent [supervisor](../tutorials/multi_agent/agent_supervisor.ipynb#4-create-delegation-tasks) example for a full example of using [`Send()`][langgraph.types.Send] in handoffs.
|
||||
|
||||
## Build a multi-agent system
|
||||
|
||||
You can use handoffs in any agents built with LangGraph. We recommend using the prebuilt [agent](../agents/overview.md) or [`ToolNode`](./tool-calling.md#toolnode), as they natively support handoffs tools returning `Command`. Below is an example of how you can implement a multi-agent system for booking travel using handoffs:
|
||||
|
||||
```python
|
||||
from langgraph.prebuilt import create_react_agent
|
||||
from langgraph.graph import StateGraph, START, MessagesState
|
||||
|
||||
def create_handoff_tool(*, agent_name: str, description: str | None = None):
|
||||
# same implementation as above
|
||||
...
|
||||
return Command(...)
|
||||
|
||||
# Handoffs
|
||||
transfer_to_hotel_assistant = create_handoff_tool(agent_name="hotel_assistant")
|
||||
transfer_to_flight_assistant = create_handoff_tool(agent_name="flight_assistant")
|
||||
|
||||
# Define agents
|
||||
flight_assistant = create_react_agent(
|
||||
model="anthropic:claude-3-5-sonnet-latest",
|
||||
# highlight-next-line
|
||||
tools=[..., transfer_to_hotel_assistant],
|
||||
# highlight-next-line
|
||||
name="flight_assistant"
|
||||
)
|
||||
hotel_assistant = create_react_agent(
|
||||
model="anthropic:claude-3-5-sonnet-latest",
|
||||
# highlight-next-line
|
||||
tools=[..., transfer_to_flight_assistant],
|
||||
# highlight-next-line
|
||||
name="hotel_assistant"
|
||||
)
|
||||
|
||||
# Define multi-agent graph
|
||||
multi_agent_graph = (
|
||||
StateGraph(MessagesState)
|
||||
# highlight-next-line
|
||||
.add_node(flight_assistant)
|
||||
# highlight-next-line
|
||||
.add_node(hotel_assistant)
|
||||
.add_edge(START, "flight_assistant")
|
||||
.compile()
|
||||
)
|
||||
```
|
||||
|
||||
??? example "Full example: Multi-agent system for booking travel"
|
||||
|
||||
```python
|
||||
from typing import Annotated
|
||||
from langchain_core.messages import convert_to_messages
|
||||
from langchain_core.tools import tool, InjectedToolCallId
|
||||
from langgraph.prebuilt import create_react_agent, InjectedState
|
||||
from langgraph.graph import StateGraph, START, MessagesState
|
||||
from langgraph.types import Command
|
||||
|
||||
# We'll use `pretty_print_messages` helper to render the streamed agent outputs nicely
|
||||
|
||||
def pretty_print_message(message, indent=False):
|
||||
pretty_message = message.pretty_repr(html=True)
|
||||
if not indent:
|
||||
print(pretty_message)
|
||||
return
|
||||
|
||||
indented = "\n".join("\t" + c for c in pretty_message.split("\n"))
|
||||
print(indented)
|
||||
|
||||
|
||||
def pretty_print_messages(update, last_message=False):
|
||||
is_subgraph = False
|
||||
if isinstance(update, tuple):
|
||||
ns, update = update
|
||||
# skip parent graph updates in the printouts
|
||||
if len(ns) == 0:
|
||||
return
|
||||
|
||||
graph_id = ns[-1].split(":")[0]
|
||||
print(f"Update from subgraph {graph_id}:")
|
||||
print("\n")
|
||||
is_subgraph = True
|
||||
|
||||
for node_name, node_update in update.items():
|
||||
update_label = f"Update from node {node_name}:"
|
||||
if is_subgraph:
|
||||
update_label = "\t" + update_label
|
||||
|
||||
print(update_label)
|
||||
print("\n")
|
||||
|
||||
messages = convert_to_messages(node_update["messages"])
|
||||
if last_message:
|
||||
messages = messages[-1:]
|
||||
|
||||
for m in messages:
|
||||
pretty_print_message(m, indent=is_subgraph)
|
||||
print("\n")
|
||||
|
||||
|
||||
def create_handoff_tool(*, agent_name: str, description: str | None = None):
|
||||
name = f"transfer_to_{agent_name}"
|
||||
description = description or f"Transfer to {agent_name}"
|
||||
|
||||
@tool(name, description=description)
|
||||
def handoff_tool(
|
||||
# highlight-next-line
|
||||
state: Annotated[MessagesState, InjectedState], # (1)!
|
||||
# highlight-next-line
|
||||
tool_call_id: Annotated[str, InjectedToolCallId],
|
||||
) -> Command:
|
||||
tool_message = {
|
||||
"role": "tool",
|
||||
"content": f"Successfully transferred to {agent_name}",
|
||||
"name": name,
|
||||
"tool_call_id": tool_call_id,
|
||||
}
|
||||
return Command( # (2)!
|
||||
# highlight-next-line
|
||||
goto=agent_name, # (3)!
|
||||
# highlight-next-line
|
||||
update={"messages": state["messages"] + [tool_message]}, # (4)!
|
||||
# highlight-next-line
|
||||
graph=Command.PARENT, # (5)!
|
||||
)
|
||||
return handoff_tool
|
||||
|
||||
# Handoffs
|
||||
transfer_to_hotel_assistant = create_handoff_tool(
|
||||
agent_name="hotel_assistant",
|
||||
description="Transfer user to the hotel-booking assistant.",
|
||||
)
|
||||
transfer_to_flight_assistant = create_handoff_tool(
|
||||
agent_name="flight_assistant",
|
||||
description="Transfer user to the flight-booking assistant.",
|
||||
)
|
||||
|
||||
# Simple agent tools
|
||||
def book_hotel(hotel_name: str):
|
||||
"""Book a hotel"""
|
||||
return f"Successfully booked a stay at {hotel_name}."
|
||||
|
||||
def book_flight(from_airport: str, to_airport: str):
|
||||
"""Book a flight"""
|
||||
return f"Successfully booked a flight from {from_airport} to {to_airport}."
|
||||
|
||||
# Define agents
|
||||
flight_assistant = create_react_agent(
|
||||
model="anthropic:claude-3-5-sonnet-latest",
|
||||
# highlight-next-line
|
||||
tools=[book_flight, transfer_to_hotel_assistant],
|
||||
prompt="You are a flight booking assistant",
|
||||
# highlight-next-line
|
||||
name="flight_assistant"
|
||||
)
|
||||
hotel_assistant = create_react_agent(
|
||||
model="anthropic:claude-3-5-sonnet-latest",
|
||||
# highlight-next-line
|
||||
tools=[book_hotel, transfer_to_flight_assistant],
|
||||
prompt="You are a hotel booking assistant",
|
||||
# highlight-next-line
|
||||
name="hotel_assistant"
|
||||
)
|
||||
|
||||
# Define multi-agent graph
|
||||
multi_agent_graph = (
|
||||
StateGraph(MessagesState)
|
||||
.add_node(flight_assistant)
|
||||
.add_node(hotel_assistant)
|
||||
.add_edge(START, "flight_assistant")
|
||||
.compile()
|
||||
)
|
||||
|
||||
# Run the multi-agent graph
|
||||
for chunk in multi_agent_graph.stream(
|
||||
{
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "book a flight from BOS to JFK and a stay at McKittrick Hotel"
|
||||
}
|
||||
]
|
||||
},
|
||||
# highlight-next-line
|
||||
subgraphs=True
|
||||
):
|
||||
pretty_print_messages(chunk)
|
||||
```
|
||||
|
||||
1. Access agent's state
|
||||
2. The `Command` primitive allows specifying a state update and a node transition as a single operation, making it useful for implementing handoffs.
|
||||
3. Name of the agent or node to hand off to.
|
||||
4. Take the agent's messages and **add** them to the parent's **state** as part of the handoff. The next agent will see the parent state.
|
||||
5. Indicate to LangGraph that we need to navigate to agent node in a **parent** multi-agent graph.
|
||||
|
||||
## Multi-turn conversation
|
||||
|
||||
Users might want to engage in a *multi-turn conversation* with one or more agents. To build a system that can handle this, you can create a node that uses an [`interrupt`][langgraph.types.interrupt] to collect user input and routes back to the **active** agent.
|
||||
|
||||
The agents can then be implemented as nodes in a graph that executes agent steps and determines the next action:
|
||||
|
||||
1. **Wait for user input** to continue the conversation, or
|
||||
2. **Route to another agent** (or back to itself, such as in a loop) via a [handoff](#handoffs)
|
||||
|
||||
```python
|
||||
def human(state) -> Command[Literal["agent", "another_agent"]]:
|
||||
"""A node for collecting user input."""
|
||||
user_input = interrupt(value="Ready for user input.")
|
||||
|
||||
# Determine the active agent.
|
||||
active_agent = ...
|
||||
|
||||
...
|
||||
return Command(
|
||||
update={
|
||||
"messages": [{
|
||||
"role": "human",
|
||||
"content": user_input,
|
||||
}]
|
||||
},
|
||||
goto=active_agent
|
||||
)
|
||||
|
||||
def agent(state) -> Command[Literal["agent", "another_agent", "human"]]:
|
||||
# The condition for routing/halting can be anything, e.g. LLM tool call / structured output, etc.
|
||||
goto = get_next_agent(...) # 'agent' / 'another_agent'
|
||||
if goto:
|
||||
return Command(goto=goto, update={"my_state_key": "my_state_value"})
|
||||
else:
|
||||
return Command(goto="human") # Go to human node
|
||||
```
|
||||
|
||||
??? example "Full example: multi-agent system for travel recommendations"
|
||||
|
||||
In this example, we will build a team of travel assistant agents that can communicate with each other via handoffs.
|
||||
|
||||
We will create 2 agents:
|
||||
|
||||
* travel_advisor: can help with travel destination recommendations. Can ask hotel_advisor for help.
|
||||
* hotel_advisor: can help with hotel recommendations. Can ask travel_advisor for help.
|
||||
|
||||
```python
|
||||
from langchain_anthropic import ChatAnthropic
|
||||
from langgraph.graph import MessagesState, StateGraph, START
|
||||
from langgraph.prebuilt import create_react_agent, InjectedState
|
||||
from langgraph.types import Command, interrupt
|
||||
from langgraph.checkpoint.memory import MemorySaver
|
||||
|
||||
|
||||
model = ChatAnthropic(model="claude-3-5-sonnet-latest")
|
||||
|
||||
class MultiAgentState(MessagesState):
|
||||
last_active_agent: str
|
||||
|
||||
|
||||
# Define travel advisor tools and ReAct agent
|
||||
travel_advisor_tools = [
|
||||
get_travel_recommendations,
|
||||
make_handoff_tool(agent_name="hotel_advisor"),
|
||||
]
|
||||
travel_advisor = create_react_agent(
|
||||
model,
|
||||
travel_advisor_tools,
|
||||
prompt=(
|
||||
"You are a general travel expert that can recommend travel destinations (e.g. countries, cities, etc). "
|
||||
"If you need hotel recommendations, ask 'hotel_advisor' for help. "
|
||||
"You MUST include human-readable response before transferring to another agent."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def call_travel_advisor(
|
||||
state: MultiAgentState,
|
||||
) -> Command[Literal["hotel_advisor", "human"]]:
|
||||
# You can also add additional logic like changing the input to the agent / output from the agent, etc.
|
||||
# NOTE: we're invoking the ReAct agent with the full history of messages in the state
|
||||
response = travel_advisor.invoke(state)
|
||||
update = {**response, "last_active_agent": "travel_advisor"}
|
||||
return Command(update=update, goto="human")
|
||||
|
||||
|
||||
# Define hotel advisor tools and ReAct agent
|
||||
hotel_advisor_tools = [
|
||||
get_hotel_recommendations,
|
||||
make_handoff_tool(agent_name="travel_advisor"),
|
||||
]
|
||||
hotel_advisor = create_react_agent(
|
||||
model,
|
||||
hotel_advisor_tools,
|
||||
prompt=(
|
||||
"You are a hotel expert that can provide hotel recommendations for a given destination. "
|
||||
"If you need help picking travel destinations, ask 'travel_advisor' for help."
|
||||
"You MUST include human-readable response before transferring to another agent."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def call_hotel_advisor(
|
||||
state: MultiAgentState,
|
||||
) -> Command[Literal["travel_advisor", "human"]]:
|
||||
response = hotel_advisor.invoke(state)
|
||||
update = {**response, "last_active_agent": "hotel_advisor"}
|
||||
return Command(update=update, goto="human")
|
||||
|
||||
|
||||
def human_node(
|
||||
state: MultiAgentState, config
|
||||
) -> Command[Literal["hotel_advisor", "travel_advisor", "human"]]:
|
||||
"""A node for collecting user input."""
|
||||
|
||||
user_input = interrupt(value="Ready for user input.")
|
||||
active_agent = state["last_active_agent"]
|
||||
|
||||
return Command(
|
||||
update={
|
||||
"messages": [
|
||||
{
|
||||
"role": "human",
|
||||
"content": user_input,
|
||||
}
|
||||
]
|
||||
},
|
||||
goto=active_agent,
|
||||
)
|
||||
|
||||
|
||||
builder = StateGraph(MultiAgentState)
|
||||
builder.add_node("travel_advisor", call_travel_advisor)
|
||||
builder.add_node("hotel_advisor", call_hotel_advisor)
|
||||
|
||||
# This adds a node to collect human input, which will route
|
||||
# back to the active agent.
|
||||
builder.add_node("human", human_node)
|
||||
|
||||
# We'll always start with a general travel advisor.
|
||||
builder.add_edge(START, "travel_advisor")
|
||||
|
||||
|
||||
checkpointer = MemorySaver()
|
||||
graph = builder.compile(checkpointer=checkpointer)
|
||||
```
|
||||
|
||||
Let's test a multi turn conversation with this application.
|
||||
|
||||
```python
|
||||
import uuid
|
||||
|
||||
thread_config = {"configurable": {"thread_id": str(uuid.uuid4())}}
|
||||
|
||||
inputs = [
|
||||
# 1st round of conversation,
|
||||
{
|
||||
"messages": [
|
||||
{"role": "user", "content": "i wanna go somewhere warm in the caribbean"}
|
||||
]
|
||||
},
|
||||
# Since we're using `interrupt`, we'll need to resume using the Command primitive.
|
||||
# 2nd round of conversation,
|
||||
Command(
|
||||
resume="could you recommend a nice hotel in one of the areas and tell me which area it is."
|
||||
),
|
||||
# 3rd round of conversation,
|
||||
Command(
|
||||
resume="i like the first one. could you recommend something to do near the hotel?"
|
||||
),
|
||||
]
|
||||
|
||||
for idx, user_input in enumerate(inputs):
|
||||
print()
|
||||
print(f"--- Conversation Turn {idx + 1} ---")
|
||||
print()
|
||||
print(f"User: {user_input}")
|
||||
print()
|
||||
for update in graph.stream(
|
||||
user_input,
|
||||
config=thread_config,
|
||||
stream_mode="updates",
|
||||
):
|
||||
for node_id, value in update.items():
|
||||
if isinstance(value, dict) and value.get("messages", []):
|
||||
last_message = value["messages"][-1]
|
||||
if isinstance(last_message, dict) or last_message.type != "ai":
|
||||
continue
|
||||
print(f"{node_id}: {last_message.content}")
|
||||
```
|
||||
|
||||
```
|
||||
--- Conversation Turn 1 ---
|
||||
|
||||
User: {'messages': [{'role': 'user', 'content': 'i wanna go somewhere warm in the caribbean'}]}
|
||||
|
||||
travel_advisor: Based on the recommendations, Aruba would be an excellent choice for your Caribbean getaway! Aruba is known as "One Happy Island" and offers:
|
||||
- Year-round warm weather with consistent temperatures around 82°F (28°C)
|
||||
- Beautiful white sand beaches like Eagle Beach and Palm Beach
|
||||
- Clear turquoise waters perfect for swimming and snorkeling
|
||||
- Minimal rainfall and location outside the hurricane belt
|
||||
- A blend of Caribbean and Dutch culture
|
||||
- Great dining options and nightlife
|
||||
- Various water sports and activities
|
||||
|
||||
Would you like me to get some specific hotel recommendations in Aruba for your stay? I can transfer you to our hotel advisor who can help with accommodations.
|
||||
|
||||
--- Conversation Turn 2 ---
|
||||
|
||||
User: Command(resume='could you recommend a nice hotel in one of the areas and tell me which area it is.')
|
||||
|
||||
hotel_advisor: Based on the recommendations, I can suggest two excellent options:
|
||||
|
||||
1. The Ritz-Carlton, Aruba - Located in Palm Beach
|
||||
- This luxury resort is situated in the vibrant Palm Beach area
|
||||
- Known for its exceptional service and amenities
|
||||
- Perfect if you want to be close to dining, shopping, and entertainment
|
||||
- Features multiple restaurants, a casino, and a world-class spa
|
||||
- Located on a pristine stretch of Palm Beach
|
||||
|
||||
2. Bucuti & Tara Beach Resort - Located in Eagle Beach
|
||||
- An adults-only boutique resort on Eagle Beach
|
||||
- Known for being more intimate and peaceful
|
||||
- Award-winning for its sustainability practices
|
||||
- Perfect for a romantic getaway or peaceful vacation
|
||||
- Located on one of the most beautiful beaches in the Caribbean
|
||||
|
||||
Would you like more specific information about either of these properties or their locations?
|
||||
|
||||
--- Conversation Turn 3 ---
|
||||
|
||||
User: Command(resume='i like the first one. could you recommend something to do near the hotel?')
|
||||
|
||||
travel_advisor: Near the Ritz-Carlton in Palm Beach, here are some highly recommended activities:
|
||||
|
||||
1. Visit the Palm Beach Plaza Mall - Just a short walk from the hotel, featuring shopping, dining, and entertainment
|
||||
2. Try your luck at the Stellaris Casino - It's right in the Ritz-Carlton
|
||||
3. Take a sunset sailing cruise - Many depart from the nearby pier
|
||||
4. Visit the California Lighthouse - A scenic landmark just north of Palm Beach
|
||||
5. Enjoy water sports at Palm Beach:
|
||||
- Jet skiing
|
||||
- Parasailing
|
||||
- Snorkeling
|
||||
- Stand-up paddleboarding
|
||||
|
||||
Would you like more specific information about any of these activities or would you like to know about other options in the area?
|
||||
```
|
||||
|
||||
## Prebuilt implementations
|
||||
|
||||
LangGraph comes with prebuilt implementations of two of the most popular multi-agent architectures:
|
||||
|
||||
- [supervisor](../agents/multi-agent.md#supervisor) — individual agents are coordinated by a central supervisor agent. The supervisor controls all communication flow and task delegation, making decisions about which agent to invoke based on the current context and task requirements. You can use [`langgraph-supervisor`](https://github.com/langchain-ai/langgraph-supervisor-py) library to create a supervisor multi-agent systems.
|
||||
- [swarm](../agents/multi-agent.md#supervisor) — agents dynamically hand off control to one another based on their specializations. The system remembers which agent was last active, ensuring that on subsequent interactions, the conversation resumes with that agent. You can use [`langgraph-swarm`](https://github.com/langchain-ai/langgraph-swarm-py) library to create a swarm multi-agent systems.
|
||||
@@ -1,559 +0,0 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Use subgraphs\n",
|
||||
"\n",
|
||||
"This guide explains the mechanics of using [subgraphs](../../concepts/subgraphs). A common application of subgraphs is to build [multi-agent](../../concepts/multi_agent) systems.\n",
|
||||
"\n",
|
||||
"When adding subgraphs, you need to define how the parent graph and the subgraph communicate:\n",
|
||||
"\n",
|
||||
"* [Shared state schemas](#shared-state-schemas) — parent and subgraph have **shared state keys** in their state [schemas](../../concepts/low_level#state)\n",
|
||||
"* [Different state schemas](#different-state-schemas) — **no shared state keys** in parent and subgraph [schemas](../../concepts/low_level#state)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Setup"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%%capture --no-stderr\n",
|
||||
"%pip install -U langgraph"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"<div class=\"admonition tip\">\n",
|
||||
" <p class=\"admonition-title\">Set up <a href=\"https://smith.langchain.com\">LangSmith</a> for LangGraph development</p>\n",
|
||||
" <p style=\"padding-top: 5px;\">\n",
|
||||
" Sign up for LangSmith to quickly spot issues and improve the performance of your LangGraph projects. LangSmith lets you use trace data to debug, test, and monitor your LLM apps built with LangGraph — read more about how to get started <a href=\"https://docs.smith.langchain.com\">here</a>. \n",
|
||||
" </p>\n",
|
||||
"</div>"
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Shared state schemas\n",
|
||||
"\n",
|
||||
"A common case is for the parent graph and subgraph to communicate over a shared state key (channel) in the [schema](../../concepts/low_level#state). For example, in [multi-agent](../../concepts/multi_agent) systems, the agents often communicate over a shared [messages](https://langchain-ai.github.io/langgraph/concepts/low_level/#why-use-messages) key.\n",
|
||||
"\n",
|
||||
"If your subgraph shares state keys with the parent graph, you can follow these steps to add it to your graph:\n",
|
||||
"\n",
|
||||
"1. Define the subgraph workflow (`subgraph_builder` in the example below) and compile it\n",
|
||||
"2. Pass compiled subgraph to the `.add_node` method when defining the parent graph workflow\n",
|
||||
"\n",
|
||||
"```python\n",
|
||||
"from typing_extensions import TypedDict\n",
|
||||
"from langgraph.graph.state import StateGraph, START\n",
|
||||
"\n",
|
||||
"class State(TypedDict):\n",
|
||||
" foo: str\n",
|
||||
"\n",
|
||||
"# Subgraph\n",
|
||||
"\n",
|
||||
"def subgraph_node_1(state: State):\n",
|
||||
" return {\"foo\": \"hi! \" + state[\"foo\"]}\n",
|
||||
"\n",
|
||||
"subgraph_builder = StateGraph(State)\n",
|
||||
"subgraph_builder.add_node(subgraph_node_1)\n",
|
||||
"subgraph_builder.add_edge(START, \"subgraph_node_1\")\n",
|
||||
"# highlight-next-line\n",
|
||||
"subgraph = subgraph_builder.compile()\n",
|
||||
"\n",
|
||||
"# Parent graph\n",
|
||||
"\n",
|
||||
"builder = StateGraph(State)\n",
|
||||
"# highlight-next-line\n",
|
||||
"builder.add_node(\"node_1\", subgraph)\n",
|
||||
"builder.add_edge(START, \"node_1\")\n",
|
||||
"graph = builder.compile()\n",
|
||||
"```\n",
|
||||
"\n",
|
||||
"??? example \"Full example: shared state schemas\"\n",
|
||||
"\n",
|
||||
" ```python\n",
|
||||
" from typing_extensions import TypedDict\n",
|
||||
" from langgraph.graph.state import StateGraph, START\n",
|
||||
"\n",
|
||||
" # Define subgraph\n",
|
||||
" class SubgraphState(TypedDict):\n",
|
||||
" foo: str # (1)! \n",
|
||||
" bar: str # (2)!\n",
|
||||
" \n",
|
||||
" def subgraph_node_1(state: SubgraphState):\n",
|
||||
" return {\"bar\": \"bar\"}\n",
|
||||
" \n",
|
||||
" def subgraph_node_2(state: SubgraphState):\n",
|
||||
" # note that this node is using a state key ('bar') that is only available in the subgraph\n",
|
||||
" # and is sending update on the shared state key ('foo')\n",
|
||||
" return {\"foo\": state[\"foo\"] + state[\"bar\"]}\n",
|
||||
" \n",
|
||||
" subgraph_builder = StateGraph(SubgraphState)\n",
|
||||
" subgraph_builder.add_node(subgraph_node_1)\n",
|
||||
" subgraph_builder.add_node(subgraph_node_2)\n",
|
||||
" subgraph_builder.add_edge(START, \"subgraph_node_1\")\n",
|
||||
" subgraph_builder.add_edge(\"subgraph_node_1\", \"subgraph_node_2\")\n",
|
||||
" subgraph = subgraph_builder.compile()\n",
|
||||
" \n",
|
||||
" # Define parent graph\n",
|
||||
" class ParentState(TypedDict):\n",
|
||||
" foo: str\n",
|
||||
" \n",
|
||||
" def node_1(state: ParentState):\n",
|
||||
" return {\"foo\": \"hi! \" + state[\"foo\"]}\n",
|
||||
" \n",
|
||||
" builder = StateGraph(ParentState)\n",
|
||||
" builder.add_node(\"node_1\", node_1)\n",
|
||||
" # highlight-next-line\n",
|
||||
" builder.add_node(\"node_2\", subgraph)\n",
|
||||
" builder.add_edge(START, \"node_1\")\n",
|
||||
" builder.add_edge(\"node_1\", \"node_2\")\n",
|
||||
" graph = builder.compile()\n",
|
||||
" \n",
|
||||
" for chunk in graph.stream({\"foo\": \"foo\"}):\n",
|
||||
" print(chunk)\n",
|
||||
" ```\n",
|
||||
"\n",
|
||||
" 1. This key is shared with the parent graph state\n",
|
||||
" 2. This key is private to the `SubgraphState` and is not visible to the parent graph\n",
|
||||
" \n",
|
||||
" ```\n",
|
||||
" {'node_1': {'foo': 'hi! foo'}}\n",
|
||||
" {'node_2': {'foo': 'hi! foobar'}}\n",
|
||||
" ```\n",
|
||||
"\n",
|
||||
" ```"
|
||||
]
|
||||
},
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Different state schemas\n",
|
||||
"\n",
|
||||
"For more complex systems you might want to define subgraphs that have a **completely different schema** from the parent graph (no shared keys). For example, you might want to keep a private message history for each of the agents in a [multi-agent](../concepts/multi_agent.md) system.\n",
|
||||
"\n",
|
||||
"If that's the case for your application, you need to define a node **function that invokes the subgraph**. This function needs to transform the input (parent) state to the subgraph state before invoking the subgraph, and transform the results back to the parent state before returning the state update from the node.\n",
|
||||
"\n",
|
||||
"```python\n",
|
||||
"from typing_extensions import TypedDict\n",
|
||||
"from langgraph.graph.state import StateGraph, START\n",
|
||||
"\n",
|
||||
"class SubgraphState(TypedDict):\n",
|
||||
" bar: str\n",
|
||||
"\n",
|
||||
"# Subgraph\n",
|
||||
"\n",
|
||||
"def subgraph_node_1(state: SubgraphState):\n",
|
||||
" return {\"bar\": \"hi! \" + state[\"bar\"]}\n",
|
||||
"\n",
|
||||
"subgraph_builder = StateGraph(SubgraphState)\n",
|
||||
"subgraph_builder.add_node(subgraph_node_1)\n",
|
||||
"subgraph_builder.add_edge(START, \"subgraph_node_1\")\n",
|
||||
"# highlight-next-line\n",
|
||||
"subgraph = subgraph_builder.compile()\n",
|
||||
"\n",
|
||||
"# Parent graph\n",
|
||||
"\n",
|
||||
"class State(TypedDict):\n",
|
||||
" foo: str\n",
|
||||
"\n",
|
||||
"def call_subgraph(state: State):\n",
|
||||
" # highlight-next-line\n",
|
||||
" subgraph_output = subgraph.invoke({\"bar\": state[\"foo\"]}) # (1)!\n",
|
||||
" # highlight-next-line\n",
|
||||
" return {\"foo\": subgraph_output[\"bar\"]} # (2)!\n",
|
||||
"\n",
|
||||
"builder = StateGraph(State)\n",
|
||||
"# highlight-next-line\n",
|
||||
"builder.add_node(\"node_1\", call_subgraph)\n",
|
||||
"builder.add_edge(START, \"node_1\")\n",
|
||||
"graph = builder.compile()\n",
|
||||
"```\n",
|
||||
"\n",
|
||||
"1. Transform the state to the subgraph state\n",
|
||||
"2. Transform response back to the parent state\n",
|
||||
"\n",
|
||||
"??? example \"Full example: different state schemas\"\n",
|
||||
"\n",
|
||||
" ```python\n",
|
||||
" from typing_extensions import TypedDict\n",
|
||||
" from langgraph.graph.state import StateGraph, START\n",
|
||||
"\n",
|
||||
" # Define subgraph\n",
|
||||
" class SubgraphState(TypedDict):\n",
|
||||
" # note that none of these keys are shared with the parent graph state\n",
|
||||
" bar: str\n",
|
||||
" baz: str\n",
|
||||
" \n",
|
||||
" def subgraph_node_1(state: SubgraphState):\n",
|
||||
" return {\"baz\": \"baz\"}\n",
|
||||
" \n",
|
||||
" def subgraph_node_2(state: SubgraphState):\n",
|
||||
" return {\"bar\": state[\"bar\"] + state[\"baz\"]}\n",
|
||||
" \n",
|
||||
" subgraph_builder = StateGraph(SubgraphState)\n",
|
||||
" subgraph_builder.add_node(subgraph_node_1)\n",
|
||||
" subgraph_builder.add_node(subgraph_node_2)\n",
|
||||
" subgraph_builder.add_edge(START, \"subgraph_node_1\")\n",
|
||||
" subgraph_builder.add_edge(\"subgraph_node_1\", \"subgraph_node_2\")\n",
|
||||
" subgraph = subgraph_builder.compile()\n",
|
||||
" \n",
|
||||
" # Define parent graph\n",
|
||||
" class ParentState(TypedDict):\n",
|
||||
" foo: str\n",
|
||||
" \n",
|
||||
" def node_1(state: ParentState):\n",
|
||||
" return {\"foo\": \"hi! \" + state[\"foo\"]}\n",
|
||||
" \n",
|
||||
" def node_2(state: ParentState):\n",
|
||||
" # highlight-next-line\n",
|
||||
" response = subgraph.invoke({\"bar\": state[\"foo\"]}) # (1)!\n",
|
||||
" # highlight-next-line\n",
|
||||
" return {\"foo\": response[\"bar\"]} # (2)!\n",
|
||||
" \n",
|
||||
" \n",
|
||||
" builder = StateGraph(ParentState)\n",
|
||||
" builder.add_node(\"node_1\", node_1)\n",
|
||||
" # highlight-next-line\n",
|
||||
" builder.add_node(\"node_2\", node_2)\n",
|
||||
" builder.add_edge(START, \"node_1\")\n",
|
||||
" builder.add_edge(\"node_1\", \"node_2\")\n",
|
||||
" graph = builder.compile()\n",
|
||||
" \n",
|
||||
" for chunk in graph.stream({\"foo\": \"foo\"}, subgraphs=True):\n",
|
||||
" print(chunk)\n",
|
||||
" ```\n",
|
||||
"\n",
|
||||
" 1. Transform the state to the subgraph state\n",
|
||||
" 2. Transform response back to the parent state\n",
|
||||
"\n",
|
||||
" ```\n",
|
||||
" ((), {'node_1': {'foo': 'hi! foo'}})\n",
|
||||
" (('node_2:9c36dd0f-151a-cb42-cbad-fa2f851f9ab7',), {'subgraph_node_1': {'baz': 'baz'}})\n",
|
||||
" (('node_2:9c36dd0f-151a-cb42-cbad-fa2f851f9ab7',), {'subgraph_node_2': {'bar': 'hi! foobaz'}})\n",
|
||||
" ((), {'node_2': {'foo': 'hi! foobaz'}})\n",
|
||||
" ```\n",
|
||||
"\n",
|
||||
"??? example \"Full example: different state schemas (two levels of subgraphs)\"\n",
|
||||
"\n",
|
||||
" This is an example with two levels of subgraphs: parent -> child -> grandchild.\n",
|
||||
"\n",
|
||||
" ```python\n",
|
||||
" # Grandchild graph\n",
|
||||
" from typing_extensions import TypedDict\n",
|
||||
" from langgraph.graph.state import StateGraph, START, END\n",
|
||||
" \n",
|
||||
" class GrandChildState(TypedDict):\n",
|
||||
" my_grandchild_key: str\n",
|
||||
" \n",
|
||||
" def grandchild_1(state: GrandChildState) -> GrandChildState:\n",
|
||||
" # NOTE: child or parent keys will not be accessible here\n",
|
||||
" return {\"my_grandchild_key\": state[\"my_grandchild_key\"] + \", how are you\"}\n",
|
||||
" \n",
|
||||
" \n",
|
||||
" grandchild = StateGraph(GrandChildState)\n",
|
||||
" grandchild.add_node(\"grandchild_1\", grandchild_1)\n",
|
||||
" \n",
|
||||
" grandchild.add_edge(START, \"grandchild_1\")\n",
|
||||
" grandchild.add_edge(\"grandchild_1\", END)\n",
|
||||
" \n",
|
||||
" grandchild_graph = grandchild.compile()\n",
|
||||
" \n",
|
||||
" # Child graph\n",
|
||||
" class ChildState(TypedDict):\n",
|
||||
" my_child_key: str\n",
|
||||
" \n",
|
||||
" def call_grandchild_graph(state: ChildState) -> ChildState:\n",
|
||||
" # NOTE: parent or grandchild keys won't be accessible here\n",
|
||||
" grandchild_graph_input = {\"my_grandchild_key\": state[\"my_child_key\"]} # (1)!\n",
|
||||
" # highlight-next-line\n",
|
||||
" grandchild_graph_output = grandchild_graph.invoke(grandchild_graph_input)\n",
|
||||
" return {\"my_child_key\": grandchild_graph_output[\"my_grandchild_key\"] + \" today?\"} # (2)!\n",
|
||||
" \n",
|
||||
" child = StateGraph(ChildState)\n",
|
||||
" # highlight-next-line\n",
|
||||
" child.add_node(\"child_1\", call_grandchild_graph) # (3)!\n",
|
||||
" child.add_edge(START, \"child_1\")\n",
|
||||
" child.add_edge(\"child_1\", END)\n",
|
||||
" child_graph = child.compile()\n",
|
||||
" \n",
|
||||
" # Parent graph\n",
|
||||
" class ParentState(TypedDict):\n",
|
||||
" my_key: str\n",
|
||||
" \n",
|
||||
" def parent_1(state: ParentState) -> ParentState:\n",
|
||||
" # NOTE: child or grandchild keys won't be accessible here\n",
|
||||
" return {\"my_key\": \"hi \" + state[\"my_key\"]}\n",
|
||||
" \n",
|
||||
" def parent_2(state: ParentState) -> ParentState:\n",
|
||||
" return {\"my_key\": state[\"my_key\"] + \" bye!\"}\n",
|
||||
" \n",
|
||||
" def call_child_graph(state: ParentState) -> ParentState:\n",
|
||||
" child_graph_input = {\"my_child_key\": state[\"my_key\"]} # (4)!\n",
|
||||
" # highlight-next-line\n",
|
||||
" child_graph_output = child_graph.invoke(child_graph_input)\n",
|
||||
" return {\"my_key\": child_graph_output[\"my_child_key\"]} # (5)!\n",
|
||||
" \n",
|
||||
" parent = StateGraph(ParentState)\n",
|
||||
" parent.add_node(\"parent_1\", parent_1)\n",
|
||||
" # highlight-next-line\n",
|
||||
" parent.add_node(\"child\", call_child_graph) # (6)!\n",
|
||||
" parent.add_node(\"parent_2\", parent_2)\n",
|
||||
" \n",
|
||||
" parent.add_edge(START, \"parent_1\")\n",
|
||||
" parent.add_edge(\"parent_1\", \"child\")\n",
|
||||
" parent.add_edge(\"child\", \"parent_2\")\n",
|
||||
" parent.add_edge(\"parent_2\", END)\n",
|
||||
" \n",
|
||||
" parent_graph = parent.compile()\n",
|
||||
" \n",
|
||||
" for chunk in parent_graph.stream({\"my_key\": \"Bob\"}, subgraphs=True):\n",
|
||||
" print(chunk)\n",
|
||||
" ```\n",
|
||||
"\n",
|
||||
" 1. We're transforming the state from the child state channels (`my_child_key`) to the child state channels (`my_grandchild_key`)\n",
|
||||
" 2. We're transforming the state from the grandchild state channels (`my_grandchild_key`) back to the child state channels (`my_child_key`)\n",
|
||||
" 3. We're passing a function here instead of just compiled graph (`grandchild_graph`)\n",
|
||||
" 4. We're transforming the state from the parent state channels (`my_key`) to the child state channels (`my_child_key`)\n",
|
||||
" 5. We're transforming the state from the child state channels (`my_child_key`) back to the parent state channels (`my_key`)\n",
|
||||
" 6. We're passing a function here instead of just a compiled graph (`child_graph`)\n",
|
||||
"\n",
|
||||
" ```\n",
|
||||
" ((), {'parent_1': {'my_key': 'hi Bob'}})\n",
|
||||
" (('child:2e26e9ce-602f-862c-aa66-1ea5a4655e3b', 'child_1:781bb3b1-3971-84ce-810b-acf819a03f9c'), {'grandchild_1': {'my_grandchild_key': 'hi Bob, how are you'}})\n",
|
||||
" (('child:2e26e9ce-602f-862c-aa66-1ea5a4655e3b',), {'child_1': {'my_child_key': 'hi Bob, how are you today?'}})\n",
|
||||
" ((), {'child': {'my_key': 'hi Bob, how are you today?'}})\n",
|
||||
" ((), {'parent_2': {'my_key': 'hi Bob, how are you today? bye!'}})\n",
|
||||
" ```"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Add persistence \n",
|
||||
"\n",
|
||||
"You only need to **provide the checkpointer when compiling the parent graph**. LangGraph will automatically propagate the checkpointer to the child subgraphs.\n",
|
||||
"\n",
|
||||
"```python\n",
|
||||
"from langgraph.graph import START, StateGraph\n",
|
||||
"from langgraph.checkpoint.memory import InMemorySaver\n",
|
||||
"from typing_extensions import TypedDict\n",
|
||||
"\n",
|
||||
"class State(TypedDict):\n",
|
||||
" foo: str\n",
|
||||
"\n",
|
||||
"# Subgraph\n",
|
||||
"\n",
|
||||
"def subgraph_node_1(state: State):\n",
|
||||
" return {\"foo\": state[\"foo\"] + \"bar\"}\n",
|
||||
"\n",
|
||||
"subgraph_builder = StateGraph(State)\n",
|
||||
"subgraph_builder.add_node(subgraph_node_1)\n",
|
||||
"subgraph_builder.add_edge(START, \"subgraph_node_1\")\n",
|
||||
"# highlight-next-line\n",
|
||||
"subgraph = subgraph_builder.compile()\n",
|
||||
"\n",
|
||||
"# Parent graph\n",
|
||||
"\n",
|
||||
"builder = StateGraph(State)\n",
|
||||
"# highlight-next-line\n",
|
||||
"builder.add_node(\"node_1\", subgraph)\n",
|
||||
"builder.add_edge(START, \"node_1\")\n",
|
||||
"\n",
|
||||
"checkpointer = InMemorySaver()\n",
|
||||
"# highlight-next-line\n",
|
||||
"graph = builder.compile(checkpointer=checkpointer)\n",
|
||||
"``` \n",
|
||||
"\n",
|
||||
"If you want the subgraph to **have its own memory**, you can compile it `with checkpointer=True`. This is useful in [multi-agent](../../concepts/multi_agent) systems, if you want agents to keep track of their internal message histories:\n",
|
||||
"\n",
|
||||
"```python\n",
|
||||
"subgraph_builder = StateGraph(...)\n",
|
||||
"# highlight-next-line\n",
|
||||
"subgraph = subgraph_builder.compile(checkpointer=True)\n",
|
||||
"```"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## View subgraph state\n",
|
||||
"\n",
|
||||
"When you enable [persistence](../persistence), you can [inspect the graph state](../persistence#manage-checkpoints) (checkpoint) via `graph.get_state(config)`. To view the subgraph state, you can use `graph.get_state(config, subgraphs=True)`.\n",
|
||||
"\n",
|
||||
"!!! important \"Available **only** when interrupted\"\n",
|
||||
"\n",
|
||||
" Subgraph state can only be viewed **when the subgraph is interrupted**. Once you resume the graph, you won't be able to access the subgraph state.\n",
|
||||
"\n",
|
||||
"??? example \"View interrupted subgraph state\"\n",
|
||||
"\n",
|
||||
" ```python\n",
|
||||
" from langgraph.graph import START, StateGraph\n",
|
||||
" from langgraph.checkpoint.memory import InMemorySaver\n",
|
||||
" from langgraph.types import interrupt, Command\n",
|
||||
" from typing_extensions import TypedDict\n",
|
||||
" \n",
|
||||
" class State(TypedDict):\n",
|
||||
" foo: str\n",
|
||||
" \n",
|
||||
" # Subgraph\n",
|
||||
" \n",
|
||||
" def subgraph_node_1(state: State):\n",
|
||||
" # highlight-next-line\n",
|
||||
" value = interrupt(\"Provide value:\")\n",
|
||||
" return {\"foo\": state[\"foo\"] + value}\n",
|
||||
" \n",
|
||||
" subgraph_builder = StateGraph(State)\n",
|
||||
" subgraph_builder.add_node(subgraph_node_1)\n",
|
||||
" subgraph_builder.add_edge(START, \"subgraph_node_1\")\n",
|
||||
" \n",
|
||||
" subgraph = subgraph_builder.compile()\n",
|
||||
" \n",
|
||||
" # Parent graph\n",
|
||||
" \n",
|
||||
" builder = StateGraph(State)\n",
|
||||
" # highlight-next-line\n",
|
||||
" builder.add_node(\"node_1\", subgraph)\n",
|
||||
" builder.add_edge(START, \"node_1\")\n",
|
||||
" \n",
|
||||
" checkpointer = InMemorySaver()\n",
|
||||
" # highlight-next-line\n",
|
||||
" graph = builder.compile(checkpointer=checkpointer)\n",
|
||||
" \n",
|
||||
" config = {\"configurable\": {\"thread_id\": \"1\"}}\n",
|
||||
" \n",
|
||||
" graph.invoke({\"foo\": \"\"}, config)\n",
|
||||
" parent_state = graph.get_state(config)\n",
|
||||
" # highlight-next-line\n",
|
||||
" subgraph_state = graph.get_state(config, subgraphs=True).tasks[0].state # (1)!\n",
|
||||
" \n",
|
||||
" # resume the subgraph\n",
|
||||
" graph.invoke(Command(resume=\"bar\"), config)\n",
|
||||
" ```\n",
|
||||
" \n",
|
||||
" 1. This will be available only when the subgraph is interrupted. Once you resume the graph, you won't be able to access the subgraph state."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Stream subgraph outputs\n",
|
||||
"\n",
|
||||
"To include outputs from [subgraphs](../concepts/low_level.md#subgraphs) in the streamed outputs, you can set `subgraphs=True` in the `.stream()` method of the parent graph. This will stream outputs from both the parent graph and any subgraphs.\n",
|
||||
"\n",
|
||||
"```python\n",
|
||||
"for chunk in graph.stream(\n",
|
||||
" {\"foo\": \"foo\"},\n",
|
||||
" # highlight-next-line\n",
|
||||
" subgraphs=True, # (1)!\n",
|
||||
" stream_mode=\"updates\",\n",
|
||||
"):\n",
|
||||
" print(chunk)\n",
|
||||
"```\n",
|
||||
"\n",
|
||||
"1. Set `subgraphs=True` to stream outputs from subgraphs.\n",
|
||||
"\n",
|
||||
"??? example \"Stream from subgraphs\"\n",
|
||||
"\n",
|
||||
" ```python\n",
|
||||
" from typing_extensions import TypedDict\n",
|
||||
" from langgraph.graph.state import StateGraph, START\n",
|
||||
"\n",
|
||||
" # Define subgraph\n",
|
||||
" class SubgraphState(TypedDict):\n",
|
||||
" foo: str\n",
|
||||
" bar: str\n",
|
||||
" \n",
|
||||
" def subgraph_node_1(state: SubgraphState):\n",
|
||||
" return {\"bar\": \"bar\"}\n",
|
||||
" \n",
|
||||
" def subgraph_node_2(state: SubgraphState):\n",
|
||||
" # note that this node is using a state key ('bar') that is only available in the subgraph\n",
|
||||
" # and is sending update on the shared state key ('foo')\n",
|
||||
" return {\"foo\": state[\"foo\"] + state[\"bar\"]}\n",
|
||||
" \n",
|
||||
" subgraph_builder = StateGraph(SubgraphState)\n",
|
||||
" subgraph_builder.add_node(subgraph_node_1)\n",
|
||||
" subgraph_builder.add_node(subgraph_node_2)\n",
|
||||
" subgraph_builder.add_edge(START, \"subgraph_node_1\")\n",
|
||||
" subgraph_builder.add_edge(\"subgraph_node_1\", \"subgraph_node_2\")\n",
|
||||
" subgraph = subgraph_builder.compile()\n",
|
||||
" \n",
|
||||
" # Define parent graph\n",
|
||||
" class ParentState(TypedDict):\n",
|
||||
" foo: str\n",
|
||||
" \n",
|
||||
" def node_1(state: ParentState):\n",
|
||||
" return {\"foo\": \"hi! \" + state[\"foo\"]}\n",
|
||||
" \n",
|
||||
" builder = StateGraph(ParentState)\n",
|
||||
" builder.add_node(\"node_1\", node_1)\n",
|
||||
" # highlight-next-line\n",
|
||||
" builder.add_node(\"node_2\", subgraph)\n",
|
||||
" builder.add_edge(START, \"node_1\")\n",
|
||||
" builder.add_edge(\"node_1\", \"node_2\")\n",
|
||||
" graph = builder.compile()\n",
|
||||
"\n",
|
||||
" for chunk in graph.stream(\n",
|
||||
" {\"foo\": \"foo\"},\n",
|
||||
" stream_mode=\"updates\",\n",
|
||||
" # highlight-next-line\n",
|
||||
" subgraphs=True, # (1)!\n",
|
||||
" ):\n",
|
||||
" print(chunk)\n",
|
||||
" ```\n",
|
||||
" \n",
|
||||
" 1. Set `subgraphs=True` to stream outputs from subgraphs.\n",
|
||||
"\n",
|
||||
" ```\n",
|
||||
" ((), {'node_1': {'foo': 'hi! foo'}})\n",
|
||||
" (('node_2:e58e5673-a661-ebb0-70d4-e298a7fc28b7',), {'subgraph_node_1': {'bar': 'bar'}})\n",
|
||||
" (('node_2:e58e5673-a661-ebb0-70d4-e298a7fc28b7',), {'subgraph_node_2': {'foo': 'hi! foobar'}})\n",
|
||||
" ((), {'node_2': {'foo': 'hi! foobar'}})\n",
|
||||
" ```"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.12.3"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 4
|
||||
}
|
||||
@@ -0,0 +1,453 @@
|
||||
# Use subgraphs
|
||||
|
||||
This guide explains the mechanics of using [subgraphs](../concepts/subgraphs.md). A common application of subgraphs is to build [multi-agent](../concepts/multi_agent.md) systems.
|
||||
|
||||
When adding subgraphs, you need to define how the parent graph and the subgraph communicate:
|
||||
|
||||
* [Shared state schemas](#shared-state-schemas) — parent and subgraph have **shared state keys** in their state [schemas](../concepts/low_level.md#state)
|
||||
* [Different state schemas](#different-state-schemas) — **no shared state keys** in parent and subgraph [schemas](../concepts/low_level.md#state)
|
||||
|
||||
## Setup
|
||||
|
||||
```bash
|
||||
pip install -U langgraph
|
||||
```
|
||||
|
||||
!!! tip "Set up LangSmith for LangGraph development"
|
||||
Sign up for [LangSmith](https://smith.langchain.com) to quickly spot issues and improve the performance of your LangGraph projects. LangSmith lets you use trace data to debug, test, and monitor your LLM apps built with LangGraph — read more about how to get started [here](https://docs.smith.langchain.com).
|
||||
|
||||
## Shared state schemas
|
||||
|
||||
A common case is for the parent graph and subgraph to communicate over a shared state key (channel) in the [schema](../concepts/low_level.md#state). For example, in [multi-agent](../concepts/multi_agent.md) systems, the agents often communicate over a shared [messages](https://langchain-ai.github.io/langgraph/concepts/low_level.md#why-use-messages) key.
|
||||
|
||||
If your subgraph shares state keys with the parent graph, you can follow these steps to add it to your graph:
|
||||
|
||||
1. Define the subgraph workflow (`subgraph_builder` in the example below) and compile it
|
||||
2. Pass compiled subgraph to the `.add_node` method when defining the parent graph workflow
|
||||
|
||||
```python
|
||||
from typing_extensions import TypedDict
|
||||
from langgraph.graph.state import StateGraph, START
|
||||
|
||||
class State(TypedDict):
|
||||
foo: str
|
||||
|
||||
# Subgraph
|
||||
|
||||
def subgraph_node_1(state: State):
|
||||
return {"foo": "hi! " + state["foo"]}
|
||||
|
||||
subgraph_builder = StateGraph(State)
|
||||
subgraph_builder.add_node(subgraph_node_1)
|
||||
subgraph_builder.add_edge(START, "subgraph_node_1")
|
||||
subgraph = subgraph_builder.compile()
|
||||
|
||||
# Parent graph
|
||||
|
||||
builder = StateGraph(State)
|
||||
builder.add_node("node_1", subgraph)
|
||||
builder.add_edge(START, "node_1")
|
||||
graph = builder.compile()
|
||||
```
|
||||
|
||||
??? example "Full example: shared state schemas"
|
||||
|
||||
```python
|
||||
from typing_extensions import TypedDict
|
||||
from langgraph.graph.state import StateGraph, START
|
||||
|
||||
# Define subgraph
|
||||
class SubgraphState(TypedDict):
|
||||
foo: str # (1)!
|
||||
bar: str # (2)!
|
||||
|
||||
def subgraph_node_1(state: SubgraphState):
|
||||
return {"bar": "bar"}
|
||||
|
||||
def subgraph_node_2(state: SubgraphState):
|
||||
# note that this node is using a state key ('bar') that is only available in the subgraph
|
||||
# and is sending update on the shared state key ('foo')
|
||||
return {"foo": state["foo"] + state["bar"]}
|
||||
|
||||
subgraph_builder = StateGraph(SubgraphState)
|
||||
subgraph_builder.add_node(subgraph_node_1)
|
||||
subgraph_builder.add_node(subgraph_node_2)
|
||||
subgraph_builder.add_edge(START, "subgraph_node_1")
|
||||
subgraph_builder.add_edge("subgraph_node_1", "subgraph_node_2")
|
||||
subgraph = subgraph_builder.compile()
|
||||
|
||||
# Define parent graph
|
||||
class ParentState(TypedDict):
|
||||
foo: str
|
||||
|
||||
def node_1(state: ParentState):
|
||||
return {"foo": "hi! " + state["foo"]}
|
||||
|
||||
builder = StateGraph(ParentState)
|
||||
builder.add_node("node_1", node_1)
|
||||
builder.add_node("node_2", subgraph)
|
||||
builder.add_edge(START, "node_1")
|
||||
builder.add_edge("node_1", "node_2")
|
||||
graph = builder.compile()
|
||||
|
||||
for chunk in graph.stream({"foo": "foo"}):
|
||||
print(chunk)
|
||||
```
|
||||
|
||||
1. This key is shared with the parent graph state
|
||||
2. This key is private to the `SubgraphState` and is not visible to the parent graph
|
||||
|
||||
```
|
||||
{'node_1': {'foo': 'hi! foo'}}
|
||||
{'node_2': {'foo': 'hi! foobar'}}
|
||||
```
|
||||
|
||||
## Different state schemas
|
||||
|
||||
For more complex systems you might want to define subgraphs that have a **completely different schema** from the parent graph (no shared keys). For example, you might want to keep a private message history for each of the agents in a [multi-agent](../concepts/multi_agent.md) system.
|
||||
|
||||
If that's the case for your application, you need to define a node **function that invokes the subgraph**. This function needs to transform the input (parent) state to the subgraph state before invoking the subgraph, and transform the results back to the parent state before returning the state update from the node.
|
||||
|
||||
```python
|
||||
from typing_extensions import TypedDict
|
||||
from langgraph.graph.state import StateGraph, START
|
||||
|
||||
class SubgraphState(TypedDict):
|
||||
bar: str
|
||||
|
||||
# Subgraph
|
||||
|
||||
def subgraph_node_1(state: SubgraphState):
|
||||
return {"bar": "hi! " + state["bar"]}
|
||||
|
||||
subgraph_builder = StateGraph(SubgraphState)
|
||||
subgraph_builder.add_node(subgraph_node_1)
|
||||
subgraph_builder.add_edge(START, "subgraph_node_1")
|
||||
subgraph = subgraph_builder.compile()
|
||||
|
||||
# Parent graph
|
||||
|
||||
class State(TypedDict):
|
||||
foo: str
|
||||
|
||||
def call_subgraph(state: State):
|
||||
subgraph_output = subgraph.invoke({"bar": state["foo"]}) # (1)!
|
||||
return {"foo": subgraph_output["bar"]} # (2)!
|
||||
|
||||
builder = StateGraph(State)
|
||||
builder.add_node("node_1", call_subgraph)
|
||||
builder.add_edge(START, "node_1")
|
||||
graph = builder.compile()
|
||||
```
|
||||
|
||||
1. Transform the state to the subgraph state
|
||||
2. Transform response back to the parent state
|
||||
|
||||
??? example "Full example: different state schemas"
|
||||
|
||||
```python
|
||||
from typing_extensions import TypedDict
|
||||
from langgraph.graph.state import StateGraph, START
|
||||
|
||||
# Define subgraph
|
||||
class SubgraphState(TypedDict):
|
||||
# note that none of these keys are shared with the parent graph state
|
||||
bar: str
|
||||
baz: str
|
||||
|
||||
def subgraph_node_1(state: SubgraphState):
|
||||
return {"baz": "baz"}
|
||||
|
||||
def subgraph_node_2(state: SubgraphState):
|
||||
return {"bar": state["bar"] + state["baz"]}
|
||||
|
||||
subgraph_builder = StateGraph(SubgraphState)
|
||||
subgraph_builder.add_node(subgraph_node_1)
|
||||
subgraph_builder.add_node(subgraph_node_2)
|
||||
subgraph_builder.add_edge(START, "subgraph_node_1")
|
||||
subgraph_builder.add_edge("subgraph_node_1", "subgraph_node_2")
|
||||
subgraph = subgraph_builder.compile()
|
||||
|
||||
# Define parent graph
|
||||
class ParentState(TypedDict):
|
||||
foo: str
|
||||
|
||||
def node_1(state: ParentState):
|
||||
return {"foo": "hi! " + state["foo"]}
|
||||
|
||||
def node_2(state: ParentState):
|
||||
response = subgraph.invoke({"bar": state["foo"]}) # (1)!
|
||||
return {"foo": response["bar"]} # (2)!
|
||||
|
||||
|
||||
builder = StateGraph(ParentState)
|
||||
builder.add_node("node_1", node_1)
|
||||
builder.add_node("node_2", node_2)
|
||||
builder.add_edge(START, "node_1")
|
||||
builder.add_edge("node_1", "node_2")
|
||||
graph = builder.compile()
|
||||
|
||||
for chunk in graph.stream({"foo": "foo"}, subgraphs=True):
|
||||
print(chunk)
|
||||
```
|
||||
|
||||
1. Transform the state to the subgraph state
|
||||
2. Transform response back to the parent state
|
||||
|
||||
```
|
||||
((), {'node_1': {'foo': 'hi! foo'}})
|
||||
(('node_2:9c36dd0f-151a-cb42-cbad-fa2f851f9ab7',), {'grandchild_1': {'my_grandchild_key': 'hi Bob, how are you'}})
|
||||
(('node_2:9c36dd0f-151a-cb42-cbad-fa2f851f9ab7',), {'grandchild_2': {'bar': 'hi! foobaz'}})
|
||||
((), {'node_2': {'foo': 'hi! foobaz'}})
|
||||
```
|
||||
|
||||
??? example "Full example: different state schemas (two levels of subgraphs)"
|
||||
|
||||
This is an example with two levels of subgraphs: parent -> child -> grandchild.
|
||||
|
||||
```python
|
||||
# Grandchild graph
|
||||
from typing_extensions import TypedDict
|
||||
from langgraph.graph.state import StateGraph, START, END
|
||||
|
||||
class GrandChildState(TypedDict):
|
||||
my_grandchild_key: str
|
||||
|
||||
def grandchild_1(state: GrandChildState) -> GrandChildState:
|
||||
# NOTE: child or parent keys will not be accessible here
|
||||
return {"my_grandchild_key": state["my_grandchild_key"] + ", how are you"}
|
||||
|
||||
|
||||
grandchild = StateGraph(GrandChildState)
|
||||
grandchild.add_node("grandchild_1", grandchild_1)
|
||||
|
||||
grandchild.add_edge(START, "grandchild_1")
|
||||
grandchild.add_edge("grandchild_1", END)
|
||||
|
||||
grandchild_graph = grandchild.compile()
|
||||
|
||||
# Child graph
|
||||
class ChildState(TypedDict):
|
||||
my_child_key: str
|
||||
|
||||
def call_grandchild_graph(state: ChildState) -> ChildState:
|
||||
# NOTE: parent or grandchild keys won't be accessible here
|
||||
grandchild_graph_input = {"my_grandchild_key": state["my_child_key"]} # (1)!
|
||||
grandchild_graph_output = grandchild_graph.invoke(grandchild_graph_input)
|
||||
return {"my_child_key": grandchild_graph_output["my_grandchild_key"] + " today?"} # (2)!
|
||||
|
||||
child = StateGraph(ChildState)
|
||||
child.add_node("child_1", call_grandchild_graph) # (3)!
|
||||
child.add_edge(START, "child_1")
|
||||
child.add_edge("child_1", END)
|
||||
child_graph = child.compile()
|
||||
|
||||
# Parent graph
|
||||
class ParentState(TypedDict):
|
||||
my_key: str
|
||||
|
||||
def parent_1(state: ParentState) -> ParentState:
|
||||
# NOTE: child or grandchild keys won't be accessible here
|
||||
return {"my_key": "hi " + state["my_key"]}
|
||||
|
||||
def parent_2(state: ParentState) -> ParentState:
|
||||
return {"my_key": state["my_key"] + " bye!"}
|
||||
|
||||
def call_child_graph(state: ParentState) -> ParentState:
|
||||
child_graph_input = {"my_child_key": state["my_key"]} # (4)!
|
||||
child_graph_output = child_graph.invoke(child_graph_input)
|
||||
return {"my_key": child_graph_output["my_child_key"]} # (5)!
|
||||
|
||||
parent = StateGraph(ParentState)
|
||||
parent.add_node("parent_1", parent_1)
|
||||
parent.add_node("child", call_child_graph) # (6)!
|
||||
parent.add_node("parent_2", parent_2)
|
||||
|
||||
parent.add_edge(START, "parent_1")
|
||||
parent.add_edge("parent_1", "child")
|
||||
parent.add_edge("child", "parent_2")
|
||||
parent.add_edge("parent_2", END)
|
||||
|
||||
parent_graph = parent.compile()
|
||||
|
||||
for chunk in parent_graph.stream({"my_key": "Bob"}, subgraphs=True):
|
||||
print(chunk)
|
||||
```
|
||||
|
||||
1. We're transforming the state from the child state channels (`my_child_key`) to the child state channels (`my_grandchild_key`)
|
||||
2. We're transforming the state from the grandchild state channels (`my_grandchild_key`) back to the child state channels (`my_child_key`)
|
||||
3. We're passing a function here instead of just compiled graph (`grandchild_graph`)
|
||||
4. We're transforming the state from the parent state channels (`my_key`) to the child state channels (`my_child_key`)
|
||||
5. We're transforming the state from the child state channels (`my_child_key`) back to the parent state channels (`my_key`)
|
||||
6. We're passing a function here instead of just a compiled graph (`child_graph`)
|
||||
|
||||
```
|
||||
((), {'parent_1': {'my_key': 'hi Bob'}})
|
||||
(('child:2e26e9ce-602f-862c-aa66-1ea5a4655e3b', 'child_1:781bb3b1-3971-84ce-810b-acf819a03f9c'), {'grandchild_1': {'my_grandchild_key': 'hi Bob, how are you'}})
|
||||
(('child:2e26e9ce-602f-862c-aa66-1ea5a4655e3b',), {'child_1': {'my_child_key': 'hi Bob, how are you today?'}})
|
||||
((), {'child': {'my_key': 'hi Bob, how are you today?'}})
|
||||
((), {'parent_2': {'my_key': 'hi Bob, how are you today? bye!'}})
|
||||
```
|
||||
|
||||
## Add persistence
|
||||
|
||||
You only need to **provide the checkpointer when compiling the parent graph**. LangGraph will automatically propagate the checkpointer to the child subgraphs.
|
||||
|
||||
```python
|
||||
from langgraph.graph import START, StateGraph
|
||||
from langgraph.checkpoint.memory import InMemorySaver
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
class State(TypedDict):
|
||||
foo: str
|
||||
|
||||
# Subgraph
|
||||
|
||||
def subgraph_node_1(state: State):
|
||||
return {"foo": state["foo"] + "bar"}
|
||||
|
||||
subgraph_builder = StateGraph(State)
|
||||
subgraph_builder.add_node(subgraph_node_1)
|
||||
subgraph_builder.add_edge(START, "subgraph_node_1")
|
||||
subgraph = subgraph_builder.compile()
|
||||
|
||||
# Parent graph
|
||||
|
||||
builder = StateGraph(State)
|
||||
builder.add_node("node_1", subgraph)
|
||||
builder.add_edge(START, "node_1")
|
||||
|
||||
checkpointer = InMemorySaver()
|
||||
graph = builder.compile(checkpointer=checkpointer)
|
||||
```
|
||||
|
||||
If you want the subgraph to **have its own memory**, you can compile it `with checkpointer=True`. This is useful in [multi-agent](../concepts/multi_agent.md) systems, if you want agents to keep track of their internal message histories:
|
||||
|
||||
```python
|
||||
subgraph_builder = StateGraph(...)
|
||||
subgraph = subgraph_builder.compile(checkpointer=True)
|
||||
```
|
||||
|
||||
## View subgraph state
|
||||
|
||||
When you enable [persistence](../concepts/persistence.md), you can [inspect the graph state](../concepts/persistence.md#checkpoints) (checkpoint) via `graph.get_state(config)`. To view the subgraph state, you can use `graph.get_state(config, subgraphs=True)`.
|
||||
|
||||
!!! important "Available **only** when interrupted"
|
||||
|
||||
Subgraph state can only be viewed **when the subgraph is interrupted**. Once you resume the graph, you won't be able to access the subgraph state.
|
||||
|
||||
??? example "View interrupted subgraph state"
|
||||
|
||||
```python
|
||||
from langgraph.graph import START, StateGraph
|
||||
from langgraph.checkpoint.memory import InMemorySaver
|
||||
from langgraph.types import interrupt, Command
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
class State(TypedDict):
|
||||
foo: str
|
||||
|
||||
# Subgraph
|
||||
|
||||
def subgraph_node_1(state: State):
|
||||
value = interrupt("Provide value:")
|
||||
return {"foo": state["foo"] + value}
|
||||
|
||||
subgraph_builder = StateGraph(State)
|
||||
subgraph_builder.add_node(subgraph_node_1)
|
||||
subgraph_builder.add_edge(START, "subgraph_node_1")
|
||||
|
||||
subgraph = subgraph_builder.compile()
|
||||
|
||||
# Parent graph
|
||||
|
||||
builder = StateGraph(State)
|
||||
builder.add_node("node_1", subgraph)
|
||||
builder.add_edge(START, "node_1")
|
||||
|
||||
checkpointer = InMemorySaver()
|
||||
graph = builder.compile(checkpointer=checkpointer)
|
||||
|
||||
config = {"configurable": {"thread_id": "1"}}
|
||||
|
||||
graph.invoke({"foo": ""}, config)
|
||||
parent_state = graph.get_state(config)
|
||||
subgraph_state = graph.get_state(config, subgraphs=True).tasks[0].state # (1)!
|
||||
|
||||
# resume the subgraph
|
||||
graph.invoke(Command(resume="bar"), config)
|
||||
```
|
||||
|
||||
1. This will be available only when the subgraph is interrupted. Once you resume the graph, you won't be able to access the subgraph state.
|
||||
|
||||
## Stream subgraph outputs
|
||||
|
||||
To include outputs from subgraphs in the streamed outputs, you can set `subgraphs=True` in the `.stream()` method of the parent graph. This will stream outputs from both the parent graph and any subgraphs.
|
||||
|
||||
```python
|
||||
for chunk in graph.stream(
|
||||
{"foo": "foo"},
|
||||
subgraphs=True, # (1)!
|
||||
stream_mode="updates",
|
||||
):
|
||||
print(chunk)
|
||||
```
|
||||
|
||||
1. Set `subgraphs=True` to stream outputs from subgraphs.
|
||||
|
||||
??? example "Stream from subgraphs"
|
||||
|
||||
```python
|
||||
from typing_extensions import TypedDict
|
||||
from langgraph.graph.state import StateGraph, START
|
||||
|
||||
# Define subgraph
|
||||
class SubgraphState(TypedDict):
|
||||
foo: str
|
||||
bar: str
|
||||
|
||||
def subgraph_node_1(state: SubgraphState):
|
||||
return {"bar": "bar"}
|
||||
|
||||
def subgraph_node_2(state: SubgraphState):
|
||||
# note that this node is using a state key ('bar') that is only available in the subgraph
|
||||
# and is sending update on the shared state key ('foo')
|
||||
return {"foo": state["foo"] + state["bar"]}
|
||||
|
||||
subgraph_builder = StateGraph(SubgraphState)
|
||||
subgraph_builder.add_node(subgraph_node_1)
|
||||
subgraph_builder.add_node(subgraph_node_2)
|
||||
subgraph_builder.add_edge(START, "subgraph_node_1")
|
||||
subgraph_builder.add_edge("subgraph_node_1", "subgraph_node_2")
|
||||
subgraph = subgraph_builder.compile()
|
||||
|
||||
# Define parent graph
|
||||
class ParentState(TypedDict):
|
||||
foo: str
|
||||
|
||||
def node_1(state: ParentState):
|
||||
return {"foo": "hi! " + state["foo"]}
|
||||
|
||||
builder = StateGraph(ParentState)
|
||||
builder.add_node("node_1", node_1)
|
||||
builder.add_node("node_2", subgraph)
|
||||
builder.add_edge(START, "node_1")
|
||||
builder.add_edge("node_1", "node_2")
|
||||
graph = builder.compile()
|
||||
|
||||
for chunk in graph.stream(
|
||||
{"foo": "foo"},
|
||||
stream_mode="updates",
|
||||
subgraphs=True, # (1)!
|
||||
):
|
||||
print(chunk)
|
||||
```
|
||||
|
||||
1. Set `subgraphs=True` to stream outputs from subgraphs.
|
||||
|
||||
```
|
||||
((), {'node_1': {'foo': 'hi! foo'}})
|
||||
(('node_2:e58e5673-a661-ebb0-70d4-e298a7fc28b7',), {'subgraph_node_1': {'bar': 'bar'}})
|
||||
(('node_2:e58e5673-a661-ebb0-70d4-e298a7fc28b7',), {'subgraph_node_2': {'foo': 'hi! foobar'}})
|
||||
((), {'node_2': {'foo': 'hi! foobar'}})
|
||||
|
||||