Compare commits

..
Author SHA1 Message Date
William Fu-Hinthorn 45b91e9a60 Prebuilt release 2025-06-25 18:37:50 -07:00
William FHandGitHub e442a9cb97 Cherry-pick prebuilt (#5204)
fix: [prebuilt] Checks for pre-bound model with builtin tools (#5203)
2025-06-25 18:36:52 -07:00
William Fu-Hinthorn d00181cebd Add doc on MAX_STREAM_CHUNK_SIZE_BYTES 2025-06-25 16:09:27 -07:00
Nuno Campos 13d66e0ebb 0.4.10 2025-06-25 10:41:51 -07:00
Nuno CamposandGitHub 9fcd0d47f5 v0.4.x: Forward compatibility with checkpoints without pending_sends (#5199) 2025-06-25 10:41:10 -07:00
Nuno Campos 4749a168a9 v0.4.x: Forward compatibility with checkpoints without pending_sends 2025-06-25 10:08:14 -07:00
Lauren Hirata Singh 8f285a7463 Add FAQ for nodes executed 2025-06-25 12:30:34 -04:00
Nuno Campos 98c369a0cf 0.4.9 2025-06-24 17:58:00 -07:00
William Fu-Hinthorn f45ee34ca3 Update cli config doc on pip_installer 2025-06-23 16:54:52 -07:00
lc-arjunandGitHub bd206c2fcd docs: fix assistants links (#5172)
* docs: fix assistants links

* fix another page
2025-06-23 13:48:20 -07:00
lc-arjunandGitHub 14ec895046 docs: Fix LGP sdk typo (#5170)
docs: fix typo in sdk docs
2025-06-23 10:15:15 -07:00
hari-dhanushkodiandGitHub fb66736ccb add more docs for lgp deployment metrics (#5168) 2025-06-23 07:11:57 -07:00
Nuno Campos c3544024b9 If FuturesDict callback has been GCed, don't call it 2025-06-17 14:06:54 -07:00
b0d1234737 docs: missing lgp docs (#5130)
* chore: add docs for lgp deployment monitoring (#5104)

* docs: studio evals (#5129)

* docs: studio evals

* docs: added studio evals images (#5076)

* docs: added studio evals images

* Update docs/docs/cloud/how-tos/studio/run_evals.md

Co-authored-by: lc-arjun <arjun@langchain.dev>

* Update docs/docs/cloud/how-tos/studio/run_evals.md

Co-authored-by: lc-arjun <arjun@langchain.dev>

* Update docs/docs/cloud/how-tos/studio/run_evals.md

Co-authored-by: lc-arjun <arjun@langchain.dev>

* docs: updated studio evals

* Update docs/docs/cloud/how-tos/studio/run_evals.md

Co-authored-by: lc-arjun <arjun@langchain.dev>

* docs: removed images

---------

Co-authored-by: lc-arjun <arjun@langchain.dev>

* final changes

* i think its this

---------

Co-authored-by: Marco Perini <perinim.98@gmail.com>

---------

Co-authored-by: hari-dhanushkodi <hari@langchain.dev>
Co-authored-by: Marco Perini <perinim.98@gmail.com>
2025-06-17 13:10:27 -07:00
Lauren Hirata Singh 53e1a238db Remove cookie consent 2025-06-16 18:42:56 -04:00
langchain-infraandGitHub fcdeafd0d1 docs: fix langgraph docs (#5065)
docs: fix config section
2025-06-11 13:23:16 -04:00
langchain-infraandGitHub 28c529feb2 docs: add mount prefix environment variable (#5061) 2025-06-11 11:21:53 -04:00
infra 91ebc8d3ed docs: add mount prefix environment variable 2025-06-11 11:19:40 -04:00
Eugene YurtsevandGitHub 6e08f4c12e v0: port GTM to v0 (#5056)
This was lost when the v0 branch was cut out and docs started being deployed from v0
2025-06-11 10:21:29 -04:00
Nuno CamposandGitHub f2dc0653f1 docs: list CipherProtocol in API (#5048) 2025-06-10 14:28:39 -07:00
Nuno CamposandNuno Campos 67177a5610 docs: list CipherProtocol in API 2025-06-10 14:25:26 -07:00
Asamu DavidandGitHub b1b238c7ea add docs for image_distro cli option (#4981) 2025-06-06 16:32:21 +01:00
David Asamu 598796ef86 add docs for image_distro cli option 2025-06-06 16:26:25 +01:00
Sydney RunkleandGitHub 3c7981201e docs: remove usage of StateGraph(dict) (#4967)
docs: remove references to `StateGraph(dict)` (#4964)

remove StateGraph(dict)
2025-06-04 21:30:39 -04:00
Sydney RunkleandGitHub 109c0dfb93 docs: deploy from v0 branch for now (#4960) (#4961)
only deploy docs on v0
2025-06-04 13:30:34 -04:00
Nuno Campos d7c364c5bb Port step_timeout/GraphBubbleUp fix to v0
See fix and tests in original PR https://github.com/langchain-ai/langgraph/pull/4950
2025-06-03 17:23:45 -07:00
Nuno Campos 746142fb07 One more 2025-06-02 16:16:11 -07:00
Nuno Campos b9c9c32c31 Allow releases from v0 2025-06-02 16:12:54 -07:00
Nuno Campos c89fe4c45d 0.4.8 2025-06-02 16:11:09 -07:00
Nuno CamposandGitHub b0e28851a6 v0: Fix Command(graph=PARENT) when used together w checkpointer=True (#4920) 2025-06-02 16:10:00 -07:00
Nuno Campos 48fb91deda Fix Command(graph=PARENT) when used together w checkpointer=True 2025-06-02 16:02:35 -07:00
Nuno CamposandGitHub efb282a197 Remove SchemaCoercionMapper (#4855) 2025-05-28 10:51:32 -07:00
Nuno Campos 89ce6ea2a8 Remove SchemaCoercionMapper 2025-05-28 10:42:43 -07:00
DHParkandGitHub 1e87312d1f Update graph-api.ipynb (#4824) 2025-05-28 13:39:22 +00:00
vksxandGitHub bcc6485f6c (docs) fix broken links (#4823) 2025-05-28 13:36:48 +00:00
Sydney RunkleandGitHub ce5f248e3b docs: fix typo (#4852)
minor fix
2025-05-28 13:35:17 +00:00
Sydney RunkleandGitHub 5602c29668 prebuilt: release 0.2.2 (#4851)
bump prebuilt
2025-05-28 13:33:39 +00:00
Sydney RunkleandGitHub 19ca6b416b fix: post_model_hook should inject state + store into tool calls if necessary (#4842) 2025-05-27 17:42:20 +00:00
Lauren Hirata SinghandGitHub 2553ae0b87 docs: Fix links (#4807) 2025-05-23 22:34:08 -04:00
Lauren Hirata Singh 3e4b69af3f Fix links 2025-05-23 22:30:43 -04:00
Lauren Hirata SinghandGitHub 0c6367c186 docs: fix link to examples page in readme.md (#4710) 2025-05-23 22:26:30 -04:00
Lauren Hirata SinghandGitHub 99860b5713 Update README.md 2025-05-23 22:12:18 -04:00
Lauren Hirata SinghandGitHub a69860baa6 Merge branch 'main' into fix-examples-link-readme 2025-05-23 22:08:32 -04:00
Lauren Hirata SinghandGitHub 6fc21046cd Update libs/langgraph/README.md 2025-05-23 22:06:43 -04:00
Lauren Hirata SinghandGitHub 754420e9a2 Update libs/langgraph/README.md 2025-05-23 22:03:39 -04:00
Lauren Hirata SinghandGitHub 15126ad827 Create overview.md 2025-05-23 22:02:14 -04:00
芥子观须弥andGitHub 6633173918 Fix: Ensure route function returns "b" to enable a → b → a loop (#4738)
fix: correct route function to return 'b' instead of 'a' when not terminating

This fixes a bug in the graph API how-to where the route function incorrectly returned 'a'. Now it correctly returns 'b' as intended.
2025-05-23 23:56:51 +00:00
Nuno Campos 0139e11ae5 0.4.7 2025-05-23 16:51:48 -07:00
Nuno CamposandGitHub bfbe55ab64 Fix stream mode not respected in subgraphs (#4806) 2025-05-23 16:47:01 -07:00
Nuno Campos 36478eb745 Fix stream mode not respected in subgraphs
- The default applied for subgraphs should be applied only when stream mode arg not passed in
2025-05-23 16:40:51 -07:00
Nuno CamposandGitHub 8fb91569b9 Add tests for stream_events when using imperative api (#4805) 2025-05-23 16:40:38 -07:00
Nuno Campos 9bf6728354 Try to make test less flaky 2025-05-23 16:32:51 -07:00
Nuno Campos 126a8f5bc6 Lock 2025-05-23 16:22:12 -07:00
Nuno Campos 9170f636d0 Lock 2025-05-23 16:14:15 -07:00
Nuno Campos 8207d3fefb Add tests for stream_events when using imperative api 2025-05-23 16:11:12 -07:00
Nuno Campos ade3f372a5 0.4.6 2025-05-23 15:24:07 -07:00
Nuno CamposandGitHub 3a55d1137b Fix exception handling for imperative tasks (#4802) 2025-05-23 15:23:15 -07:00
Nuno Campos bece43dc67 Fix 2025-05-23 15:06:18 -07:00
Nuno Campos 913b8d5e95 Lint 2025-05-23 14:32:45 -07:00
Andrew NguonlyandGitHub 29f6ea7f61 docs: Add warning about immutable deployment types (#4804)
* Add more details about database for deployment types. Clarify that deployment type cannot be changed.

* Add note about Development type disk capacity.
2025-05-23 14:04:46 -07:00
Nuno Campos 3c0d9346c2 Add sync test 2025-05-23 13:51:13 -07:00
Nuno Campos 0ebb78d9b2 Fix 2025-05-23 13:50:11 -07:00
Nuno Campos 70153ceba2 Fix exception handling for imperative tasks
- These exceptions should not be re-raised at end of tick, given they're handled explicitly by the developer in their entrypoint
2025-05-23 12:26:27 -07:00
Sydney RunkleandGitHub a9c87ed8b6 prebuilt: release 0.2.1 (#4801)
lockfile and version updates
2025-05-23 18:07:24 +00:00
Sydney RunkleandGitHub 837fe59e24 prebuilt: support provider builtin tools in create_react_agent (#4800) 2025-05-23 13:58:53 -04:00
Andrew NguonlyandGitHub 596a26461c docs: Add note about Enterprise plan in banner for all self-hosted deployment options. (#4797)
Add note about Enterprise plan in banner for all self-hosted deployment options.
2025-05-22 18:38:06 -07:00
Sydney RunkleandGitHub aff3be03dc prebuilt: release 0.2.0 (#4793) 2025-05-22 17:54:58 +00:00
David DuongandGitHub 1000b81eca feat(langgraph): push_messages should directly write to the state (#4791) 2025-05-22 19:41:51 +02:00
Tat Dat Duong 10c6ed7320 Code review 2025-05-22 19:35:44 +02:00
Tat Dat Duong 28e0e7f3ae feat(langgraph): push_messages should directly write to the state 2025-05-22 19:35:15 +02:00
Sydney RunkleandGitHub 87fa661ac0 temp: remove ToolInterruptNode code (#4792)
remove tool node specific code for post_model_hook release
2025-05-22 13:28:59 -04:00
David DuongandGitHub 3189b8fcda feat(sdk-js): Add rejoining of streams (#4744) 2025-05-22 19:19:07 +02:00
Tat Dat Duong 74b18acfc2 Bump to 0.0.78 2025-05-22 19:08:39 +02:00
Tat Dat Duong 1ff5e2966b Add joinStream method 2025-05-22 19:07:01 +02:00
Diwakar GuptaandGitHub 1ba2b3fba9 Merge branch 'main' into fix-examples-link-readme 2025-05-22 22:34:22 +05:30
Tat Dat Duong 102b1f63f3 Fix assumption on sessionStorage 2025-05-22 19:01:14 +02:00
Tat Dat Duong 74dbccd408 Rename to reconnectOnMount 2025-05-22 18:42:38 +02:00
Tat Dat Duong f5a2410ddc Make useStream more hackable 2025-05-22 18:38:09 +02:00
Sydney RunkleandGitHub 4cade428d8 docs: adding interactive graph widget (#4785) 2025-05-22 12:23:43 -04:00
Tat Dat Duong 5823a659fc use sessionStorage instead 2025-05-22 18:11:38 +02:00
Tat Dat Duong f2c32727e8 Fix invalid states 2025-05-22 18:09:16 +02:00
Tat Dat Duong 9d71d941fd resumable 2025-05-22 17:45:52 +02:00
Tat Dat Duong 0db618ae75 Further cleanup 2025-05-22 17:45:52 +02:00
Tat Dat Duong 49746ab3a3 Code cleanup 2025-05-22 17:45:51 +02:00
Tat Dat Duong 5c7ef9a4fc Fix race condition 2025-05-22 17:45:51 +02:00
Tat Dat Duong 62e688bb37 Add rejoining of streams 2025-05-22 17:45:51 +02:00
Sydney RunkleandGitHub 42eff39cd0 docs: fix top nav (#4783)
fix top nav
2025-05-21 19:30:13 -04:00
David DuongandGitHub 39172f2ff9 feat(graph): add push_message method to push manually to messages / message-tuple stream (#4722) 2025-05-22 01:01:48 +02:00
Nuno CamposandGitHub 0202c83e73 Apply same condition for stream_mode=values in suppress interrupt (#4782) 2025-05-21 15:55:55 -07:00
Tat Dat Duong ab924c72fa Add message state test 2025-05-22 00:49:23 +02:00
Nuno Campos 1833889316 Apply same condition for stream_mode=values in suppress interrupt 2025-05-21 15:23:27 -07:00
Tat Dat Duong 7a6bdb3441 Remove redundant cast 2025-05-22 00:23:26 +02:00
David DuongandGitHub ea7f45dba7 feat(sdk-py): resumable streams (#4765) 2025-05-22 00:19:43 +02:00
Tat Dat Duong d2875cc576 feat(graph): add push_message method to push manually to messages / message-tuple stream 2025-05-22 00:18:12 +02:00
Tat Dat Duong e77197a00f Here as well 2025-05-22 00:13:22 +02:00
Tat Dat Duong 30e6ea7aed Last uv.lock? 2025-05-22 00:13:10 +02:00
Tat Dat Duong 461afe0aa6 Again? 2025-05-22 00:12:40 +02:00
Tat Dat Duong 92f8dde61e uv.lock? 2025-05-22 00:07:56 +02:00
Tat Dat Duong f4f7a79907 Bump to 0.1.70 2025-05-22 00:03:48 +02:00
Tat Dat Duong 9c1267af1a Import re 2025-05-22 00:03:41 +02:00
Tat Dat Duong e0a4420b8e feat(sdk-py): resumable streams 2025-05-22 00:03:41 +02:00
Andrew NguonlyandGitHub 94a8067c12 docs: Remove outdated docs regarding graph construction (#4779)
Remove outdated docs regarding graph construction.
2025-05-21 12:21:32 -07:00
Lauren Hirata SinghandGitHub 957db60d89 docs: fix (#4778) 2025-05-21 14:48:36 -04:00
Lauren Hirata Singh a17efb1120 fix 2025-05-21 14:47:55 -04:00
Eugene YurtsevandGitHub d4b428de62 docs: improved llms.txt (#4777)
Improved llms.txt
2025-05-21 14:40:01 -04:00
Eugene YurtsevandGitHub fd0b70eb05 docs: improve llms.txt to generate title and description based on content (#4775)
Update llms.txt based on content
2025-05-21 14:39:13 -04:00
Lauren Hirata SinghandGitHub b8daf323ac docs: fix redirect (#4776) 2025-05-21 14:35:04 -04:00
Lauren Hirata Singh 2d3a3de1ce docs: fix redirect 2025-05-21 14:34:02 -04:00
Nuno CamposandGitHub 96e2f68b2d Only emit stream values chunks when the output channels have changed (#4774) 2025-05-21 13:09:42 -04:00
Eugene YurtsevandGitHub 364508ff20 docs: Add script to generate llms-txt links from yaml (#4771)
A first pass at the script to fix the immediate issue. Will follow up with a few additional improvements.
2025-05-21 11:54:23 -04:00
Eugene YurtsevandGitHub fa1af5c364 docs: replace llms.txt with updated links (#4772)
This is a stop gap solution to fix broken links.

This PR will be followed up with a better llms.txt file
2025-05-21 11:53:26 -04:00
le-codeur-rapideandGitHub 8ec29b4df7 docs: fix example pregel reducer (#4740) 2025-05-21 10:38:29 -04:00
Sydney RunkleandGitHub 06607e08ea prebuilts hitl: fix branching logic + add structural snapshot tests (#4767) 2025-05-21 09:29:59 -04:00
Diwakar GuptaandGitHub 364fdf5dfe Merge branch 'main' into fix-examples-link-readme 2025-05-21 00:00:09 +05:30
Diwakar GuptaandGitHub fe5d303ccd Merge branch 'main' into fix-examples-link-readme 2025-05-17 13:56:41 +05:30
Diwakar GuptaandGitHub c9fa11ae7d Merge branch 'langchain-ai:main' into fix-examples-link-readme 2025-05-16 16:32:53 +05:30
Diw 988805d60b fix link to examples page in readme.md 2025-05-15 23:11:17 +05:30
108 changed files with 5646 additions and 7125 deletions
+1 -1
View File
@@ -13,7 +13,7 @@ env:
jobs:
build:
if: github.ref == 'refs/heads/main'
if: github.ref == 'refs/heads/main' || github.ref == 'refs/heads/v0'
runs-on: ubuntu-latest
outputs:
+7 -5
View File
@@ -4,9 +4,11 @@ on:
push:
branches:
- main
- v0
pull_request:
branches:
- main
- v0
workflow_dispatch:
permissions:
@@ -82,9 +84,9 @@ jobs:
run: make llms-text
- name: Build site
run: |
# If this is main branch, then we want to download stats. we do this
# If this is v0 branch, then we want to download stats. we do this
# with the env variable DOWNLOAD_STATS=true
if [ "${{ github.ref }}" == "refs/heads/main" ]; then
if [ "${{ github.ref }}" == "refs/heads/v0" ]; then
DOWNLOAD_STATS=true make build-docs
else
make build-docs
@@ -144,8 +146,8 @@ jobs:
fi
- name: Configure GitHub Pages
if: github.ref == 'refs/heads/main'
uses: actions/configure-pages@v4
if: github.ref == 'refs/heads/v0'
uses: actions/configure-pages@v5
- name: Upload Pages Artifact
# if: github.ref == 'refs/heads/main'
@@ -154,6 +156,6 @@ jobs:
path: ./docs/site/
- name: Deploy to GitHub Pages
if: github.ref == 'refs/heads/main'
if: github.ref == 'refs/heads/v0'
id: deployment
uses: actions/deploy-pages@v4
+1 -1
View File
@@ -13,7 +13,7 @@ env:
jobs:
build:
if: github.ref == 'refs/heads/main'
if: github.ref == 'refs/heads/main' || github.ref == 'refs/heads/v0'
runs-on: ubuntu-latest
outputs:
+1 -1
View File
@@ -74,7 +74,7 @@ While LangGraph can be used standalone, it also integrates seamlessly with any L
- [Guides](https://langchain-ai.github.io/langgraph/how-tos/): Quick, actionable code snippets for topics such as streaming, adding memory & persistence, and design patterns (e.g. branching, subgraphs, etc.).
- [Reference](https://langchain-ai.github.io/langgraph/reference/graphs/): Detailed reference on core classes, methods, how to use the graph and checkpointing APIs, and higher-level prebuilt components.
- [Examples](https://langchain-ai.github.io/langgraph/tutorials/): Guided examples on getting started with LangGraph.
- [Examples](https://langchain-ai.github.io/langgraph/tutorials/overview/): Guided examples on getting started with LangGraph.
- [LangChain Academy](https://academy.langchain.com/courses/intro-to-langgraph): Learn the basics of LangGraph in our free, structured course.
- [Templates](https://langchain-ai.github.io/langgraph/concepts/template_applications/): Pre-built reference apps for common agentic workflows (e.g. ReAct agent, memory, retrieval etc.) that can be cloned and adapted.
- [Case studies](https://www.langchain.com/built-with-langgraph): Hear how industry leaders use LangGraph to ship AI applications at scale.
+238 -26
View File
@@ -1,10 +1,19 @@
"""Experimental script to generate consolidated llms text from the docs."""
import asyncio
import glob
import os
from typing import TypedDict, List, Optional
import pydantic
import re
from pydantic import BaseModel, Field
from langchain_core.rate_limiters import InMemoryRateLimiter
import yaml
from langchain.chat_models import init_chat_model
from mkdocs.structure.files import File
from mkdocs.structure.pages import Page
from yaml import SafeLoader
from _scripts.notebook_hooks import _on_page_markdown_with_config
@@ -13,7 +22,49 @@ HERE = os.path.dirname(os.path.abspath(__file__))
SOURCE_DIR = os.path.abspath(os.path.join(os.path.dirname(HERE), "docs"))
def _make_llms_text(output_file: str) -> str:
async def convert_ipynb_to_md(file_path: str) -> Optional[str]:
"""Process a file (markdown or notebook) to markdown format.
Args:
file_path: Path to the file to process
Returns:
Processed markdown content if successful, None otherwise
"""
rel_path = os.path.relpath(file_path, SOURCE_DIR)
# Create File and Page objects to match mkdocs structure
file_obj = File(
path=rel_path, src_dir=SOURCE_DIR, dest_dir="", use_directory_urls=True
)
page = Page(
title="",
file=file_obj,
config={},
)
try:
# Read raw content
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
# Convert to markdown without logic to resolve API references
processed_content = _on_page_markdown_with_config(
content, page, add_api_references=False, remove_base64_images=True
)
# Remove self-closing img tags <img ... />
processed_content = re.sub(r"<img[^>]*/>", "", processed_content)
# Remove img tags with content <img ...>...</img>
processed_content = re.sub(
r"<img[^>]*>.*?</img>", "", processed_content, flags=re.DOTALL
)
return processed_content
except Exception as e:
print(f"Error processing file {file_path}: {e}")
return None
async def generate_full_llms_text(output_file: str) -> None:
"""Generate a consolidated text file from markdown/notebook files for LLM training.
Args:
@@ -21,11 +72,9 @@ def _make_llms_text(output_file: str) -> str:
"""
# Collect all markdown and notebook files
all_files = glob.glob(os.path.join(SOURCE_DIR, "how-tos/*.md"), recursive=True)
all_files.extend(
glob.glob(os.path.join(SOURCE_DIR, "how-tos/*.ipynb"), recursive=True)
)
# Add all concepts
all_files.extend(
glob.glob(os.path.join(SOURCE_DIR, "concepts/*.md"), recursive=True)
)
@@ -35,30 +84,14 @@ def _make_llms_text(output_file: str) -> str:
all_content = []
# Process each file
for file_path in all_files:
print(f"Processing {file_path}")
rel_path = os.path.relpath(file_path, SOURCE_DIR)
# Process files concurrently
tasks = [convert_ipynb_to_md(file_path) for file_path in all_files]
results = await asyncio.gather(*tasks)
# Create File and Page objects to match mkdocs structure
file_obj = File(
path=rel_path, src_dir=SOURCE_DIR, dest_dir="", use_directory_urls=True
)
page = Page(
title="",
file=file_obj,
config={},
)
# Read raw content
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
# Convert to markdown without logic to resolve API references
processed_content = _on_page_markdown_with_config(
content, page, add_api_references=False, remove_base64_images=True
)
# Combine results with file paths
for file_path, processed_content in zip(all_files, results):
if processed_content:
rel_path = os.path.relpath(file_path, SOURCE_DIR)
# Add file name
all_content.append(f"---\n{rel_path}\n---")
# Add content
@@ -69,6 +102,168 @@ def _make_llms_text(output_file: str) -> str:
f.write("\n\n".join(all_content))
def no_op_constructor(*args):
"""No-op"""
SafeLoader.add_multi_constructor(
"tag:yaml.org,2002:python/name",
no_op_constructor,
)
class NavItem(TypedDict):
title: str
url: str
hierarchy: tuple[str, ...]
description: str
def _flatten_nav(
nav: list[dict[str, str | list] | str], path: tuple[str, ...] = ()
) -> list[NavItem]:
flat: List[NavItem] = []
for item in nav:
if isinstance(item, dict):
for title, node in item.items():
new_path = path + (title,)
if isinstance(node, str):
# Leaf page
flat.append(
{
"title": title,
"url": node,
"hierarchy": new_path,
"description": "",
}
)
elif isinstance(node, list):
# Dive in, carrying along the updated path
flat.extend(_flatten_nav(node, new_path))
else:
raise TypeError(
f"Unexpected node type {type(node)} under {title!r}"
)
elif isinstance(item, str):
# Bare string entry → use itself as title, and as URL
new_path = path + (item,)
flat.append(
{"title": item, "url": item, "hierarchy": new_path, "description": ""}
)
else:
raise TypeError(f"Unexpected item type {type(item)} in nav")
return flat
class PageInfo(BaseModel):
title: str = Field(description="The title of the page")
description: str = Field(
description="A short description of the page no longer than 3 sentences "
"explaining the kind of content that can be found in the page."
)
async def process_nav_items(nav_items: list[NavItem]) -> list[NavItem]:
"""Open the contents of each nav item and come up with a better title and description."""
rate_limiter = InMemoryRateLimiter(requests_per_second=10)
model = init_chat_model("gpt-4o-mini", temperature=0.0, rate_limiter=rate_limiter)
model = model.with_structured_output(PageInfo)
async def process_single_item(item: NavItem) -> NavItem:
path = item["url"]
file_path = os.path.join(SOURCE_DIR, path)
# Process the file content (handles both markdown and notebooks)
if path.endswith(".ipynb"):
content = await convert_ipynb_to_md(file_path)
else:
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
if not content:
return item
# Generate a better title and description
response = await model.ainvoke(
[
{
"role": "system",
"content": "You are a technical documentation writer. "
"You are given a markdown page of documentation. "
"Please come up with an appropriate title and "
"description for the page. The description should "
"be a short summary of the page content that is "
"no longer than 3 sentences.",
},
{
"role": "user",
"content": "The markdown page is as follows:\n\n" + content,
},
]
)
return {
"title": response.title,
"url": item["url"],
"hierarchy": item["hierarchy"],
"description": response.description,
}
# Remove any items that start with http:// or https:// looking only for
# local file at this stages.
nav_items = [
item for item in nav_items if not item["url"].startswith(("http://", "https://"))
]
# Process items in parallel
tasks = [process_single_item(item) for item in nav_items]
new_nav_items = await asyncio.gather(*tasks)
return new_nav_items
async def generate_nav_links_text(
output_file: str, *, replace_links: bool = False
) -> None:
"""Generate llms.txt from mkdocs.yaml."""
# Get path to mkdocs.yaml relative to this script
script_dir = os.path.dirname(os.path.abspath(__file__))
mkdocs_path = os.path.join(os.path.dirname(script_dir), "mkdocs.yml")
# Load and parse yaml
with open(mkdocs_path, "r") as f:
config = yaml.safe_load(f)
# Extract nav section
nav = config.get("nav", [])
flattened = _flatten_nav(nav)
processed_nav = await process_nav_items(flattened)
with open(output_file, "w") as f:
current_section = None
for item in processed_nav:
# Get the top-level section (first item in hierarchy)
section = item["hierarchy"][0]
if section not in {"Guides", "Examples", "Resources"}:
continue
# If we're starting a new section, add a heading
if section != current_section:
f.write(f"\n# {section}\n\n")
current_section = section
title = item["title"]
# Process URL based on replace_links flag
url = item["url"]
if replace_links:
# Remove .md extension and ensure single trailing slash
url = url.removesuffix(".md")
url = url.removesuffix(".ipynb")
url = url.rstrip("/") + "/"
url = f"https://langchain-ai.github.io/langgraph/{url}"
f.write(f"- [{title}]({url}): {item['description']}\n")
if __name__ == "__main__":
import argparse
@@ -78,6 +273,23 @@ if __name__ == "__main__":
)
)
parser.add_argument("output_file", help="Path to output the consolidated text file")
parser.add_argument(
"--link-only",
action="store_true",
help="Only include link references in the output",
)
parser.add_argument(
"--replace-links",
action="store_true",
help="Replace markdown links with full URLs in the output",
)
args = parser.parse_args()
_make_llms_text(args.output_file)
if args.link_only:
coro = generate_nav_links_text(
args.output_file, replace_links=args.replace_links
)
else:
coro = generate_full_llms_text(args.output_file)
asyncio.run(coro)
+57 -5
View File
@@ -1,9 +1,16 @@
"""mkdocs hooks for adding custom logic to documentation pipeline.
Lifecycle events: https://www.mkdocs.org/dev-guide/plugins/#events
"""
import logging
import os
import posixpath
import re
from typing import Any, Dict
from bs4 import BeautifulSoup
from mkdocs.config.defaults import MkDocsConfig
from mkdocs.structure.files import Files, File
from mkdocs.structure.pages import Page
@@ -71,7 +78,7 @@ REDIRECT_MAP = {
"cloud/faq/studio.md": "concepts/langgraph_studio.md#studio-faqs",
"cloud/how-tos/human_in_the_loop_edit_state.md": "cloud/how-tos/add-human-in-the-loop.md",
"cloud/how-tos/human_in_the_loop_user_input.md": "cloud/how-tos/add-human-in-the-loop.md",
"concepts/platform_architecture.md": "langgraph/concepts/langgraph_cloud#architecture",
"concepts/platform_architecture.md": "concepts/langgraph_cloud#architecture",
# cloud streaming redirects
"cloud/how-tos/stream_values.md": "cloud/how-tos/streaming.md#stream-graph-state",
"cloud/how-tos/stream_updates.md": "cloud/how-tos/streaming.md#stream-graph-state",
@@ -101,8 +108,7 @@ REDIRECT_MAP = {
"how-tos/deploy-self-hosted.md": "cloud/deployment/self_hosted_data_plane.md",
"concepts/self_hosted.md": "concepts/langgraph_self_hosted_data_plane.md",
# assistant redirects
"cloud/how-tos/assistant_versioning.md": "cloud/how-tos/configuration_cloud.md"
"cloud/how-tos/assistant_versioning.md": "cloud/how-tos/configuration_cloud.md",
}
@@ -292,7 +298,7 @@ Redirecting...
"""
def write_html(site_dir, old_path, new_path):
def _write_html(site_dir, old_path, new_path):
"""Write an HTML file in the site_dir with a meta redirect to the new page"""
# Determine all relevant paths
old_path_abs = os.path.join(site_dir, old_path)
@@ -308,6 +314,52 @@ def write_html(site_dir, old_path, new_path):
f.write(content)
def _inject_gtm(html: str) -> str:
"""Inject Google Tag Manager code into the HTML.
Code to inject Google Tag Manager noscript tag immediately after <body>.
This is done via hooks rather than via a template because the MkDocs material
theme does not seem to allow placing the code immediately after the <body> tag
without modifying the template files directly.
Args:
html: The HTML content to modify.
Returns:
The modified HTML content with GTM code injected.
"""
# Code was copied from Google Tag Manager setup instructions.
gtm_code = """
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-T35S4S46"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
"""
soup = BeautifulSoup(html, "html.parser")
body = soup.body
if body:
# Insert the GTM code as raw HTML at the top of <body>
body.insert(0, BeautifulSoup(gtm_code, "html.parser"))
return str(soup)
else:
return html # fallback if no <body> found
def on_post_page(output: str, page: Page, config: MkDocsConfig) -> str:
"""Inject Google Tag Manager noscript tag immediately after <body>.
Args:
output: The HTML output of the page.
page: The page instance.
config: The MkDocs configuration object.
Returns:
modified HTML output with GTM code injected.
"""
return _inject_gtm(output)
# Create HTML files for redirects after site dir has been built
def on_post_build(config):
use_directory_urls = config.get("use_directory_urls")
@@ -324,4 +376,4 @@ def on_post_build(config):
+ hash
+ suffix
)
write_html(config["site_dir"], old_html_path, new_html_path)
_write_html(config["site_dir"], old_html_path, new_html_path)
+1 -1
View File
@@ -15,7 +15,7 @@ This guide shows you how to set up and use LangGraph's **prebuilt**, **reusable*
Before you start this tutorial, ensure you have the following:
- An [Anthropic](https://console.anthropic.com/settings/admin-keys) API key
- An [Anthropic](https://console.anthropic.com/settings/keys) API key
## 1. Install dependencies
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 9.3 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 11 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 10 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 12 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 10 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 13 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 12 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 14 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 11 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 12 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 12 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 14 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 12 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 14 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 13 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 16 KiB

+1 -1
View File
@@ -82,7 +82,7 @@ ny_response = agent.invoke(
```
1. The `InMemorySaver` is a checkpointer that stores the agent's state in memory. In a production setting, you would typically use a database or other persistent storage. Please review the [checkpointer documentation](../reference/checkpoints.md) for more options. If you're deploying with **LangGraph Platform**, the platform will provide a production-ready checkpointer for you.
2. The `checkpointer` is passed to the agent. This enables the agent to persist its state across invocations. Please note that
2. The `checkpointer` is passed to the agent. This enables the agent to persist its state across invocations.
3. A unique `thread_id` is provided in the config. This ID is used to identify the conversation session. The value is controlled by the user and can be any string.
4. The agent will continue the conversation using the same `thread_id`. This will allow the agent to infer that the user is asking specifically about the **weather** in New York.
+136
View File
@@ -53,3 +53,139 @@ The high-level components are organized into several packages, each with a speci
| `langmem` | Agent memory management: [**short-term and long-term**](./memory.md) | `pip install -U langmem` |
| `agentevals` | Utilities to [**evaluate agent performance**](./evals.md) | `pip install -U agentevals` |
## Visualize an agent graph
Use the following tool to visualize the graph generated by
[`create_react_agent`][langgraph.prebuilt.chat_agent_executor.create_react_agent]
and to view an outline of the corresponding code.
It allows you to explore the infrastructure of the agent as defined by the presence of:
* [`tools`](../agents/tools.md): A list of tools (functions, APIs, or other callable objects) that the agent can use to perform tasks.
* [`pre_model_hook`](../how-tos/create-react-agent-manage-message-history.ipynb): A function that is called before the model is invoked. It can be used to condense messages or perform other preprocessing tasks.
* `post_model_hook`: A function that is called after the model is invoked. It can be used to implement guardrails, human-in-the-loop flows, or other postprocessing tasks.
* [`response_format`](../agents/agents.md#6-configure-structured-output): A data structure used to constrain the type of the final output, e.g., a `pydantic` `BaseModel`.
<div class="agent-layout">
<div class="agent-graph-features-container">
<div class="agent-graph-features">
<h3 class="agent-section-title">Features</h3>
<label><input type="checkbox" id="tools" checked> <code>tools</code></label>
<label><input type="checkbox" id="pre_model_hook"> <code>pre_model_hook</code></label>
<label><input type="checkbox" id="post_model_hook"> <code>post_model_hook</code></label>
<label><input type="checkbox" id="response_format"> <code>response_format</code></label>
</div>
</div>
<div class="agent-graph-container">
<h3 class="agent-section-title">Graph</h3>
<img id="agent-graph-img" src="../assets/react_agent_graphs/0001.svg" alt="graph image" style="max-width: 100%;"/>
</div>
</div>
The following code snippet shows how to create the above agent (and underlying graph) with
[`create_react_agent`][langgraph.prebuilt.chat_agent_executor.create_react_agent]:
<div class="language-python">
<pre><code id="agent-code" class="language-python"></code></pre>
</div>
<script>
function getCheckedValue(id) {
return document.getElementById(id).checked ? "1" : "0";
}
function getKey() {
return [
getCheckedValue("response_format"),
getCheckedValue("post_model_hook"),
getCheckedValue("pre_model_hook"),
getCheckedValue("tools")
].join("");
}
function generateCodeSnippet({ tools, pre, post, response }) {
const lines = [
"from langgraph.prebuilt import create_react_agent",
"from langchain_openai import ChatOpenAI"
];
if (response) lines.push("from pydantic import BaseModel");
lines.push("", 'model = ChatOpenAI("o4-mini")', "");
if (tools) {
lines.push(
"def tool() -> None:",
' """Testing tool."""',
" ...",
""
);
}
if (pre) {
lines.push(
"def pre_model_hook() -> None:",
' """Pre-model hook."""',
" ...",
""
);
}
if (post) {
lines.push(
"def post_model_hook() -> None:",
' """Post-model hook."""',
" ...",
""
);
}
if (response) {
lines.push(
"class ResponseFormat(BaseModel):",
' """Response format for the agent."""',
" result: str",
""
);
}
lines.push("agent = create_react_agent(");
lines.push(" model,");
if (tools) lines.push(" tools=[tool],");
if (pre) lines.push(" pre_model_hook=pre_model_hook,");
if (post) lines.push(" post_model_hook=post_model_hook,");
if (response) lines.push(" response_format=ResponseFormat,");
lines.push(")", "", "agent.get_graph().draw_mermaid_png()");
return lines.join("\n");
}
async function render() {
const key = getKey();
document.getElementById("agent-graph-img").src = `../assets/react_agent_graphs/${key}.svg`;
const state = {
tools: document.getElementById("tools").checked,
pre: document.getElementById("pre_model_hook").checked,
post: document.getElementById("post_model_hook").checked,
response: document.getElementById("response_format").checked
};
document.getElementById("agent-code").textContent = generateCodeSnippet(state);
}
function initializeWidget() {
render(); // no need for `await` here
document.querySelectorAll(".agent-graph-features input").forEach((input) => {
input.addEventListener("change", render);
});
}
// Init for both full reload and SPA nav (used by MkDocs Material)
window.addEventListener("DOMContentLoaded", initializeWidget);
document$.subscribe(initializeWidget);
</script>
+15 -1
View File
@@ -280,7 +280,21 @@ LangGraph allows access to short-term and long-term memory from tools. See [Memo
## Prebuilt tools
LangChain supports a wide range of prebuilt tool integrations for interacting with APIs, databases, file systems, web data, and more. These tools extend the functionality of agents and enable rapid development.
You can use prebuilt tools from model providers by passing a dictionary with tool specs to the `tools` parameter of `create_react_agent`. For example, to use the `web_search_preview` tool from OpenAI:
```python
from langgraph.prebuilt import create_react_agent
agent = create_react_agent(
model="openai:gpt-4o-mini",
tools=[{"type": "web_search_preview"}]
)
response = agent.invoke(
{"messages": ["What was a positive news story from today?"]}
)
```
Additionally, LangChain supports a wide range of prebuilt tool integrations for interacting with APIs, databases, file systems, web data, and more. These tools extend the functionality of agents and enable rapid development.
You can browse the full list of available integrations in the [LangChain integrations directory](https://python.langchain.com/docs/integrations/tools/).
+19
View File
@@ -0,0 +1,19 @@
{
"0000": "graph TD;\n\t__start__ --> agent;\n\tagent --> __end__;",
"0001": "graph TD;\n\t__start__ --> agent;\n\tagent -.-> __end__;\n\tagent -.-> tools;\n\ttools --> agent;",
"0010": "graph TD;\n\t__start__ --> pre_model_hook;\n\tpre_model_hook --> agent;\n\tagent --> __end__;",
"0011": "graph TD;\n\t__start__ --> pre_model_hook;\n\tagent -.-> __end__;\n\tagent -.-> tools;\n\tpre_model_hook --> agent;\n\ttools --> pre_model_hook;",
"0100": "graph TD;\n\t__start__ --> agent;\n\tagent --> post_model_hook;\n\tpost_model_hook --> __end__;",
"0101": "graph TD;\n\t__start__ --> agent;\n\tagent --> post_model_hook;\n\tpost_model_hook -.-> __end__;\n\tpost_model_hook -.-> agent;\n\tpost_model_hook -.-> tools;\n\ttools --> agent;",
"0110": "graph TD;\n\t__start__ --> pre_model_hook;\n\tagent --> post_model_hook;\n\tpre_model_hook --> agent;\n\tpost_model_hook --> __end__;",
"0111": "graph TD;\n\t__start__ --> pre_model_hook;\n\tagent --> post_model_hook;\n\tpost_model_hook -.-> __end__;\n\tpost_model_hook -.-> pre_model_hook;\n\tpost_model_hook -.-> tools;\n\tpre_model_hook --> agent;\n\ttools --> pre_model_hook;",
"1000": "graph TD;\n\t__start__ --> agent;\n\tagent --> generate_structured_response;\n\tgenerate_structured_response --> __end__;",
"1001": "graph TD;\n\t__start__ --> agent;\n\tagent -.-> generate_structured_response;\n\tagent -.-> tools;\n\ttools --> agent;\n\tgenerate_structured_response --> __end__;",
"1010": "graph TD;\n\t__start__ --> pre_model_hook;\n\tagent --> generate_structured_response;\n\tpre_model_hook --> agent;\n\tgenerate_structured_response --> __end__;",
"1011": "graph TD;\n\t__start__ --> pre_model_hook;\n\tagent -.-> generate_structured_response;\n\tagent -.-> tools;\n\tpre_model_hook --> agent;\n\ttools --> pre_model_hook;\n\tgenerate_structured_response --> __end__;",
"1100": "graph TD;\n\t__start__ --> agent;\n\tagent --> post_model_hook;\n\tpost_model_hook --> generate_structured_response;\n\tgenerate_structured_response --> __end__;",
"1101": "graph TD;\n\t__start__ --> agent;\n\tagent --> post_model_hook;\n\tpost_model_hook -.-> agent;\n\tpost_model_hook -.-> generate_structured_response;\n\tpost_model_hook -.-> tools;\n\ttools --> agent;\n\tgenerate_structured_response --> __end__;",
"1110": "graph TD;\n\t__start__ --> pre_model_hook;\n\tagent --> post_model_hook;\n\tpost_model_hook --> generate_structured_response;\n\tpre_model_hook --> agent;\n\tgenerate_structured_response --> __end__;",
"1111": "graph TD;\n\t__start__ --> pre_model_hook;\n\tagent --> post_model_hook;\n\tpost_model_hook -.-> generate_structured_response;\n\tpost_model_hook -.-> pre_model_hook;\n\tpost_model_hook -.-> tools;\n\tpre_model_hook --> agent;\n\ttools --> pre_model_hook;\n\tgenerate_structured_response --> __end__;"
}
+9
View File
@@ -62,6 +62,15 @@ Starting from the `LangGraph Platform` view...
1. In the panel, select the `Server` tab to view server logs for the revision. Server logs are only available after a revision has been deployed.
1. Within the `Server` tab, adjust the date/time range picker as needed. By default, the date/time range picker is set to the `Last 7 days`.
## View Deployment Metrics
Starting from the <a href="https://smith.langchain.com/" target="_blank">LangSmith UI</a>...
1. In the left-hand navigation panel, select `LangGraph Platform`. The `LangGraph Platform` view contains a list of existing LangGraph Platform deployments.
1. Select an existing deployment to monitor.
1. Select the `Monitoring` tab to view the deployment metrics. See a list of [all available metrics](../../concepts/langgraph_control_plane.md#monitoring).
1. Within the `Monitoring` tab, use the date/time range picker as needed. By default, the date/time range picker is set to the `Last 15 minutes`.
## Interrupt Revision
Interrupting a revision will stop deployment of the revision.
@@ -2,8 +2,8 @@
Before deploying, review the [conceptual guide for the Self-Hosted Control Plane](../../concepts/langgraph_self_hosted_control_plane.md) deployment option.
!!! important "Beta"
The Self-Hosted Control Plane deployment option is currently in beta stage.
!!! info "Important"
The Self-Hosted Control Plane deployment option is currently in beta stage and requires an [Enterprise](../../concepts/plans.md) plan.
## Prerequisites
@@ -30,18 +30,17 @@ Before deploying, review the [conceptual guide for the Self-Hosted Control Plane
1. `LangGraphPlatform CRD`: A CRD for LangGraph Platform deployments. This contains the spec for managing an instance of a LangGraph platform deployment.
1. `operator`: This operator handles changes to your LangGraph Platform CRDs.
1. `host-backend`: This is the [control plane](../../concepts/langgraph_control_plane.md).
1. Two additional images will be used by the chart.
1. Two additional images will be used by the chart. Use the images that are specified in the latest release.
hostBackendImage:
repository: "docker.io/langchain/hosted-langserve-backend"
pullPolicy: IfNotPresent
tag: "0.9.80"
operatorImage:
repository: "docker.io/langchain/langgraph-operator"
pullPolicy: IfNotPresent
tag: "aa9dff4"
1. In your `values.yaml` file, enable the `langgraphPlatform` option. Note that you must also have a valid ingress setup:
1. In your config file for langsmith (usually `langsmith_config.yaml`, enable the `langgraphPlatform` option. Note that you must also have a valid ingress setup:
config:
langgraphPlatform:
enabled: true
@@ -2,8 +2,8 @@
Before deploying, review the [conceptual guide for the Self-Hosted Data Plane](../../concepts/langgraph_self_hosted_data_plane.md) deployment option.
!!! important "Beta"
The Self-Hosted Data Plane deployment option is currently in beta stage.
!!! info "Important"
The Self-Hosted Data Plane deployment option is currently in beta stage and requires an [Enterprise](../../concepts/plans.md) plan.
## Prerequisites
-3
View File
@@ -129,9 +129,6 @@ workflow.add_edge("action", "agent")
graph = workflow.compile()
```
!!! warning "Assign `CompiledGraph` to Variable"
The build process for LangGraph Platform requires that the `CompiledGraph` object be assigned to a variable at the top-level of a Python module (alternatively, you can provide [a function that creates a graph](./graph_rebuild.md)).
Example file directory:
```bash
@@ -155,10 +155,6 @@ const workflow = new StateGraph(MessagesAnnotation)
export const graph = workflow.compile();
```
!!! info "Assign `CompiledGraph` to Variable"
The build process for LangGraph Platform requires that the `CompiledGraph` object be assigned to a variable at the top-level of a JavaScript module (alternatively, you can provide [a function that creates a graph](./graph_rebuild.md)).
Example file directory:
```bash
@@ -142,9 +142,6 @@ workflow.add_edge("action", "agent")
graph = workflow.compile()
```
!!! warning "Assign `CompiledGraph` to Variable"
The build process for LangGraph Platform requires that the `CompiledGraph` object be assigned to a variable at the top-level of a Python module.
Example file directory:
```bash
@@ -2,7 +2,7 @@
!!! info "Prerequisites"
- [Assistants Overview](../../concepts/assistants.md)
- [Assistants Overview](../../../concepts/assistants.md)
LangGraph Studio lets you view, edit, and update your assistants, and allows you to run your graph using these assistant configurations.
@@ -0,0 +1,57 @@
# Run experiments over a dataset
LangGraph Studio supports evaluations by allowing you to run your assistant over a pre-defined LangSmith dataset. This enables you to understand how your application performs over a variety of inputs, compare the results to reference outputs, and score the results using [evaluators](../../../agents/evals.md).
This guide shows you how to run an experiment end-to-end from Studio.
---
## Prerequisites
Before running an experiment, ensure you have the following:
1. **A LangSmith dataset**: Your dataset should contain the inputs you want to test and optionally, reference outputs for comparison.
- The schema for the inputs must match the required input schema for the assistant. For more information on schemas, see [here](../../../concepts/low_level.md#schema).
- For more on creating datasets, see [How to Manage Datasets](https://docs.smith.langchain.com/evaluation/how_to_guides/manage_datasets_in_application#set-up-your-dataset).
2. **(Optional) Evaluators**: You can attach evaluators (e.g., LLM-as-a-Judge, heuristics, or custom functions) to your dataset in LangSmith. These will run automatically after the graph has processed all inputs.
- To learn more, read about [Evaluation Concepts](https://docs.smith.langchain.com/evaluation/concepts#evaluators).
3. **A running application**: The experiment can be run against:
- An application deployed on [LangGraph Platform](../../quick_start.md).
- A locally running application started via the [langgraph-cli](../../../tutorials/langgraph-platform/local-server.md).
---
## Step-by-step guide
### 1. Launch the experiment
Click the **Run experiment** button in the top right corner of the Studio page.
### 2. Select your dataset
In the modal that appears, select the dataset (or a specific dataset split) to use for the experiment and click **Start**.
### 3. Monitor the progress
All of the inputs in the dataset will now be run against the active assistant. Monitor the experiment's progress via the badge in the top right corner.
You can continue to work in Studio while the experiment runs in the background. Click the arrow icon button at any time to navigate to LangSmith and view the detailed experiment results.
---
## Troubleshooting
### "Run experiment" button is disabled
If the "Run experiment" button is disabled, check the following:
- **Deployed application**: If your application is deployed on LangGraph Platform, you may need to create a new revision to enable this feature.
- **Local development server**: If you are running your application locally, make sure you have upgraded to the latest version of the `langgraph-cli` (`pip install -U langgraph-cli`). Additionally, ensure you have tracing enabled by setting the `LANGSMITH_API_KEY` in your project's `.env` file.
### Evaluator results are missing
When you run an experiment, any attached evaluators are scheduled for execution in a queue. If you don't see results immediately, it likely means they are still pending.
+23 -7
View File
@@ -40,15 +40,17 @@ The LangGraph CLI requires a JSON configuration file that follows this [schema](
| Key | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| <span style="white-space: nowrap;">`dependencies`</span> | **Required**. Array of dependencies for LangGraph Platform API server. Dependencies can be one of the following: <ul><li>A single period (`"."`), which will look for local Python packages.</li><li>The directory path where `pyproject.toml`, `setup.py` or `requirements.txt` is located.</br></br>For example, if `requirements.txt` is located in the root of the project directory, specify `"./"`. If it's located in a subdirectory called `local_package`, specify `"./local_package"`. Do not specify the string `"requirements.txt"` itself.</li><li>A Python package name.</li></ul> |
| <span style="white-space: nowrap;">`graphs`</span> | **Required**. Mapping from graph ID to path where the compiled graph or a function that makes a graph is defined. Example: <ul><li>`./your_package/your_file.py:variable`, where `variable` is an instance of `langgraph.graph.state.CompiledStateGraph`</li><li>`./your_package/your_file.py:make_graph`, where `make_graph` is a function that takes a config dictionary (`langchain_core.runnables.RunnableConfig`) and creates an instance of `langgraph.graph.state.StateGraph` / `langgraph.graph.state.CompiledStateGraph`.</li></ul> |
| <span style="white-space: nowrap;">`graphs`</span> | **Required**. Mapping from graph ID to path where the compiled graph or a function that makes a graph is defined. Example: <ul><li>`./your_package/your_file.py:variable`, where `variable` is an instance of `langgraph.graph.state.CompiledStateGraph`</li><li>`./your_package/your_file.py:make_graph`, where `make_graph` is a function that takes a config dictionary (`langchain_core.runnables.RunnableConfig`) and returns an instance of `langgraph.graph.state.StateGraph` or `langgraph.graph.state.CompiledStateGraph`. See [how to rebuild a graph at runtime](../../cloud/deployment/graph_rebuild.md) for more details.</li></ul> |
| <span style="white-space: nowrap;">`auth`</span> | _(Added in v0.0.11)_ Auth configuration containing the path to your authentication handler. Example: `./your_package/auth.py:auth`, where `auth` is an instance of `langgraph_sdk.Auth`. See [authentication guide](../../concepts/auth.md) for details. |
| <span style="white-space: nowrap;">`base_image`</span> | Optional. Base image to use for the LangGraph API server. Defaults to `langchain/langgraph-api` or `langchain/langgraphjs-api`. Use this to pin your builds to a particular version of the langgraph API, such as `"langchain/langgraph-server:0.2"`. See https://hub.docker.com/r/langchain/langgraph-server/tags for more details. (added in `langgraph-cli==0.2.8`) |
| <span style="white-space: nowrap;">`image_distro`</span> | Optional. Linux distribution for the base image. Must be either `"debian"` or `"wolfi"`. If omitted, defaults to `"debian"`. Available in `langgraph-cli>=0.2.11`.|
| <span style="white-space: nowrap;">`env`</span> | Path to `.env` file or a mapping from environment variable to its value. |
| <span style="white-space: nowrap;">`store`</span> | Configuration for adding semantic search and/or time-to-live (TTL) to the BaseStore. Contains the following fields: <ul><li>`index` (optional): Configuration for semantic search indexing with fields `embed`, `dims`, and optional `fields`.</li><li>`ttl` (optional): Configuration for item expiration. An object with optional fields: `refresh_on_read` (boolean, defaults to `true`), `default_ttl` (float, lifespan in **minutes**, defaults to no expiration), and `sweep_interval_minutes` (integer, how often to check for expired items, defaults to no sweeping).</li></ul> |
| <span style="white-space: nowrap;">`ui`</span> | Optional. Named definitions of UI components emitted by the agent, each pointing to a JS/TS file. (added in `langgraph-cli==0.1.84`) |
| <span style="white-space: nowrap;">`python_version`</span> | `3.11`, `3.12`, or `3.13`. Defaults to `3.11`. |
| <span style="white-space: nowrap;">`node_version`</span> | Specify `node_version: 20` to use LangGraph.js. |
| <span style="white-space: nowrap;">`pip_config_file`</span> | Path to `pip` config file. |
| <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&nbsp;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>`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> |
@@ -57,7 +59,7 @@ The LangGraph CLI requires a JSON configuration file that follows this [schema](
| Key | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| <span style="white-space: nowrap;">`graphs`</span> | **Required**. Mapping from graph ID to path where the compiled graph or a function that makes a graph is defined. Example: <ul><li>`./src/graph.ts:variable`, where `variable` is an instance of `CompiledStateGraph`</li><li>`./src/graph.ts:makeGraph`, where `makeGraph` is a function that takes a config dictionary (`LangGraphRunnableConfig`) and creates an instance of `StateGraph` / `CompiledStateGraph`.</li></ul> |
| <span style="white-space: nowrap;">`graphs`</span> | **Required**. Mapping from graph ID to path where the compiled graph or a function that makes a graph is defined. Example: <ul><li>`./src/graph.ts:variable`, where `variable` is an instance of `CompiledStateGraph`</li><li>`./src/graph.ts:makeGraph`, where `makeGraph` is a function that takes a config dictionary (`LangGraphRunnableConfig`) and returns an instance of `StateGraph` or `CompiledStateGraph`. See [how to rebuild a graph at runtime](../../cloud/deployment/graph_rebuild.md) for more details.</li></ul> |
| <span style="white-space: nowrap;">`env`</span> | Path to `.env` file or a mapping from environment variable to its value. |
| <span style="white-space: nowrap;">`store`</span> | Configuration for adding semantic search and/or time-to-live (TTL) to the BaseStore. Contains the following fields: <ul><li>`index` (optional): Configuration for semantic search indexing with fields `embed`, `dims`, and optional `fields`.</li><li>`ttl` (optional): Configuration for item expiration. An object with optional fields: `refresh_on_read` (boolean, defaults to `true`), `default_ttl` (float, lifespan in **minutes**, defaults to no expiration), and `sweep_interval_minutes` (integer, how often to check for expired items, defaults to no sweeping).</li></ul> |
| <span style="white-space: nowrap;">`node_version`</span> | Specify `node_version: 20` to use LangGraph.js. |
@@ -79,6 +81,20 @@ The LangGraph CLI requires a JSON configuration file that follows this [schema](
}
```
#### Using Wolfi Base Images
You can specify the Linux distribution for your base image using the `image_distro` field. Valid options are `debian` or `wolfi`. Wolfi is the recommended option as it provides smaller and more secure images. This is available in `langgraph-cli>=0.2.11`.
```json
{
"dependencies": ["."],
"graphs": {
"chat": "./chat/graph.py:graph"
},
"image_distro": "wolfi"
}
```
#### Adding semantic search to the store
All deployments come with a DB-backed BaseStore. Adding an "index" configuration to your `langgraph.json` will enable [semantic search](../deployment/semantic_search.md) within the BaseStore of your deployment.
@@ -113,7 +129,7 @@ The LangGraph CLI requires a JSON configuration file that follows this [schema](
- `cohere:embed-english-v3.0`: 1024
- `cohere:embed-english-light-v3.0`: 384
- `cohere:embed-multilingual-v3.0`: 1024
- `cohere:embed-multilingual-light-v3.0`: 384
- `cohere:embed-multilingual-light-v3.0`: 384
#### Semantic search with a custom embedding function
@@ -346,8 +362,8 @@ The LangGraph CLI requires a JSON configuration file that follows this [schema](
**Options**
| Option | Default | Description |
| -------------------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| Option | Default | Description |
| -------------------- | ---------------- | --------------------------------------------------------------------------------------------------------------- |
| `--platform TEXT` | | Target platform(s) to build the Docker image for. Example: `langgraph build --platform linux/amd64,linux/arm64` |
| `-t, --tag TEXT` | | **Required**. Tag for the Docker image. Example: `langgraph build -t my-image` |
| `--pull / --no-pull` | `--pull` | Build with latest remote Docker image. Use `--no-pull` for running the LangGraph Platform API server with locally built images. |
@@ -366,8 +382,8 @@ The LangGraph CLI requires a JSON configuration file that follows this [schema](
**Options**
| Option | Default | Description |
| -------------------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| Option | Default | Description |
| -------------------- | ---------------- | --------------------------------------------------------------------------------------------------------------- |
| `--platform TEXT` | | Target platform(s) to build the Docker image for. Example: `langgraph build --platform linux/amd64,linux/arm64` |
| `-t, --tag TEXT` | | **Required**. Tag for the Docker image. Example: `langgraph build -t my-image` |
| `--no-pull` | | Use locally built images. Defaults to `false` to build with latest remote Docker image. |
+21
View File
@@ -123,3 +123,24 @@ Defaults to `''`.
Set `REDIS_CLUSTER` to `True` to enable Redis Cluster mode. When enabled, the system will connect to Redis using cluster mode. This is useful when connecting to a Redis Cluster deployment.
Defaults to `False`.
## `MAX_STREAM_CHUNK_SIZE_BYTES`
!!! info "Available in API Server version 0.2.44+"
This environment variable is supported in API Server version 0.2.44 and above.
Configure the maximum size of a chunk of data that can be added to Redis for streaming events to the client. This is meant to prevent run failure from data that is above the size supported by your redis instance. Default is 128MB (1024 * 1024 * 128).
Set `MAX_STREAM_CHUNK_SIZE_BYTES` to specify the maximum size of a chunk of data that can be sent in a stream. This is useful when connecting to a Redis Cluster deployment.
Defaults to `1024 * 1024`.
## `MOUNT_PREFIX`
!!! info "Only Allowed in Self-Hosted Deployments"
The `MOUNT_PREFIX` environment variable is only allowed in Self-Hosted Deployment models, LangGraph Platform SaaS will not allow this environment variable.
Set `MOUNT_PREFIX` to serve the LangGraph Server under a specific path prefix. This is useful for deployments where the server is behind a reverse proxy or load balancer that requires a specific path prefix.
For example, if the server is to be served under `https://example.com/langgraph`, set `MOUNT_PREFIX` to `/langgraph`.
+4 -4
View File
@@ -40,8 +40,8 @@ For more information, please see:
## Self-Hosted Data Plane
!!! important "Beta"
The Self-Hosted Data Plane deployment option is currently in beta stage.
!!! info "Important"
The Self-Hosted Data Plane deployment option is currently in beta stage and requires an [Enterprise](../concepts/plans.md) plan.
The [Self-Hosted Data Plane](./langgraph_self_hosted_data_plane.md) deployment option is a "hybrid" model for deployment where we manage the [control plane](./langgraph_control_plane.md) in our cloud and you manage the [data plane](./langgraph_data_plane.md) in your cloud. This option provides a way to securely manage your data plane infrastructure, while offloading control plane management to us.
@@ -56,8 +56,8 @@ For more information, please see:
## Self-Hosted Control Plane
!!! important "Beta"
The Self-Hosted Control Plane deployment option is currently in beta stage.
!!! info "Important"
The Self-Hosted Control Plane deployment option is currently in beta stage and requires an [Enterprise](../concepts/plans.md) plan.
The [Self-Hosted Control Plane](./langgraph_self_hosted_control_plane.md) deployment option is a fully self-hosted model for deployment where you manage the [control plane](./langgraph_control_plane.md) and [data plane](./langgraph_data_plane.md) in your cloud. This option give you full control and responsibility of the control plane and data plane infrastructure.
+5 -1
View File
@@ -63,4 +63,8 @@ Yes! LangGraph is totally ambivalent to what LLMs are used under the hood. The m
Yes! You can use the [development version of LangGraph Server](../tutorials/langgraph-platform/local-server.md) to run the backend locally.
This will connect to the studio frontend hosted as part of LangSmith.
If you set an environment variable of `LANGSMITH_TRACING=false` then no traces will be sent to LangSmith.
If you set an environment variable of `LANGSMITH_TRACING=false`, then no traces will be sent to LangSmith.
## What does "nodes executed" mean for LangGraph Platform usage?
**Nodes Executed** is the aggregate number of nodes in a LangGraph application that are called and completed successfully during an invocation of the application. If a node in the graph is not called during execution or ends in an error state, these nodes will not be counted. If a node is called and completes successfully multiple times, each occurrence will be counted.
+23 -6
View File
@@ -19,6 +19,7 @@ From the control plane UI, you can:
- Update a deployment.
- Update environment variables for a deployment.
- View build and server logs of a deployment.
- View deployment metrics such as CPU and memory usage.
- Delete a deployment.
The Control Plane UI is embedded in [LangSmith](https://docs.smith.langchain.com/langgraph_cloud).
@@ -47,17 +48,22 @@ This section describes various features of the control plane.
For simplicity, the control plane offers two deployment types with different resource allocations: `Development` and `Production`.
| **Deployment Type** | **CPU** | **Memory** | **Scaling** |
|---------------------|---------|------------|---------------------|
| Development | 1 CPU | 1 GB | Up to 1 container |
| Production | 2 CPU | 2 GB | Up to 10 containers |
| **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) |
CPU and memory resources are per container.
!!! info "For [Cloud SaaS](../concepts/langgraph_cloud.md)"
!!! 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
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.
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.
### Database Provisioning
@@ -83,6 +89,17 @@ Infrastructure for deployments and revisions are provisioned and deployed asynch
The control plane and [LangGraph Data Plane](./langgraph_data_plane.md) "listener" application coordinate to achieve asynchronous deployments.
### Monitoring
After a deployment is ready, the control plane monitors the deployment and records various metrics, such as:
- CPU and memory usage of the deployment.
- Number of container restarts.
- Number of replicas (this will increase with [autoscaling](../concepts/langgraph_data_plane.md#autoscaling)).
- [Postgres](../concepts/langgraph_data_plane.md#postgres) CPU, memory usage, and disk usage.
These metrics are displayed as charts in the Control Plane UI.
### LangSmith Integration
A [LangSmith](https://docs.smith.langchain.com/) tracing project is automatically created for each deployment. The tracing project has the same name as the deployment. When creating a deployment, the `LANGCHAIN_TRACING` and `LANGSMITH_API_KEY`/`LANGCHAIN_API_KEY` environment variables do not need to be specified; they are set automatically by the control plane.
@@ -2,8 +2,8 @@
There are two versions of the self-hosted deployment: [Self-Hosted Data Plane](./deployment_options.md#self-hosted-data-plane) and [Self-Hosted Control Plane](./deployment_options.md#self-hosted-control-plane).
!!! important "Beta"
The Self-Hosted Control Plane deployment option is currently in beta stage.
!!! info "Important"
The Self-Hosted Control Plane deployment option is currently in beta stage and requires an [Enterprise](../../concepts/plans.md) plan.
## Requirements
@@ -7,8 +7,8 @@ search:
There are two versions of the self-hosted deployment: [Self-Hosted Data Plane](./deployment_options.md#self-hosted-data-plane) and [Self-Hosted Control Plane](./deployment_options.md#self-hosted-control-plane).
!!! important "Beta"
The Self-Hosted Data Plane deployment option is currently in beta stage.
!!! info "Important"
The Self-Hosted Data Plane deployment option is currently in beta stage and requires an [Enterprise](../../concepts/plans.md) plan.
## Requirements
+1 -1
View File
@@ -17,7 +17,7 @@ Use LangGraph Server to create and manage [assistants](assistants.md), [threads]
There are two versions of LangGraph Server:
- `Lite` is a limited version of the LangGraph Server that you can run locally or in a self-hosted manner (up to 1 million nodes executed per year).
- `Lite` is a limited version of the LangGraph Server that you can run locally or in a self-hosted manner (up to 1 million [nodes executed](../concepts/faq.md#what-does-nodes-executed-mean-for-langgraph-platform-usage) per year).
- `Enterprise` is the full version of the LangGraph Server. To use the `Enterprise` version, you must acquire a license key that you will need to specify when running the Docker image. To acquire a license key, please email sales@langchain.dev.
Feature Differences:
+3 -2
View File
@@ -21,9 +21,10 @@ Key features of LangGraph Studio:
- Visualize your graph architecture
- [Run and interact with your agent](../cloud/how-tos/invoke_studio.md)
- [Manage assistants](../cloud/how-tos/studio/manage_assistants.md.md)
- [Manage assistants](../cloud/how-tos/studio/manage_assistants.md)
- [Manage threads](../cloud/how-tos/threads_studio.md)
- [Iterate on prompts](../cloud/how-tos/iterate_graph_studio.md)
- [Run experiments over a dataset](../cloud/how-tos/studio/run_evals.md)
- Manage [long term memory](memory.md)
- Debug agent state via [time travel](time-travel.md)
@@ -41,4 +42,4 @@ Chat mode is a simpler UI for iterating on and testing chat-specific agents. It
## Learn more
- See this guide on how to [get started](../cloud/how-tos/studio/quick_start.md) with LangGraph Studio.
- See this guide on how to [get started](../cloud/how-tos/studio/quick_start.md) with LangGraph Studio.
+9 -3
View File
@@ -197,19 +197,25 @@ In LangGraph, nodes are typically python functions (sync or async) where the **f
Similar to `NetworkX`, you add these nodes to a graph using the [add_node][langgraph.graph.StateGraph.add_node] method:
```python
from typing_extensions import TypedDict
from langchain_core.runnables import RunnableConfig
from langgraph.graph import StateGraph
builder = StateGraph(dict)
class State(TypedDict):
input: str
results: str
builder = StateGraph(State)
def my_node(state: dict, config: RunnableConfig):
def my_node(state: State, config: RunnableConfig):
print("In node: ", config["configurable"]["user_id"])
return {"results": f"Hello, {state['input']}!"}
# The second argument is optional
def my_other_node(state: dict):
def my_other_node(state: State):
return state
+26 -1
View File
@@ -470,9 +470,34 @@ If the checkpointer is used with asynchronous graph execution (i.e. executing th
### Serializer
When checkpointers save the graph state, they need to serialize the channel values in the state. This is done using serializer objects.
When checkpointers save the graph state, they need to serialize the channel values in the state. This is done using serializer objects.
`langgraph_checkpoint` defines [protocol][langgraph.checkpoint.serde.base.SerializerProtocol] for implementing serializers provides a default implementation ([JsonPlusSerializer][langgraph.checkpoint.serde.jsonplus.JsonPlusSerializer]) that handles a wide variety of types, including LangChain and LangGraph primitives, datetimes, enums and more.
#### Encryption
Checkpointers can optionally encrypt all persisted state. To enable this, pass an instance of [`EncryptedSerializer`][langgraph.checkpoint.serde.encrypted.EncryptedSerializer] to the `serde` argument of any `BaseCheckpointSaver` implementation. The easiest way to create an encrypted serializer is via [`from_pycryptodome_aes`][langgraph.checkpoint.serde.encrypted.EncryptedSerializer.from_pycryptodome_aes], which reads the AES key from the `LANGGRAPH_AES_KEY` environment variable (or accepts a `key` argument):
```python
import sqlite3
from langgraph.checkpoint.serde.encrypted import EncryptedSerializer
from langgraph.checkpoint.sqlite import SqliteSaver
serde = EncryptedSerializer.from_pycryptodome_aes() # reads LANGGRAPH_AES_KEY
checkpointer = SqliteSaver(sqlite3.connect("checkpoint.db"), serde=serde)
```
```python
from langgraph.checkpoint.serde.encrypted import EncryptedSerializer
from langgraph.checkpoint.postgres import PostgresSaver
serde = EncryptedSerializer.from_pycryptodome_aes()
checkpointer = PostgresSaver.from_conn_string("postgresql://...", serde=serde)
checkpointer.setup()
```
When running on LangGraph Platform, encryption is automatically enabled whenever `LANGGRAPH_AES_KEY` is present, so you only need to provide the environment variable. Other encryption schemes can be used by implementing [`CipherProtocol`][langgraph.checkpoint.serde.base.CipherProtocol] and supplying it to `EncryptedSerializer`.
## Capabilities
### Human-in-the-loop
+1 -1
View File
@@ -20,7 +20,7 @@ There are three different plans for using it.
| | Developer | Plus | Enterprise |
|------------------------------------------------------------------|---------------------------------------------|-------------------------------------------------------|-----------------------------------------------------|
| Deployment Options | Standalone Container (Lite) | Cloud SaaS | <ul><li>Cloud SaaS</li><li>Self-Hosted Data Plane</li><li>Self-Hosted Control Plane</li><li>Standalone Container (Enterprise)</li></ul> |
| Usage | Free, limited to 1M nodes executed per year | Free while in Beta, will be charged per node executed | Custom |
| Usage | Free, limited to 1M [nodes executed](../concepts/faq.md#what-does-nodes-executed-mean-for-langgraph-platform-usage) per year | See [Pricing](https://www.langchain.com/langgraph-platform-pricing) | Custom |
| APIs for retrieving and updating state and conversational history | ✅ | ✅ | ✅ |
| APIs for retrieving and updating long-term memory | ✅ | ✅ | ✅ |
| Horizontally scalable task queues and servers | ✅ | ✅ | ✅ |
+1 -1
View File
@@ -180,7 +180,7 @@ Below are a few different examples to give you a sense of the Pregel API.
def reducer(current, update):
if current:
return current + " | " + "update"
return current + " | " + update
else:
return update
+1 -1
View File
@@ -5,7 +5,7 @@ search:
# LangGraph SDK
LangGraph Platform provides both a Python SDK for interacting with [LangGraph Server](./langgraph_server.md).
LangGraph Platform provides both a Python and JS SDK for interacting with [LangGraph Server](./langgraph_server.md).
!!! tip "Python SDK reference"
+1 -11
View File
@@ -2235,7 +2235,7 @@
" if termination_condition(state):\n",
" return END\n",
" else:\n",
" return \"a\"\n",
" return \"b\"\n",
"\n",
"builder.add_edge(START, \"a\")\n",
"builder.add_conditional_edges(\"a\", route)\n",
@@ -2950,16 +2950,6 @@
" 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](../../concepts/low_level#schema), you **must** define a [reducer](../../concepts/low_level#reducers) for the key you're updating in the parent graph state. See the example below."
]
},
{
"cell_type": "markdown",
"id": "6be0aeb9-e138-4adc-a1df-5d743a8eb348",
"metadata": {},
"source": [
"!!! important \"State updates with `Command.PARENT`\"\n",
"\n",
" 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](../../concepts/low_level#schema), you **must** define a [reducer](../../concepts/low_level#reducers) for the key you're updating in the parent graph state."
]
},
{
"cell_type": "code",
"execution_count": 6,
+148 -201
View File
@@ -1,202 +1,149 @@
# LangGraph
## Tutorials
[Learn the basics](https://langchain-ai.github.io/langgraph/tutorials/introduction/): LLM should read this page when needing to build a LangGraph chatbot or when learning about chat agents with memory, human-in-the-loop functionality, and state management. This page provides a comprehensive LangGraph quickstart tutorial covering building a support chatbot with web search capability, conversation memory, human review routing, custom state management, and time travel functionality to explore alternative conversation paths.
[Local Deploy](https://langchain-ai.github.io/langgraph/tutorials/langgraph-platform/local-server/): LLM should read this page when setting up a LangGraph app locally using `langgraph dev` and troubleshooting LangGraph server deployment. This page contains a quickstart guide for launching a LangGraph server locally, including installation steps, app creation from templates, environment setup, API testing with Python/JS SDKs, and links to deployment options and further documentation.
[Workflows and Agents](https://langchain-ai.github.io/langgraph/tutorials/workflows/): LLM should read this page when implementing agent systems, designing workflow architectures, or troubleshooting LLM orchestration strategies. The page covers patterns for LLM system design, comparing workflows (predefined paths) vs agents (dynamic control), with implementations of prompt chaining, parallelization, routing, orchestrator-worker, evaluator-optimizer, and agent patterns using both graph and functional APIs in LangGraph.
## Concepts
[Concepts](https://langchain-ai.github.io/langgraph/concepts/): LLM should read this page when needing to understand LangGraph's key concepts or when planning to deploy LangGraph applications. Comprehensive guide covering LangGraph fundamentals (graph primitives, agents, multi-agent systems, breakpoints, persistence), features (time travel, memory, streaming), and LangGraph Platform deployment options (self-hosted, cloud, enterprise).
[Agent architectures](https://langchain-ai.github.io/langgraph/concepts/agentic_concepts/): LLM should read this page when designing agent architectures, implementing control flows for LLM applications, or customizing agent behavior patterns. This page covers different LLM agent architectures including routers, tool calling agents (ReAct), structured outputs, memory systems, planning capabilities, and advanced customization options like human-in-the-loop, parallelization, subgraphs, and reflection mechanisms.
[Application Structure](https://langchain-ai.github.io/langgraph/concepts/application_structure/): LLM should read this page when needing to understand LangGraph application structure, preparing to deploy a LangGraph application, or troubleshooting configuration issues. This page details the structure of LangGraph applications, including required components (graphs, langgraph.json config file, dependency files, optional .env), file organization patterns for Python/JavaScript projects, configuration file format with all supported fields, and how to specify dependencies, graphs, and environment variables.
[Assistants](https://langchain-ai.github.io/langgraph/concepts/assistants/): LLM should read this page when looking for information about LangGraph assistants, understanding assistant configuration in LangGraph Platform, or learning about versioning agent configurations. This page explains LangGraph assistants, which allow developers to modify agent configurations (prompts, models, etc.) without changing graph logic, supports versioning for tracking changes, and is available only in LangGraph Platform (not open source).
[Authentication & Access Control](https://langchain-ai.github.io/langgraph/concepts/auth/): LLM should read this page when implementing authentication in LangGraph Platform, designing access control for LangGraph applications, or troubleshooting security issues in LangGraph deployments. This page explains LangGraph's authentication and authorization system, covering the difference between authentication and authorization, system architecture, implementing custom auth handlers, common access patterns, and supported resources/actions for access control.
[Deployment Options](https://langchain-ai.github.io/langgraph/concepts/deployment_options/): LLM should read this page when needing information about LangGraph deployment options, comparing different deployment methods, or understanding LangGraph Platform plans. This page outlines four deployment options for LangGraph Platform: Self-Hosted Lite (available for all plans), Self-Hosted Enterprise (Enterprise plan only), Cloud SaaS (Plus and Enterprise plans), and Bring Your Own Cloud (Enterprise plan only, AWS-only).
[Double Texting](https://langchain-ai.github.io/langgraph/concepts/double_texting/): LLM should read this page when handling concurrent user interactions in LangGraph Platform, implementing double-texting safeguards, or designing stateful conversation systems. This page explains four approaches to handling "double texting" in LangGraph (when users send a second message before the first completes): Reject, Enqueue, Interrupt, and Rollback, noting these features are currently only available in LangGraph Platform.
[Durable Execution](https://langchain-ai.github.io/langgraph/concepts/durable_execution/): LLM should read this page when needing to understand durable execution in LangGraph, implementing workflow persistence, or troubleshooting workflow resumption. This page explains durable execution in LangGraph: how workflows save progress to resume later, requirements (checkpointers and thread IDs), determinism guidelines for consistent replay, using tasks to encapsulate non-deterministic operations, and approaches for pausing/resuming workflows.
[FAQ](https://langchain-ai.github.io/langgraph/concepts/faq/): LLM should read this page when needing to understand differences between LangGraph and LangChain, exploring deployment options for LangGraph Platform, or determining compatibility with various LLMs. FAQ covering LangGraph basics, comparisons with other frameworks, deployment options (free self-hosted, Cloud SaaS, Enterprise), compatibility with different LLMs including OSS models, and feature differences between open-source LangGraph and proprietary LangGraph Platform.
[Functional API](https://langchain-ai.github.io/langgraph/concepts/functional_api/): LLM should read this page when implementing workflows with persistent state, adding human-in-the-loop features, or converting existing code to use LangGraph. The page documents LangGraph's Functional API, which allows adding persistence, memory, and human-in-the-loop capabilities with minimal code changes using @entrypoint and @task decorators, handling serialization requirements, state management, and common patterns for parallel execution and error handling.
[Why LangGraph?](https://langchain-ai.github.io/langgraph/concepts/high_level/): LLM should read this page when understanding LangGraph's core capabilities, exploring LLM application infrastructure, or evaluating agent/workflow persistence options. LangGraph provides infrastructure for LLM applications with three key benefits: persistence for memory and human-in-the-loop capabilities, streaming of workflow events and LLM outputs, and tools for debugging and deployment via LangGraph Platform.
[Human-in-the-loop](https://langchain-ai.github.io/langgraph/concepts/human_in_the_loop/): LLM should read this page when implementing human-in-the-loop workflows in LangGraph, designing approval systems with LLMs, or creating interactive multi-turn conversation agents. This page explains human-in-the-loop patterns in LangGraph using the interrupt function, showing how to pause graph execution for human review/input and resume with Command. Includes design patterns for approval workflows, state editing, tool call reviews, and multi-turn conversations, with code examples and warnings about execution flow and common pitfalls.
[LangGraph CLI](https://langchain-ai.github.io/langgraph/concepts/langgraph_cli/): LLM should read this page when looking for information about LangGraph CLI installation or when needing to deploy a LangGraph API server locally. The page covers LangGraph CLI installation methods (Homebrew, pip), key commands (build, dev, up, dockerfile), and features like hot reloading, debugger support, and database management for running LangGraph servers.
[Cloud SaaS](https://langchain-ai.github.io/langgraph/concepts/langgraph_cloud/): LLM should read this page when learning about LangGraph's Cloud SaaS offering, understanding deployment options for LangGraph Servers, or planning autoscaling infrastructure for LangGraph applications. This page describes LangGraph Cloud SaaS, a managed deployment service for LangGraph Servers with details on deployment types (Development/Production), revisions, persistence, autoscaling capabilities (up to 10 containers), LangSmith integration, IP whitelisting, and automatic deletion policies after 28 days of non-use.
[LangGraph Platform](https://langchain-ai.github.io/langgraph/concepts/langgraph_platform/): LLM should read this page when seeking information about LangGraph Platform's components or evaluating production deployment options for agentic applications. The page details the LangGraph Platform, a commercial solution for deploying agentic applications, including its components (Server, Studio, CLI, SDK, Remote Graph) and key benefits like streaming support, background runs, long run handling, burstiness management, and human-in-the-loop capabilities.
[LangGraph Server](https://langchain-ai.github.io/langgraph/concepts/langgraph_server/): LLM should read this page when developing applications with LangGraph Server, deploying agent-based applications, or integrating persistent state management in agent workflows. LangGraph Server provides an API for creating and managing agent applications with key features like streaming endpoints, background runs, task queues, persistence, webhooks, cron jobs, and monitoring capabilities through a structured system of assistants, threads, runs, and stores.
[LangGraph Studio](https://langchain-ai.github.io/langgraph/concepts/langgraph_studio/): LLM should read this page when looking for information about LangGraph Studio features, needing to troubleshoot LangGraph Studio issues, or learning how to connect a LangGraph application to the Studio. LangGraph Studio is a specialized agent IDE for visualizing, interacting with, and debugging LLM applications, offering features such as graph visualization, state editing, assistant management, and integration with LangSmith, with instructions for connecting via deployed applications or local development servers, plus troubleshooting FAQs.
[LangGraph Glossary](https://langchain-ai.github.io/langgraph/concepts/low_level/): LLM should read this page when needing to understand LangGraph terminology, implementing agent workflows as graphs, or developing modular multi-step AI systems. The page covers core LangGraph concepts including StateGraph, nodes, edges, state management, messaging, persistence, configuration, human-in-the-loop features, subgraphs, and visualization capabilities.
[Memory](https://langchain-ai.github.io/langgraph/concepts/memory/): LLM should read this page when implementing memory systems for AI agents, managing conversation context across sessions, or designing systems that require both short-term and long-term information retention. This page explains memory systems in LangGraph, covering short-term (thread-scoped) memory for managing conversation history and long-term memory across threads, with techniques for handling long conversations, summarizing past interactions, and organizing persistent memories in namespaces.
[Multi-agent Systems](https://langchain-ai.github.io/langgraph/concepts/multi_agent/): LLM should read this page when implementing multi-agent systems, troubleshooting complex agent architectures, or designing agent communication patterns. Multi-agent systems organize LLMs into modular architectures (network, supervisor, hierarchical, custom) with different communication patterns, using Command objects for handoffs between agents, and supporting various state management approaches.
[Persistence](https://langchain-ai.github.io/langgraph/concepts/persistence/): LLM should read this page when needing to understand LangGraph persistence mechanisms, implementing stateful workflows, or managing conversation history across interactions. This page covers LangGraph's persistence features including checkpointers, threads, state snapshots, replay functionality, forking state, cross-thread memory via InMemoryStore, and semantic search capabilities for stored memories.
[LangGraph Platform Plans](https://langchain-ai.github.io/langgraph/concepts/plans/): LLM should read this page when determining LangGraph Platform pricing tiers, comparing deployment options, or researching features available across different plans. This page outlines LangGraph Platform plans (Developer, Plus, Enterprise), detailing deployment options, usage limitations, feature availability, and pricing structure for agentic application deployment.
[LangGraph Platform Architecture](https://langchain-ai.github.io/langgraph/concepts/platform_architecture/): LLM should read this page when needing to understand LangGraph Platform's technical architecture or troubleshooting deployment issues. The page details how LangGraph Platform uses Postgres for persistent storage of user/run data and Redis for worker communication (run cancellation, output streaming) and ephemeral metadata storage (retry attempts).
[LangGraph's Runtime (Pregel)](https://langchain-ai.github.io/langgraph/concepts/pregel/): LLM should read this page when learning about LangGraph's runtime, implementing applications with Pregel directly, or understanding how LangGraph executes graph applications. Explains LangGraph's Pregel runtime which manages graph application execution through a three-phase process (Plan, Execution, Update), describes different channel types (LastValue, Topic, Context, BinaryOperatorAggregate), provides direct implementation examples, and contrasts the StateGraph API with the Functional API.
[LangGraph Platform: Scalability & Resilience](https://langchain-ai.github.io/langgraph/concepts/scalability_and_resilience/): LLM should read this page when needing to understand LangGraph Platform's scaling capabilities, designing high-availability LangGraph deployments, or troubleshooting resilience issues. This page details LangGraph Platform's horizontal scaling features including stateless server instances, queue worker scaling, resilience mechanisms for handling crashes, and database failover strategies in Postgres and Redis.
[LangGraph SDK](https://langchain-ai.github.io/langgraph/concepts/sdk/): LLM should read this page when looking for installation instructions for LangGraph SDK, needing to choose between sync and async Python clients, or requiring SDK API references. The page covers LangGraph SDK installation for Python and JS, provides API reference links, explains the difference between synchronous and asynchronous Python clients, and includes code examples for both client types.
[Self-Hosted](https://langchain-ai.github.io/langgraph/concepts/self_hosted/): LLM should read this page when looking for LangGraph deployment options, understanding self-hosted versions, or seeking requirements for self-hosting LangGraph. This page details two self-hosted deployment options for LangGraph Platform: Self-Hosted Lite (limited to 1M nodes/year) and Self-Hosted Enterprise (full version requiring license). Includes requirements, deployment process using Redis/Postgres, Docker, and optional Kubernetes deployment via Helm chart.
[Streaming](https://langchain-ai.github.io/langgraph/concepts/streaming/): LLM should read this page when implementing streaming features in LangGraph applications, understanding different streaming modes, or building responsive LLM applications. This page explains streaming in LangGraph, covering the main types (workflow progress, LLM tokens, custom updates) and streaming modes (values, updates, custom, messages, debug, events), with details on how to use multiple modes simultaneously and differences between LangGraph library and Platform implementations.
[Template Applications](https://langchain-ai.github.io/langgraph/concepts/template_applications/): LLM should read this page when looking for LangGraph template applications, setting up a new LangGraph project, or finding reference implementations for agentic workflows. This page presents LangGraph template applications with installation requirements, available templates (including ReAct Agent, Memory Agent, Retrieval Agent, etc.), instructions for creating new apps using the CLI, deployment options, and links to further learning resources.
[Time Travel ⏱️](https://langchain-ai.github.io/langgraph/concepts/time-travel/): LLM should read this page when debugging LLM-based agent behavior, analyzing decision-making paths, or exploring alternative execution branches in LangGraph. This page explains LangGraph's Time Travel debugging features: Replaying (reproducing past actions up to specific checkpoints) and Forking (creating alternative execution paths from specific points), with code examples for retrieving checkpoints, configuring replay, and creating forked states.
## How Tos
[How-to Guides](https://langchain-ai.github.io/langgraph/how-tos/): LLM should read this page when looking for specific implementation techniques in LangGraph or when trying to deploy LangGraph applications to production environments. This page contains an extensive collection of how-to guides for LangGraph, covering graph fundamentals, persistence, memory management, human-in-the-loop features, tool calling, multi-agent systems, streaming, and deployment options through LangGraph Platform.
[How to implement handoffs between agents](https://langchain-ai.github.io/langgraph/how-tos/agent-handoffs/): LLM should read this page when implementing multi-agent systems that require agent coordination, when building systems with specialized agents that need to work together, or when needing to implement handoffs between agents. This page explains how to implement handoffs between agents in LangGraph using Command objects, both directly from agent nodes and through specialized handoff tools, with code examples for creating multi-agent systems.
[How to run a graph asynchronously](https://langchain-ai.github.io/langgraph/how-tos/async/): LLM should read this page when needing to implement asynchronous graph execution in LangGraph or when optimizing IO-bound LLM applications. This page explains how to convert synchronous graphs to asynchronous in LangGraph, including updating node definitions with async/await, using StateGraph with TypedDict, implementing conditional edges, and streaming results.
[How to integrate LangGraph with AutoGen, CrewAI, and other frameworks](https://langchain-ai.github.io/langgraph/how-tos/autogen-integration/): LLM should read this page when integrating LangGraph with other agent frameworks, building multi-agent systems, or adding persistence features to agents. The page demonstrates how to combine LangGraph with AutoGen by calling AutoGen agents inside LangGraph nodes, showing code examples for setting up the integration with memory and conversation persistence.
[How to integrate LangGraph (functional API) with AutoGen, CrewAI, and other frameworks](https://langchain-ai.github.io/langgraph/how-tos/autogen-integration-functional/): LLM should read this page when integrating LangGraph with other agent frameworks, building multi-agent systems with different frameworks, or adding LangGraph features to existing agent systems. This page demonstrates how to integrate LangGraph's functional API with AutoGen, including code examples for creating a workflow that calls AutoGen agents, leveraging LangGraph's memory and persistence features.
[How to create branches for parallel node execution](https://langchain-ai.github.io/langgraph/how-tos/branching/): LLM should read this page when needing to implement parallel node execution in LangGraph, optimizing graph performance, or handling conditional branching in workflows. This page explains how to create branches for parallel execution in LangGraph using fan-out/fan-in mechanisms, reducer functions for state accumulation, handling exceptions during parallel execution, and implementing conditional branching logic between nodes.
[How to combine control flow and state updates with Command](https://langchain-ai.github.io/langgraph/how-tos/command): LLM should read this page when learning how to combine control flow with state updates in LangGraph, understanding Command objects, or navigating between parent graphs and subgraphs. This page explains how to use Command objects to simultaneously update state and control flow between nodes, demonstrates using Command.PARENT to navigate from subgraphs to parent graphs, and includes examples of implementing reducers for state updates across graph hierarchies.
[How to add runtime configuration to your graph](https://langchain-ai.github.io/langgraph/how-tos/configuration/): LLM should read this page when implementing runtime configuration for LangGraph, adding model selection options to agents, or enabling dynamic system messages. This page demonstrates how to configure LangGraph at runtime, including selecting different LLMs dynamically and adding custom configuration options like system messages through the configurable dictionary.
[How to use the pre-built ReAct agent](https://langchain-ai.github.io/langgraph/how-tos/create-react-agent/): LLM should read this page when implementing a ReAct agent, needing pre-built agent solutions, or learning how to integrate tools with LLM agents. This page covers how to use the pre-built ReAct agent in LangGraph, including setup instructions, creating a weather checking tool, implementing the agent architecture, and examples of running the agent with and without tool calls.
[How to add human-in-the-loop processes to the prebuilt ReAct agent](https://langchain-ai.github.io/langgraph/how-tos/create-react-agent-hitl/): LLM should read this page when implementing human-in-the-loop processes for ReAct agents, debugging tool calls, or learning about interrupts in LangGraph. This guide demonstrates how to add human-in-the-loop functionality to prebuilt ReAct agents using interrupt_before=["tools"], working with MemorySaver checkpoints, and showing how to approve or edit tool calls before they execute.
[How to add thread-level memory to a ReAct Agent](https://langchain-ai.github.io/langgraph/how-tos/create-react-agent-memory/): LLM should read this page when adding memory to ReAct agents, implementing thread-level persistence in LangGraph, or building stateful conversational agents. This guide demonstrates how to add memory to a ReAct agent using LangGraph's checkpointer interface, with code examples showing MemorySaver implementation, thread_id configuration, and persistent chat context across multiple interactions.
[How to return structured output from the prebuilt ReAct agent](https://langchain-ai.github.io/langgraph/how-tos/create-react-agent-structured-output/): LLM should read this page when implementing structured output with ReAct agents, customizing agent response formats, or working with LangGraph agents. This page explains how to return structured output from prebuilt ReAct agents by providing a response_format parameter with a Pydantic schema, including examples with weather data and options for customizing the prompt.
[How to add a custom system prompt to the prebuilt ReAct agent](https://langchain-ai.github.io/langgraph/how-tos/create-react-agent-system-prompt/): LLM should read this page when learning to customize ReAct agents, needing to add system prompts to agents, or working with LangGraph's prebuilt agents. This tutorial demonstrates how to add a custom system prompt to a prebuilt ReAct agent, with code examples showing model setup, tool creation, and using the prompt parameter in the create_react_agent function.
[How to add cross-thread persistence to your graph](https://langchain-ai.github.io/langgraph/how-tos/cross-thread-persistence): LLM should read this page when needing to implement persistence across multiple threads in LangGraph, when storing user data between conversations, or when implementing shared memory in graph-based LLM applications. This page demonstrates how to use LangGraph's Store API to persist data across threads, including creating an InMemoryStore with embedding search capabilities, passing stores to graph nodes, and accessing user-specific memories in different conversation threads.
[How to add cross-thread persistence (functional API)](https://langchain-ai.github.io/langgraph/how-tos/cross-thread-persistence-functional): LLM should read this page when needing to implement cross-thread persistence in LangGraph functional API, storing user data across different conversation threads, or creating shared memory between workflows. This page explains how to add cross-thread persistence to LangGraph using the Store interface, including defining a store, configuring the entrypoint decorator, and implementing a workflow that can store and retrieve user information across different conversation threads.
[How to do a Self-hosted deployment of LangGraph](https://langchain-ai.github.io/langgraph/how-tos/deploy-self-hosted/): LLM should read this page when implementing a self-hosted deployment of LangGraph, configuring required environment variables, or building Docker images for LangGraph applications. This page explains how to deploy LangGraph applications using Docker, covering environment requirements (Redis, Postgres), how to build Docker images with the LangGraph CLI, configuration using environment variables, and deployment options using Docker or Docker Compose.
[How to disable streaming for models that don't support it](https://langchain-ai.github.io/langgraph/how-tos/disable-streaming/): LLM should read this page when handling models that don't support streaming, implementing LangGraph with non-streaming models, or troubleshooting streaming errors with OpenAI's O1 models. This page explains how to use the disable_streaming=True parameter with ChatOpenAI to make non-streaming models work with LangGraph's astream_events API, with code examples showing the error case and proper implementation.
[How to edit graph state](https://langchain-ai.github.io/langgraph/how-tos/human_in_the_loop/edit-graph-state/): LLM should read this page when needing to implement human intervention in LangGraph workflows, wanting to edit graph state during execution, or implementing breakpoints in agent systems. This page explains how to edit graph state in LangGraph using breakpoints, including implementing human-in-the-loop interactions, setting up interruptions before specific nodes, and updating state during agent execution.
[How to Review Tool Calls](https://langchain-ai.github.io/langgraph/how-tos/human_in_the_loop/review-tool-calls/): LLM should read this page when implementing human review of tool calls, creating interactive agent workflows, or building approval systems for AI actions. This page explains how to implement human-in-the-loop review for tool calls in LangGraph, including approving tool calls, modifying tool calls manually, and providing natural language feedback to agents with complete code examples and explanations.
[How to view and update past graph state](https://langchain-ai.github.io/langgraph/how-tos/human_in_the_loop/time-travel/): LLM should read this page when needing to access or modify past states in LangGraph, when debugging agent execution, or when implementing user interventions in agent workflows. This page demonstrates how to view and update past graph states in LangGraph using get_state and update_state methods, with examples of replaying execution from checkpoints and branching workflows.
[How to wait for user input using interrupt](https://langchain-ai.github.io/langgraph/how-tos/human_in_the_loop/wait-user-input/): LLM should read this page when implementing wait-for-user functions in LangGraph, implementing human-in-the-loop interactions, or learning how to use the interrupt() function. This page explains how to pause graph execution to collect user input using LangGraph's interrupt() function, with examples of simple feedback collection and more complex agent interactions that ask clarifying questions.
[How to define input/output schema for your graph](https://langchain-ai.github.io/langgraph/how-tos/input_output_schema/): LLM should read this page when needing to define separate input/output schemas for LangGraph, implementing schema-based data filtering, or understanding schema definitions in StateGraph. This page explains how to define distinct input and output schemas for a StateGraph, showing how input schema validates the provided data structure while output schema filters internal data to return only relevant information, with code examples demonstrating implementation.
[How to handle large numbers of tools](https://langchain-ai.github.io/langgraph/how-tos/many-tools/): LLM should read this page when handling large tool collections, implementing dynamic tool selection, or creating retrieval-based tool management in LangGraph. This page demonstrates how to manage large numbers of tools by using vector search to dynamically select relevant tools based on user queries, implementing tool selection nodes in LangGraph, and handling tool selection errors with retry mechanisms.
[How to create map-reduce branches for parallel execution](https://langchain-ai.github.io/langgraph/how-tos/map-reduce/): LLM should read this page when learning to implement parallel execution in LangGraph, creating map-reduce operations, or handling dynamic task decomposition. This guide explains how to use LangGraph's Send API to create map-reduce workflows, breaking tasks into parallel sub-tasks and recombining results, with examples showing joke generation across multiple subjects.
[How to add summary of the conversation history](https://langchain-ai.github.io/langgraph/how-tos/memory/add-summary-conversation-history/): LLM should read this page when implementing conversation summarization, managing context windows, or building chatbots with memory management. This page demonstrates how to add summary functionality to conversation history using LangGraph, including checking conversation length, creating summaries, and removing old messages while maintaining context.
[How to delete messages](https://langchain-ai.github.io/langgraph/how-tos/memory/delete-messages): LLM should read this page when attempting to manage message history in LangGraph, needing to delete specific messages from conversational state, or implementing memory management in LLM applications. This page explains how to delete messages from a LangGraph application using RemoveMessage modifiers, covering both manual deletion with message IDs and programmatic deletion within graph logic to maintain conversation history limits.
[How to manage conversation history](https://langchain-ai.github.io/langgraph/how-tos/memory/manage-conversation-history/): LLM should read this page when managing conversation history in LangGraph, preventing context window issues, or implementing custom message filtering. This page explains how to manage conversation history in LangGraph to prevent context window overflow by implementing message filtering functions that control which messages are sent to the LLM.
[How to add semantic search to your agent's memory](https://langchain-ai.github.io/langgraph/how-tos/memory/semantic-search/): LLM should read this page when implementing semantic search in agent memory, enabling memory-aware AI assistants, or configuring advanced memory retrieval systems. This page demonstrates how to add semantic search to LangGraph agent memory stores, covering basic setup with embeddings, storing memories, searching by semantic similarity, integrating memory in agents and ReAct agents, and advanced usage like multi-vector indexing and selective memory indexing.
[How to add multi-turn conversation in a multi-agent application](https://langchain-ai.github.io/langgraph/how-tos/multi-agent-multi-turn-convo/): LLM should read this page when implementing multi-turn conversations between agents, creating interactive agent systems with human input, or learning about langgraph interrupts and agent handoffs. This page demonstrates how to build a multi-agent system with multi-turn conversations, including human-in-the-loop interactions, agent handoffs, and state management using LangGraph, Command objects, and interrupts.
[How to add multi-turn conversation in a multi-agent application (functional API)](https://langchain-ai.github.io/langgraph/how-tos/multi-agent-multi-turn-convo-functional/): LLM should read this page when building multi-turn conversational agents, implementing agent-to-agent handoffs, or using interrupts to collect user input in LangGraph. This guide demonstrates how to create a multi-agent system with multi-turn conversations using LangGraph's functional API, featuring agent handoffs, interrupt mechanics for user input, and a complete example of travel and hotel advisor agents that can transfer control between each other.
[How to build a multi-agent network](https://langchain-ai.github.io/langgraph/how-tos/multi-agent-network/): LLM should read this page when implementing multi-agent networks, setting up agent communication via handoffs, or building travel assistance agents. This page explains how to create a fully-connected multi-agent network with LangGraph where agents can communicate with each other via handoffs, including custom agent implementation and using prebuilt ReAct agents with tools.
[How to build a multi-agent network (functional API)](https://langchain-ai.github.io/langgraph/how-tos/multi-agent-network-functional/): LLM should read this page when building multi-agent systems, implementing agent handoffs between specialists, or creating fully-connected agent networks. This guide demonstrates how to create a multi-agent network using LangGraph's functional API, with tasks for individual agents and entrypoint functions to manage agent handoffs based on tool calls.
[How to add node retry policies](https://langchain-ai.github.io/langgraph/how-tos/node-retries/): LLM should read this page when implementing error handling in LangGraph nodes, configuring API retry mechanisms, or troubleshooting node failures in graph workflows. Shows how to add custom retry policies to LangGraph nodes, including specifying which exceptions to retry on, setting max attempts, intervals, backoff factors, and implementing different retry behaviors for different node types.
[How to pass config to tools](https://langchain-ai.github.io/langgraph/how-tos/pass-config-to-tools/): LLM should read this page when implementing secure tool configuration in LangChain, passing user-specific parameters to tools, or configuring tools with runtime values. This page explains how to pass configuration to LangChain tools using RunnableConfig, allowing application-controlled values (like user IDs) to be securely passed to tools without LLM control, with examples of implementing tools that access user-specific data.
[How to pass private state between nodes](https://langchain-ai.github.io/langgraph/how-tos/pass_private_state/): LLM should read this page when implementing data sharing between specific nodes in LangGraph, handling private state in graph workflows, or designing multi-node sequential processes with selective data visibility. This page demonstrates how to pass private data between specific nodes in a LangGraph without making it part of the main schema, using typed dictionaries to define both public and private states, and showing a three-node example where private data flows only between the first two nodes.
[How to add thread-level persistence to your graph](https://langchain-ai.github.io/langgraph/how-tos/persistence/): LLM should read this page when implementing persistence in LangGraph, needing to preserve context across user interactions, or learning about thread-level state management. This page explains how to add thread-level persistence to LangGraph applications using MemorySaver, including code examples for creating stateful conversations where context is maintained across multiple interactions.
[How to add thread-level persistence (functional API)](https://langchain-ai.github.io/langgraph/how-tos/persistence-functional/): LLM should read this page when implementing thread-level persistence in LangGraph, creating conversational agents with memory, or using functional API with state management. This page explains how to add thread-level persistence to LangGraph functional API workflows using checkpointers, including code examples for creating a simple chatbot with memory across conversation turns.
[How to use MongoDB checkpointer for persistence](https://langchain-ai.github.io/langgraph/how-tos/persistence_mongodb/): LLM should read this page when implementing persistence in LangGraph agents, setting up MongoDB for state checkpointing, or working with MongoDB connections in LangGraph applications. This page explains how to use the MongoDB checkpointer for LangGraph persistence, covering connection methods (direct, client-based, async), basic setup requirements, and practical examples of saving and retrieving agent state between interactions.
[How to use Postgres checkpointer for persistence](https://langchain-ai.github.io/langgraph/how-tos/persistence_postgres/): LLM should read this page when setting up persistence for LangGraph agents, implementing PostgreSQL as a checkpoint storage backend, or working with either synchronous or asynchronous database connections. This page details how to use PostgreSQL for persisting LangGraph agent state, covering setup and configuration of PostgresSaver and AsyncPostgresSaver with different connection methods (pool, direct connection, connection string).
[How to create a custom checkpointer using Redis](https://langchain-ai.github.io/langgraph/how-tos/persistence_redis/): LLM should read this page when implementing persistence in LangGraph applications, creating custom checkpoint mechanisms for agents, or working with Redis as a storage backend. This page demonstrates how to create custom checkpointers for LangGraph agents using Redis, including implementations for both synchronous and asynchronous interfaces that save and retrieve agent state.
[How to create a ReAct agent from scratch](https://langchain-ai.github.io/langgraph/how-tos/react-agent-from-scratch/): LLM should read this page when needing to create a custom ReAct agent, wanting more control than prebuilt agents, or implementing ReAct from scratch with LangGraph. This guide shows how to build a custom ReAct agent using LangGraph, covering state definition, model/tool setup, node/edge configuration, graph creation, and testing the implementation with a weather query example.
[How to create a ReAct agent from scratch (Functional API)](https://langchain-ai.github.io/langgraph/how-tos/react-agent-from-scratch-functional): LLM should read this page when creating a ReAct agent using LangGraph's Functional API, implementing tool-calling workflows, or building conversational agents with thread persistence. This page explains how to build a ReAct agent from scratch using LangGraph's Functional API, including model and tool setup, defining tasks for model/tool calling, creating an entrypoint for orchestration, and adding thread-level persistence for conversational experiences.
[How to force tool-calling agent to structure output](https://langchain-ai.github.io/langgraph/how-tos/react-agent-structured-output): LLM should read this page when needing to force tool-calling agents to produce structured output, implementing consistent output formats for downstream software, or choosing between single-LLM vs two-LLM structured output approaches. The page explains two methods for implementing structured output with tool-calling agents: binding output as a tool (single LLM approach) and using two LLMs with structured output conversion, with code examples for both approaches using LangGraph.
[How to create and control loops](https://langchain-ai.github.io/langgraph/how-tos/recursion-limit/): LLM should read this page when building loops in computational graphs, needing to implement termination conditions, or handling recursion limits in LangGraph. The page explains how to create graphs with loops using conditional edges for termination, set recursion limits, handle GraphRecursionError, and implement complex loops with branches.
[How to review tool calls (Functional API)](https://langchain-ai.github.io/langgraph/how-tos/review-tool-calls-functional/): LLM should read this page when implementing human review of tool calls, creating ReAct agents with Functional API, or adding human-in-the-loop workflows. This page demonstrates how to review tool calls before execution in a ReAct agent using LangGraph's Functional API, including accepting, revising, or generating custom tool messages with the interrupt function.
[How to pass custom run ID or set tags and metadata for graph runs in LangSmith](https://langchain-ai.github.io/langgraph/how-tos/run-id-langsmith/): LLM should read this page when needing to customize trace information in LangSmith for LangGraph runs or when debugging graph runs with custom identifiers. The page explains how to pass custom run_id, set tags, add metadata, and customize run names for LangGraph traces in LangSmith using RunnableConfig, with examples showing implementation with a ReAct agent.
[How to create a sequence of steps](https://langchain-ai.github.io/langgraph/how-tos/sequence/): LLM should read this page when implementing sequential workflows in LangGraph, creating multi-step processes in applications, or learning about state management in graph-based systems. This page explains how to create sequences in LangGraph, covering methods for building sequential graphs using .add_node/.add_edge or the shorthand .add_sequence, defining state with TypedDict, creating nodes as functions that update state, and compiling/invoking graphs with examples.
[How to use Pydantic model as graph state](https://langchain-ai.github.io/langgraph/how-tos/state-model): LLM should read this page when implementing Pydantic models for state validation in LangGraph, handling complex state schema definitions, or troubleshooting validation errors in graph nodes. This guide explains how to use Pydantic BaseModel as a state schema in LangGraph for runtime validation, covering basic implementation, limitations, validation behavior across multiple nodes, serialization patterns, type coercion, and working with message models.
[How to update graph state from nodes](https://langchain-ai.github.io/langgraph/how-tos/state-reducers/): LLM should read this page when needing to update state in LangGraph, designing graphs with nodes that modify state, or implementing reducers for state management. This page explains how to define state schemas in LangGraph using TypedDict, how nodes can update state, and how to use reducers to control state updates, with specific examples using message handling.
[How to stream](https://langchain-ai.github.io/langgraph/how-tos/streaming/): LLM should read this page when needing to implement streaming in LangGraph applications, understanding different streaming modes, or troubleshooting LLM response delivery. This page explains how to stream LLM outputs using LangGraph, covering different streaming modes (values, updates, custom, messages, debug), with code examples for each mode and how to combine multiple streaming modes.
[How to stream data from within a tool](https://langchain-ai.github.io/langgraph/how-tos/streaming-events-from-within-tools/): LLM should read this page when implementing streaming functionality in tools, integrating LLM outputs with custom data streams, or developing LangGraph applications with real-time feedback. This page explains how to stream data from within tools using LangGraph, covering custom data streaming with stream_mode="custom", LLM token streaming with stream_mode="messages", and implementation approaches both with and without LangChain.
[How to stream LLM tokens from specific nodes](https://langchain-ai.github.io/langgraph/how-tos/streaming-specific-nodes/): LLM should read this page when needing to filter token streaming from specific nodes in LangGraph, implementing selective streaming in multi-node workflows, or controlling which node outputs are displayed. Guide explains how to stream LLM tokens from specific nodes using stream_mode="messages" and filtering by the langgraph_node metadata field, with complete code examples for implementing this in StateGraph applications.
[How to stream from subgraphs](https://langchain-ai.github.io/langgraph/how-tos/streaming-subgraphs/): LLM should read this page when needing to stream outputs from subgraphs in LangGraph, implementing nested graph streaming, or debugging hierarchical graph execution. This page explains how to stream outputs from subgraphs in LangGraph by using the subgraphs=True parameter in the parent graph's stream() method, with a complete code example showing the difference between regular streaming and subgraph streaming.
[How to stream LLM tokens from your graph](https://langchain-ai.github.io/langgraph/how-tos/streaming-tokens): LLM should read this page when needing to stream LLM tokens from a LangGraph application, implementing custom token streaming, or filtering streamed outputs. This page explains how to stream individual LLM tokens from LangGraph nodes using graph.stream() with different stream_mode options, including examples with and without LangChain, async implementations, and how to filter streamed tokens using metadata.
[How to use subgraphs](https://langchain-ai.github.io/langgraph/how-tos/subgraph/): LLM should read this page when building complex systems with subgraphs, implementing multi-agent systems, or needing to share state between parent graphs and subgraphs. The page explains two methods for using subgraphs: adding compiled subgraphs when schemas share keys, and invoking subgraphs via node functions when schemas differ, with code examples for both approaches.
[How to add thread-level persistence to a subgraph](https://langchain-ai.github.io/langgraph/how-tos/subgraph-persistence/): LLM should read this page when implementing persistence in nested LangGraph architectures, adding thread-level storage to subgraphs, or debugging state propagation in LangGraph applications. This guide demonstrates how to add thread-level persistence to subgraphs by passing a checkpointer only to the parent graph during compilation, accessing persisted states from both parent and child graphs, and retrieving subgraph state using the proper configuration parameters.
[How to transform inputs and outputs of a subgraph](https://langchain-ai.github.io/langgraph/how-tos/subgraph-transform-state/): LLM should read this page when needing to work with nested subgraphs, transforming state between parent and child graphs, or integrating independent state components in LangGraph. This page demonstrates how to transform inputs and outputs between parent graphs and subgraphs with different state structures, showing implementation of three nested graphs (parent, child, grandchild) with separate state dictionaries and transformation functions.
[How to view and update state in subgraphs](https://langchain-ai.github.io/langgraph/how-tos/subgraphs-manage-state/): LLM should read this page when working with state management in nested subgraphs, implementing human-in-the-loop patterns, or debugging complex graph flows. This guide covers viewing and updating state in LangGraph subgraphs, including how to resume execution from breakpoints, modify subgraph state, act as specific nodes, and work with multi-level nested subgraphs.
[How to call tools using ToolNode](https://langchain-ai.github.io/langgraph/how-tos/tool-calling/): LLM should read this page when learning how to implement tool calling with LangGraph, when working with the ToolNode component, or when building ReAct agents. This page covers using LangGraph's ToolNode for tool calling, including setup, manual invocation, working with chat models, building a ReAct agent, handling single and parallel tool calls, and error handling.
[How to handle tool calling errors](https://langchain-ai.github.io/langgraph/how-tos/tool-calling-errors/): LLM should read this page when handling tool call errors, implementing error handling for LLM-tool interactions, or creating fallback strategies for failed tool calls. This page covers strategies for handling tool calling errors in LangGraph, including using the prebuilt ToolNode with built-in error handling, implementing custom error handling patterns, and fallback mechanisms with model upgrades when tools fail.
[How to update graph state from tools](https://langchain-ai.github.io/langgraph/how-tos/update-state-from-tools/): LLM should read this page when needing to update graph state from tools in LangGraph, implementing personalized responses based on tool updates, or using Command objects to modify state. This page details how to update graph state from tools using Command objects, creating personalized agents with state tracking, and implementing dynamic prompt construction based on updated state values.
[How to interact with the deployment using RemoteGraph](https://langchain-ai.github.io/langgraph/how-tos/use-remote-graph/): LLM should read this page when needing to interact with LangGraph Platform deployments remotely, when implementing RemoteGraph interfaces, or when using deployed graphs as subgraphs. This page explains how to use RemoteGraph to interact with LangGraph Platform deployments, covering initialization methods (URL-based or client-based), synchronous/asynchronous invocation, thread-level persistence, and using RemoteGraph as a subgraph in larger applications.
[How to visualize your graph](https://langchain-ai.github.io/langgraph/how-tos/visualization): LLM should read this page when needing to visualize LangGraph graphs, looking for graph visualization methods, or working with graph visualization in Python. Comprehensive guide for visualizing graphs in LangGraph with multiple methods: Mermaid syntax, Mermaid.ink API for PNG rendering, Pyppeteer-based visualization, and Graphviz, with customization options for colors, styles, and layout.
[How to wait for user input (Functional API)](https://langchain-ai.github.io/langgraph/how-tos/wait-user-input-functional/): LLM should read this page when implementing human-in-the-loop workflows, integrating user input into agent systems, or adding interruption capabilities to LangGraph applications. The page explains how to use the `interrupt()` function in LangGraph's Functional API to pause execution for human input, with examples for both simple workflows and ReAct agents, including code implementations with checkpointing.
# Guides
- [LangGraph Documentation](https://langchain-ai.github.io/langgraph/index/): This page provides an overview of the LangGraph project, including its logo and essential scripts for functionality within MkDocs. It also includes a reference to the README.md file for detailed information about the project. The content is designed to be user-friendly and visually appealing.
- [LangGraph Quickstart Guide](https://langchain-ai.github.io/langgraph/agents/agents/): This quickstart guide provides step-by-step instructions for setting up and using LangGraph's prebuilt components to create agentic systems. It covers prerequisites, installation, agent creation, configuration of language models, and advanced features like memory and structured output. Ideal for developers looking to leverage LangGraph for building intelligent agents.
- [Getting Started with LangGraph: Building AI Agents](https://langchain-ai.github.io/langgraph/concepts/why-langgraph/): This page provides an overview of LangGraph, a platform designed for developers to create adaptable AI agents. It highlights key features such as reliability, extensibility, and streaming support, and offers a series of tutorials to help users build a support chatbot with various capabilities. By following the tutorials, developers will learn to implement essential functionalities like conversation state management and human-in-the-loop controls.
- [Building a Basic Chatbot with LangGraph](https://langchain-ai.github.io/langgraph/tutorials/get-started/1-build-basic-chatbot/): This tutorial guides you through the process of creating a basic chatbot using LangGraph. It covers prerequisites, installation of necessary packages, and step-by-step instructions to set up a state machine for the chatbot. By the end of the tutorial, you will have a functional chatbot that can engage in simple conversations.
- [Integrating Web Search Tools into Your Chatbot](https://langchain-ai.github.io/langgraph/tutorials/get-started/2-add-tools/): This tutorial guides you through the process of enhancing your chatbot's capabilities by integrating a web search tool, specifically the Tavily Search Engine. It covers prerequisites, installation, configuration, and the implementation of the search tool within a LangGraph-based chatbot. By the end, you'll have a functional chatbot that can retrieve real-time information to answer user queries beyond its training data.
- [Implementing Memory in Chatbots with LangGraph](https://langchain-ai.github.io/langgraph/tutorials/get-started/3-add-memory/): This page provides a comprehensive guide on how to add memory functionality to chatbots using LangGraph's persistent checkpointing feature. It details the steps to create a `MemorySaver` checkpointer, compile the graph, and interact with the chatbot to maintain context across multiple interactions. Additionally, it explains how to inspect the state of the chatbot and highlights the advantages of checkpointing over simple memory solutions.
- [Implementing Human-in-the-Loop Controls in LangGraph](https://langchain-ai.github.io/langgraph/tutorials/get-started/4-human-in-the-loop/): This page provides a comprehensive guide on adding human-in-the-loop controls to LangGraph workflows, enabling agents to pause execution for human input. It details the use of the `interrupt` function to facilitate user feedback and outlines the steps to integrate a `human_assistance` tool into a chatbot. Additionally, the tutorial covers graph compilation, visualization, and resuming execution with human input.
- [Customizing State in LangGraph for Enhanced Chatbot Functionality](https://langchain-ai.github.io/langgraph/tutorials/get-started/5-customize-state/): This tutorial guides you through the process of adding custom fields to the state in LangGraph, enabling complex behaviors in your chatbot without relying solely on message lists. You will learn how to implement human-in-the-loop controls to verify information before it is stored in the state. By the end of this tutorial, you will have a deeper understanding of state management and how to enhance your chatbot's capabilities.
- [Implementing Time Travel in LangGraph Chatbots](https://langchain-ai.github.io/langgraph/tutorials/get-started/6-time-travel/): This page provides a comprehensive guide on utilizing the time travel functionality in LangGraph to enhance chatbot interactions. It covers how to rewind, add steps, and replay the state history of a chatbot, allowing users to explore different outcomes and fix mistakes. Additionally, it includes code snippets and practical examples to help developers implement these features effectively.
- [LangGraph Deployment Options](https://langchain-ai.github.io/langgraph/tutorials/deployment/): This page outlines the various options available for deploying LangGraph applications, including local testing and different cloud-based solutions. It details free deployment methods such as Local and Standalone Container (Lite), as well as production options like Cloud SaaS and self-hosted solutions. Each deployment method is linked to further documentation for in-depth guidance.
- [Agent Development with LangGraph](https://langchain-ai.github.io/langgraph/agents/overview/): This page provides an overview of agent development using LangGraph, highlighting its prebuilt components and capabilities for building agent-based applications. It explains the structure of an agent, key features such as memory integration and human-in-the-loop control, and outlines the package ecosystem available for developers. With LangGraph, users can focus on application logic while leveraging robust infrastructure for state management and feedback.
- [Guide to Running Agents in LangGraph](https://langchain-ai.github.io/langgraph/agents/run_agents/): This page provides a comprehensive overview of how to execute agents in LangGraph, detailing both synchronous and asynchronous methods. It covers input and output formats, streaming capabilities, and how to manage execution limits to prevent infinite loops. Additionally, it includes code examples and links to further resources for deeper understanding.
- [Streaming Data in LangGraph](https://langchain-ai.github.io/langgraph/agents/streaming/): This page provides an overview of streaming data types in LangGraph, including agent progress, LLM tokens, and custom updates. It includes code examples for both synchronous and asynchronous streaming methods. Additionally, it covers how to stream multiple modes and disable streaming when necessary.
- [Configuring Chat Models for Agents](https://langchain-ai.github.io/langgraph/agents/models/): This page provides detailed instructions on how to configure various chat models for use with agents in LangChain. It covers model initialization, tool calling support, and how to specify models from different providers such as OpenAI, Anthropic, Azure, Google Gemini, and AWS Bedrock. Additionally, it includes information on disabling streaming, adding model fallbacks, and links to further resources.
- [Using Tools in LangChain](https://langchain-ai.github.io/langgraph/agents/tools/): This page provides an overview of how to define, customize, and manage tools within the LangChain framework. It covers creating simple tools, handling tool errors, and utilizing prebuilt integrations for enhanced functionality. Additionally, it discusses advanced features such as memory management and controlling tool behavior during agent execution.
- [Integrating MCP with LangGraph Agents](https://langchain-ai.github.io/langgraph/agents/mcp/): This page provides a comprehensive guide on how to integrate the Model Context Protocol (MCP) with LangGraph agents using the `langchain-mcp-adapters` library. It includes installation instructions, example code for using MCP tools, and guidance on creating custom MCP servers. Additional resources for further reading on MCP are also provided.
- [Understanding Context in LangGraph Agents](https://langchain-ai.github.io/langgraph/agents/context/): This page provides an overview of how to supply context to agents in LangGraph, detailing the three primary types: Config, State, and Long-Term Memory. It explains how to use these context types to enhance agent behavior, customize prompts, and access context in tools. Additionally, it includes code examples for implementing context in various scenarios.
- [Understanding Memory in LangGraph for Conversational Agents](https://langchain-ai.github.io/langgraph/agents/memory/): This documentation page provides an overview of the two types of memory supported by LangGraph: short-term and long-term memory. It explains how to implement these memory types in conversational agents, including code examples and best practices for managing message history. Additionally, it covers the use of persistent storage and tools for enhancing memory functionality.
- [Implementing Human-in-the-Loop in LangGraph](https://langchain-ai.github.io/langgraph/agents/human-in-the-loop/): This documentation page provides a comprehensive guide on how to implement Human-in-the-Loop (HIL) features in LangGraph, allowing for human review and approval of tool calls in agents. It covers the use of the `interrupt()` function to pause execution for human input, along with practical examples and code snippets. Additionally, it explains how to create a wrapper to add HIL capabilities to any tool seamlessly.
- [Building Multi-Agent Systems](https://langchain-ai.github.io/langgraph/agents/multi-agent/): This page provides an overview of multi-agent systems, detailing how to create and manage them using supervisor and swarm architectures. It includes practical examples of implementing a flight and hotel booking assistant using the LangGraph libraries. Additionally, the page explains the concept of handoffs between agents, allowing for seamless communication and task delegation.
- [Evaluating Agent Performance with LangSmith](https://langchain-ai.github.io/langgraph/agents/evals/): This page provides a comprehensive guide on how to evaluate the performance of agents using the LangSmith evaluations framework. It includes instructions on defining evaluator functions, utilizing prebuilt evaluators from the AgentEvals package, and running evaluations with specific datasets. Additionally, it covers different evaluation techniques, including trajectory matching and using LLMs as judges.
- [Deploying Your LangGraph Agent](https://langchain-ai.github.io/langgraph/agents/deployment/): This page provides a comprehensive guide on how to deploy a LangGraph agent, including setting up a LangGraph app for both local development and production. It covers essential features, installation steps, and configuration requirements, along with instructions for launching the local server and utilizing the LangGraph Studio Web UI for debugging. Additionally, it offers links to further resources for deployment options.
- [Agent Chat UI Documentation](https://langchain-ai.github.io/langgraph/agents/ui/): This page provides comprehensive guidance on using the Agent Chat UI for interacting with LangGraph agents. It covers setup instructions, features like human-in-the-loop workflows, and the integration of generative UI components. Users can find links to relevant resources and tips for customizing their chat experience.
- [Overview of Agent Architectures in LLM Applications](https://langchain-ai.github.io/langgraph/concepts/agentic_concepts/): This page provides a comprehensive overview of various agent architectures used in large language model (LLM) applications, highlighting their control flows and functionalities. It discusses key concepts such as routers, tool-calling agents, memory management, and planning, along with customization options for specific tasks. Additionally, it covers advanced features like human-in-the-loop, parallelization, subgraphs, and reflection mechanisms to enhance agent performance.
- [Understanding Workflows and Agents in LangGraph](https://langchain-ai.github.io/langgraph/tutorials/workflows/): This documentation page provides an in-depth overview of workflows and agents within LangGraph, highlighting their differences and use cases. It covers various patterns for building agentic systems, including setup instructions, building blocks, and advanced concepts like prompt chaining, parallelization, and routing. Additionally, it offers practical examples and code snippets to help users implement these workflows effectively.
- [Understanding LangGraph: Core Concepts and Components](https://langchain-ai.github.io/langgraph/concepts/low_level/): This documentation page provides an in-depth overview of the core concepts of LangGraph, focusing on how agent workflows are modeled as graphs. It covers essential components such as States, Nodes, and Edges, and explains how they interact to create complex workflows. Additionally, it discusses graph compilation, message handling, and configuration options to enhance the functionality of your graphs.
- [LangGraph Runtime Overview](https://langchain-ai.github.io/langgraph/concepts/pregel/): This page provides a comprehensive overview of the LangGraph runtime, specifically focusing on the Pregel execution model. It details the structure and functionality of actors and channels within the Pregel framework, along with examples of how to implement applications. Additionally, it introduces high-level APIs for creating Pregel applications using StateGraph and Functional API.
- [Using the LangGraph API: A Comprehensive Guide](https://langchain-ai.github.io/langgraph/how-tos/graph-api/): This documentation provides a detailed overview of how to utilize the LangGraph Graph API, covering essential concepts such as state management, node creation, and control flow. It includes practical examples for building sequences, branches, and loops, as well as advanced features like retry policies and async execution. Additionally, the guide offers insights into visualizing graphs and integrating with external tools.
- [LangGraph Streaming System](https://langchain-ai.github.io/langgraph/concepts/streaming/): This page provides an overview of the streaming capabilities of LangGraph, enabling real-time updates for enhanced user experiences. It details the types of data that can be streamed, including workflow progress, LLM tokens, and custom updates. Additionally, it outlines various functionalities and modes available for streaming within the LangGraph framework.
- [Streaming Outputs in LangGraph](https://langchain-ai.github.io/langgraph/how-tos/streaming/): This documentation page provides an overview of how to utilize the streaming capabilities of LangGraph, including synchronous and asynchronous streaming methods. It covers various stream modes, such as updates, values, and custom data, along with examples of how to implement them in your graphs. Additionally, it discusses the integration of Large Language Models (LLMs) and how to handle streaming outputs effectively.
- [LangGraph Persistence and Checkpointing](https://langchain-ai.github.io/langgraph/concepts/persistence/): This page provides an in-depth overview of the persistence layer in LangGraph, focusing on the use of checkpointers to save graph states at each super-step. It covers key concepts such as threads, checkpoints, state retrieval, and memory management, along with practical examples and code snippets. Additionally, it discusses advanced features like time travel, fault tolerance, and the integration of memory stores for cross-thread information retention.
- [Understanding Durable Execution in LangGraph](https://langchain-ai.github.io/langgraph/concepts/durable_execution/): This page provides an overview of durable execution, a technique that allows workflows to save their progress and resume from key points. It details the requirements for implementing durable execution in LangGraph, including the use of persistence and tasks to ensure deterministic and consistent replay. Additionally, it covers how to handle pausing, resuming, and recovering workflows effectively.
- [Implementing Memory in LangGraph for AI Applications](https://langchain-ai.github.io/langgraph/how-tos/persistence/): This documentation page provides a comprehensive guide on adding persistence to AI applications using LangGraph. It covers both short-term and long-term memory implementations, including code examples for managing conversation context and user-specific data. Additionally, it discusses the use of various storage backends and semantic search capabilities for enhanced memory management.
- [Understanding Memory in AI Agents](https://langchain-ai.github.io/langgraph/concepts/memory/): This documentation page provides an in-depth overview of memory types in AI agents, focusing on short-term and long-term memory. It explains how these memory types can be implemented and managed within applications using LangGraph, including techniques for handling conversation history and storing memories. Additionally, it discusses the importance of memory in enhancing user interactions and the various strategies for writing and updating memories.
- [Memory Management in LangGraph for AI Applications](https://langchain-ai.github.io/langgraph/how-tos/memory/): This page provides an overview of memory management in LangGraph, focusing on short-term and long-term memory functionalities essential for conversational agents. It includes detailed instructions on how to implement memory strategies such as trimming, summarizing, and deleting messages to optimize conversation tracking without exceeding context limits. Code examples are provided to illustrate the implementation of these memory management techniques.
- [Human-in-the-Loop Workflows in LangGraph](https://langchain-ai.github.io/langgraph/concepts/human_in_the_loop/): This page provides an overview of the human-in-the-loop (HIL) capabilities within LangGraph, highlighting how human intervention can enhance automated processes. It details key features such as persistent execution state and flexible integration points, along with typical use cases for validating outputs and providing context. Additionally, it outlines the implementation of HIL through specific functions and primitives.
- [Implementing Human-in-the-Loop Workflows with Interrupts](https://langchain-ai.github.io/langgraph/how-tos/human_in_the_loop/add-human-in-the-loop/): This documentation page provides a comprehensive guide on using the `interrupt` function in LangGraph to facilitate human-in-the-loop workflows. It covers the implementation details, design patterns, and best practices for pausing graph execution to gather human input, as well as how to resume execution with that input. Additionally, it highlights common pitfalls and offers extended examples to illustrate various use cases.
- [Understanding Breakpoints in LangGraph](https://langchain-ai.github.io/langgraph/concepts/breakpoints/): This page provides an overview of breakpoints in LangGraph, which allow users to pause graph execution at specific points for inspection. It explains how breakpoints utilize the persistence layer to save the graph state and how execution can be resumed after inspection. An illustrative example is included to demonstrate the concept visually.
- [Using Breakpoints in Graph Execution](https://langchain-ai.github.io/langgraph/how-tos/human_in_the_loop/breakpoints/): This page provides a comprehensive guide on how to implement breakpoints in graph execution for debugging purposes. It covers the requirements for setting breakpoints, the difference between static and dynamic breakpoints, and includes code examples for both compile-time and run-time configurations. Additionally, it explains how to manage breakpoints in subgraphs.
- [Time Travel Functionality in LangGraph](https://langchain-ai.github.io/langgraph/concepts/time-travel/): This page explains the time travel feature in LangGraph, which allows users to analyze and debug decision-making processes in non-deterministic systems. It outlines how to understand reasoning, debug mistakes, and explore alternative solutions by resuming execution from prior checkpoints. The functionality enables users to create new forks in the execution history for deeper insights.
- [Using Time-Travel in LangGraph](https://langchain-ai.github.io/langgraph/how-tos/human_in_the_loop/time-travel/): This page provides a comprehensive guide on how to implement time-travel functionality in LangGraph. It outlines the steps to run a graph, identify checkpoints, modify graph states, and resume execution from specific checkpoints. Additionally, an example workflow is included to illustrate the process of generating and modifying jokes using LangGraph.
- [Integrating Tools with AI Models](https://langchain-ai.github.io/langgraph/concepts/tools/): This page provides an overview of how AI models can interact with external systems using tool calling. It explains the concept of tools, their integration with chat models, and how to create or use prebuilt tools for various applications. Additionally, it highlights the importance of relevance in tool invocation and offers links to further resources and guides.
- [Using Tools in LangChain](https://langchain-ai.github.io/langgraph/how-tos/tool-calling/): This documentation page provides a comprehensive guide on how to create and utilize tools within the LangChain framework. It covers defining simple and customized tools, managing tool arguments, accessing configuration and state, and integrating tools with chat models and agents. Additionally, it discusses error handling and strategies for managing a large number of tools.
- [Understanding Subgraphs in LangGraph](https://langchain-ai.github.io/langgraph/concepts/subgraphs/): This page provides an overview of subgraphs in LangGraph, explaining their role as encapsulated nodes within larger graphs. It discusses the benefits of using subgraphs, such as facilitating multi-agent systems and enabling independent team work. Additionally, it outlines the communication methods between parent graphs and subgraphs, detailing scenarios involving shared and different state schemas.
- [Using Subgraphs in LangGraph](https://langchain-ai.github.io/langgraph/how-tos/subgraph/): This guide provides an overview of how to effectively use subgraphs within LangGraph, including communication methods between parent graphs and subgraphs. It covers shared and different state schemas, setup instructions, and examples for implementing subgraphs in multi-agent systems. Additionally, it discusses persistence, state management, and streaming outputs from subgraphs.
- [Understanding Multi-Agent Systems](https://langchain-ai.github.io/langgraph/concepts/multi_agent/): This page provides an in-depth overview of multi-agent systems, focusing on the architecture and benefits of using multiple independent agents to manage complex applications. It discusses various multi-agent architectures, including network, supervisor, and hierarchical models, as well as communication strategies and state management techniques for effective agent interaction.
- [Building Multi-Agent Systems with LangGraph](https://langchain-ai.github.io/langgraph/how-tos/multi_agent/): This guide provides an overview of how to build multi-agent systems using LangGraph, focusing on the implementation of handoffs for agent communication. It covers the creation of independent agents, the use of handoffs to transfer control and data between agents, and examples of prebuilt multi-agent architectures. Additionally, it includes code snippets and best practices for managing agent interactions and state.
- [Understanding the Functional API in LangGraph](https://langchain-ai.github.io/langgraph/concepts/functional_api/): This documentation page provides an overview of the Functional API in LangGraph, detailing its key features such as persistence, memory, and human-in-the-loop capabilities. It explains how to define workflows using the `@entrypoint` and `@task` decorators, along with examples and best practices for implementing workflows with state management and streaming. Additionally, it compares the Functional API with the Graph API, highlighting their differences and use cases.
- [Functional API Documentation](https://langchain-ai.github.io/langgraph/how-tos/use-functional-api/): This page provides comprehensive guidance on using the Functional API, including creating workflows, handling parallel execution, and integrating with other APIs. It covers various features such as retry policies, caching, and human-in-the-loop workflows, along with practical examples. Additionally, it discusses memory management strategies for both short-term and long-term use cases.
- [Overview of LangGraph Platform](https://langchain-ai.github.io/langgraph/concepts/langgraph_platform/): The LangGraph Platform is designed for developing, deploying, and managing long-running agent workflows with ease. This page outlines the platform's features, including streaming support, background runs, and memory management, which enhance the performance and reliability of agent applications. Additionally, it provides links to resources for getting started and deploying agents effectively.
- [LangGraph Platform Quickstart Guide](https://langchain-ai.github.io/langgraph/tutorials/langgraph-platform/local-server/): This quickstart guide provides step-by-step instructions for running a LangGraph application locally. It covers prerequisites, installation of the LangGraph CLI, app creation, dependency installation, and launching the server. Additionally, it includes testing your application using the LangGraph Studio and API.
- [LangGraph Platform Deployment Quickstart](https://langchain-ai.github.io/langgraph/cloud/quick_start/): This quickstart guide provides step-by-step instructions for deploying an application on the LangGraph Platform using GitHub. It covers prerequisites, repository creation, deployment procedures, and testing your application and API. Follow these steps to successfully set up and run your application in the LangGraph environment.
- [Overview of LangGraph Platform Components](https://langchain-ai.github.io/langgraph/concepts/langgraph_components/): This page provides a comprehensive overview of the various components that make up the LangGraph Platform. It details the functionalities of each component, including the LangGraph Server, CLI, Studio, SDKs, and the control and data planes. Users can learn how these components work together to facilitate the development, deployment, and management of LangGraph applications.
- [LangGraph Server Documentation](https://langchain-ai.github.io/langgraph/concepts/langgraph_server/): This page provides an overview of the LangGraph Server, an API designed for creating and managing agent-based applications. It details the server versions, application structure, deployment components, and the use of assistants, persistence, and task queues. Additionally, it includes links to further resources and guides for effective deployment and usage.
- [LangGraph Application Structure Guide](https://langchain-ai.github.io/langgraph/concepts/application_structure/): This page provides an overview of the structure of a LangGraph application, detailing the essential components such as the configuration file, dependencies, graphs, and environment variables. It includes examples of directory structures for both Python and JavaScript applications, as well as guidance on how to specify the necessary information for deployment. Additionally, it covers key concepts related to the configuration file and the role of dependencies and environment variables in the application.
- [Setting Up a LangGraph Application with requirements.txt](https://langchain-ai.github.io/langgraph/cloud/deployment/setup/): This guide provides step-by-step instructions for configuring a LangGraph application for deployment using a requirements.txt file to manage dependencies. It covers essential topics such as specifying dependencies, defining environment variables, and creating the LangGraph configuration file. Additionally, it includes examples and tips for alternative setup methods.
- [Setting Up a LangGraph Application with pyproject.toml](https://langchain-ai.github.io/langgraph/cloud/deployment/setup_pyproject/): This guide provides step-by-step instructions for configuring a LangGraph application using the `pyproject.toml` file for dependency management. It covers the necessary components, including specifying dependencies, environment variables, and defining graphs, along with examples and best practices. Additionally, it offers tips for alternative setups and links to further resources for deployment.
- [Setting Up a LangGraph.js Application](https://langchain-ai.github.io/langgraph/cloud/deployment/setup_javascript/): This guide provides step-by-step instructions for configuring a LangGraph.js application for deployment on the LangGraph Platform or for self-hosting. It covers essential topics such as specifying dependencies, environment variables, defining graphs, and creating the necessary configuration file. By following this walkthrough, users will learn how to structure their application and prepare it for deployment.
- [Customizing Your Dockerfile in LangGraph](https://langchain-ai.github.io/langgraph/cloud/deployment/custom_docker/): This page provides a guide on how to customize your Dockerfile by adding additional commands through the `langgraph.json` configuration file. It explains how to specify the `dockerfile_lines` key to include necessary dependencies, such as installing system packages and Python libraries. An example is provided to illustrate the process of integrating the Pillow library for image processing.
- [LangGraph CLI Documentation](https://langchain-ai.github.io/langgraph/concepts/langgraph_cli/): This page provides an overview of the LangGraph CLI, a command-line tool for building and running the LangGraph API server locally. It includes installation instructions, a list of core commands, and their descriptions to help users effectively utilize the CLI for development and deployment. For further details, users can refer to the LangGraph CLI Reference.
- [LangGraph Studio Documentation](https://langchain-ai.github.io/langgraph/concepts/langgraph_studio/): This page provides an overview of LangGraph Studio, an IDE for visualizing, interacting with, and debugging agentic systems that utilize the LangGraph Server API. It outlines the prerequisites for using the studio, key features, and the two operational modes: Graph mode and Chat mode. Additionally, it includes links to further resources for getting started with LangGraph Studio.
- [Getting Started with LangGraph Studio](https://langchain-ai.github.io/langgraph/cloud/how-tos/studio/quick_start/): This page provides a comprehensive guide on how to connect and use LangGraph Studio with both deployed applications on the LangGraph Platform and local development servers. It includes instructions for installation, running the server, accessing the Studio UI, and debugging options. Additionally, troubleshooting tips and next steps for further exploration of LangGraph Studio features are also provided.
- [Running Applications: A Comprehensive Guide](https://langchain-ai.github.io/langgraph/cloud/how-tos/invoke_studio/): This page provides a detailed guide on how to submit a run to your application, covering both Graph and Chat modes. It includes instructions on specifying input, managing assistants, enabling streaming, and using breakpoints. Additionally, it offers tips for running applications from specific checkpoints in existing threads.
- [Managing Assistants in LangGraph Studio](https://langchain-ai.github.io/langgraph/cloud/how-tos/studio/manage_assistants/): This page provides guidance on how to manage assistants within LangGraph Studio, including viewing, editing, and updating assistant configurations. It covers both Graph mode and Chat mode, detailing how to activate assistants and make changes to their settings. Users will learn how to navigate the interface to effectively manage their assistant configurations for graph runs.
- [Managing Threads in Studio](https://langchain-ai.github.io/langgraph/cloud/how-tos/threads_studio/): This page provides a comprehensive guide on how to view and edit threads within the Studio application. It covers both Graph and Chat modes, detailing the steps to create new threads, view thread history, and edit thread states. Additionally, it includes links to related concepts for further learning.
- [Modifying Prompts in LangGraph Studio](https://langchain-ai.github.io/langgraph/cloud/how-tos/iterate_graph_studio/): This page provides guidance on how to modify prompts within LangGraph Studio using two methods: direct node editing and the LangSmith Playground interface. It details the configuration options available for nodes, including `langgraph_nodes` and `langgraph_type`, along with examples for both Pydantic models and dataclasses. Additionally, it outlines the steps for editing prompts in the UI and utilizing the LangSmith Playground for testing LLM calls.
- [Debugging LangSmith Traces in LangGraph Studio](https://langchain-ai.github.io/langgraph/cloud/how-tos/clone_traces_studio/): This guide provides step-by-step instructions for opening and debugging LangSmith traces in LangGraph Studio. It covers how to deploy threads and test local agents with remote traces, ensuring a seamless debugging experience. Additionally, it outlines the requirements for local agents and the process for cloning threads for local testing.
- [How to Add Nodes to LangSmith Datasets](https://langchain-ai.github.io/langgraph/cloud/how-tos/datasets_studio/): This guide provides step-by-step instructions on how to add examples from nodes in the thread log to LangSmith datasets. It covers selecting threads, choosing nodes, and editing inputs/outputs before adding them to the dataset. Additionally, it includes links to further resources on evaluating intermediate steps.
- [LangGraph SDK Documentation](https://langchain-ai.github.io/langgraph/concepts/sdk/): This page provides an overview of the LangGraph SDK, including installation instructions for both Python and JavaScript. It details the synchronous and asynchronous client options available for interacting with the LangGraph Server. Additionally, it offers links to further resources and references for the SDK.
- [Integrating Semantic Search in LangGraph](https://langchain-ai.github.io/langgraph/cloud/deployment/semantic_search/): This guide provides step-by-step instructions on how to implement semantic search in your LangGraph deployment. It covers prerequisites, configuration of the store, and usage examples for searching memories and documents by semantic similarity. Additionally, it includes information on using custom embeddings and querying via the LangGraph SDK.
- [Configuring Time-to-Live (TTL) in LangGraph Applications](https://langchain-ai.github.io/langgraph/how-tos/ttl/configure_ttl/): This guide provides detailed instructions on how to configure Time-to-Live (TTL) settings for checkpoints and store items in LangGraph applications. It covers the necessary configurations in the `langgraph.json` file, including strategies for managing data lifecycle and memory. Additionally, it explains how to combine TTL configurations and override them at runtime.
- [LangGraph Authentication & Access Control Overview](https://langchain-ai.github.io/langgraph/concepts/auth/): This page provides a comprehensive guide to the authentication and authorization mechanisms within the LangGraph Platform. It explains the core concepts of authentication versus authorization, outlines default security models, and details the system architecture involved in user identity management. Additionally, it covers implementation examples for authentication and authorization handlers, along with common access patterns and supported resources.
- [Custom Authentication Setup for LangGraph Platform](https://langchain-ai.github.io/langgraph/how-tos/auth/custom_auth/): This guide provides step-by-step instructions on how to implement custom authentication in your LangGraph Platform application. It covers the necessary prerequisites, implementation details, configuration updates, and client connection methods. The guide is applicable to both managed and Enterprise self-hosted deployments, but not to Lite self-hosted plans.
- [Documenting API Authentication in OpenAPI for LangGraph](https://langchain-ai.github.io/langgraph/how-tos/auth/openapi_security/): This guide provides instructions on how to customize the security schema for your LangGraph Platform API documentation using OpenAPI. It covers default security schemes for both LangGraph Platform and self-hosted deployments, as well as how to implement custom authentication. Additionally, it includes examples for OAuth2 and API key authentication, along with testing procedures.
- [Managing Assistants in LangGraph](https://langchain-ai.github.io/langgraph/concepts/assistants/): This page provides an overview of how to create and manage assistants within the LangGraph Platform, which allows for separate configuration of agents without altering the core graph logic. It covers the prerequisites, configuration options, and versioning of assistants, highlighting their role in optimizing agent performance for different tasks. Additionally, it includes links to relevant API references and how-to guides for further assistance.
- [Managing Assistants in LangGraph](https://langchain-ai.github.io/langgraph/cloud/how-tos/configuration_cloud/): This documentation page provides a comprehensive guide on how to create, configure, and manage assistants using the LangGraph SDK and Platform UI. It includes code examples in Python and JavaScript, as well as instructions for creating new versions and using previous versions of assistants. Additionally, it covers the process of utilizing assistants in various environments.
- [Understanding Threads in LangGraph](https://langchain-ai.github.io/langgraph/cloud/concepts/threads/): This page provides an overview of threads in the LangGraph framework, detailing how they accumulate the state of runs and the importance of checkpoints. It explains the process of creating threads and retrieving their current and historical states. Additionally, it offers links to further resources on threads, checkpoints, and the LangGraph API for managing thread states.
- [Managing Threads in LangGraph](https://langchain-ai.github.io/langgraph/cloud/how-tos/use_threads/): This documentation page provides a comprehensive guide on how to create, view, and inspect threads using the LangGraph SDK. It includes detailed instructions for creating empty threads, copying existing threads, and initializing threads with prepopulated states. Additionally, it covers how to list and inspect threads, including filtering and sorting options.
- [Understanding Runs in LangGraph Platform](https://langchain-ai.github.io/langgraph/cloud/concepts/runs/): This page provides an overview of what constitutes a run in the LangGraph Platform, including its input, configuration, and metadata. It also highlights the ability to execute runs on threads and offers links to the API reference for managing runs.
- [Starting Background Runs for Your Agent](https://langchain-ai.github.io/langgraph/cloud/how-tos/background_run/): This guide provides step-by-step instructions on how to initiate background runs for your agent using Python, JavaScript, and CURL. It covers the setup process, checking current runs, starting new runs, and retrieving the final results. By following this documentation, users can efficiently manage long-running jobs within their applications.
- [Running Multiple Agents on the Same Thread in LangGraph](https://langchain-ai.github.io/langgraph/cloud/how-tos/same-thread/): This documentation page explains how to run multiple agents on the same thread using the LangGraph Platform. It provides step-by-step examples in Python, JavaScript, and CURL to create agents, run them on a thread, and demonstrate how the second agent can utilize the context from the first agent's responses. By following the examples, users can learn to effectively manage multiple agents and their interactions.
- [Scheduling Cron Jobs with LangGraph](https://langchain-ai.github.io/langgraph/cloud/how-tos/cron_jobs/): This page provides a comprehensive guide on how to schedule cron jobs using the LangGraph Platform. It includes setup instructions for different programming languages, examples of creating and deleting cron jobs, and details on managing stateless cron jobs. Users will learn how to automate tasks such as sending weekly emails without writing custom scripts.
- [Guide to Stateless Runs in LangGraph](https://langchain-ai.github.io/langgraph/cloud/how-tos/stateless_runs/): This page provides a comprehensive guide on how to implement stateless runs using the LangGraph Platform. It includes setup instructions for various programming languages, examples of streaming results, and methods for waiting for stateless results. Users will learn how to execute runs without maintaining persistent state, making their applications more efficient.
- [Configurable Headers in LangGraph](https://langchain-ai.github.io/langgraph/cloud/how-tos/configurable_headers/): This page provides guidance on how to configure headers dynamically in the LangGraph platform to modify agent behavior and permissions. It details how to include or exclude specific headers in the runtime configuration using the `langgraph.json` file. Additionally, it explains how to access these headers within your graph and offers an option to opt-out of configurable headers.
- [Streaming in LangGraph Platform](https://langchain-ai.github.io/langgraph/cloud/concepts/streaming/): This page provides an overview of streaming capabilities within the LangGraph Platform, detailing the various streaming modes available for LLM applications. It includes instructions for creating streaming runs, handling stateless runs, and joining active background runs. Additionally, code examples in Python, JavaScript, and cURL are provided to illustrate the implementation of these features.
- [Streaming Outputs with LangGraph SDK](https://langchain-ai.github.io/langgraph/cloud/how-tos/streaming/): This documentation page provides detailed instructions on how to stream outputs from the LangGraph API server using the LangGraph SDK in Python, JavaScript, and cURL. It covers various streaming modes, including updates, values, and custom data, along with examples for each mode. Additionally, it explains how to handle subgraphs, debug information, and LLM tokens during streaming.
- [Human-in-the-Loop Workflows in LangGraph](https://langchain-ai.github.io/langgraph/cloud/how-tos/add-human-in-the-loop/): This page provides an overview of the human-in-the-loop (HIL) capabilities in LangGraph, allowing for human intervention in automated processes. It details the `interrupt` function, which pauses execution for human input, and includes examples in Python, JavaScript, and cURL for implementing HIL workflows. Additionally, it links to further resources for understanding and utilizing HIL features effectively.
- [Using Breakpoints in LangGraph](https://langchain-ai.github.io/langgraph/cloud/how-tos/human_in_the_loop_breakpoint/): This page provides an overview of how to set and use breakpoints in LangGraph to pause graph execution for inspection. It includes examples for setting breakpoints at compile time and run time in Python, JavaScript, and cURL. Additionally, it offers guidance on resuming execution after hitting a breakpoint.
- [Using Time Travel in LangGraph](https://langchain-ai.github.io/langgraph/cloud/how-tos/human_in_the_loop_time_travel/): This page provides a comprehensive guide on how to utilize the time travel functionality in LangGraph, allowing users to resume execution from previous checkpoints. It outlines the steps to run a graph, identify checkpoints, modify graph states, and resume execution. Additionally, the page includes code examples in Python, JavaScript, and cURL for practical implementation.
- [Model Context Protocol (MCP) Endpoint Documentation](https://langchain-ai.github.io/langgraph/concepts/server-mcp/): This page provides comprehensive documentation on the Model Context Protocol (MCP) endpoint available in LangGraph Server. It covers the requirements for using MCP, how to expose agents as MCP tools, and includes examples for connecting with MCP-compliant clients in various programming languages. Additionally, it outlines session behavior, authentication, and instructions for disabling the MCP endpoint.
- [Managing Double Texting in LangGraph](https://langchain-ai.github.io/langgraph/concepts/double_texting/): This page provides an overview of how to handle double texting scenarios in LangGraph, where users may send multiple messages before the first has completed. It outlines four strategies: Reject, Enqueue, Interrupt, and Rollback, each with links to detailed configuration guides. Prerequisites for implementing these strategies include having the LangGraph Server set up.
- [Using the Interrupt Option in Double Texting](https://langchain-ai.github.io/langgraph/cloud/how-tos/interrupt_concurrent/): This guide provides detailed instructions on how to utilize the `interrupt` option for double texting, allowing users to interrupt a prior run of a graph and start a new one. It includes setup instructions, code examples in Python, JavaScript, and CURL, as well as guidance on viewing run results and verifying the status of interrupted runs. Familiarity with double texting is assumed, and a link to a conceptual guide is provided for further understanding.
- [Using the Rollback Option in Double Texting](https://langchain-ai.github.io/langgraph/cloud/how-tos/rollback_concurrent/): This guide provides detailed instructions on how to utilize the `rollback` option in double texting, which allows users to interrupt a previous run and start a new one while permanently deleting the prior run from the database. It includes setup instructions, code examples in Python, JavaScript, and CURL, and demonstrates how to view run results and verify the deletion of the original run. Familiarity with double texting is assumed, and a link to a conceptual guide is provided for further reading.
- [Using the Reject Option in Double Texting](https://langchain-ai.github.io/langgraph/cloud/how-tos/reject_concurrent/): This guide provides an overview of the `reject` option in double texting, which prevents new runs of a graph from starting while an original run is still in progress. It includes setup instructions, code examples in Python, JavaScript, and CURL, and demonstrates how to handle errors when attempting to create concurrent runs. Additionally, it shows how to view the results of the original run after the rejection.
- [Using the Enqueue Option for Double Texting](https://langchain-ai.github.io/langgraph/cloud/how-tos/enqueue_concurrent/): This guide provides an overview of the `enqueue` option for double texting, which allows interruptions to be queued and executed in the order they are received. It includes setup instructions, code examples in Python, JavaScript, and CURL for creating runs, and methods for viewing run results. Familiarity with double texting concepts is assumed, and a helper function for output formatting is also provided.
- [Understanding Webhooks in LangGraph Platform](https://langchain-ai.github.io/langgraph/cloud/concepts/webhooks/): This page provides an overview of webhooks and their role in enabling event-driven communication between LangGraph Platform applications and external services. It explains how to use the `webhook` parameter in various endpoints to trigger requests upon the completion of API calls. For further details, a link to a comprehensive how-to guide is also included.
- [Using Webhooks with LangGraph Platform](https://langchain-ai.github.io/langgraph/cloud/how-tos/webhooks/): This documentation page provides a comprehensive guide on how to implement webhooks in the LangGraph Platform to receive updates after API calls. It includes details on supported endpoints, setup instructions for different programming languages, and examples of how to specify webhook parameters in API requests. Additionally, it covers security measures and testing tools for verifying webhook functionality.
- [Scheduling Tasks with Cron Jobs on LangGraph Platform](https://langchain-ai.github.io/langgraph/cloud/concepts/cron_jobs/): This page provides an overview of how to use cron jobs on the LangGraph Platform to run assistants on a defined schedule. It explains the process of setting up a cron job, including specifying the schedule, assistant, and input. Additionally, it includes links to a how-to guide and API reference for further details.
- [Scheduling Cron Jobs with LangGraph](https://langchain-ai.github.io/langgraph/cloud/how-tos/cron_jobs/): This page provides a comprehensive guide on how to use cron jobs with the LangGraph Platform to automate graph executions on a schedule. It includes setup instructions for various programming languages, examples of creating and deleting cron jobs, and tips for managing stateless cron jobs. Users will learn how to efficiently schedule tasks without manual intervention, ensuring timely execution of automated processes.
- [Adding Custom Lifespan Events in LangGraph](https://langchain-ai.github.io/langgraph/how-tos/http/custom_lifespan/): This page provides a guide on how to implement custom lifespan events in your LangGraph Platform applications, specifically for Python deployments. It covers the initialization and cleanup of resources during server startup and shutdown using FastAPI. Additionally, it includes code examples and configuration steps to help you integrate these events into your application.
- [Adding Custom Middleware to LangGraph Platform](https://langchain-ai.github.io/langgraph/how-tos/http/custom_middleware/): This page provides a step-by-step guide on how to add custom middleware to your server when deploying agents to the LangGraph Platform. It covers the necessary code implementation using FastAPI, configuration settings in `langgraph.json`, and instructions for testing and deploying your application. Additionally, it offers links to related topics such as custom routes and lifespan events for further customization.
- [Adding Custom Routes in LangGraph](https://langchain-ai.github.io/langgraph/how-tos/http/custom_routes/): This page provides a step-by-step guide on how to add custom routes to your LangGraph platform application using a Starlette or FastAPI app. It includes instructions for creating a new app, configuring the `langgraph.json` file, and testing the server locally. Additionally, it explains how custom routes can override default endpoints and offers suggestions for further customization.
- [LangGraph Deployment Options](https://langchain-ai.github.io/langgraph/concepts/deployment_options/): This page outlines the various deployment options available for the LangGraph Platform, including Cloud SaaS, Self-Hosted Data Plane, Self-Hosted Control Plane, and Standalone Container. Each option is described in detail, highlighting key features, management responsibilities, and compatibility. A comparison table is also provided to help users choose the best deployment strategy for their needs.
- [LangGraph Data Plane Overview](https://langchain-ai.github.io/langgraph/concepts/langgraph_data_plane/): This page provides a comprehensive overview of the LangGraph Data Plane, detailing its components including the server infrastructure, listener application, and data management systems like Postgres and Redis. It also covers key features such as autoscaling, static IP addresses, and custom configurations for Postgres and Redis. Additionally, the page outlines telemetry, licensing, and tracing functionalities relevant to different deployment options.
- [LangGraph Control Plane Overview](https://langchain-ai.github.io/langgraph/concepts/langgraph_control_plane/): This page provides a comprehensive overview of the LangGraph Control Plane, detailing its UI and API functionalities for managing LangGraph Servers. It covers deployment types, environment variables, database provisioning, and asynchronous deployment processes. Additionally, it highlights the integration with LangSmith for tracing projects.
- [Cloud SaaS Deployment Guide](https://langchain-ai.github.io/langgraph/concepts/langgraph_cloud/): This page provides a comprehensive guide on deploying the LangGraph Server using the Cloud SaaS model. It outlines the roles of the control plane and data plane, detailing their functionalities and management. Additionally, it includes an architectural diagram to illustrate the deployment structure.
- [Deployment Guide for LangGraph Platform](https://langchain-ai.github.io/langgraph/cloud/deployment/cloud/): This page provides a comprehensive guide on how to deploy applications to the LangGraph Platform using GitHub repositories. It covers prerequisites, steps for creating new deployments and revisions, managing deployment settings, and viewing logs. Additionally, it includes instructions for whitelisting IP addresses and modifying GitHub repository access.
- [Self-Hosted Data Plane Deployment Guide](https://langchain-ai.github.io/langgraph/concepts/langgraph_self_hosted_data_plane/): This page provides an overview of the Self-Hosted Data Plane deployment option, which allows users to manage their data plane infrastructure while offloading control plane management to LangChain. It outlines the requirements, architecture, and supported compute platforms for deployment. Additionally, it includes important information regarding the beta status of this deployment option.
- [Deploying a Self-Hosted Data Plane](https://langchain-ai.github.io/langgraph/cloud/deployment/self_hosted_data_plane/): This page provides a comprehensive guide on deploying a Self-Hosted Data Plane using Kubernetes and Amazon ECS. It outlines the prerequisites, setup steps, and configuration details necessary for a successful deployment. Additionally, it highlights the current beta status of this deployment option.
- [Self-Hosted Control Plane Deployment Guide](https://langchain-ai.github.io/langgraph/concepts/langgraph_self_hosted_control_plane/): This page provides an overview of the Self-Hosted Control Plane deployment option, currently in beta. It outlines the requirements, architecture, and compute platforms supported for deploying the control and data planes in your cloud environment. Additionally, it includes important links and resources for managing your self-hosted infrastructure.
- [Deploying a Self-Hosted Control Plane](https://langchain-ai.github.io/langgraph/cloud/deployment/self_hosted_control_plane/): This page provides a comprehensive guide on deploying a Self-Hosted Control Plane using Kubernetes. It outlines the prerequisites, setup steps, and configuration details necessary for a successful deployment. Additionally, it highlights the beta status of this deployment option and includes links to relevant resources for further assistance.
- [Deploying LangGraph Server with Standalone Container](https://langchain-ai.github.io/langgraph/concepts/langgraph_standalone_container/): This page provides a comprehensive guide on deploying a LangGraph Server using the Standalone Container option. It outlines the architecture, supported compute platforms, and differences between Lite and Enterprise server versions. Users will find essential information on managing the data plane infrastructure without a control plane.
- [Deploying a Standalone Container with LangGraph](https://langchain-ai.github.io/langgraph/cloud/deployment/standalone_container/): This documentation provides a comprehensive guide on deploying a standalone container for the LangGraph application. It covers prerequisites, environment variable configurations, and deployment methods using Docker and Docker Compose. Additionally, it includes instructions for deploying on Kubernetes using Helm.
- [Scalability and Resilience of LangGraph Platform](https://langchain-ai.github.io/langgraph/concepts/scalability_and_resilience/): This page provides an overview of the scalability and resilience features of the LangGraph Platform. It details how the platform handles server and queue scalability, as well as the mechanisms in place for ensuring resilience during both graceful and hard shutdowns. Additionally, it covers the resilience strategies employed for Postgres and Redis to maintain service availability.
- [LangGraph Platform Plans Overview](https://langchain-ai.github.io/langgraph/concepts/plans/): This page provides an overview of the different plans available for the LangGraph Platform, including Developer, Plus, and Enterprise options. Each plan offers varying deployment options, usage limits, and features tailored to different user needs. For detailed pricing and related resources, links to additional documentation are also included.
# Examples
- [Building an Agentic RAG System](https://langchain-ai.github.io/langgraph/tutorials/rag/langgraph_agentic_rag/): This tutorial guides you through the process of creating a retrieval agent (RAG) system using LangChain and LangGraph. You will learn how to fetch and preprocess documents, create a retriever tool, and build an agentic RAG that intelligently decides when to retrieve information or respond directly to user queries. By the end, you'll have a functional system capable of semantic search and context-aware responses.
- [Building a Multi-Agent Supervisor System](https://langchain-ai.github.io/langgraph/tutorials/multi_agent/agent_supervisor/): This tutorial guides you through the process of creating a multi-agent supervisor system using specialized agents for research and math tasks. You will learn how to set up the environment, create individual worker agents, and implement a supervisor that orchestrates their interactions. By the end, you'll have a fully functional multi-agent architecture capable of handling complex queries.
- [Building a SQL Agent with LangChain](https://langchain-ai.github.io/langgraph/tutorials/sql-agent/): This tutorial provides a step-by-step guide on how to create a SQL agent capable of answering questions about a SQL database. It covers the setup of necessary dependencies, configuration of a SQLite database, and the implementation of a prebuilt agent that interacts with the database to generate and execute queries. Additionally, it discusses customizing the agent for more control over its behavior.
- [Custom Run ID, Tags, and Metadata for LangSmith Graph Runs](https://langchain-ai.github.io/langgraph/how-tos/run-id-langsmith/): This guide provides instructions on how to pass a custom run ID and set tags and metadata for graph runs in LangSmith. It covers prerequisites, configuration options, and includes code examples for setting up and running a graph with LangGraph. Additionally, it explains how to view and filter traces in the LangSmith platform.
- [Custom Authentication Setup for Chatbots](https://langchain-ai.github.io/langgraph/tutorials/auth/getting_started/): This tutorial guides you through the process of setting up custom authentication for a chatbot using the LangGraph platform. You will learn how to implement token-based security to control user access, starting with a basic example and preparing for more advanced authentication methods in future tutorials. By the end, you'll have a functional chatbot that restricts access to authenticated users.
- [Implementing Private Conversations in Chatbots](https://langchain-ai.github.io/langgraph/tutorials/auth/resource_auth/): This tutorial guides you through extending a chatbot to enable private conversations for each user by implementing resource-level access control. You'll learn how to add authorization handlers to ensure users can only access their own threads and test the functionality to confirm proper access restrictions. Additionally, the tutorial covers scoped authorization handlers for more granular control over resource access.
- [Integrating OAuth2 Authentication with Supabase](https://langchain-ai.github.io/langgraph/tutorials/auth/add_auth_server/): This tutorial guides you through replacing hard-coded tokens with real user accounts using OAuth2 for secure authentication in your LangGraph application. You'll learn how to set up Supabase as your identity provider, implement token validation, and ensure proper user authorization. By the end, you'll have a production-ready authentication system that allows users to securely access their own data.
- [Rebuilding Graphs at Runtime in LangGraph](https://langchain-ai.github.io/langgraph/cloud/deployment/graph_rebuild/): This guide explains how to rebuild your graph at runtime with different configurations in LangGraph. It covers the necessary prerequisites, how to define graphs, and the steps to modify your graph-making function for dynamic behavior based on user input. Additionally, it provides examples of both static and dynamic graph configurations.
- [Interacting with RemoteGraph in LangGraph](https://langchain-ai.github.io/langgraph/how-tos/use-remote-graph/): This documentation page provides a comprehensive guide on how to interact with a LangGraph Platform deployment using the RemoteGraph interface. It covers the initialization of RemoteGraph, invoking the graph both asynchronously and synchronously, and utilizing it as a subgraph. Additionally, it includes code examples in Python and JavaScript to facilitate understanding and implementation.
- [Deploying Agents on LangGraph Platform](https://langchain-ai.github.io/langgraph/how-tos/autogen-langgraph-platform/): This page provides a comprehensive guide on how to deploy agents like AutoGen and CrewAI using the LangGraph Platform. It covers the necessary setup, agent definition, and wrapping the agent in a LangGraph node for deployment. Additionally, it highlights the benefits of using LangGraph for scalable infrastructure and memory support.
- [Integrating LangGraph with React: A Comprehensive Guide](https://langchain-ai.github.io/langgraph/cloud/how-tos/use_stream_react/): This documentation provides a detailed guide on how to integrate the LangGraph platform into your React applications using the `useStream()` hook. It covers installation, key features, example implementations, and customization options for building chat experiences. Additionally, it includes advanced topics such as event handling, TypeScript support, and managing conversation threads.
- [Implementing Generative User Interfaces with LangGraph](https://langchain-ai.github.io/langgraph/cloud/how-tos/generative_ui_react/): This documentation provides a comprehensive guide on how to implement Generative User Interfaces (Generative UI) using the LangGraph platform. It covers prerequisites, step-by-step tutorials for defining UI components, sending them in graphs, and handling them in React applications. Additionally, it includes how-to guides for customizing components and managing UI state effectively.
# Resources
- [LangGraph FAQ](https://langchain-ai.github.io/langgraph/concepts/faq/): This FAQ page provides answers to common questions about LangGraph, an orchestration framework for complex agentic systems. It covers topics such as the differences between LangGraph and LangChain, performance impacts, open-source status, and compatibility with various LLMs. Additionally, it outlines the distinctions between LangGraph and LangGraph Platform, including features and deployment options.
- [Getting Started with LangGraph Templates](https://langchain-ai.github.io/langgraph/concepts/template_applications/): This page provides an overview of open source reference applications known as templates, designed to help users quickly build applications with LangGraph. It includes installation instructions for the LangGraph CLI, a list of available templates with their descriptions, and guidance on creating and deploying a new LangGraph app. Users can find links to repositories for each template and next steps for customizing their applications.
- [Guide to Using llms.txt and llms-full.txt for LLMs](https://langchain-ai.github.io/langgraph/llms-txt-overview/): This page provides an overview of the `llms.txt` and `llms-full.txt` formats, which facilitate access to programming documentation for large language models (LLMs) and agents. It outlines the differences between the two formats, usage instructions via an MCP server, and best practices for integrating these files into integrated development environments (IDEs). Additionally, it highlights considerations for managing large documentation files effectively.
- [Community Agents for LangGraph](https://langchain-ai.github.io/langgraph/agents/prebuilt/): This page provides a list of community-built libraries that extend the functionality of LangGraph. Each entry includes the library name, GitHub URL, a brief description, and additional metrics like weekly downloads and stars. Additionally, it outlines how to contribute your own library to the LangGraph documentation.
- [LangGraph Error Reference Guide](https://langchain-ai.github.io/langgraph/troubleshooting/errors/index/): This page serves as a comprehensive reference for resolving common errors encountered while using the LangGraph platform. It includes a list of error codes and links to detailed guides for troubleshooting specific issues. Users can find solutions for errors related to graph recursion, concurrent updates, node return values, and more.
- [Handling Recursion Limits in LangGraph](https://langchain-ai.github.io/langgraph/troubleshooting/errors/GRAPH_RECURSION_LIMIT/): This page provides guidance on managing recursion limits in LangGraph's StateGraph. It explains how to identify potential infinite loops in your graph and offers solutions for increasing the recursion limit when working with complex graphs. Additionally, it includes code examples to illustrate the concepts discussed.
- [Handling INVALID_CONCURRENT_GRAPH_UPDATE in LangGraph](https://langchain-ai.github.io/langgraph/troubleshooting/errors/INVALID_CONCURRENT_GRAPH_UPDATE/): This page explains the INVALID_CONCURRENT_GRAPH_UPDATE error that occurs in LangGraph when multiple nodes attempt to update the same state property concurrently. It provides an example of how this error can arise and offers a solution by using a reducer to combine values from parallel node executions. Additionally, troubleshooting tips are included to help resolve this issue.
- [Handling Invalid Node Return Values in LangGraph](https://langchain-ai.github.io/langgraph/troubleshooting/errors/INVALID_GRAPH_NODE_RETURN_VALUE/): This page provides guidance on the error encountered when a LangGraph node returns a non-dict value. It includes an example of incorrect node implementation and the resulting error message. Additionally, troubleshooting tips are offered to ensure that all nodes return the expected dictionary format.
- [Handling Multiple Subgraphs in LangGraph](https://langchain-ai.github.io/langgraph/troubleshooting/errors/MULTIPLE_SUBGRAPHS/): This page discusses the limitations of calling multiple subgraphs within a single LangGraph node when checkpointing is enabled. It provides troubleshooting tips to resolve related errors, including suggestions for compiling subgraphs without checkpointing and using the Send API for graph calls.
- [Handling INVALID_CHAT_HISTORY Error in create_react_agent](https://langchain-ai.github.io/langgraph/troubleshooting/errors/INVALID_CHAT_HISTORY/): This page provides an overview of the INVALID_CHAT_HISTORY error encountered in the create_react_agent function when a malformed list of messages is passed. It outlines the potential causes of the error and offers troubleshooting steps to resolve it. Users can learn how to properly invoke the graph and manage tool calls to avoid this issue.
- [Handling INVALID_LICENSE Error in LangGraph Platform](https://langchain-ai.github.io/langgraph/troubleshooting/errors/INVALID_LICENSE/): This page provides guidance on troubleshooting the INVALID_LICENSE error encountered when starting a self-hosted LangGraph Platform server. It outlines the scenarios in which this error may occur and offers solutions based on different deployment types. Additionally, it includes steps to verify the necessary credentials for successful deployment.
- [LangGraph Studio Troubleshooting Guide](https://langchain-ai.github.io/langgraph/troubleshooting/studio/): This page provides troubleshooting solutions for common connection issues encountered in LangGraph Studio, particularly with Safari and Brave browsers. It also addresses potential graph edge issues and offers methods to define routing paths for conditional edges. Users can find step-by-step instructions for resolving these issues using Cloudflare Tunnel and browser settings.
- [LangGraph Case Studies](https://langchain-ai.github.io/langgraph/adopters/): This page provides a comprehensive list of companies that have successfully implemented LangGraph, showcasing their unique use cases and the benefits they have achieved. Each entry includes links to detailed case studies or blog posts for further reading. If your company uses LangGraph, you are encouraged to share your success story to contribute to this growing collection.
+7 -1
View File
@@ -12,12 +12,18 @@
options:
members:
- SerializerProtocol
- CipherProtocol
::: langgraph.checkpoint.serde.jsonplus
options:
members:
- JsonPlusSerializer
::: langgraph.checkpoint.serde.encrypted
options:
members:
- EncryptedSerializer
::: langgraph.checkpoint.memory
::: langgraph.checkpoint.sqlite
@@ -32,4 +38,4 @@
::: langgraph.checkpoint.postgres.aio
options:
members:
- AsyncPostgresSaver
- AsyncPostgresSaver
@@ -0,0 +1,57 @@
.agent-layout {
display: flex;
flex-wrap: nowrap;
gap: 1rem;
align-items: flex-start;
margin-top: 1rem;
}
.agent-layout h3 {
margin: 0;
}
.agent-graph-features {
display: flex;
flex-direction: column;
gap: 0.5rem;
padding: 1rem;
max-width: 300px;
flex-shrink: 0;
border: 1px solid var(--md-default-fg-color--lightest);
border-radius: 0.5rem;
background-color: var(--md-default-bg-color);
}
.agent-graph-features label {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.9rem;
color: var(--md-typeset-color);
cursor: pointer;
}
.agent-graph-features input[type="checkbox"] {
accent-color: var(--md-accent-fg-color);
transform: scale(1.2);
}
.agent-graph-container {
flex: 1 1 50%;
max-width: 70%;
padding: 1rem;
overflow: auto;
height: auto;
box-sizing: border-box;
border: 1px solid var(--md-default-fg-color--lightest);
border-radius: 0.5rem;
background-color: var(--md-default-bg-color);
}
.agent-graph-container img {
display: block;
margin: 0 auto;
}
@@ -6,7 +6,7 @@ In this tutorial, you will build a basic chatbot. This chatbot is the basis for
Before you start this tutorial, ensure you have access to a LLM that supports
tool-calling features, such as [OpenAI](https://platform.openai.com/api-keys),
[Anthropic](https://console.anthropic.com/settings/admin-keys), or
[Anthropic](https://console.anthropic.com/settings/keys), or
[Google Gemini](https://ai.google.dev/gemini-api/docs/api-key).
## 1. Install packages
@@ -146,7 +146,7 @@ graph_builder.add_node("tools", tool_node)
!!! note
If you do not want to build this yourself in the future, you can use LangGraph's prebuilt [ToolNode](https://langchain-ai.github.io/langgraph/reference/prebuilt/#toolnode).
If you do not want to build this yourself in the future, you can use LangGraph's prebuilt [ToolNode](https://langchain-ai.github.io/langgraph/reference/agents/#langgraph.prebuilt.tool_node.ToolNode).
## 6. Define the `conditional_edges`
+21
View File
@@ -0,0 +1,21 @@
# Examples
The pages in this section provide end-to-end examples for the following topics:
## General
- [Agentic RAG](./rag/langgraph_adaptive_rag.ipynb)
- [Agent Supervisor](./multi_agent/agent_supervisor.ipynb)
- [SQL agent](./sql-agent.ipynb)
- [Graph runs in LangSmith](../how-tos/run-id-langsmith.ipynb)
## LangGraph Platform
- [Set up custom authentication](./auth/getting_started.md)
- [Make conversations private](./auth/resource_auth.md)
- [Connect an authentication provider](./auth/add_auth_server.md)
- [Rebuild graph at runtime](../cloud/deployment/graph_rebuild.md)
- [Use RemoteGraph](../how-tos/use-remote-graph.md)
- [Deploy CrewAI, AutoGen, and other frameworks](../how-tos/autogen-langgraph-platform.ipynb)
- [Integrate LangGraph into a React app](../cloud/how-tos/use_stream_react.md)
- [Implement Generative User Interfaces with LangGraph](../cloud/how-tos/generative_ui_react.md)
+3 -31
View File
@@ -19,7 +19,6 @@ theme:
- content.tabs.link
- content.action.edit
- content.tooltips
- header.autohide
- navigation.indexes
- navigation.footer
- navigation.instant
@@ -28,7 +27,6 @@ theme:
- navigation.instant.progress
- navigation.path
- navigation.tabs
- navigation.tabs.sticky
- navigation.top
- navigation.prune
- navigation.tracking
@@ -181,6 +179,7 @@ nav:
- cloud/how-tos/studio/manage_assistants.md
- cloud/how-tos/threads_studio.md
- cloud/how-tos/iterate_graph_studio.md
- cloud/how-tos/studio/run_evals.md
- cloud/how-tos/clone_traces_studio.md
- cloud/how-tos/datasets_studio.md
- LangGraph SDK: concepts/sdk.md
@@ -366,16 +365,6 @@ markdown_extensions:
hooks:
- _scripts/notebook_hooks.py
extra:
consent:
title: Cookie consent
actions:
- accept
- reject
description: >-
We use cookies to recognize your repeated visits and preferences, as well
as to measure the effectiveness of our documentation and whether users
find what they're searching for. <strong>Clicking "Accept" makes our
documentation better. Thank you!</strong> ❤️
social:
- icon: fontawesome/brands/js
link: https://langchain-ai.github.io/langgraphjs/
@@ -383,25 +372,6 @@ extra:
link: https://github.com/langchain-ai/langgraph
- icon: fontawesome/brands/twitter
link: https://twitter.com/LangChainAI
analytics:
provider: google
property: G-G8X6ELZYE0
feedback:
title: Was this page helpful?
ratings:
- icon: material/emoticon-happy-outline
name: This page was helpful
data: 1
note: >-
Thanks for your feedback!
- icon: material/emoticon-sad-outline
name: This page could be improved
data: 0
note: >-
Thanks for your feedback! Please help us improve this page by adding to the discussion below.
shared_analytics:
provider: google
property: G-47WX3HKKY2
validation:
# https://www.mkdocs.org/user-guide/configuration/
# We are still raising for omitted files because they determine the breadcrumbs for pages.
@@ -418,3 +388,5 @@ extra_css:
- stylesheets/version_admonitions.css
- stylesheets/logos.css
- stylesheets/sticky_navigation.css
- stylesheets/agent_graph_widget.css
+11 -2
View File
@@ -1,5 +1,16 @@
{% extends "base.html" %}
{% block analytics %}
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-T35S4S46');</script>
<!-- End Google Tag Manager -->
{% endblock %}
{% block extrahead %}
<meta name="algolia-site-verification" content="165B7E7C89E49946" />
<style>
@@ -185,7 +196,6 @@
</style>
{% endblock %}
{% block content %}
<div class="notebook-links">
{% if page.nb_url %}
@@ -209,7 +219,6 @@
{% endif %}
{% endblock %}
{% block announce %}
<strong>We are growing and hiring for multiple roles for LangChain, LangGraph and LangSmith. <a href="https://www.langchain.com/careers" target="_blank" rel="noopener noreferrer"> Join our team!</a></strong>
{% endblock %}
Generated
+6 -5
View File
@@ -2590,7 +2590,7 @@ wheels = [
[[package]]
name = "langgraph"
version = "0.4.5"
version = "0.4.7"
source = { editable = "../libs/langgraph" }
dependencies = [
{ name = "langchain-core" },
@@ -2891,7 +2891,7 @@ test = [
[[package]]
name = "langgraph-prebuilt"
version = "0.1.8"
version = "0.2.2"
source = { editable = "../libs/prebuilt" }
dependencies = [
{ name = "langchain-core" },
@@ -2917,11 +2917,12 @@ dev = [
{ name = "pytest-mock" },
{ name = "pytest-watcher" },
{ name = "ruff" },
{ name = "syrupy" },
]
[[package]]
name = "langgraph-sdk"
version = "0.1.69"
version = "0.1.70"
source = { editable = "../libs/sdk-py" }
dependencies = [
{ name = "httpx" },
@@ -2947,8 +2948,8 @@ dev = [
[[package]]
name = "langgraph-supervisor"
version = "0.0.21"
source = { git = "https://github.com/langchain-ai/langgraph-supervisor-py#6367bebd5462ac899e7def931ac6ab9cc6a9b070" }
version = "0.0.25"
source = { git = "https://github.com/langchain-ai/langgraph-supervisor-py#79380b5c21d3170e2d20dc6c55149ee057a306b1" }
dependencies = [
{ name = "langchain-core" },
{ name = "langgraph" },
-28
View File
@@ -1,28 +0,0 @@
.PHONY: all format build test
# Default target executed when no arguments are given to make.
all: help
format:
go fmt ./...
build:
go build ./...
test:
go test ./...
######################
# HELP
######################
help:
@echo '===================='
@echo '-- DOCUMENTATION --'
@echo '-- LINTING --'
@echo 'format - run code formatters'
@echo 'build - build the project'
@echo 'test - run unit tests'
-10
View File
@@ -1,10 +0,0 @@
module langchain.dev/langgraph
go 1.23.0
toolchain go1.23.9
require (
github.com/google/uuid v1.6.0 // indirect
golang.org/x/sync v0.14.0 // indirect
)
-4
View File
@@ -1,4 +0,0 @@
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
golang.org/x/sync v0.14.0 h1:woo0S4Yywslg6hp4eUFjTVOyKt0RookbpAHG4c1HmhQ=
golang.org/x/sync v0.14.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
-522
View File
@@ -1,522 +0,0 @@
package pregel
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"reflect"
"sort"
"strconv"
"strings"
)
func PrepareNextTasks(
ctx context.Context,
checkpoint Checkpoint,
pendingWrites []interface{},
processes map[string]PregelNode,
channels map[string]BaseChannel,
managed ManagedValueMapping,
config RunnableConfig,
step int,
forExecution bool,
store BaseStore,
checkpointer BaseCheckpointSaver,
// ─ optimisation hints (optional) ─
triggerToNodes map[string][]string,
updatedChannels map[string]struct{},
) (map[string]interface{}, error) {
// Decode checkpoint.id (UUID/xxhash) into raw bytes for deterministic task-id hashing.
cleanID := strings.ReplaceAll(checkpoint.ID, "-", "")
checkpointIDBytes, err := hex.DecodeString(cleanID)
if err != nil {
return nil, err
}
nullVersion := checkpointNullVersion(checkpoint)
tasks := make(map[string]interface{})
// Consume pending sends
for idx := range checkpoint.PendingSends {
task, err := PrepareSingleTask(
ctx,
[]interface{}{PUSH, idx},
"",
checkpoint,
checkpointIDBytes,
nullVersion,
pendingWrites,
processes,
channels,
managed,
config,
step,
forExecution,
store,
checkpointer,
)
if err != nil {
return nil, err
}
if task == nil {
continue
}
if id, ok := taskID(task); ok {
tasks[id] = task
}
}
var candidateNodes []string
if len(updatedChannels) > 0 && len(triggerToNodes) > 0 {
nodeSet := map[string]struct{}{}
for ch := range updatedChannels {
for _, n := range triggerToNodes[ch] {
nodeSet[n] = struct{}{}
}
}
for n := range nodeSet {
candidateNodes = append(candidateNodes, n)
}
sort.Strings(candidateNodes) // deterministic order
} else if len(checkpoint.ChannelVersions) == 0 {
candidateNodes = nil
} else {
for n := range processes {
candidateNodes = append(candidateNodes, n)
}
sort.Strings(candidateNodes)
}
for _, name := range candidateNodes {
task, err := PrepareSingleTask(
ctx,
[]interface{}{PULL, name},
"", // checksum only used when resuming a partial step
checkpoint,
checkpointIDBytes,
nullVersion,
pendingWrites,
processes,
channels,
managed,
config,
step,
forExecution,
store,
checkpointer,
)
if err != nil {
return nil, err
}
if task == nil {
continue
}
if id, ok := taskID(task); ok {
tasks[id] = task
}
}
return tasks, nil
}
func PrepareSingleTask(
ctx context.Context,
taskPath []interface{}, // e.g. [PUSH, idx] OR [PULL, "node"]
taskIDChecksum string, // optional used when resuming
checkpoint Checkpoint, // state captured at end of previous step
checkpointIDBytes []byte, // checkpoint.id as bytes (uuid / xxhash)
checkpointNullVersion interface{}, // sentinel “null” version value
pendingWrites []interface{}, // successful writes from *this* step so far
processes map[string]PregelNode, // graph definition
channels map[string]BaseChannel, // live channel values
managed ManagedValueMapping, // placeholder resolver
config RunnableConfig, // config inherited from graph.Invoke()
step int, // current super-step (n+1)
forExecution bool, // false = planning pass, true = exec pass
store BaseStore, // needed for reads/writes
checkpointer BaseCheckpointSaver, // used only when executing
) (interface{}, error) {
// Ensure checkpoint.ChannelVersions is initialized
if checkpoint.ChannelVersions == nil {
checkpoint.ChannelVersions = make(map[string]int64)
}
cfgSection := config.Configurable
if cfgSection == nil {
cfgSection = map[string]interface{}{}
}
parentNS, _ := cfgSection[CONFIG_KEY_CHECKPOINT_NS].(string)
emitConfig := func(base RunnableConfig, md map[string]interface{}) RunnableConfig {
// Make a shallow copy of the struct
out := base
if out.Configurable == nil {
out.Configurable = map[string]interface{}{}
}
confClone := make(map[string]interface{}, len(out.Configurable))
for k, v := range out.Configurable {
confClone[k] = v
}
confClone[CONFIG_KEY_SCRATCHPAD] = createScratchpad(
out.Configurable[CONFIG_KEY_SCRATCHPAD].(map[string]interface{}),
pendingWrites,
md["langgraph_checkpoint_ns"].(string),
md["langgraph_checkpoint_ns"].(string),
out.Configurable[CONFIG_KEY_RESUME_MAP].(map[string]interface{}),
)
confClone[CONFIG_KEY_CHECKPOINTER] = checkpointer
out.Configurable = confClone
if out.Metadata == nil {
out.Metadata = map[string]interface{}{}
}
for k, v := range md {
out.Metadata[k] = v
}
return out
}
// Convenience for checksum comparison
checkSumMatch := func(need string) error {
if taskIDChecksum != "" && taskIDChecksum != need {
return fmt.Errorf("%s != %s", need, taskIDChecksum)
}
return nil
}
// PUSH
if len(taskPath) > 0 && taskPath[0] == PUSH {
// PUSH triggered via explicit Call (happens during node execution)
// taskPath shape: [PUSH, parentPath, writeIdx, parentTaskID, Call]
if len(taskPath) >= 5 {
call, ok := taskPath[4].(Call)
if ok {
name, isStr := call.Func.(string)
if !isStr {
name = "unknown"
}
// Hash-stable checkpoint namespace
var checkpointNS string
if parentNS == "" {
checkpointNS = name
} else {
checkpointNS = parentNS + NS_SEP + name
}
// Deterministic task-id
taskID := taskIDFunc(
checkpointIDBytes,
checkpointNS,
strconv.Itoa(step),
name,
PUSH,
taskPathStr(taskPath[1]),
fmt.Sprintf("%v", taskPath[2]),
)
if err := checkSumMatch(taskID); err != nil {
return nil, err
}
taskCheckpointNS := checkpointNS + NS_END + taskID
metadata := map[string]interface{}{
"langgraph_step": step,
"langgraph_node": name,
"langgraph_triggers": []string{PUSH},
"langgraph_path": taskPath[:3],
"langgraph_checkpoint_ns": taskCheckpointNS,
}
if forExecution {
var node NodeRunnable
if proc, ok := processes[name]; ok {
node = proc.Node
}
return PregelExecutableTask{
PregelTask: PregelTask{
ID: taskID,
Name: name,
Path: taskPath[:3],
},
Input: call.Input,
Node: node,
Writes: []Write{},
Config: emitConfig(config, metadata),
Triggers: []string{PUSH},
}, nil
}
return PregelTask{ID: taskID, Name: name, Path: taskPath[:3]}, nil
}
}
// ---------------------------------------------------------------------
// 1b. Standard pending-send packet: taskPath shape [PUSH, idx]
// ---------------------------------------------------------------------
if len(taskPath) == 2 {
idx, ok := taskPath[1].(int)
if !ok || idx >= len(checkpoint.PendingSends) {
return nil, nil
}
packet := checkpoint.PendingSends[idx]
proc, ok := processes[packet.Node]
if !ok || proc.Node == nil {
return nil, nil
}
checkpointNS := parentNS
if checkpointNS != "" {
checkpointNS += NS_SEP + packet.Node
} else {
checkpointNS = packet.Node
}
taskID := taskIDFunc(
checkpointIDBytes,
checkpointNS,
strconv.Itoa(step),
packet.Node,
PUSH,
strconv.Itoa(idx),
)
if err := checkSumMatch(taskID); err != nil {
return nil, err
}
taskCheckpointNS := checkpointNS + NS_END + taskID
metadata := map[string]interface{}{
"langgraph_step": step,
"langgraph_node": packet.Node,
"langgraph_triggers": []string{PUSH},
"langgraph_path": taskPath,
"langgraph_checkpoint_ns": taskCheckpointNS,
}
if forExecution {
return PregelExecutableTask{
PregelTask: PregelTask{
ID: taskID,
Name: packet.Node,
Path: taskPath,
},
Input: packet.Arg,
Node: proc.Node,
Writes: nil,
Config: emitConfig(config, metadata),
Triggers: []string{PUSH},
}, nil
}
return PregelTask{ID: taskID, Name: packet.Node, Path: taskPath}, nil
}
// An ill-formed PUSH path nothing to schedule
return nil, nil
}
// PULL branch
if len(taskPath) > 0 && taskPath[0] == PULL {
if len(taskPath) < 2 {
return nil, nil
}
name, ok := taskPath[1].(string)
if !ok {
return nil, nil
}
proc, ok := processes[name]
if !ok || proc.Node == nil {
return nil, nil
}
seen := map[string]interface{}{}
if v, _ := checkpoint.VersionsSeen[name].(map[string]interface{}); v != nil {
for k, vv := range v { // shallow copy
seen[k] = vv
}
}
var triggers []string
for _, ch := range proc.Triggers {
cv, exists := checkpoint.ChannelVersions[ch]
if !exists {
cv = checkpointNullVersion.(int64) // use the provided null version
}
sv, _ := seen[ch].(int64) // default to 0 if not exists or wrong type
if compareVersion(cv, sv) > 0 {
triggers = append(triggers, ch)
}
}
if len(triggers) == 0 {
return nil, nil // not ready
}
sort.Strings(triggers)
input := map[string]interface{}{}
for _, ch := range proc.Triggers {
if v, ok := channels[ch]; ok {
input[ch] = v
}
}
checkpointNS := parentNS
if checkpointNS != "" {
checkpointNS += NS_SEP + name
} else {
checkpointNS = name
}
taskID := taskIDFunc(
checkpointIDBytes,
checkpointNS,
strconv.Itoa(step),
name,
PULL,
// join triggers to guarantee deterministic id
fmt.Sprintf("%v", triggers),
)
if err := checkSumMatch(taskID); err != nil {
return nil, err
}
taskCheckpointNS := checkpointNS + NS_END + taskID
metadata := map[string]interface{}{
"langgraph_step": step,
"langgraph_node": name,
"langgraph_triggers": triggers,
"langgraph_path": taskPath,
"langgraph_checkpoint_ns": taskCheckpointNS,
}
if forExecution {
return PregelExecutableTask{
PregelTask: PregelTask{
ID: taskID,
Name: name,
Path: taskPath,
},
Input: input,
Node: proc.Node,
Writes: nil,
Config: emitConfig(config, metadata),
Triggers: triggers,
}, nil
}
return PregelTask{ID: taskID, Name: name, Path: taskPath}, nil
}
return nil, nil
}
// Private / Helpers
// taskIDFunc deterministically hashes the checkpoint-scoped information that
// must be unique for a task in a given super-step.
func taskIDFunc(checkpointIDBytes []byte, parts ...string) string {
h := sha256.New()
_, _ = h.Write(checkpointIDBytes)
for _, p := range parts {
_, _ = h.Write([]byte(p))
}
return hex.EncodeToString(h.Sum(nil))
}
// taskPathStr is only used so the path element contributes to the hash in a
// deterministic textual form.
func taskPathStr(path interface{}) string {
return fmt.Sprintf("%v", path)
}
// createScratchpad returns an *immutable* copy of the scratchpad that will
// be injected into the task-local Config. We:
//
// 1. start from the previous scratchpad (if any),
// 2. merge in any successful writes from earlier tasks in this super-step,
// 3. copy-on-write so individual tasks never share interior maps.
//
// The logic below is intentionally simple; extend as needed.
func createScratchpad(
current map[string]interface{},
pendingWrites []interface{},
taskID string,
checkpointHash string,
resumeMap map[string]interface{},
) map[string]interface{} {
out := map[string]interface{}{}
for k, v := range current {
out[k] = v
}
if len(pendingWrites) > 0 {
out["pending_writes"] = append([]interface{}{}, pendingWrites...)
}
if checkpointHash != "" {
out["checkpoint_hash"] = checkpointHash
}
if resumeMap != nil {
out["resume_map"] = resumeMap
}
out["task_id"] = taskID
return out
}
func checkpointNullVersion(_ Checkpoint) interface{} {
// Return the zero value for int64 as the null version
return int64(0)
}
func taskID(t interface{}) (string, bool) {
switch v := t.(type) {
case PregelTask:
return v.ID, true
case PregelExecutableTask:
return v.ID, true
default:
return "", false
}
}
func compareVersion(a, b interface{}) int {
switch av := a.(type) {
case int:
bv, _ := b.(int)
return av - bv
case int64:
var bv int64
switch bvVal := b.(type) {
case int64:
bv = bvVal
case int:
bv = int64(bvVal)
default:
bv = 0
}
if av == bv {
return 0
}
if av < bv {
return -1
}
return 1
case string:
bv, _ := b.(string)
if av == bv {
return 0
}
if av < bv {
return -1
}
return 1
// Fallback to reflect.DeepEqual comparison: not perfect but safe.
default:
if reflect.DeepEqual(a, b) {
return 0
}
return 1
}
}
-28
View File
@@ -1,28 +0,0 @@
package pregel
import (
"context"
"time"
"github.com/google/uuid"
)
func EmptyCheckpoint() (*Checkpoint, error) {
uid, err := uuid.NewV6()
if err != nil {
return nil, err
}
return &Checkpoint{
Version: 1,
ID: uid.String(),
Timestamp: time.Now().Format(time.RFC3339),
ChannelValues: map[string]interface{}{},
ChannelVersions: map[string]int64{},
VersionsSeen: map[string]interface{}{},
PendingSends: []Send{},
}, nil
}
type Checkpointer interface {
PutWrites(ctx context.Context, checkpoint Checkpoint, writes []Write) error
}
-138
View File
@@ -1,138 +0,0 @@
package pregel
import (
"context"
"errors"
)
// Pregel is the top-level graph object.
type Pregel struct {
Name string
Nodes map[string]PregelNode
Channels map[string]BaseChannel
LoopCfg RunnableConfig
Checkptr BaseCheckpointSaver
Store BaseStore
Debug bool
}
func (g *Pregel) Stream(
input any,
cfg RunnableConfig,
opts *StreamOptions,
) (<-chan StreamChunk, <-chan error) {
eventCh := make(chan StreamChunk, 16)
errCh := make(chan error, 1)
if opts == nil {
opts = &StreamOptions{}
}
ctx := opts.Context
if ctx == nil {
ctx = context.Background()
}
mode := opts.Mode
if mode == "" {
mode = StreamValues
}
// TODO: opts.Debug
// ensure output channels are set / valid
outChans := opts.OutputChannels
if len(outChans) == 0 {
for k := range g.Channels {
if _, ok := g.Channels[k]; ok {
outChans = append(outChans, k)
}
}
}
if opts.MaxConcurrency > 0 {
cfg.MaxConcurrency = opts.MaxConcurrency
}
if cfg.MaxConcurrency == 0 {
cfg.MaxConcurrency = 4
}
if cfg.RecursionLimit == 0 {
cfg.RecursionLimit = 25
}
if opts.CheckpointDuring != nil {
cfg.Configurable[CONFIG_KEY_CHECKPOINT_DURING] = *opts.CheckpointDuring
}
checkpoint, err := EmptyCheckpoint()
if err != nil {
errCh <- err
return nil, errCh
}
loop := NewLoop(
ctx,
*checkpoint,
g.Nodes,
g.channelsAsConcrete(),
nil, // managed values
cfg,
nil, // g.checkpointer, // may be nil
nil, // g.store,
)
loop.interruptBefore = opts.InterruptBefore
loop.interruptAfter = opts.InterruptAfter
loop.streamCh = eventCh
loop.streamMode = mode
// loop.debug = debug
go func() {
defer close(eventCh)
defer close(errCh)
// Create a runner to execute tasks
runner := NewPregelRunner(loop, nil)
// Use the tick method in a loop instead of Run()
for {
more, err := loop.tick(outChans)
if err != nil {
// Check if this is a GraphInterrupt error
var interrupt GraphInterrupt
if errors.As(err, &interrupt) {
// Handle interrupt gracefully
break
}
// Otherwise, it's a real error
errCh <- err
return
}
runnerOpts := TickOptions{
MaxConcurrency: cfg.MaxConcurrency,
}
if opts.Debug != nil && *opts.Debug {
runnerOpts.OnStepWrite = func(step int, writes []Write) {
// TODO: Handle debugging info
}
}
if err := runner.tick(runnerOpts); err != nil {
errCh <- err
return
}
// No more iterations needed, we're done
if !more {
break
}
}
}()
return eventCh, errCh
}
func (g *Pregel) channelsAsConcrete() map[string]BaseChannel {
out := make(map[string]BaseChannel, len(g.Channels))
for k, v := range g.Channels {
if ch, ok := v.(BaseChannel); ok {
out[k] = ch
}
}
return out
}
-500
View File
@@ -1,500 +0,0 @@
package pregel
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"sync"
"time"
)
type GraphInterrupt struct {
Interrupts any
}
func (e GraphInterrupt) Error() string { return "graph interrupted" }
type GraphDelegate struct {
Payload map[string]any
}
func (e GraphDelegate) Error() string { return "graph delegation requested" }
func hashID(checkpointID string, parts ...string) string {
b, _ := hex.DecodeString(checkpointID)
h := sha256.New()
h.Write(b)
for _, p := range parts {
h.Write([]byte(p))
}
return hex.EncodeToString(h.Sum(nil))
}
type PregelLoop struct {
ctx context.Context
cancel context.CancelFunc
cfg RunnableConfig
store BaseStore
checkpoint Checkpoint
checkporter BaseCheckpointSaver
processes map[string]PregelNode
channels map[string]BaseChannel
managed ManagedValueMapping
step int
stop int
interruptBefore []string
interruptAfter []string
pendingWrites []WriteRecord
tasks map[string]*PregelExecutableTask
toInterrupt []*PregelExecutableTask
triggerToNodes map[string][]string
updatedChans map[string]struct{}
// synchronisation / workers
workers int
wg sync.WaitGroup
errMu sync.Mutex
runErr error
// Streaming
streamCh chan<- StreamChunk
streamMode StreamMode
pendingMu sync.Mutex
checkpointPendingWrites []PendingWrite
checkpointer Checkpointer // interface with PutWrites()
checkpointConfig RunnableConfig
emit func(task *PregelExecutableTask, writes []Write, cached bool)
}
type WriteRecord struct {
Task string
Chan string
Value any
}
// NewLoop initialises a fully-featured loop.
func NewLoop(
ctx context.Context,
checkpoint Checkpoint,
processes map[string]PregelNode,
channels map[string]BaseChannel,
managed ManagedValueMapping,
cfg RunnableConfig,
checkporter BaseCheckpointSaver,
store BaseStore,
) *PregelLoop {
c, cancel := context.WithCancel(ctx)
// Ensure checkpoint is properly initialized
if checkpoint.ChannelVersions == nil {
checkpoint = NewCheckpoint()
}
loop := &PregelLoop{
ctx: c,
cancel: cancel,
checkpoint: checkpoint,
processes: processes,
channels: channels,
managed: managed,
cfg: cfg,
checkporter: checkporter,
store: store,
step: 0,
stop: cfg.RecursionLimit,
workers: cfg.MaxConcurrency,
pendingWrites: make([]WriteRecord, 0, 16),
tasks: map[string]*PregelExecutableTask{},
}
if loop.workers <= 0 {
loop.workers = 1
}
return loop
}
// Run blocks until completion (or first error)
func (l *PregelLoop) Run() error {
defer l.cancel()
for {
more, err := l.tick(nil)
if err != nil {
if errors.As(err, &GraphInterrupt{}) {
return nil
}
return err
}
if !more {
break
}
}
return nil
}
// tick executes a single iteration of the Pregel loop.
// Returns true if more iterations are needed, false if done.
func (l *PregelLoop) tick(inputKeys []string) (bool, error) {
// TODO: Use inputKeys to get the first values.
// Check if we need to evaluate interrupts before execution
if err := l.evaluateInterrupt("before"); err != nil {
return false, err
}
// Build tasks
tasks, err := PrepareNextTasks(
l.ctx,
l.checkpoint,
convertPending(l.pendingWrites),
l.processes,
l.channels,
l.managed,
l.cfg,
l.step,
true,
l.store,
l.checkporter,
l.triggerToNodes,
l.updatedChans,
)
if err != nil {
return false, err
}
if len(tasks) == 0 {
return false, nil // done, no more tasks
}
l.tasks = make(map[string]*PregelExecutableTask)
for k, v := range tasks {
te := v.(PregelExecutableTask)
l.tasks[k] = &te
}
// parallel execute
workCh := make(chan *PregelExecutableTask)
errCh := make(chan error, l.workers)
for i := 0; i < l.workers; i++ {
go l.worker(workCh, errCh)
}
for _, t := range l.tasks {
if len(t.Writes) > 0 {
continue // already satisfied
}
workCh <- t
}
close(workCh)
for i := 0; i < l.workers; i++ {
if err := <-errCh; err != nil {
return false, err
}
}
// All tasks finished; apply writes
if err := l.applyWrites(); err != nil {
return false, err
}
// checkpoint
if err := l.saveCheckpoint(); err != nil {
return false, err
}
// Check if we need to evaluate interrupts after execution
if err := l.evaluateInterrupt("after"); err != nil {
return false, err
}
// Check if we've exceeded the recursion limit
l.step++
if l.step > l.stop {
return false, fmt.Errorf("exceeded recursion limit (%d)", l.stop)
}
return true, nil
}
// prepareAndExecuteStep is kept for backward compatibility
func (l *PregelLoop) prepareAndExecuteStep() error {
more, err := l.tick(nil)
if err != nil {
return err
}
if !more {
return nil
}
return nil
}
func (l *PregelLoop) worker(in <-chan *PregelExecutableTask, out chan<- error) {
for task := range in {
err := l.runTask(task)
out <- err
}
}
func (l *PregelLoop) runTask(t *PregelExecutableTask) error {
// retry loop
attempts := 0
max := 1
if p, ok := l.processes[t.Name]; ok {
max = maxAttempts(p.Retry)
}
for {
attempts++
select {
case <-l.ctx.Done():
return l.ctx.Err()
default:
}
writes, err := t.Node.Invoke(l.ctx, t.Input, t.Config, l)
if err == nil {
for _, w := range writes {
l.recordWrite(t.ID, w.Channel, w.Value)
}
t.Writes = writes
return nil
}
if attempts >= max {
return err
}
time.Sleep(backoffDelay(attempts))
}
}
// putWrites is called by PregelRunner (or nested tasks via the SEND helper)
// to persist writes produced by a task *during the current super-step*.
// It is safe for concurrent use.
func (l *PregelLoop) putWrites(taskID string, writes []Write) {
if len(writes) == 0 {
return
}
// ---------------------------------------------------------------------
// 1. Deduplicate if every write is for a “special” indexed channel.
// (“last one wins”, exactly like in TS / Python)
// ---------------------------------------------------------------------
allIndexed := true
for _, w := range writes {
if _, ok := WRITES_IDX_MAP[w.Channel]; !ok {
allIndexed = false
break
}
}
if allIndexed {
dedup := make(map[string]Write, len(writes))
for _, w := range writes {
dedup[w.Channel] = w
}
writes = make([]Write, 0, len(dedup))
for _, w := range dedup {
writes = append(writes, w)
}
}
// ---------------------------------------------------------------------
// 2. Merge into l.checkpointPendingWrites.
// We need a mutex because PregelRunner goroutines call us in parallel.
// ---------------------------------------------------------------------
l.pendingMu.Lock()
for _, w := range writes {
replaced := false
// If it is an indexed channel and an entry already exists for (task,channel),
// overwrite it (=> keep only the newest write).
if _, special := WRITES_IDX_MAP[w.Channel]; special {
for i := range l.checkpointPendingWrites {
pw := &l.checkpointPendingWrites[i]
if pw.TaskID == taskID && pw.Channel == w.Channel {
pw.Value = w.Value
replaced = true
break
}
}
}
// Otherwise (or if not found) just append.
if !replaced {
l.checkpointPendingWrites = append(
l.checkpointPendingWrites,
PendingWrite{TaskID: taskID, Channel: w.Channel, Value: w.Value},
)
}
}
l.pendingMu.Unlock()
// ---------------------------------------------------------------------
// 3. Forward the writes to the configured checkpointer (if any).
// We dont block the caller a quick “fire-and-forget” goroutine
// is fine because checkpointer.PutWrites() is thread-safe by design.
// ---------------------------------------------------------------------
// if l.checkpointer != nil {
// cfg := l.checkpointConfig // shallow copy is enough we never mutate it
// go l.checkpointer.PutWrites(cfg, writes, taskID)
// }
// ---------------------------------------------------------------------
// 4. Emit stream/debug output if the loop is already running.
// ---------------------------------------------------------------------
if len(l.tasks) > 0 {
l.outputWrites(taskID, writes, false)
}
}
// outputWrites mirrors TS _outputWrites (omits hidden tasks & handles modes).
// This is a *minimal* version; extend if you need streaming/debug UI parity.
func (l *PregelLoop) outputWrites(taskID string, writes []Write, cached bool) {
task, ok := l.tasks[taskID]
if !ok {
return
}
for _, tag := range task.Config.Tags {
if tag == TAG_HIDDEN {
return
}
}
// TODO: implement streaming
// delegate to whatever streaming mechanism you implemented…
// if l.emit != nil {
// l.emit(task, writes, cached)
// }
}
func maxAttempts(r RetryPolicy) int {
if r.MaxAttempts <= 0 {
return 1
}
return r.MaxAttempts
}
func backoffDelay(at int) time.Duration { return time.Duration(at) * 50 * time.Millisecond }
func (l *PregelLoop) Send(taskID string, writes []Write) {
for _, w := range writes {
l.recordWrite(taskID, w.Channel, w.Value)
}
}
// Read returns a copy of current channel values
func (l *PregelLoop) Read(selectKeys []string) map[string]any {
out := map[string]any{}
for _, k := range selectKeys {
if ch, ok := l.channels[k]; ok {
out[k] = ch.Get()
}
}
return out
}
func (l *PregelLoop) AcceptPush(origin PregelExecutableTask, writeIdx int, call *Call) (*PregelExecutableTask, error) {
ppath := origin.Path
newPath := []interface{}{PUSH, ppath, writeIdx, origin.ID, call}
cpid, _ := hex.DecodeString(l.checkpoint.ID)
nullVer := -1
task, err := PrepareSingleTask(
l.ctx,
newPath,
"",
l.checkpoint,
cpid,
nullVer,
convertPending(l.pendingWrites),
l.processes,
l.channels,
l.managed,
l.cfg,
l.step,
true,
l.store,
l.checkporter,
)
if err != nil {
return nil, err
}
if task == nil {
return nil, nil
}
te := task.(PregelExecutableTask)
l.tasks[te.ID] = &te
return &te, nil
}
func (l *PregelLoop) recordWrite(taskID, ch string, val any) {
l.pendingWrites = append(l.pendingWrites, WriteRecord{taskID, ch, val})
}
func convertPending(ws []WriteRecord) []interface{} {
out := make([]interface{}, 0, len(ws))
for _, w := range ws {
out = append(out, []interface{}{w.Task, w.Chan, w.Value})
}
return out
}
func (l *PregelLoop) applyWrites() error {
if len(l.pendingWrites) == 0 {
return nil
}
for _, wr := range l.pendingWrites {
ch, ok := l.channels[wr.Chan]
if !ok {
ch = &simpleChan{}
l.channels[wr.Chan] = ch
}
ch.Set(wr.Value)
// TODO: Handle other version types.
if _, exists := l.checkpoint.ChannelVersions[wr.Chan]; !exists {
l.checkpoint.ChannelVersions[wr.Chan] = 0
}
l.checkpoint.ChannelVersions[wr.Chan]++
}
l.pendingWrites = l.pendingWrites[:0]
return nil
}
func (l *PregelLoop) saveCheckpoint() error {
if l.checkporter == nil {
return nil
}
md := map[string]any{
"step": l.step,
"source": "loop",
"time": time.Now().UTC().Format(time.RFC3339Nano),
}
return l.checkporter.Put(l.cfg, l.checkpoint, md, nil)
}
func (l *PregelLoop) evaluateInterrupt(stage string) error {
var conditions []string
if stage == "before" {
conditions = l.interruptBefore
} else {
conditions = l.interruptAfter
}
if len(conditions) == 0 {
return nil
}
seen := map[string]struct{}{}
for _, t := range l.tasks {
for _, trg := range t.Triggers {
seen[trg] = struct{}{}
}
}
for _, cond := range conditions {
if _, ok := seen[cond]; ok || cond == "*" {
return GraphInterrupt{}
}
}
return nil
}
type Result struct {
Err error
}
-217
View File
@@ -1,217 +0,0 @@
// runner.go
package pregel
import (
"context"
"errors"
"sync"
"time"
"golang.org/x/sync/errgroup"
)
// PregelRunner is responsible for executing the set of tasks that a
// PregelLoop prepared for the *current super-step*. It runs them with
// respect to retry-policy, max-concurrency, timeouts, cancellation and
// Pregel-specific error semantics (GraphInterrupt / GraphBubbleUp).
type PregelRunner struct {
loop *PregelLoop
nodeFinished func(string) // Optional user-callback
}
// NewPregelRunner links the runner to its parent loop.
func NewPregelRunner(loop *PregelLoop, nodeFinished func(string)) *PregelRunner {
return &PregelRunner{loop: loop, nodeFinished: nodeFinished}
}
// TickOptions mirrors the semantics in the TS/Python implementations.
type TickOptions struct {
Timeout time.Duration // Deadline for the whole super-step
RetryPolicy RetryPolicy // Per-task retry policy
OnStepWrite func(int, []Write) // Hook after *all* writes are committed
MaxConcurrency int // ≤0 ⇒ unlimited
Ctx context.Context // Root ctx (optional)
}
// Tick executes every task whose Writes slice is still empty.
// It returns when *all* tasks have completed (successfully or not) **or**
// when the first non-interrupt error bubbles up.
func (r *PregelRunner) tick(opt TickOptions) error {
// Choose base context
ctx := opt.Ctx
if ctx == nil {
ctx = context.Background()
}
// We cancel siblings on first fatal error
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// Optional global timeout
if opt.Timeout > 0 {
ctx, cancel = context.WithTimeout(ctx, opt.Timeout)
defer cancel()
}
// Gather tasks that still need to run in this super-step
var pending []*PregelExecutableTask
for _, t := range r.loop.tasks {
if len(t.Writes) == 0 {
pending = append(pending, t)
}
}
if len(pending) == 0 {
return nil // nothing to do
}
// errgroup manages goroutines and collects the first returned error
g, gctx := errgroup.WithContext(ctx)
maxConc := opt.MaxConcurrency
if maxConc <= 0 {
maxConc = len(pending)
}
sem := make(chan struct{}, maxConc)
var mu sync.Mutex
for _, task := range pending {
task := task // capture
sem <- struct{}{}
g.Go(func() error {
defer func() { <-sem }()
err := runWithRetry(gctx, opt.RetryPolicy, func(c context.Context) error {
// NOTE: Node.Run must honour ctx for cancellation / deadlines.
writes, runErr := task.Node.Invoke(c, task.Input, task.Config, r.loop)
if runErr == nil {
task.Writes = writes
}
return runErr
})
r.commit(task, err)
switch {
case err == nil:
return nil
case errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded):
return err // propagate
}
var gi GraphInterrupt
if errors.As(err, &gi) {
mu.Lock()
defer mu.Unlock()
// kep track so that loop can raise combined interrupt later
return gi
}
cancel()
return err
})
}
// Wait for all goroutines (or first fatal error)
if err := g.Wait(); err != nil {
return err
}
// Step-level callback after *all* commits
if opt.OnStepWrite != nil {
var all []Write
for _, t := range r.loop.tasks {
all = append(all, t.Writes...)
}
opt.OnStepWrite(r.loop.step, all)
}
return nil
}
// commit replicates the Python/TS commit semantics.
func (r *PregelRunner) commit(task *PregelExecutableTask, execErr error) {
// On success ensure at least one NO_WRITES marker so loop knows it's done.
if execErr == nil && len(task.Writes) == 0 {
task.Writes = append(task.Writes, Write{Channel: NO_WRITES})
}
// Persist writes (or error) through the loops thread-safe adaptor.
switch {
case execErr == nil:
r.loop.putWrites(task.ID, task.Writes)
case errors.As(execErr, new(GraphInterrupt)):
// Interrupt carries its own writes payload
r.loop.putWrites(task.ID, task.Writes)
default:
// Record generic error
r.loop.putWrites(task.ID, []Write{{Channel: ERROR, Value: execErr}})
}
// optional callback
if execErr == nil && r.nodeFinished != nil {
r.nodeFinished(task.Name)
}
}
// runWithRetry is a minimal exponential-back-off retry helper.
func runWithRetry(ctx context.Context, pol RetryPolicy, fn func(context.Context) error) error {
if pol.MaxAttempts <= 0 {
pol.MaxAttempts = 1
}
// if pol.Backoff == nil {
// // default: exponential capped at 2 s
// pol.Backoff = func(attempt int) time.Duration {
// d := time.Duration(math.Pow(2, float64(attempt))) * 50 * time.Millisecond
// if d > 2*time.Second {
// d = 2 * time.Second
// }
// return d
// }
// }
// if pol.Retryable == nil {
// pol.Retryable = func(error) bool { return true }
// }
var err error
for attempt := 0; attempt < pol.MaxAttempts; attempt++ {
if err = fn(ctx); err == nil { // || !pol.Retryable(err) {
return err
}
// // wait before next try
// wait := pol.Backoff(attempt)
// select {
// case <-time.After(wait):
// case <-ctx.Done():
// return ctx.Err()
// }
}
return err
}
/* --------------------------------------------------------------------------
Missing symbols? If your project does not yet declare the following items
just add minimal stubs like the ones below (remove before wiring in
real implementations to avoid duplicates).
// Constants that mark write types
const (
ERROR = "error"
NO_WRITES = "no_writes"
)
// GraphInterrupt / BubbleUp marker errors
type GraphInterrupt struct{ Msg string }
func (g GraphInterrupt) Error() string { return g.Msg }
type GraphBubbleUp struct{ error }
// Minimal Write + RetryPolicy
type Write struct{ Channel string; Value any }
type RetryPolicy struct {
MaxAttempts int
Backoff func(attempt int) time.Duration
Retryable func(error) bool
}
// PregelExecutableTask, PregelLoop, etc. should exist elsewhere.
// -------------------------------------------------------------------------- */
-292
View File
@@ -1,292 +0,0 @@
package pregel
import (
"context"
"sync"
)
// Constants for task types and reserved keys
const (
// Task types
PUSH = "__pregel_push" // Denotes push-style tasks, ie. those created by Send objects
PULL = "__pregel_pull" // Denotes pull-style tasks, ie. those triggered by edges
// Reserved write keys
INPUT = "__input__" // For values passed as input to the graph
INTERRUPT = "__interrupt__" // For dynamic interrupts raised by nodes
RESUME = "__resume__" // For values passed to resume a node after an interrupt
ERROR = "__error__" // For errors raised by nodes
NO_WRITES = "__no_writes__" // Marker to signal node didn't write anything
SCHEDULED = "__scheduled__" // Marker to signal node was scheduled (in distributed mode)
TASKS = "__pregel_tasks" // For Send objects returned by nodes/edges
RETURN = "__return__" // For writes of a task where we simply record the return value
// Public constants
START = "__start__" // The first (maybe virtual) node in graph-style Pregel
END = "__end__" // The last (maybe virtual) node in graph-style Pregel
SELF = "__self__" // The implicit branch that handles each node's Control values
PREVIOUS = "__previous__" // Previous value
// Other constants
NS_SEP = "|" // For checkpoint_ns, separates each level (ie. graph|subgraph|subsubgraph)
NS_END = ":" // For checkpoint_ns, for each level, separates the namespace from the task_id
NULL_TASK_ID = "00000000-0000-0000-0000-000000000000" // The task_id to use for writes that are not associated with a task
CONF = "configurable" // Key for the configurable dict in RunnableConfig
// Reserved config.configurable keys
CONFIG_KEY_SEND = "__pregel_send" // Holds the `write` function that accepts writes to state/edges/reserved keys
CONFIG_KEY_READ = "__pregel_read" // Holds the `read` function that returns a copy of the current state
CONFIG_KEY_CALL = "__pregel_call" // Holds the `call` function that accepts a node/func, args and returns a future
CONFIG_KEY_CHECKPOINTER = "__pregel_checkpointer" // Holds a `BaseCheckpointSaver` passed from parent graph to child graphs
CONFIG_KEY_STREAM = "__pregel_stream" // Holds a `StreamProtocol` passed from parent graph to child graphs
CONFIG_KEY_STREAM_WRITER = "__pregel_stream_writer" // Holds a `StreamWriter` for stream_mode=custom
CONFIG_KEY_STORE = "__pregel_store" // Holds a `BaseStore` made available to managed values
CONFIG_KEY_CACHE = "__pregel_cache" // Holds a `BaseCache` made available to subgraphs
CONFIG_KEY_RESUMING = "__pregel_resuming" // Holds a boolean indicating if subgraphs should resume from a previous checkpoint
CONFIG_KEY_TASK_ID = "__pregel_task_id" // Holds the task ID for the current task
CONFIG_KEY_DEDUPE_TASKS = "__pregel_dedupe_tasks" // Holds a boolean indicating if tasks should be deduplicated (for distributed mode)
CONFIG_KEY_ENSURE_LATEST = "__pregel_ensure_latest" // Holds a boolean indicating whether to assert the requested checkpoint is the latest
CONFIG_KEY_DELEGATE = "__pregel_delegate" // Holds a boolean indicating whether to delegate subgraphs (for distributed mode)
CONFIG_KEY_THREAD_ID = "thread_id" // Holds the thread ID for the current invocation
CONFIG_KEY_CHECKPOINT_MAP = "checkpoint_map" // Holds a mapping of checkpoint_ns -> checkpoint_id for parent graphs
CONFIG_KEY_CHECKPOINT_ID = "checkpoint_id" // Holds the current checkpoint_id, if any
CONFIG_KEY_CHECKPOINT_NS = "checkpoint_ns" // Holds the current checkpoint_ns, "" for root graph
CONFIG_KEY_NODE_FINISHED = "__pregel_node_finished" // Holds a callback to be called when a node is finished
CONFIG_KEY_SCRATCHPAD = "__pregel_scratchpad" // Holds a mutable dict for temporary storage scoped to the current task
CONFIG_KEY_PREVIOUS = "__pregel_previous" // Holds the previous return value from a stateful Pregel graph
CONFIG_KEY_RUNNER_SUBMIT = "__pregel_runner_submit" // Holds a function that receives tasks from runner, executes them and returns results
CONFIG_KEY_CHECKPOINT_DURING = "__pregel_checkpoint_during" // Holds a boolean indicating whether to checkpoint during the run (or only at the end)
CONFIG_KEY_RESUME_MAP = "__pregel_resume_map" // Holds a mapping of task ns -> resume value for resuming tasks
TAG_HIDDEN = "langsmith:hidden" // Holds a boolean indicating whether to hide a node/edge from certain tracing/streaming environments.
)
// StreamMode defines how the graph streams its output
type StreamMode string
// WRITES_IDX_MAP maps special channel names to negative indices
// to avoid conflicts with regular writes.
var WRITES_IDX_MAP = map[string]int{
ERROR: -1,
SCHEDULED: -2,
INTERRUPT: -3,
RESUME: -4,
}
// TS
// export type PendingWriteValue = unknown;
// export type PendingWrite<Channel = string> = [Channel, PendingWriteValue];
// export type CheckpointPendingWrite<TaskId = string> = [
// TaskId,
// ...PendingWrite<string>
// ];
// Py
// PendingWrite = Tuple[str, str, Any]
type PendingWrite struct {
TaskID string
Channel string
Value interface{}
}
const (
// StreamValues emits all values in the state after each step
StreamValues StreamMode = "values"
// StreamUpdates emits only the node or task names and updates
StreamUpdates StreamMode = "updates"
// StreamCustom emits custom data from inside nodes or tasks
StreamCustom StreamMode = "custom"
// StreamMessages emits LLM messages token-by-token
StreamMessages StreamMode = "messages"
// StreamDebug emits debug events with as much information as possible
StreamDebug StreamMode = "debug"
)
// PregelTask represents a task in the Pregel system
type PregelTask struct {
ID string
Name string
Path []interface{}
Error error
Interrupts []interface{}
Result interface{}
}
// PregelExecutableTask represents a task that can be executed
type PregelExecutableTask struct {
PregelTask
Input interface{}
Node NodeRunnable
Writes []Write
Config RunnableConfig
Triggers []string
RetryPolicy interface{}
CacheKey *CacheKey
Writers map[string]interface{} // Flat writers
Subgraphs map[string]interface{} // Subgraphs
}
// StreamChunk is what the consumer receives.
type StreamChunk struct {
Namespace []string // sub-graph path (reserved for future use)
Mode StreamMode
Payload any
}
type StreamOptions struct {
Mode StreamMode
OutputChannels []string // defaults to all non-context channels
InterruptBefore []string // interrupt gate (before)
InterruptAfter []string // interrupt gate (after)
MaxConcurrency int // overrides config[ "max_concurrency" ]
CheckpointDuring *bool // nil → inherit config
Debug *bool // nil → inherit graph.debug
Context context.Context // optional, default = context.Background()
}
// CacheKey represents a key for caching
type CacheKey struct {
Namespace []string
Key string
TTL int64
}
type PregelNode struct {
Node NodeRunnable
Triggers []string
Metadata map[string]interface{}
Tags []string
CachePolicy interface{} // CachePolicy equivalent
RetryPolicy interface{} // RetryPolicy equivalent
FlatWriters map[string]interface{}
Subgraphs map[string]interface{}
Retry RetryPolicy
}
type NodeRunnable interface {
Invoke(ctx context.Context, input any, cfg RunnableConfig, loop LoopCallback) ([]Write, error)
}
type Write struct {
Channel string
Value any
}
// Checkpoint represents a checkpoint in the Pregel system
type Checkpoint struct {
ID string
ChannelValues map[string]interface{} `json:"channel_values,omitempty"`
ChannelVersions map[string]int64 `json:"channel_versions,omitempty"`
VersionsSeen map[string]interface{} `json:"versions_seen,omitempty"`
PendingSends []Send `json:"pending_sends,omitempty"`
Version int `json:"version,omitempty"`
Timestamp string `json:"timestamp,omitempty"`
}
// NewCheckpoint creates a new Checkpoint with all fields properly initialized
func NewCheckpoint() Checkpoint {
return Checkpoint{
ChannelValues: make(map[string]interface{}),
ChannelVersions: make(map[string]int64),
VersionsSeen: make(map[string]interface{}),
PendingSends: make([]Send, 0),
}
}
// Send represents a message to be sent to a node
type Send struct {
Node string
Arg interface{}
}
// Call represents a function call
type Call struct {
Func interface{} // Function to call
Input []interface{} // Arguments
Callbacks interface{} // Callbacks
CachePolicy interface{} // CachePolicy
Retry interface{} // RetryPolicy
}
// PregelTaskWrites represents writes from a task
type PregelTaskWrites struct {
Path []interface{}
Name string
Writes []interface{} // Deque in Python
Triggers []string
}
// ---------------------------------------------------------------------------
// Interfaces from previous snippets (slim versions here)
// ---------------------------------------------------------------------------
type RetryPolicy struct {
MaxAttempts int
BackoffMs int
}
type BaseChannel interface {
Set(v any)
Get() any
}
type simpleChan struct{ val atomicValue }
type atomicValue struct {
mu sync.RWMutex
v any
}
func (a *atomicValue) Store(v any) {
a.mu.Lock()
a.v = v
a.mu.Unlock()
}
func (a *atomicValue) Load() (v any) { a.mu.RLock(); v = a.v; a.mu.RUnlock(); return }
func (c *simpleChan) Set(v any) { c.val.Store(v) }
func (c *simpleChan) Get() any { return c.val.Load() }
// Managed values -------------------------------------------------------------
type WritableManagedValue interface {
Update([]any) error
}
type ManagedValueMapping map[string]WritableManagedValue
type SendPacket struct {
Node string
Arg any
}
type BaseCheckpointSaver interface {
Put(cfg RunnableConfig, cp Checkpoint, md map[string]any, newVers map[string]int) error
GetTuple(cfg RunnableConfig) (*Checkpoint, error)
}
// Stores ---------------------------------------------------------------------
type BaseStore interface{}
// Loop callback interface passed to Nodes for localWrite / localRead
type LoopCallback interface {
Send(taskID string, writes []Write)
Read(selectKeys []string) map[string]any
AcceptPush(originTask PregelExecutableTask, writeIdx int, call *Call) (*PregelExecutableTask, error)
}
// RunnableConfig represents configuration for a Runnable.
// Fields are optional
type RunnableConfig struct {
Tags []string `json:"tags,omitempty"` // Tags for this call and sub-calls.
Metadata map[string]interface{} `json:"metadata,omitempty"` // Metadata for this call and sub-calls.
Callbacks interface{} `json:"callbacks,omitempty"` // Callbacks for this call and sub-calls.
RunName *string `json:"run_name,omitempty"` // Name for the tracer run for this call.
MaxConcurrency int `json:"max_concurrency,omitempty"` // Max number of parallel calls.
RecursionLimit int `json:"recursion_limit,omitempty"` // Max recursion depth.
Configurable map[string]interface{} `json:"configurable,omitempty"` // Runtime values for configurable attributes.
RunID *string `json:"run_id,omitempty"` // Unique identifier for the tracer run (UUID as string).
}
-4
View File
@@ -1,4 +0,0 @@
.PHONY: build
build:
uv run python -m grpc_tools.protoc -I . --python_out=stubs/ --grpc_python_out=stubs/ --pyi_out=stubs/ server.proto
-63
View File
@@ -1,63 +0,0 @@
# LangGraph Worker Python gRPC Server
This directory contains a Python implementation of the gRPC server defined in `server.proto`. The server implements the `Worker` service which provides methods for streaming nodes and invoking reducers.
## Setup
1. Install the required dependencies:
```bash
pip install -r requirements.txt
```
2. Compile the Protocol Buffer definition to generate Python code:
```bash
python compile_proto.py
```
This will generate the necessary Python modules in the `stubs` directory.
## Server Implementation
The server implementation is in `grpc_server.py`. It provides:
- A `WorkerServicer` class that implements the `Worker` service defined in the proto file
- Methods to register handlers for nodes and reducers
- Helper methods to create write and error events
## Running the Server
To run the server:
```bash
python grpc_server.py [port]
```
By default, the server listens on port 50051.
## Customizing the Server
To customize the server behavior, modify the `register_handlers` function in `grpc_server.py` to register your own node and reducer handlers.
Example:
```python
def register_handlers(servicer: WorkerServicer):
# Custom node handler
def my_node_handler(inputs, config, path):
# Process inputs and return results
return {"output": b"Processed result"}
# Register the handler
servicer.register_node_handler("my_node", my_node_handler)
```
## Protocol Buffer Definition
The Protocol Buffer definition in `server.proto` defines:
- `Config`: Configuration for checkpoints
- `PregelExecutableTask`: Task information for execution
- `Event`: Output events (write or error)
- `Worker` service: Service with methods for streaming nodes and invoking reducers
-206
View File
@@ -1,206 +0,0 @@
import concurrent.futures
import logging
import sys
import time
from typing import Dict, Callable, Iterator, Dict
from stubs import server_pb2, server_pb2_grpc
import grpc
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
)
logger = logging.getLogger(__name__)
class WorkerServicer(server_pb2_grpc.WorkerServicer):
"""Implementation of the Worker service."""
def __init__(self):
# You might want to initialize resources here
self.node_handlers: Dict[str, Callable] = {}
self.reducer_handlers: Dict[str, Callable] = {}
def register_node_handler(self, name: str, handler: Callable):
"""Register a handler for a specific node."""
self.node_handlers[name] = handler
def register_reducer_handler(self, name: str, handler: Callable):
"""Register a handler for a specific reducer."""
self.reducer_handlers[name] = handler
def StreamNode(self, request: server_pb2.PregelExecutableTask,
context: grpc.ServicerContext) -> Iterator[server_pb2.Event]:
"""Call stream on a task.
Args:
request: The PregelExecutableTask containing task details
context: The gRPC context
Yields:
Event messages with write or error events
"""
logger.info(f"StreamNode called with task_id: {request.task_id}, name: {request.name}")
try:
# Check if we have a handler for this node
if request.name not in self.node_handlers:
error_msg = f"No handler registered for node: {request.name}"
logger.error(error_msg)
# Return an error event
yield self._create_error_event("handler_not_found", error_msg.encode())
return
# Call the handler
handler = self.node_handlers[request.name]
# Process inputs (you may need to deserialize them based on your needs)
inputs = request.input
# Call the handler and process its results
results = handler(inputs, request.config, request.path)
# Yield results as Event messages
for name, value in results.items():
yield self._create_write_event(name, value)
except Exception as e:
logger.exception(f"Error in StreamNode: {str(e)}")
yield self._create_error_event("internal_error", str(e).encode())
def InvokeReducer(self, request: server_pb2.PregelExecutableTask,
context: grpc.ServicerContext) -> Iterator[server_pb2.Event]:
"""Invoke a reducer.
Args:
request: The PregelExecutableTask containing task details
context: The gRPC context
Yields:
Event messages with write or error events
"""
logger.info(f"InvokeReducer called with task_id: {request.task_id}, name: {request.name}")
try:
# Check if we have a handler for this reducer
if request.name not in self.reducer_handlers:
error_msg = f"No handler registered for reducer: {request.name}"
logger.error(error_msg)
# Return an error event
yield self._create_error_event("handler_not_found", error_msg.encode())
return
# Call the handler
handler = self.reducer_handlers[request.name]
# Process inputs (you may need to deserialize them based on your needs)
inputs = request.input
# Call the handler and process its results
results = handler(inputs, request.config, request.path)
# Yield results as Event messages
for name, value in results.items():
yield self._create_write_event(name, value)
except Exception as e:
logger.exception(f"Error in InvokeReducer: {str(e)}")
yield self._create_error_event("internal_error", str(e).encode())
def _create_write_event(self, name: str, value: bytes) -> server_pb2.Event:
"""Create a write event."""
event = server_pb2.Event()
event.write.name = name
event.write.value = value
return event
def _create_error_event(self, name: str, value: bytes) -> server_pb2.Event:
"""Create an error event."""
event = server_pb2.Event()
event.error.name = name
event.error.value = value
return event
def serve(port: int = 50051, max_workers: int = 10):
"""Start the gRPC server.
Args:
port: The port to listen on
max_workers: Maximum number of worker threads
"""
server = grpc.server(
concurrent.futures.ThreadPoolExecutor(max_workers=max_workers)
)
# Create and register the servicer
servicer = WorkerServicer()
server_pb2_grpc.add_WorkerServicer_to_server(servicer, server)
# Add a secure port (you might want to add proper credentials in production)
server.add_insecure_port(f'[::]:{port}')
# Start the server
server.start()
logger.info(f"Server started, listening on port {port}")
# Keep the server running until interrupted
try:
while True:
time.sleep(86400) # Sleep for a day
except KeyboardInterrupt:
logger.info("Shutting down server...")
server.stop(0)
def register_handlers(servicer: WorkerServicer):
"""Register handlers for nodes and reducers.
This is where you would register your custom handlers for different
node types and reducers.
Args:
servicer: The WorkerServicer instance
"""
# Example node handler
def example_node_handler(inputs, config, path):
# Process inputs and return results
# This is just a placeholder implementation
return {"result": b"Example node result"}
# Example reducer handler
def example_reducer_handler(inputs, config, path):
# Process inputs and return results
# This is just a placeholder implementation
return {"result": b"Example reducer result"}
# Register handlers
servicer.register_node_handler("example_node", example_node_handler)
servicer.register_reducer_handler("example_reducer", example_reducer_handler)
def main():
"""Main entry point."""
# Parse command line arguments if needed
port = 50051
if len(sys.argv) > 1:
try:
port = int(sys.argv[1])
except ValueError:
logger.error(f"Invalid port number: {sys.argv[1]}")
sys.exit(1)
# Create the servicer
servicer = WorkerServicer()
# Register handlers
register_handlers(servicer)
# Start the server
serve(port=port)
if __name__ == "__main__":
main()
@@ -1,15 +0,0 @@
[project]
name = "worker-py"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.12"
dependencies = []
[dependency-groups]
dev = [
"grpcio>=1.71.0",
"grpcio-tools>=1.71.0",
"grpclib>=0.4.8",
"protobuf>=5.29.4",
]
-58
View File
@@ -1,58 +0,0 @@
syntax = "proto3";
package langgraph;
message Config {
string checkpoint_ns = 1;
}
message PregelExecutableTask{
string task_id = 1;
string name = 2;
repeated string input= 3;
Config config = 4;
repeated string path = 5;
}
message Event {
message Write {
string name = 1;
bytes value = 2;
}
message Error {
string name = 1;
bytes value = 2;
}
oneof event_oneof {
Write write = 1;
Error error = 2;
}
}
message Empty {
}
message ListGraphsResponse {
message Graph {
message Node {
string name = 1;
repeated string input = 2;
}
repeated Node nodes = 1;
repeated string channel_names = 2;
}
repeated Graph graphs = 1;
}
service Worker {
// Call stream on a task
rpc StreamNode(PregelExecutableTask) returns (stream Event) {}
// Invoke a reducer
rpc InvokeReducer(PregelExecutableTask) returns (stream Event) {}
// List available graphs
rpc ListGraphs(Empty) returns (ListGraphsResponse) {}
}
@@ -1,54 +0,0 @@
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# NO CHECKED-IN PROTOBUF GENCODE
# source: server.proto
# Protobuf Python Version: 5.29.0
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import runtime_version as _runtime_version
from google.protobuf import symbol_database as _symbol_database
from google.protobuf.internal import builder as _builder
_runtime_version.ValidateProtobufRuntimeVersion(
_runtime_version.Domain.PUBLIC,
5,
29,
0,
'',
'server.proto'
)
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0cserver.proto\x12\tlanggraph\"\x1f\n\x06\x43onfig\x12\x15\n\rcheckpoint_ns\x18\x01 \x01(\t\"u\n\x14PregelExecutableTask\x12\x0f\n\x07task_id\x18\x01 \x01(\t\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\r\n\x05input\x18\x03 \x03(\t\x12!\n\x06\x63onfig\x18\x04 \x01(\x0b\x32\x11.langgraph.Config\x12\x0c\n\x04path\x18\x05 \x03(\t\"\xb4\x01\n\x05\x45vent\x12\'\n\x05write\x18\x01 \x01(\x0b\x32\x16.langgraph.Event.WriteH\x00\x12\'\n\x05\x65rror\x18\x02 \x01(\x0b\x32\x16.langgraph.Event.ErrorH\x00\x1a$\n\x05Write\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x0c\x1a$\n\x05\x45rror\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x0c\x42\r\n\x0b\x65vent_oneof\"\x07\n\x05\x45mpty\"\xc7\x01\n\x12ListGraphsResponse\x12\x33\n\x06graphs\x18\x01 \x03(\x0b\x32#.langgraph.ListGraphsResponse.Graph\x1a|\n\x05Graph\x12\x37\n\x05nodes\x18\x01 \x03(\x0b\x32(.langgraph.ListGraphsResponse.Graph.Node\x12\x15\n\rchannel_names\x18\x02 \x03(\t\x1a#\n\x04Node\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05input\x18\x02 \x03(\t2\xd6\x01\n\x06Worker\x12\x43\n\nStreamNode\x12\x1f.langgraph.PregelExecutableTask\x1a\x10.langgraph.Event\"\x00\x30\x01\x12\x46\n\rInvokeReducer\x12\x1f.langgraph.PregelExecutableTask\x1a\x10.langgraph.Event\"\x00\x30\x01\x12?\n\nListGraphs\x12\x10.langgraph.Empty\x1a\x1d.langgraph.ListGraphsResponse\"\x00\x62\x06proto3')
_globals = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'server_pb2', _globals)
if not _descriptor._USE_C_DESCRIPTORS:
DESCRIPTOR._loaded_options = None
_globals['_CONFIG']._serialized_start=27
_globals['_CONFIG']._serialized_end=58
_globals['_PREGELEXECUTABLETASK']._serialized_start=60
_globals['_PREGELEXECUTABLETASK']._serialized_end=177
_globals['_EVENT']._serialized_start=180
_globals['_EVENT']._serialized_end=360
_globals['_EVENT_WRITE']._serialized_start=271
_globals['_EVENT_WRITE']._serialized_end=307
_globals['_EVENT_ERROR']._serialized_start=309
_globals['_EVENT_ERROR']._serialized_end=345
_globals['_EMPTY']._serialized_start=362
_globals['_EMPTY']._serialized_end=369
_globals['_LISTGRAPHSRESPONSE']._serialized_start=372
_globals['_LISTGRAPHSRESPONSE']._serialized_end=571
_globals['_LISTGRAPHSRESPONSE_GRAPH']._serialized_start=447
_globals['_LISTGRAPHSRESPONSE_GRAPH']._serialized_end=571
_globals['_LISTGRAPHSRESPONSE_GRAPH_NODE']._serialized_start=536
_globals['_LISTGRAPHSRESPONSE_GRAPH_NODE']._serialized_end=571
_globals['_WORKER']._serialized_start=574
_globals['_WORKER']._serialized_end=788
# @@protoc_insertion_point(module_scope)
@@ -1,72 +0,0 @@
from google.protobuf.internal import containers as _containers
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from typing import ClassVar as _ClassVar, Iterable as _Iterable, Mapping as _Mapping, Optional as _Optional, Union as _Union
DESCRIPTOR: _descriptor.FileDescriptor
class Config(_message.Message):
__slots__ = ("checkpoint_ns",)
CHECKPOINT_NS_FIELD_NUMBER: _ClassVar[int]
checkpoint_ns: str
def __init__(self, checkpoint_ns: _Optional[str] = ...) -> None: ...
class PregelExecutableTask(_message.Message):
__slots__ = ("task_id", "name", "input", "config", "path")
TASK_ID_FIELD_NUMBER: _ClassVar[int]
NAME_FIELD_NUMBER: _ClassVar[int]
INPUT_FIELD_NUMBER: _ClassVar[int]
CONFIG_FIELD_NUMBER: _ClassVar[int]
PATH_FIELD_NUMBER: _ClassVar[int]
task_id: str
name: str
input: _containers.RepeatedScalarFieldContainer[str]
config: Config
path: _containers.RepeatedScalarFieldContainer[str]
def __init__(self, task_id: _Optional[str] = ..., name: _Optional[str] = ..., input: _Optional[_Iterable[str]] = ..., config: _Optional[_Union[Config, _Mapping]] = ..., path: _Optional[_Iterable[str]] = ...) -> None: ...
class Event(_message.Message):
__slots__ = ("write", "error")
class Write(_message.Message):
__slots__ = ("name", "value")
NAME_FIELD_NUMBER: _ClassVar[int]
VALUE_FIELD_NUMBER: _ClassVar[int]
name: str
value: bytes
def __init__(self, name: _Optional[str] = ..., value: _Optional[bytes] = ...) -> None: ...
class Error(_message.Message):
__slots__ = ("name", "value")
NAME_FIELD_NUMBER: _ClassVar[int]
VALUE_FIELD_NUMBER: _ClassVar[int]
name: str
value: bytes
def __init__(self, name: _Optional[str] = ..., value: _Optional[bytes] = ...) -> None: ...
WRITE_FIELD_NUMBER: _ClassVar[int]
ERROR_FIELD_NUMBER: _ClassVar[int]
write: Event.Write
error: Event.Error
def __init__(self, write: _Optional[_Union[Event.Write, _Mapping]] = ..., error: _Optional[_Union[Event.Error, _Mapping]] = ...) -> None: ...
class Empty(_message.Message):
__slots__ = ()
def __init__(self) -> None: ...
class ListGraphsResponse(_message.Message):
__slots__ = ("graphs",)
class Graph(_message.Message):
__slots__ = ("nodes", "channel_names")
class Node(_message.Message):
__slots__ = ("name", "input")
NAME_FIELD_NUMBER: _ClassVar[int]
INPUT_FIELD_NUMBER: _ClassVar[int]
name: str
input: _containers.RepeatedScalarFieldContainer[str]
def __init__(self, name: _Optional[str] = ..., input: _Optional[_Iterable[str]] = ...) -> None: ...
NODES_FIELD_NUMBER: _ClassVar[int]
CHANNEL_NAMES_FIELD_NUMBER: _ClassVar[int]
nodes: _containers.RepeatedCompositeFieldContainer[ListGraphsResponse.Graph.Node]
channel_names: _containers.RepeatedScalarFieldContainer[str]
def __init__(self, nodes: _Optional[_Iterable[_Union[ListGraphsResponse.Graph.Node, _Mapping]]] = ..., channel_names: _Optional[_Iterable[str]] = ...) -> None: ...
GRAPHS_FIELD_NUMBER: _ClassVar[int]
graphs: _containers.RepeatedCompositeFieldContainer[ListGraphsResponse.Graph]
def __init__(self, graphs: _Optional[_Iterable[_Union[ListGraphsResponse.Graph, _Mapping]]] = ...) -> None: ...
@@ -1,186 +0,0 @@
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
import warnings
import server_pb2 as server__pb2
GRPC_GENERATED_VERSION = '1.71.0'
GRPC_VERSION = grpc.__version__
_version_not_supported = False
try:
from grpc._utilities import first_version_is_lower
_version_not_supported = first_version_is_lower(GRPC_VERSION, GRPC_GENERATED_VERSION)
except ImportError:
_version_not_supported = True
if _version_not_supported:
raise RuntimeError(
f'The grpc package installed is at version {GRPC_VERSION},'
+ f' but the generated code in server_pb2_grpc.py depends on'
+ f' grpcio>={GRPC_GENERATED_VERSION}.'
+ f' Please upgrade your grpc module to grpcio>={GRPC_GENERATED_VERSION}'
+ f' or downgrade your generated code using grpcio-tools<={GRPC_VERSION}.'
)
class WorkerStub(object):
"""Missing associated documentation comment in .proto file."""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.StreamNode = channel.unary_stream(
'/langgraph.Worker/StreamNode',
request_serializer=server__pb2.PregelExecutableTask.SerializeToString,
response_deserializer=server__pb2.Event.FromString,
_registered_method=True)
self.InvokeReducer = channel.unary_stream(
'/langgraph.Worker/InvokeReducer',
request_serializer=server__pb2.PregelExecutableTask.SerializeToString,
response_deserializer=server__pb2.Event.FromString,
_registered_method=True)
self.ListGraphs = channel.unary_unary(
'/langgraph.Worker/ListGraphs',
request_serializer=server__pb2.Empty.SerializeToString,
response_deserializer=server__pb2.ListGraphsResponse.FromString,
_registered_method=True)
class WorkerServicer(object):
"""Missing associated documentation comment in .proto file."""
def StreamNode(self, request, context):
"""Call stream on a task
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def InvokeReducer(self, request, context):
"""Invoke a reducer
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def ListGraphs(self, request, context):
"""List available graphs
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_WorkerServicer_to_server(servicer, server):
rpc_method_handlers = {
'StreamNode': grpc.unary_stream_rpc_method_handler(
servicer.StreamNode,
request_deserializer=server__pb2.PregelExecutableTask.FromString,
response_serializer=server__pb2.Event.SerializeToString,
),
'InvokeReducer': grpc.unary_stream_rpc_method_handler(
servicer.InvokeReducer,
request_deserializer=server__pb2.PregelExecutableTask.FromString,
response_serializer=server__pb2.Event.SerializeToString,
),
'ListGraphs': grpc.unary_unary_rpc_method_handler(
servicer.ListGraphs,
request_deserializer=server__pb2.Empty.FromString,
response_serializer=server__pb2.ListGraphsResponse.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'langgraph.Worker', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
server.add_registered_method_handlers('langgraph.Worker', rpc_method_handlers)
# This class is part of an EXPERIMENTAL API.
class Worker(object):
"""Missing associated documentation comment in .proto file."""
@staticmethod
def StreamNode(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_stream(
request,
target,
'/langgraph.Worker/StreamNode',
server__pb2.PregelExecutableTask.SerializeToString,
server__pb2.Event.FromString,
options,
channel_credentials,
insecure,
call_credentials,
compression,
wait_for_ready,
timeout,
metadata,
_registered_method=True)
@staticmethod
def InvokeReducer(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_stream(
request,
target,
'/langgraph.Worker/InvokeReducer',
server__pb2.PregelExecutableTask.SerializeToString,
server__pb2.Event.FromString,
options,
channel_credentials,
insecure,
call_credentials,
compression,
wait_for_ready,
timeout,
metadata,
_registered_method=True)
@staticmethod
def ListGraphs(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(
request,
target,
'/langgraph.Worker/ListGraphs',
server__pb2.Empty.SerializeToString,
server__pb2.ListGraphsResponse.FromString,
options,
channel_credentials,
insecure,
call_credentials,
compression,
wait_for_ready,
timeout,
metadata,
_registered_method=True)
-214
View File
@@ -1,214 +0,0 @@
version = 1
revision = 2
requires-python = ">=3.12"
[[package]]
name = "grpcio"
version = "1.71.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/1c/95/aa11fc09a85d91fbc7dd405dcb2a1e0256989d67bf89fa65ae24b3ba105a/grpcio-1.71.0.tar.gz", hash = "sha256:2b85f7820475ad3edec209d3d89a7909ada16caab05d3f2e08a7e8ae3200a55c", size = 12549828, upload-time = "2025-03-10T19:28:49.203Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/4c/83/bd4b6a9ba07825bd19c711d8b25874cd5de72c2a3fbf635c3c344ae65bd2/grpcio-1.71.0-cp312-cp312-linux_armv7l.whl", hash = "sha256:0ff35c8d807c1c7531d3002be03221ff9ae15712b53ab46e2a0b4bb271f38537", size = 5184101, upload-time = "2025-03-10T19:24:54.11Z" },
{ url = "https://files.pythonhosted.org/packages/31/ea/2e0d90c0853568bf714693447f5c73272ea95ee8dad107807fde740e595d/grpcio-1.71.0-cp312-cp312-macosx_10_14_universal2.whl", hash = "sha256:b78a99cd1ece4be92ab7c07765a0b038194ded2e0a26fd654591ee136088d8d7", size = 11310927, upload-time = "2025-03-10T19:24:56.1Z" },
{ url = "https://files.pythonhosted.org/packages/ac/bc/07a3fd8af80467390af491d7dc66882db43884128cdb3cc8524915e0023c/grpcio-1.71.0-cp312-cp312-manylinux_2_17_aarch64.whl", hash = "sha256:dc1a1231ed23caac1de9f943d031f1bc38d0f69d2a3b243ea0d664fc1fbd7fec", size = 5654280, upload-time = "2025-03-10T19:24:58.55Z" },
{ url = "https://files.pythonhosted.org/packages/16/af/21f22ea3eed3d0538b6ef7889fce1878a8ba4164497f9e07385733391e2b/grpcio-1.71.0-cp312-cp312-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e6beeea5566092c5e3c4896c6d1d307fb46b1d4bdf3e70c8340b190a69198594", size = 6312051, upload-time = "2025-03-10T19:25:00.682Z" },
{ url = "https://files.pythonhosted.org/packages/49/9d/e12ddc726dc8bd1aa6cba67c85ce42a12ba5b9dd75d5042214a59ccf28ce/grpcio-1.71.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d5170929109450a2c031cfe87d6716f2fae39695ad5335d9106ae88cc32dc84c", size = 5910666, upload-time = "2025-03-10T19:25:03.01Z" },
{ url = "https://files.pythonhosted.org/packages/d9/e9/38713d6d67aedef738b815763c25f092e0454dc58e77b1d2a51c9d5b3325/grpcio-1.71.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:5b08d03ace7aca7b2fadd4baf291139b4a5f058805a8327bfe9aece7253b6d67", size = 6012019, upload-time = "2025-03-10T19:25:05.174Z" },
{ url = "https://files.pythonhosted.org/packages/80/da/4813cd7adbae6467724fa46c952d7aeac5e82e550b1c62ed2aeb78d444ae/grpcio-1.71.0-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:f903017db76bf9cc2b2d8bdd37bf04b505bbccad6be8a81e1542206875d0e9db", size = 6637043, upload-time = "2025-03-10T19:25:06.987Z" },
{ url = "https://files.pythonhosted.org/packages/52/ca/c0d767082e39dccb7985c73ab4cf1d23ce8613387149e9978c70c3bf3b07/grpcio-1.71.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:469f42a0b410883185eab4689060a20488a1a0a00f8bbb3cbc1061197b4c5a79", size = 6186143, upload-time = "2025-03-10T19:25:08.877Z" },
{ url = "https://files.pythonhosted.org/packages/00/61/7b2c8ec13303f8fe36832c13d91ad4d4ba57204b1c723ada709c346b2271/grpcio-1.71.0-cp312-cp312-win32.whl", hash = "sha256:ad9f30838550695b5eb302add33f21f7301b882937460dd24f24b3cc5a95067a", size = 3604083, upload-time = "2025-03-10T19:25:10.736Z" },
{ url = "https://files.pythonhosted.org/packages/fd/7c/1e429c5fb26122055d10ff9a1d754790fb067d83c633ff69eddcf8e3614b/grpcio-1.71.0-cp312-cp312-win_amd64.whl", hash = "sha256:652350609332de6dac4ece254e5d7e1ff834e203d6afb769601f286886f6f3a8", size = 4272191, upload-time = "2025-03-10T19:25:13.12Z" },
{ url = "https://files.pythonhosted.org/packages/04/dd/b00cbb45400d06b26126dcfdbdb34bb6c4f28c3ebbd7aea8228679103ef6/grpcio-1.71.0-cp313-cp313-linux_armv7l.whl", hash = "sha256:cebc1b34ba40a312ab480ccdb396ff3c529377a2fce72c45a741f7215bfe8379", size = 5184138, upload-time = "2025-03-10T19:25:15.101Z" },
{ url = "https://files.pythonhosted.org/packages/ed/0a/4651215983d590ef53aac40ba0e29dda941a02b097892c44fa3357e706e5/grpcio-1.71.0-cp313-cp313-macosx_10_14_universal2.whl", hash = "sha256:85da336e3649a3d2171e82f696b5cad2c6231fdd5bad52616476235681bee5b3", size = 11310747, upload-time = "2025-03-10T19:25:17.201Z" },
{ url = "https://files.pythonhosted.org/packages/57/a3/149615b247f321e13f60aa512d3509d4215173bdb982c9098d78484de216/grpcio-1.71.0-cp313-cp313-manylinux_2_17_aarch64.whl", hash = "sha256:f9a412f55bb6e8f3bb000e020dbc1e709627dcb3a56f6431fa7076b4c1aab0db", size = 5653991, upload-time = "2025-03-10T19:25:20.39Z" },
{ url = "https://files.pythonhosted.org/packages/ca/56/29432a3e8d951b5e4e520a40cd93bebaa824a14033ea8e65b0ece1da6167/grpcio-1.71.0-cp313-cp313-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:47be9584729534660416f6d2a3108aaeac1122f6b5bdbf9fd823e11fe6fbaa29", size = 6312781, upload-time = "2025-03-10T19:25:22.823Z" },
{ url = "https://files.pythonhosted.org/packages/a3/f8/286e81a62964ceb6ac10b10925261d4871a762d2a763fbf354115f9afc98/grpcio-1.71.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7c9c80ac6091c916db81131d50926a93ab162a7e97e4428ffc186b6e80d6dda4", size = 5910479, upload-time = "2025-03-10T19:25:24.828Z" },
{ url = "https://files.pythonhosted.org/packages/35/67/d1febb49ec0f599b9e6d4d0d44c2d4afdbed9c3e80deb7587ec788fcf252/grpcio-1.71.0-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:789d5e2a3a15419374b7b45cd680b1e83bbc1e52b9086e49308e2c0b5bbae6e3", size = 6013262, upload-time = "2025-03-10T19:25:26.987Z" },
{ url = "https://files.pythonhosted.org/packages/a1/04/f9ceda11755f0104a075ad7163fc0d96e2e3a9fe25ef38adfc74c5790daf/grpcio-1.71.0-cp313-cp313-musllinux_1_1_i686.whl", hash = "sha256:1be857615e26a86d7363e8a163fade914595c81fec962b3d514a4b1e8760467b", size = 6643356, upload-time = "2025-03-10T19:25:29.606Z" },
{ url = "https://files.pythonhosted.org/packages/fb/ce/236dbc3dc77cf9a9242adcf1f62538734ad64727fabf39e1346ad4bd5c75/grpcio-1.71.0-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:a76d39b5fafd79ed604c4be0a869ec3581a172a707e2a8d7a4858cb05a5a7637", size = 6186564, upload-time = "2025-03-10T19:25:31.537Z" },
{ url = "https://files.pythonhosted.org/packages/10/fd/b3348fce9dd4280e221f513dd54024e765b21c348bc475516672da4218e9/grpcio-1.71.0-cp313-cp313-win32.whl", hash = "sha256:74258dce215cb1995083daa17b379a1a5a87d275387b7ffe137f1d5131e2cfbb", size = 3601890, upload-time = "2025-03-10T19:25:33.421Z" },
{ url = "https://files.pythonhosted.org/packages/be/f8/db5d5f3fc7e296166286c2a397836b8b042f7ad1e11028d82b061701f0f7/grpcio-1.71.0-cp313-cp313-win_amd64.whl", hash = "sha256:22c3bc8d488c039a199f7a003a38cb7635db6656fa96437a8accde8322ce2366", size = 4273308, upload-time = "2025-03-10T19:25:35.79Z" },
]
[[package]]
name = "grpcio-tools"
version = "1.71.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "grpcio" },
{ name = "protobuf" },
{ name = "setuptools" },
]
sdist = { url = "https://files.pythonhosted.org/packages/05/d2/c0866a48c355a6a4daa1f7e27e210c7fa561b1f3b7c0bce2671e89cfa31e/grpcio_tools-1.71.0.tar.gz", hash = "sha256:38dba8e0d5e0fb23a034e09644fdc6ed862be2371887eee54901999e8f6792a8", size = 5326008, upload-time = "2025-03-10T19:29:03.38Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/de/e4/156956b92ad0298290c3d68e6670bc5a6fbefcccfe1ec3997480605e7135/grpcio_tools-1.71.0-cp312-cp312-linux_armv7l.whl", hash = "sha256:61c0409d5bdac57a7bd0ce0ab01c1c916728fe4c8a03d77a25135ad481eb505c", size = 2385480, upload-time = "2025-03-10T19:27:46.425Z" },
{ url = "https://files.pythonhosted.org/packages/c1/08/9930eb4bb38c5214041c9f24f8b35e9864a7938282db986836546c782d52/grpcio_tools-1.71.0-cp312-cp312-macosx_10_14_universal2.whl", hash = "sha256:28784f39921d061d2164a9dcda5164a69d07bf29f91f0ea50b505958292312c9", size = 5951891, upload-time = "2025-03-10T19:27:48.219Z" },
{ url = "https://files.pythonhosted.org/packages/73/65/931f29ec9c33719d48e1e30446ecce6f5d2cd4e4934fa73fbe07de41c43b/grpcio_tools-1.71.0-cp312-cp312-manylinux_2_17_aarch64.whl", hash = "sha256:192808cf553cedca73f0479cc61d5684ad61f24db7a5f3c4dfe1500342425866", size = 2351967, upload-time = "2025-03-10T19:27:50.09Z" },
{ url = "https://files.pythonhosted.org/packages/b8/26/2ec8748534406214f20a4809c36efcfa88d1a26246e8312102e3ef8c295d/grpcio_tools-1.71.0-cp312-cp312-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:989ee9da61098230d3d4c8f8f8e27c2de796f1ff21b1c90110e636d9acd9432b", size = 2745003, upload-time = "2025-03-10T19:27:52.333Z" },
{ url = "https://files.pythonhosted.org/packages/f1/33/87b4610c86a4e10ee446b543a4d536f94ab04f828bab841f0bc1a083de72/grpcio_tools-1.71.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:541a756276c8a55dec991f6c0106ae20c8c8f5ce8d0bdbfcb01e2338d1a8192b", size = 2476455, upload-time = "2025-03-10T19:27:54.493Z" },
{ url = "https://files.pythonhosted.org/packages/00/7c/f7f0cc36a43be9d45b3ce2a55245f3c7d063a24b7930dd719929e58871a4/grpcio_tools-1.71.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:870c0097700d13c403e5517cb7750ab5b4a791ce3e71791c411a38c5468b64bd", size = 2854333, upload-time = "2025-03-10T19:27:56.693Z" },
{ url = "https://files.pythonhosted.org/packages/07/c4/34b9ea62b173c13fa7accba5f219355b320c05c80c79c3ba70fe52f47b2f/grpcio_tools-1.71.0-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:abd57f615e88bf93c3c6fd31f923106e3beb12f8cd2df95b0d256fa07a7a0a57", size = 3304297, upload-time = "2025-03-10T19:27:58.437Z" },
{ url = "https://files.pythonhosted.org/packages/5c/ef/9d3449db8a07688dc3de7dcbd2a07048a128610b1a491c5c0cb3e90a00c5/grpcio_tools-1.71.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:753270e2d06d37e6d7af8967d1d059ec635ad215882041a36294f4e2fd502b2e", size = 2916212, upload-time = "2025-03-10T19:28:00.208Z" },
{ url = "https://files.pythonhosted.org/packages/2e/c6/990e8194c934dfe7cf89ef307c319fa4f2bc0b78aeca707addbfa1e502f1/grpcio_tools-1.71.0-cp312-cp312-win32.whl", hash = "sha256:0e647794bd7138b8c215e86277a9711a95cf6a03ff6f9e555d54fdf7378b9f9d", size = 948849, upload-time = "2025-03-10T19:28:01.81Z" },
{ url = "https://files.pythonhosted.org/packages/42/95/3c36d3205e6bd19853cc2420e44b6ef302eb4cfcf56498973c7e85f6c03b/grpcio_tools-1.71.0-cp312-cp312-win_amd64.whl", hash = "sha256:48debc879570972d28bfe98e4970eff25bb26da3f383e0e49829b2d2cd35ad87", size = 1120294, upload-time = "2025-03-10T19:28:03.517Z" },
{ url = "https://files.pythonhosted.org/packages/84/a7/70dc7e9957bcbaccd4dcb6cc11215e0b918f546d55599221522fe0d073e0/grpcio_tools-1.71.0-cp313-cp313-linux_armv7l.whl", hash = "sha256:9a78d07d6c301a25ef5ede962920a522556a1dfee1ccc05795994ceb867f766c", size = 2384758, upload-time = "2025-03-10T19:28:05.327Z" },
{ url = "https://files.pythonhosted.org/packages/65/79/57320b28d0a0c5ec94095fd571a65292f8ed7e1c47e59ae4021e8a48d49b/grpcio_tools-1.71.0-cp313-cp313-macosx_10_14_universal2.whl", hash = "sha256:580ac88141c9815557e63c9c04f5b1cdb19b4db8d0cb792b573354bde1ee8b12", size = 5951661, upload-time = "2025-03-10T19:28:07.879Z" },
{ url = "https://files.pythonhosted.org/packages/80/3d/343df5ed7c5dd66fc7a19e4ef3e97ccc4f5d802122b04cd6492f0dcd79f5/grpcio_tools-1.71.0-cp313-cp313-manylinux_2_17_aarch64.whl", hash = "sha256:f7c678e68ece0ae908ecae1c4314a0c2c7f83e26e281738b9609860cc2c82d96", size = 2351571, upload-time = "2025-03-10T19:28:09.909Z" },
{ url = "https://files.pythonhosted.org/packages/56/2f/b9736e8c84e880c4237f5b880c6c799b4977c5cde190999bc7ab4b2ec445/grpcio_tools-1.71.0-cp313-cp313-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:56ecd6cc89b5e5eed1de5eb9cafce86c9c9043ee3840888cc464d16200290b53", size = 2744580, upload-time = "2025-03-10T19:28:11.866Z" },
{ url = "https://files.pythonhosted.org/packages/76/9b/bdb384967353da7bf64bac4232f4cf8ae43f19d0f2f640978d4d4197e667/grpcio_tools-1.71.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e52a041afc20ab2431d756b6295d727bd7adee813b21b06a3483f4a7a15ea15f", size = 2475978, upload-time = "2025-03-10T19:28:14.236Z" },
{ url = "https://files.pythonhosted.org/packages/26/71/1411487fd7862d347b98fda5e3beef611a71b2ac2faac62a965d9e2536b3/grpcio_tools-1.71.0-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:2a1712f12102b60c8d92779b89d0504e0d6f3a59f2b933e5622b8583f5c02992", size = 2853314, upload-time = "2025-03-10T19:28:16.085Z" },
{ url = "https://files.pythonhosted.org/packages/03/06/59d0523eb1ba2f64edc72cb150152fa1b2e77061cae3ef3ecd3ef2a87f51/grpcio_tools-1.71.0-cp313-cp313-musllinux_1_1_i686.whl", hash = "sha256:41878cb7a75477e62fdd45e7e9155b3af1b7a5332844021e2511deaf99ac9e6c", size = 3303981, upload-time = "2025-03-10T19:28:18.129Z" },
{ url = "https://files.pythonhosted.org/packages/c2/71/fb9fb49f2b738ec1dfbbc8cdce0b26e5f9c5fc0edef72e453580620d6a36/grpcio_tools-1.71.0-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:682e958b476049ccc14c71bedf3f979bced01f6e0c04852efc5887841a32ad6b", size = 2915876, upload-time = "2025-03-10T19:28:20.045Z" },
{ url = "https://files.pythonhosted.org/packages/bd/0f/0d49f6fe6fa2d09e9820dd9eeb30437e86002303076be2b6ada0fb52b8f2/grpcio_tools-1.71.0-cp313-cp313-win32.whl", hash = "sha256:0ccfb837152b7b858b9f26bb110b3ae8c46675d56130f6c2f03605c4f129be13", size = 948245, upload-time = "2025-03-10T19:28:21.876Z" },
{ url = "https://files.pythonhosted.org/packages/bb/14/ab131a39187bfea950280b2277a82d2033469fe8c86f73b10b19f53cc5ca/grpcio_tools-1.71.0-cp313-cp313-win_amd64.whl", hash = "sha256:ffff9bc5eacb34dd26b487194f7d44a3e64e752fc2cf049d798021bf25053b87", size = 1119649, upload-time = "2025-03-10T19:28:23.679Z" },
]
[[package]]
name = "grpclib"
version = "0.4.8"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "h2" },
{ name = "multidict" },
]
sdist = { url = "https://files.pythonhosted.org/packages/19/75/0f0d3524b38b35e5cd07334b754aa9bd0570140ad982131b04ebfa3b0374/grpclib-0.4.8.tar.gz", hash = "sha256:d8823763780ef94fed8b2c562f7485cf0bbee15fc7d065a640673667f7719c9a", size = 62793, upload-time = "2025-05-04T16:27:30.051Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/03/8b/ad381ec1b8195fa4a9a693cb8087e031b99530c0d6b8ad036dcb99e144c4/grpclib-0.4.8-py3-none-any.whl", hash = "sha256:a5047733a7acc1c1cee6abf3c841c7c6fab67d2844a45a853b113fa2e6cd2654", size = 76311, upload-time = "2025-05-04T16:27:22.818Z" },
]
[[package]]
name = "h2"
version = "4.2.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "hpack" },
{ name = "hyperframe" },
]
sdist = { url = "https://files.pythonhosted.org/packages/1b/38/d7f80fd13e6582fb8e0df8c9a653dcc02b03ca34f4d72f34869298c5baf8/h2-4.2.0.tar.gz", hash = "sha256:c8a52129695e88b1a0578d8d2cc6842bbd79128ac685463b887ee278126ad01f", size = 2150682, upload-time = "2025-02-02T07:43:51.815Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/d0/9e/984486f2d0a0bd2b024bf4bc1c62688fcafa9e61991f041fb0e2def4a982/h2-4.2.0-py3-none-any.whl", hash = "sha256:479a53ad425bb29af087f3458a61d30780bc818e4ebcf01f0b536ba916462ed0", size = 60957, upload-time = "2025-02-01T11:02:26.481Z" },
]
[[package]]
name = "hpack"
version = "4.1.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/2c/48/71de9ed269fdae9c8057e5a4c0aa7402e8bb16f2c6e90b3aa53327b113f8/hpack-4.1.0.tar.gz", hash = "sha256:ec5eca154f7056aa06f196a557655c5b009b382873ac8d1e66e79e87535f1dca", size = 51276, upload-time = "2025-01-22T21:44:58.347Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/07/c6/80c95b1b2b94682a72cbdbfb85b81ae2daffa4291fbfa1b1464502ede10d/hpack-4.1.0-py3-none-any.whl", hash = "sha256:157ac792668d995c657d93111f46b4535ed114f0c9c8d672271bbec7eae1b496", size = 34357, upload-time = "2025-01-22T21:44:56.92Z" },
]
[[package]]
name = "hyperframe"
version = "6.1.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/02/e7/94f8232d4a74cc99514c13a9f995811485a6903d48e5d952771ef6322e30/hyperframe-6.1.0.tar.gz", hash = "sha256:f630908a00854a7adeabd6382b43923a4c4cd4b821fcb527e6ab9e15382a3b08", size = 26566, upload-time = "2025-01-22T21:41:49.302Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/48/30/47d0bf6072f7252e6521f3447ccfa40b421b6824517f82854703d0f5a98b/hyperframe-6.1.0-py3-none-any.whl", hash = "sha256:b03380493a519fce58ea5af42e4a42317bf9bd425596f7a0835ffce80f1a42e5", size = 13007, upload-time = "2025-01-22T21:41:47.295Z" },
]
[[package]]
name = "multidict"
version = "6.4.4"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/91/2f/a3470242707058fe856fe59241eee5635d79087100b7042a867368863a27/multidict-6.4.4.tar.gz", hash = "sha256:69ee9e6ba214b5245031b76233dd95408a0fd57fdb019ddcc1ead4790932a8e8", size = 90183, upload-time = "2025-05-19T14:16:37.381Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/d2/b5/5675377da23d60875fe7dae6be841787755878e315e2f517235f22f59e18/multidict-6.4.4-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:dc388f75a1c00000824bf28b7633e40854f4127ede80512b44c3cfeeea1839a2", size = 64293, upload-time = "2025-05-19T14:14:44.724Z" },
{ url = "https://files.pythonhosted.org/packages/34/a7/be384a482754bb8c95d2bbe91717bf7ccce6dc38c18569997a11f95aa554/multidict-6.4.4-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:98af87593a666f739d9dba5d0ae86e01b0e1a9cfcd2e30d2d361fbbbd1a9162d", size = 38096, upload-time = "2025-05-19T14:14:45.95Z" },
{ url = "https://files.pythonhosted.org/packages/66/6d/d59854bb4352306145bdfd1704d210731c1bb2c890bfee31fb7bbc1c4c7f/multidict-6.4.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:aff4cafea2d120327d55eadd6b7f1136a8e5a0ecf6fb3b6863e8aca32cd8e50a", size = 37214, upload-time = "2025-05-19T14:14:47.158Z" },
{ url = "https://files.pythonhosted.org/packages/99/e0/c29d9d462d7cfc5fc8f9bf24f9c6843b40e953c0b55e04eba2ad2cf54fba/multidict-6.4.4-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:169c4ba7858176b797fe551d6e99040c531c775d2d57b31bcf4de6d7a669847f", size = 224686, upload-time = "2025-05-19T14:14:48.366Z" },
{ url = "https://files.pythonhosted.org/packages/dc/4a/da99398d7fd8210d9de068f9a1b5f96dfaf67d51e3f2521f17cba4ee1012/multidict-6.4.4-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:b9eb4c59c54421a32b3273d4239865cb14ead53a606db066d7130ac80cc8ec93", size = 231061, upload-time = "2025-05-19T14:14:49.952Z" },
{ url = "https://files.pythonhosted.org/packages/21/f5/ac11add39a0f447ac89353e6ca46666847051103649831c08a2800a14455/multidict-6.4.4-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7cf3bd54c56aa16fdb40028d545eaa8d051402b61533c21e84046e05513d5780", size = 232412, upload-time = "2025-05-19T14:14:51.812Z" },
{ url = "https://files.pythonhosted.org/packages/d9/11/4b551e2110cded705a3c13a1d4b6a11f73891eb5a1c449f1b2b6259e58a6/multidict-6.4.4-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f682c42003c7264134bfe886376299db4cc0c6cd06a3295b41b347044bcb5482", size = 231563, upload-time = "2025-05-19T14:14:53.262Z" },
{ url = "https://files.pythonhosted.org/packages/4c/02/751530c19e78fe73b24c3da66618eda0aa0d7f6e7aa512e46483de6be210/multidict-6.4.4-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a920f9cf2abdf6e493c519492d892c362007f113c94da4c239ae88429835bad1", size = 223811, upload-time = "2025-05-19T14:14:55.232Z" },
{ url = "https://files.pythonhosted.org/packages/c7/cb/2be8a214643056289e51ca356026c7b2ce7225373e7a1f8c8715efee8988/multidict-6.4.4-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:530d86827a2df6504526106b4c104ba19044594f8722d3e87714e847c74a0275", size = 216524, upload-time = "2025-05-19T14:14:57.226Z" },
{ url = "https://files.pythonhosted.org/packages/19/f3/6d5011ec375c09081f5250af58de85f172bfcaafebff286d8089243c4bd4/multidict-6.4.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:ecde56ea2439b96ed8a8d826b50c57364612ddac0438c39e473fafad7ae1c23b", size = 229012, upload-time = "2025-05-19T14:14:58.597Z" },
{ url = "https://files.pythonhosted.org/packages/67/9c/ca510785df5cf0eaf5b2a8132d7d04c1ce058dcf2c16233e596ce37a7f8e/multidict-6.4.4-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:dc8c9736d8574b560634775ac0def6bdc1661fc63fa27ffdfc7264c565bcb4f2", size = 226765, upload-time = "2025-05-19T14:15:00.048Z" },
{ url = "https://files.pythonhosted.org/packages/36/c8/ca86019994e92a0f11e642bda31265854e6ea7b235642f0477e8c2e25c1f/multidict-6.4.4-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:7f3d3b3c34867579ea47cbd6c1f2ce23fbfd20a273b6f9e3177e256584f1eacc", size = 222888, upload-time = "2025-05-19T14:15:01.568Z" },
{ url = "https://files.pythonhosted.org/packages/c6/67/bc25a8e8bd522935379066950ec4e2277f9b236162a73548a2576d4b9587/multidict-6.4.4-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:87a728af265e08f96b6318ebe3c0f68b9335131f461efab2fc64cc84a44aa6ed", size = 234041, upload-time = "2025-05-19T14:15:03.759Z" },
{ url = "https://files.pythonhosted.org/packages/f1/a0/70c4c2d12857fccbe607b334b7ee28b6b5326c322ca8f73ee54e70d76484/multidict-6.4.4-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:9f193eeda1857f8e8d3079a4abd258f42ef4a4bc87388452ed1e1c4d2b0c8740", size = 231046, upload-time = "2025-05-19T14:15:05.698Z" },
{ url = "https://files.pythonhosted.org/packages/c1/0f/52954601d02d39742aab01d6b92f53c1dd38b2392248154c50797b4df7f1/multidict-6.4.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:be06e73c06415199200e9a2324a11252a3d62030319919cde5e6950ffeccf72e", size = 227106, upload-time = "2025-05-19T14:15:07.124Z" },
{ url = "https://files.pythonhosted.org/packages/af/24/679d83ec4379402d28721790dce818e5d6b9f94ce1323a556fb17fa9996c/multidict-6.4.4-cp312-cp312-win32.whl", hash = "sha256:622f26ea6a7e19b7c48dd9228071f571b2fbbd57a8cd71c061e848f281550e6b", size = 35351, upload-time = "2025-05-19T14:15:08.556Z" },
{ url = "https://files.pythonhosted.org/packages/52/ef/40d98bc5f986f61565f9b345f102409534e29da86a6454eb6b7c00225a13/multidict-6.4.4-cp312-cp312-win_amd64.whl", hash = "sha256:5e2bcda30d5009996ff439e02a9f2b5c3d64a20151d34898c000a6281faa3781", size = 38791, upload-time = "2025-05-19T14:15:09.825Z" },
{ url = "https://files.pythonhosted.org/packages/df/2a/e166d2ffbf4b10131b2d5b0e458f7cee7d986661caceae0de8753042d4b2/multidict-6.4.4-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:82ffabefc8d84c2742ad19c37f02cde5ec2a1ee172d19944d380f920a340e4b9", size = 64123, upload-time = "2025-05-19T14:15:11.044Z" },
{ url = "https://files.pythonhosted.org/packages/8c/96/e200e379ae5b6f95cbae472e0199ea98913f03d8c9a709f42612a432932c/multidict-6.4.4-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:6a2f58a66fe2c22615ad26156354005391e26a2f3721c3621504cd87c1ea87bf", size = 38049, upload-time = "2025-05-19T14:15:12.902Z" },
{ url = "https://files.pythonhosted.org/packages/75/fb/47afd17b83f6a8c7fa863c6d23ac5ba6a0e6145ed8a6bcc8da20b2b2c1d2/multidict-6.4.4-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:5883d6ee0fd9d8a48e9174df47540b7545909841ac82354c7ae4cbe9952603bd", size = 37078, upload-time = "2025-05-19T14:15:14.282Z" },
{ url = "https://files.pythonhosted.org/packages/fa/70/1af3143000eddfb19fd5ca5e78393985ed988ac493bb859800fe0914041f/multidict-6.4.4-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9abcf56a9511653fa1d052bfc55fbe53dbee8f34e68bd6a5a038731b0ca42d15", size = 224097, upload-time = "2025-05-19T14:15:15.566Z" },
{ url = "https://files.pythonhosted.org/packages/b1/39/d570c62b53d4fba844e0378ffbcd02ac25ca423d3235047013ba2f6f60f8/multidict-6.4.4-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:6ed5ae5605d4ad5a049fad2a28bb7193400700ce2f4ae484ab702d1e3749c3f9", size = 230768, upload-time = "2025-05-19T14:15:17.308Z" },
{ url = "https://files.pythonhosted.org/packages/fd/f8/ed88f2c4d06f752b015933055eb291d9bc184936903752c66f68fb3c95a7/multidict-6.4.4-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:bbfcb60396f9bcfa63e017a180c3105b8c123a63e9d1428a36544e7d37ca9e20", size = 231331, upload-time = "2025-05-19T14:15:18.73Z" },
{ url = "https://files.pythonhosted.org/packages/9c/6f/8e07cffa32f483ab887b0d56bbd8747ac2c1acd00dc0af6fcf265f4a121e/multidict-6.4.4-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b0f1987787f5f1e2076b59692352ab29a955b09ccc433c1f6b8e8e18666f608b", size = 230169, upload-time = "2025-05-19T14:15:20.179Z" },
{ url = "https://files.pythonhosted.org/packages/e6/2b/5dcf173be15e42f330110875a2668ddfc208afc4229097312212dc9c1236/multidict-6.4.4-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1d0121ccce8c812047d8d43d691a1ad7641f72c4f730474878a5aeae1b8ead8c", size = 222947, upload-time = "2025-05-19T14:15:21.714Z" },
{ url = "https://files.pythonhosted.org/packages/39/75/4ddcbcebe5ebcd6faa770b629260d15840a5fc07ce8ad295a32e14993726/multidict-6.4.4-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:83ec4967114295b8afd120a8eec579920c882831a3e4c3331d591a8e5bfbbc0f", size = 215761, upload-time = "2025-05-19T14:15:23.242Z" },
{ url = "https://files.pythonhosted.org/packages/6a/c9/55e998ae45ff15c5608e384206aa71a11e1b7f48b64d166db400b14a3433/multidict-6.4.4-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:995f985e2e268deaf17867801b859a282e0448633f1310e3704b30616d269d69", size = 227605, upload-time = "2025-05-19T14:15:24.763Z" },
{ url = "https://files.pythonhosted.org/packages/04/49/c2404eac74497503c77071bd2e6f88c7e94092b8a07601536b8dbe99be50/multidict-6.4.4-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:d832c608f94b9f92a0ec8b7e949be7792a642b6e535fcf32f3e28fab69eeb046", size = 226144, upload-time = "2025-05-19T14:15:26.249Z" },
{ url = "https://files.pythonhosted.org/packages/62/c5/0cd0c3c6f18864c40846aa2252cd69d308699cb163e1c0d989ca301684da/multidict-6.4.4-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:d21c1212171cf7da703c5b0b7a0e85be23b720818aef502ad187d627316d5645", size = 221100, upload-time = "2025-05-19T14:15:28.303Z" },
{ url = "https://files.pythonhosted.org/packages/71/7b/f2f3887bea71739a046d601ef10e689528d4f911d84da873b6be9194ffea/multidict-6.4.4-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:cbebaa076aaecad3d4bb4c008ecc73b09274c952cf6a1b78ccfd689e51f5a5b0", size = 232731, upload-time = "2025-05-19T14:15:30.263Z" },
{ url = "https://files.pythonhosted.org/packages/e5/b3/d9de808349df97fa75ec1372758701b5800ebad3c46ae377ad63058fbcc6/multidict-6.4.4-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:c93a6fb06cc8e5d3628b2b5fda215a5db01e8f08fc15fadd65662d9b857acbe4", size = 229637, upload-time = "2025-05-19T14:15:33.337Z" },
{ url = "https://files.pythonhosted.org/packages/5e/57/13207c16b615eb4f1745b44806a96026ef8e1b694008a58226c2d8f5f0a5/multidict-6.4.4-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:8cd8f81f1310182362fb0c7898145ea9c9b08a71081c5963b40ee3e3cac589b1", size = 225594, upload-time = "2025-05-19T14:15:34.832Z" },
{ url = "https://files.pythonhosted.org/packages/3a/e4/d23bec2f70221604f5565000632c305fc8f25ba953e8ce2d8a18842b9841/multidict-6.4.4-cp313-cp313-win32.whl", hash = "sha256:3e9f1cd61a0ab857154205fb0b1f3d3ace88d27ebd1409ab7af5096e409614cd", size = 35359, upload-time = "2025-05-19T14:15:36.246Z" },
{ url = "https://files.pythonhosted.org/packages/a7/7a/cfe1a47632be861b627f46f642c1d031704cc1c0f5c0efbde2ad44aa34bd/multidict-6.4.4-cp313-cp313-win_amd64.whl", hash = "sha256:8ffb40b74400e4455785c2fa37eba434269149ec525fc8329858c862e4b35373", size = 38903, upload-time = "2025-05-19T14:15:37.507Z" },
{ url = "https://files.pythonhosted.org/packages/68/7b/15c259b0ab49938a0a1c8f3188572802704a779ddb294edc1b2a72252e7c/multidict-6.4.4-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:6a602151dbf177be2450ef38966f4be3467d41a86c6a845070d12e17c858a156", size = 68895, upload-time = "2025-05-19T14:15:38.856Z" },
{ url = "https://files.pythonhosted.org/packages/f1/7d/168b5b822bccd88142e0a3ce985858fea612404edd228698f5af691020c9/multidict-6.4.4-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:0d2b9712211b860d123815a80b859075d86a4d54787e247d7fbee9db6832cf1c", size = 40183, upload-time = "2025-05-19T14:15:40.197Z" },
{ url = "https://files.pythonhosted.org/packages/e0/b7/d4b8d98eb850ef28a4922ba508c31d90715fd9b9da3801a30cea2967130b/multidict-6.4.4-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:d2fa86af59f8fc1972e121ade052145f6da22758f6996a197d69bb52f8204e7e", size = 39592, upload-time = "2025-05-19T14:15:41.508Z" },
{ url = "https://files.pythonhosted.org/packages/18/28/a554678898a19583548e742080cf55d169733baf57efc48c2f0273a08583/multidict-6.4.4-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:50855d03e9e4d66eab6947ba688ffb714616f985838077bc4b490e769e48da51", size = 226071, upload-time = "2025-05-19T14:15:42.877Z" },
{ url = "https://files.pythonhosted.org/packages/ee/dc/7ba6c789d05c310e294f85329efac1bf5b450338d2542498db1491a264df/multidict-6.4.4-cp313-cp313t-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:5bce06b83be23225be1905dcdb6b789064fae92499fbc458f59a8c0e68718601", size = 222597, upload-time = "2025-05-19T14:15:44.412Z" },
{ url = "https://files.pythonhosted.org/packages/24/4f/34eadbbf401b03768dba439be0fb94b0d187facae9142821a3d5599ccb3b/multidict-6.4.4-cp313-cp313t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:66ed0731f8e5dfd8369a883b6e564aca085fb9289aacabd9decd70568b9a30de", size = 228253, upload-time = "2025-05-19T14:15:46.474Z" },
{ url = "https://files.pythonhosted.org/packages/c0/e6/493225a3cdb0d8d80d43a94503fc313536a07dae54a3f030d279e629a2bc/multidict-6.4.4-cp313-cp313t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:329ae97fc2f56f44d91bc47fe0972b1f52d21c4b7a2ac97040da02577e2daca2", size = 226146, upload-time = "2025-05-19T14:15:48.003Z" },
{ url = "https://files.pythonhosted.org/packages/2f/70/e411a7254dc3bff6f7e6e004303b1b0591358e9f0b7c08639941e0de8bd6/multidict-6.4.4-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c27e5dcf520923d6474d98b96749e6805f7677e93aaaf62656005b8643f907ab", size = 220585, upload-time = "2025-05-19T14:15:49.546Z" },
{ url = "https://files.pythonhosted.org/packages/08/8f/beb3ae7406a619100d2b1fb0022c3bb55a8225ab53c5663648ba50dfcd56/multidict-6.4.4-cp313-cp313t-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:058cc59b9e9b143cc56715e59e22941a5d868c322242278d28123a5d09cdf6b0", size = 212080, upload-time = "2025-05-19T14:15:51.151Z" },
{ url = "https://files.pythonhosted.org/packages/9c/ec/355124e9d3d01cf8edb072fd14947220f357e1c5bc79c88dff89297e9342/multidict-6.4.4-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:69133376bc9a03f8c47343d33f91f74a99c339e8b58cea90433d8e24bb298031", size = 226558, upload-time = "2025-05-19T14:15:52.665Z" },
{ url = "https://files.pythonhosted.org/packages/fd/22/d2b95cbebbc2ada3be3812ea9287dcc9712d7f1a012fad041770afddb2ad/multidict-6.4.4-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:d6b15c55721b1b115c5ba178c77104123745b1417527ad9641a4c5e2047450f0", size = 212168, upload-time = "2025-05-19T14:15:55.279Z" },
{ url = "https://files.pythonhosted.org/packages/4d/c5/62bfc0b2f9ce88326dbe7179f9824a939c6c7775b23b95de777267b9725c/multidict-6.4.4-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:a887b77f51d3d41e6e1a63cf3bc7ddf24de5939d9ff69441387dfefa58ac2e26", size = 217970, upload-time = "2025-05-19T14:15:56.806Z" },
{ url = "https://files.pythonhosted.org/packages/79/74/977cea1aadc43ff1c75d23bd5bc4768a8fac98c14e5878d6ee8d6bab743c/multidict-6.4.4-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:632a3bf8f1787f7ef7d3c2f68a7bde5be2f702906f8b5842ad6da9d974d0aab3", size = 226980, upload-time = "2025-05-19T14:15:58.313Z" },
{ url = "https://files.pythonhosted.org/packages/48/fc/cc4a1a2049df2eb84006607dc428ff237af38e0fcecfdb8a29ca47b1566c/multidict-6.4.4-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:a145c550900deb7540973c5cdb183b0d24bed6b80bf7bddf33ed8f569082535e", size = 220641, upload-time = "2025-05-19T14:15:59.866Z" },
{ url = "https://files.pythonhosted.org/packages/3b/6a/a7444d113ab918701988d4abdde373dbdfd2def7bd647207e2bf645c7eac/multidict-6.4.4-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:cc5d83c6619ca5c9672cb78b39ed8542f1975a803dee2cda114ff73cbb076edd", size = 221728, upload-time = "2025-05-19T14:16:01.535Z" },
{ url = "https://files.pythonhosted.org/packages/2b/b0/fdf4c73ad1c55e0f4dbbf2aa59dd37037334091f9a4961646d2b7ac91a86/multidict-6.4.4-cp313-cp313t-win32.whl", hash = "sha256:3312f63261b9df49be9d57aaa6abf53a6ad96d93b24f9cc16cf979956355ce6e", size = 41913, upload-time = "2025-05-19T14:16:03.199Z" },
{ url = "https://files.pythonhosted.org/packages/8e/92/27989ecca97e542c0d01d05a98a5ae12198a243a9ee12563a0313291511f/multidict-6.4.4-cp313-cp313t-win_amd64.whl", hash = "sha256:ba852168d814b2c73333073e1c7116d9395bea69575a01b0b3c89d2d5a87c8fb", size = 46112, upload-time = "2025-05-19T14:16:04.909Z" },
{ url = "https://files.pythonhosted.org/packages/84/5d/e17845bb0fa76334477d5de38654d27946d5b5d3695443987a094a71b440/multidict-6.4.4-py3-none-any.whl", hash = "sha256:bd4557071b561a8b3b6075c3ce93cf9bfb6182cb241805c3d66ced3b75eff4ac", size = 10481, upload-time = "2025-05-19T14:16:36.024Z" },
]
[[package]]
name = "protobuf"
version = "5.29.4"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/17/7d/b9dca7365f0e2c4fa7c193ff795427cfa6290147e5185ab11ece280a18e7/protobuf-5.29.4.tar.gz", hash = "sha256:4f1dfcd7997b31ef8f53ec82781ff434a28bf71d9102ddde14d076adcfc78c99", size = 424902, upload-time = "2025-03-19T21:23:24.25Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/9a/b2/043a1a1a20edd134563699b0e91862726a0dc9146c090743b6c44d798e75/protobuf-5.29.4-cp310-abi3-win32.whl", hash = "sha256:13eb236f8eb9ec34e63fc8b1d6efd2777d062fa6aaa68268fb67cf77f6839ad7", size = 422709, upload-time = "2025-03-19T21:23:08.293Z" },
{ url = "https://files.pythonhosted.org/packages/79/fc/2474b59570daa818de6124c0a15741ee3e5d6302e9d6ce0bdfd12e98119f/protobuf-5.29.4-cp310-abi3-win_amd64.whl", hash = "sha256:bcefcdf3976233f8a502d265eb65ea740c989bacc6c30a58290ed0e519eb4b8d", size = 434506, upload-time = "2025-03-19T21:23:11.253Z" },
{ url = "https://files.pythonhosted.org/packages/46/de/7c126bbb06aa0f8a7b38aaf8bd746c514d70e6a2a3f6dd460b3b7aad7aae/protobuf-5.29.4-cp38-abi3-macosx_10_9_universal2.whl", hash = "sha256:307ecba1d852ec237e9ba668e087326a67564ef83e45a0189a772ede9e854dd0", size = 417826, upload-time = "2025-03-19T21:23:13.132Z" },
{ url = "https://files.pythonhosted.org/packages/a2/b5/bade14ae31ba871a139aa45e7a8183d869efe87c34a4850c87b936963261/protobuf-5.29.4-cp38-abi3-manylinux2014_aarch64.whl", hash = "sha256:aec4962f9ea93c431d5714ed1be1c93f13e1a8618e70035ba2b0564d9e633f2e", size = 319574, upload-time = "2025-03-19T21:23:14.531Z" },
{ url = "https://files.pythonhosted.org/packages/46/88/b01ed2291aae68b708f7d334288ad5fb3e7aa769a9c309c91a0d55cb91b0/protobuf-5.29.4-cp38-abi3-manylinux2014_x86_64.whl", hash = "sha256:d7d3f7d1d5a66ed4942d4fefb12ac4b14a29028b209d4bfb25c68ae172059922", size = 319672, upload-time = "2025-03-19T21:23:15.839Z" },
{ url = "https://files.pythonhosted.org/packages/12/fb/a586e0c973c95502e054ac5f81f88394f24ccc7982dac19c515acd9e2c93/protobuf-5.29.4-py3-none-any.whl", hash = "sha256:3fde11b505e1597f71b875ef2fc52062b6a9740e5f7c8997ce878b6009145862", size = 172551, upload-time = "2025-03-19T21:23:22.682Z" },
]
[[package]]
name = "setuptools"
version = "80.8.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/8d/d2/ec1acaaff45caed5c2dedb33b67055ba9d4e96b091094df90762e60135fe/setuptools-80.8.0.tar.gz", hash = "sha256:49f7af965996f26d43c8ae34539c8d99c5042fbff34302ea151eaa9c207cd257", size = 1319720, upload-time = "2025-05-20T14:02:53.503Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/58/29/93c53c098d301132196c3238c312825324740851d77a8500a2462c0fd888/setuptools-80.8.0-py3-none-any.whl", hash = "sha256:95a60484590d24103af13b686121328cc2736bee85de8936383111e421b9edc0", size = 1201470, upload-time = "2025-05-20T14:02:51.348Z" },
]
[[package]]
name = "worker-py"
version = "0.1.0"
source = { virtual = "." }
[package.dev-dependencies]
dev = [
{ name = "grpcio" },
{ name = "grpcio-tools" },
{ name = "grpclib" },
{ name = "protobuf" },
]
[package.metadata]
[package.metadata.requires-dev]
dev = [
{ name = "grpcio", specifier = ">=1.71.0" },
{ name = "grpcio-tools", specifier = ">=1.71.0" },
{ name = "grpclib", specifier = ">=0.4.8" },
{ name = "protobuf", specifier = ">=5.29.4" },
]
+1 -1
View File
@@ -74,7 +74,7 @@ While LangGraph can be used standalone, it also integrates seamlessly with any L
- [Guides](https://langchain-ai.github.io/langgraph/how-tos/): Quick, actionable code snippets for topics such as streaming, adding memory & persistence, and design patterns (e.g. branching, subgraphs, etc.).
- [Reference](https://langchain-ai.github.io/langgraph/reference/graphs/): Detailed reference on core classes, methods, how to use the graph and checkpointing APIs, and higher-level prebuilt components.
- [Examples](https://langchain-ai.github.io/langgraph/tutorials/): Guided examples on getting started with LangGraph.
- [Examples](https://langchain-ai.github.io/langgraph/tutorials/overview/): Guided examples on getting started with LangGraph.
- [LangChain Academy](https://academy.langchain.com/courses/intro-to-langgraph): Learn the basics of LangGraph in our free, structured course.
- [Templates](https://langchain-ai.github.io/langgraph/concepts/template_applications/): Pre-built reference apps for common agentic workflows (e.g. ReAct agent, memory, retrieval etc.) that can be cloned and adapted.
- [Case studies](https://www.langchain.com/built-with-langgraph): Hear how industry leaders use LangGraph to ship AI applications at scale.
+50
View File
@@ -23,6 +23,7 @@ from langchain_core.messages import (
)
from typing_extensions import TypedDict
from langgraph.constants import CONF, CONFIG_KEY_SEND
from langgraph.graph.state import StateGraph
Messages = Union[list[MessageLikeRepresentation], MessageLikeRepresentation]
@@ -294,3 +295,52 @@ def _format_messages(messages: Sequence[BaseMessage]) -> list[BaseMessage]:
return list(messages)
else:
return convert_to_messages(convert_to_openai_messages(messages))
def push_message(
message: Union[MessageLikeRepresentation, BaseMessageChunk],
*,
state_key: Optional[str] = "messages",
) -> AnyMessage:
"""Write a message manually to the `messages` / `messages-tuple` stream mode.
Will automatically write to the channel specified in the `state_key` unless `state_key` is `None`.
"""
from langchain_core.callbacks.base import (
BaseCallbackHandler,
BaseCallbackManager,
)
from langgraph.config import get_config
from langgraph.constants import NS_SEP
from langgraph.pregel.messages import StreamMessagesHandler
config = get_config()
message = next(x for x in convert_to_messages([message]))
if message.id is None:
raise ValueError("Message ID is required")
if isinstance(config["callbacks"], BaseCallbackManager):
manager = config["callbacks"]
handlers = manager.handlers
elif isinstance(config["callbacks"], list) and all(
isinstance(x, BaseCallbackHandler) for x in config["callbacks"]
):
handlers = config["callbacks"]
if stream_handler := next(
(x for x in handlers if isinstance(x, StreamMessagesHandler)), None
):
metadata = config["metadata"]
message_meta = (
tuple(cast(str, metadata["langgraph_checkpoint_ns"]).split(NS_SEP)),
metadata,
)
stream_handler._emit(message_meta, message, dedupe=False)
if state_key:
config[CONF][CONFIG_KEY_SEND]([(state_key, message)])
return message
@@ -1,268 +0,0 @@
import functools
import logging
import weakref
from dataclasses import is_dataclass
from inspect import isclass
from typing import (
Annotated,
Any,
Callable,
Optional,
Union,
get_args,
get_origin,
get_type_hints,
)
from pydantic import BaseModel, ConfigDict, TypeAdapter
from typing_extensions import is_typeddict
__all__ = ["SchemaCoercionMapper"]
logger = logging.getLogger(__name__)
_cache: weakref.WeakKeyDictionary[type[Any], dict[int, "SchemaCoercionMapper"]] = (
weakref.WeakKeyDictionary()
)
class SchemaCoercionMapper:
"""Lightweight coercion of *dict* → *BaseModel* instances."""
def __new__(
cls,
schema: type[Any],
type_hints: Optional[dict[str, Any]] = None,
*,
max_depth: int = 12,
) -> "SchemaCoercionMapper":
by_depth = _cache.setdefault(schema, {})
if max_depth in by_depth:
return by_depth[max_depth]
inst = super().__new__(cls)
by_depth[max_depth] = inst
return inst
def __init__(
self,
schema: type[BaseModel],
type_hints: Optional[dict[str, Any]] = None,
*,
max_depth: int = 12,
) -> None:
if hasattr(self, "_initialised"):
return
self._initialised = True
self.schema = schema
self.max_depth = max_depth
self.type_hints = (
type_hints
if type_hints is not None
else get_type_hints(schema, localns={schema.__name__: schema})
)
if issubclass(schema, BaseModel):
self._fields = {
n: self.type_hints.get(n, f.annotation)
for n, f in schema.model_fields.items()
}
self._construct: Callable[..., Any] = schema.model_construct
unhandled_attrs = ("validators", "field_validators", "root_validators")
if (decorators := getattr(schema, "__pydantic_decorators__", None)) and any(
getattr(decorators, attr, None) for attr in unhandled_attrs
):
self.coerce = lambda v, _: schema.model_validate(v)
else:
self.coerce = self._coerce
else:
raise TypeError("Schema must be a Pydantic V2 model.")
self._field_coercers: Optional[dict[str, Callable[[Any, int], Any]]] = None
def __call__(self, input_data: Any, depth: Optional[int] = None) -> Any:
return self.coerce(input_data, depth)
def _coerce(self, input_data: Any, depth: Optional[int] = None) -> Any:
if depth is None:
depth = self.max_depth
if not isinstance(input_data, dict) or depth <= 0:
return input_data
if self._field_coercers is None:
self._field_coercers = {
n: self._build_coercer(t, depth - 1) for n, t in self._fields.items()
}
processed: dict[str, Any] = {}
for k, v in input_data.items():
fn = self._field_coercers.get(k)
processed[k] = fn(v, depth - 1) if fn else v
return self._construct(**processed)
def _build_coercer(
self, field_type: Any, depth: int, *, throw: bool = False
) -> Callable[[Any, Any], Any]:
if depth == 0:
return self._passthrough
origin = get_origin(field_type)
if (field_type in _IDENTITY_TYPES) or (origin in _IDENTITY_TYPES):
return self._passthrough
if origin is Annotated:
real_type, *_ = get_args(field_type)
sub = self._build_coercer(real_type, depth - 1)
return lambda v, d: sub(v, d)
if isclass(field_type):
# This is needed bcs. of issubclass issues on older versions of python
try:
is_bm_subclass = issubclass(field_type, BaseModel)
except TypeError:
# python < 3.11 issue.
is_bm_subclass = False
if is_bm_subclass:
mapper = SchemaCoercionMapper(field_type, max_depth=depth - 1)
return lambda v, d: mapper.coerce(v, d) if isinstance(v, dict) else v
if origin is list:
args = get_args(field_type)
if len(args) != 1:
return self._passthrough
sub = self._build_coercer(args[0], depth - 1)
def list_coercer(v: Any, d: Any) -> Any:
if not isinstance(v, (list, tuple)):
return v
return [sub(x, d - 1) for x in v]
return list_coercer
if origin is set or field_type is set:
args = get_args(field_type)
if len(args) > 1:
return self._passthrough
elif len(args) == 1:
sub = self._build_coercer(args[0], depth - 1)
else:
sub = None # type: ignore
def set_coercer(v: Any, d: Any) -> Any:
if not isinstance(v, (list, tuple, set)):
return v
if sub is None:
return set(v)
return {sub(x, d - 1) for x in v}
return set_coercer
if origin is dict or field_type is dict:
args = get_args(field_type)
if len(args) != 2:
def dict_coercer(v: Any, d: Any) -> Any:
if not isinstance(v, dict):
if throw:
raise TypeError(f"Expected dict, got {type(v)}")
return v
return dict_coercer
k_sub = self._build_coercer(args[0], depth - 1)
v_sub = self._build_coercer(args[1], depth - 1)
def dict_coercer(v: Any, d: Any) -> Any:
if not isinstance(v, dict):
if throw:
raise TypeError(f"Expected dict, got {type(v)}")
return v
return {k_sub(k, d - 1): v_sub(val, d - 1) for k, val in v.items()}
return dict_coercer
if origin is tuple:
elem_types = get_args(field_type)
if not elem_types:
return self._passthrough
subs = [self._build_coercer(t, depth - 1) for t in elem_types]
return lambda v, d: (
tuple(
subs[i](v[i] if i < len(v) else None, d - 1)
for i in range(len(subs))
)
if isinstance(v, (list, tuple))
else v
)
if origin is Union:
uargs = get_args(field_type)
subs, none_in_union = [], False
for ix, arg in enumerate(uargs):
if arg is type(None):
none_in_union = True
else:
subs.append(
self._build_coercer(arg, depth - 1, throw=ix < len(uargs) - 1)
)
def union_coercer(v: Any, d: Any) -> Any:
if v is None and none_in_union:
return None
err = None
for sp in subs:
try:
return sp(v, d - 1)
except TypeError as e:
err = e
if err:
raise err
return v
return union_coercer
adapter_fn = _get_adapter(field_type)
return lambda v, _d: adapter_fn(v)
@staticmethod
def _passthrough(v: Any, _d: Any) -> Any: # noqa: D401
return v
_adapter_cache: dict[Any, Callable[[Any], Any]] = {}
_IDENTITY_TYPES: tuple[type[Any], ...] = (
int,
float,
str,
bool,
bytes,
bytearray,
complex,
memoryview,
type(None),
)
@functools.lru_cache(maxsize=2048)
def _adapter_for(tp: Any) -> Callable[[Any], Any]: # noqa: D401
try:
config = (
None
if (issubclass(tp, BaseModel) or is_dataclass(tp) or is_typeddict(tp))
else ConfigDict(arbitrary_types_allowed=True)
)
except TypeError:
config = None
return TypeAdapter(tp, config=config).validate_python
def _get_adapter(tp: Any) -> Callable[[Any], Any]:
try:
return _adapter_cache[tp]
except KeyError:
fn = _adapter_for(tp)
_adapter_cache[tp] = fn
return fn
+11 -9
View File
@@ -64,7 +64,6 @@ from langgraph.graph.graph import (
Graph,
Send,
)
from langgraph.graph.schema_utils import SchemaCoercionMapper
from langgraph.managed.base import (
ChannelKeyPlaceholder,
ChannelTypePlaceholder,
@@ -320,12 +319,18 @@ class StateGraph(Graph):
Example:
```python
from typing_extensions import TypedDict
from langchain_core.runnables import RunnableConfig
from langgraph.graph import START, StateGraph
def my_node(state, config):
class State(TypedDict):
x: int
def my_node(state: State, config: RunnableConfig) -> State:
return {"x": state["x"] + 1}
builder = StateGraph(dict)
builder = StateGraph(State)
builder.add_node(my_node) # node name will be 'my_node'
builder.add_edge(START, "my_node")
graph = builder.compile()
@@ -335,7 +340,7 @@ class StateGraph(Graph):
Example: Customize the name:
```python
builder = StateGraph(dict)
builder = StateGraph(State)
builder.add_node("my_fair_node", my_node)
builder.add_edge(START, "my_fair_node")
graph = builder.compile()
@@ -1042,11 +1047,8 @@ def _pick_mapper(
) -> Optional[Callable[[Any], Any]]:
if state_keys == ["__root__"]:
return None
if isclass(schema):
if issubclass(schema, dict):
return None
if issubclass(schema, BaseModel):
return SchemaCoercionMapper(schema, type_hints=type_hints)
if isclass(schema) and issubclass(schema, dict):
return None
return partial(_coerce_state, schema)
+3 -2
View File
@@ -54,7 +54,7 @@ def push_ui_message(
id: Optional[str] = None,
metadata: Optional[dict[str, Any]] = None,
message: Optional[AnyMessage] = None,
state_key: str = "ui",
state_key: Optional[str] = "ui",
merge: bool = False,
) -> UIMessage:
"""Push a new UI message to update the UI state.
@@ -111,7 +111,8 @@ def push_ui_message(
}
writer(evt)
config[CONF][CONFIG_KEY_SEND]([(state_key, evt)])
if state_key:
config[CONF][CONFIG_KEY_SEND]([(state_key, evt)])
return evt
+7 -5
View File
@@ -411,7 +411,7 @@ class Pregel(PregelProtocol):
def reducer(current, update):
if current:
return current + " | " + "update"
return current + " | " + update
else:
return update
@@ -2214,12 +2214,14 @@ class Pregel(PregelProtocol):
validate_keys(output_keys, self.channels)
interrupt_before = interrupt_before or self.interrupt_before_nodes
interrupt_after = interrupt_after or self.interrupt_after_nodes
stream_mode = stream_mode if stream_mode is not None else self.stream_mode
if stream_mode is None and CONFIG_KEY_TASK_ID in config.get(CONF, {}):
# if being called as a node in another graph, default to values mode
# but don't overwrite stream_mode arg if provided
stream_mode = ["values"]
elif stream_mode is None:
stream_mode = self.stream_mode
if not isinstance(stream_mode, list):
stream_mode = [stream_mode]
if CONFIG_KEY_TASK_ID in config.get(CONF, {}):
# if being called as a node in another graph, always use values mode
stream_mode = ["values"]
if self.checkpointer is False:
checkpointer: BaseCheckpointSaver | None = None
elif CONFIG_KEY_CHECKPOINTER in config.get(CONF, {}):
+5 -16
View File
@@ -275,7 +275,7 @@ def apply_writes(
)
# clear pending sends
if checkpoint["pending_sends"] and bump_step:
if checkpoint.get("pending_sends") and bump_step:
checkpoint["pending_sends"].clear()
# Group writes by channel
@@ -286,7 +286,7 @@ def apply_writes(
if chan in (NO_WRITES, PUSH, RESUME, INTERRUPT, RETURN, ERROR):
pass
elif chan == TASKS:
checkpoint["pending_sends"].append(val)
checkpoint.setdefault("pending_sends", []).append(val)
elif chan in channels:
pending_writes_by_channel[chan].append(val)
else:
@@ -327,7 +327,7 @@ def apply_writes(
# If this is (tentatively) the last superstep, notify all channels of finish
if (
bump_step
and not checkpoint["pending_sends"]
and not checkpoint.get("pending_sends")
and updated_channels.isdisjoint(trigger_to_nodes)
):
for chan in channels:
@@ -344,17 +344,6 @@ def apply_writes(
return pending_writes_by_managed, updated_channels
def has_next_tasks(
trigger_to_nodes: Mapping[str, Sequence[str]],
updated_channels: set[str],
checkpoint: Checkpoint,
) -> bool:
"""Check if there are any tasks that should be run in the next step."""
return bool(checkpoint["pending_sends"]) or not updated_channels.isdisjoint(
trigger_to_nodes
)
@overload
def prepare_next_tasks(
checkpoint: Checkpoint,
@@ -446,7 +435,7 @@ def prepare_next_tasks(
null_version = checkpoint_null_version(checkpoint)
tasks: list[Union[PregelTask, PregelExecutableTask]] = []
# Consume pending_sends from previous step
for idx, _ in enumerate(checkpoint["pending_sends"]):
for idx, _ in enumerate(checkpoint.get("pending_sends", ())):
if task := prepare_single_task(
(PUSH, idx),
None,
@@ -648,7 +637,7 @@ def prepare_single_task(
# SEND tasks, executed in superstep n+1
# (PUSH, idx of pending send)
idx = cast(int, task_path[1])
if idx >= len(checkpoint["pending_sends"]):
if idx >= len(checkpoint.get("pending_sends", ())):
return
packet = checkpoint["pending_sends"][idx]
if not isinstance(packet, Send):
+21 -12
View File
@@ -135,7 +135,6 @@ P = ParamSpec("P")
INPUT_DONE = object()
INPUT_RESUMING = object()
INPUT_SHOULD_VALIDATE = object()
SPECIAL_CHANNELS = (ERROR, INTERRUPT, SCHEDULED)
WritesT = Sequence[tuple[str, Any]]
@@ -509,9 +508,14 @@ class PregelLoop(LoopProtocol):
**read_channels(self.channels, self.stream_keys)
)
# produce values output
self._emit(
"values", map_output_values, self.output_keys, writes, self.channels
)
if not updated_channels.isdisjoint(
(self.output_keys,)
if isinstance(self.output_keys, str)
else self.output_keys
):
self._emit(
"values", map_output_values, self.output_keys, writes, self.channels
)
# clear pending writes
self.checkpoint_pending_writes.clear()
# "not skip_done_tasks" only applies to first tick after resuming
@@ -887,7 +891,7 @@ class PregelLoop(LoopProtocol):
and self.checkpoint_pending_writes
and any(task.writes for task in self.tasks.values())
):
mv_writes, _ = apply_writes(
mv_writes, updated_channels = apply_writes(
self.checkpoint,
self.channels,
self.tasks.values(),
@@ -896,13 +900,18 @@ class PregelLoop(LoopProtocol):
)
for key, values in mv_writes.items():
self._update_mv(key, values)
self._emit(
"values",
map_output_values,
self.output_keys,
[w for t in self.tasks.values() for w in t.writes],
self.channels,
)
if not updated_channels.isdisjoint(
(self.output_keys,)
if isinstance(self.output_keys, str)
else self.output_keys
):
self._emit(
"values",
map_output_values,
self.output_keys,
[w for t in self.tasks.values() for w in t.writes],
self.channels,
)
# emit INTERRUPT if exception is empty (otherwise emitted by put_writes)
if exc_value is not None and (not exc_value.args or not exc_value.args[0]):
self._emit(
+2 -2
View File
@@ -41,7 +41,7 @@ def run_with_retry(
except ParentCommand as exc:
ns: str = config[CONF][CONFIG_KEY_CHECKPOINT_NS]
cmd = exc.args[0]
if cmd.graph == ns:
if cmd.graph in (ns, task.name):
# this command is for the current graph, handle it
for w in task.writers:
w.invoke(cmd, config)
@@ -137,7 +137,7 @@ async def arun_with_retry(
except ParentCommand as exc:
ns: str = config[CONF][CONFIG_KEY_CHECKPOINT_NS]
cmd = exc.args[0]
if cmd.graph == ns:
if cmd.graph in (ns, task.name):
# this command is for the current graph, handle it
for w in task.writers:
w.invoke(cmd, config)
+22 -19
View File
@@ -56,6 +56,10 @@ EXCLUDED_FRAME_FNAMES = (
"concurrent/futures/_base.py",
)
SKIP_RERAISE_SET: weakref.WeakSet[Union[concurrent.futures.Future, asyncio.Future]] = (
weakref.WeakSet()
)
class FuturesDict(Generic[F, E], dict[F, Optional[PregelExecutableTask]]):
event: E
@@ -100,7 +104,8 @@ class FuturesDict(Generic[F, E], dict[F, Optional[PregelExecutableTask]]):
fut: F,
) -> None:
try:
self.callback()(task, _exception(fut)) # type: ignore[misc]
if cb := self.callback():
cb(task, _exception(fut))
finally:
with self.lock:
self.done.add(fut)
@@ -165,7 +170,6 @@ class PregelRunner:
futures=weakref.ref(futures),
schedule_task=schedule_task,
submit=self.submit,
reraise=reraise,
),
},
)
@@ -207,7 +211,6 @@ class PregelRunner:
futures=weakref.ref(futures),
schedule_task=schedule_task,
submit=self.submit,
reraise=reraise,
),
},
__reraise_on_exit__=reraise,
@@ -302,7 +305,6 @@ class PregelRunner:
futures=weakref.ref(futures),
schedule_task=schedule_task,
submit=self.submit,
reraise=reraise,
loop=loop,
),
},
@@ -349,7 +351,6 @@ class PregelRunner:
futures=weakref.ref(futures),
schedule_task=schedule_task,
submit=self.submit,
reraise=reraise,
loop=loop,
),
},
@@ -431,10 +432,11 @@ class PregelRunner:
writes.extend(resumes)
self.put_writes()(task.id, writes) # type: ignore[misc]
elif isinstance(exception, GraphBubbleUp):
raise exception
pass
else:
# save error to checkpointer
self.put_writes()(task.id, [(ERROR, exception)]) # type: ignore[misc]
task.writes.append((ERROR, exception))
self.put_writes()(task.id, task.writes) # type: ignore[misc]
else:
if self.node_finished and (
task.config is None or TAG_HIDDEN not in task.config.get("tags", [])
@@ -456,7 +458,7 @@ def _should_stop_others(
if fut.cancelled():
continue
elif exc := fut.exception():
if not isinstance(exc, GraphBubbleUp):
if not isinstance(exc, GraphBubbleUp) and fut not in SKIP_RERAISE_SET:
return True
return False
@@ -494,7 +496,8 @@ def _panic_or_proceed(
interrupts: list[GraphInterrupt] = []
while done:
# if any task failed
if exc := _exception(done.pop()):
fut = done.pop()
if exc := _exception(fut):
# cancel all pending tasks
while inflight:
inflight.pop().cancel()
@@ -503,7 +506,7 @@ def _panic_or_proceed(
if isinstance(exc, GraphInterrupt):
# collect interrupts
interrupts.append(exc)
else:
elif fut not in SKIP_RERAISE_SET:
raise exc
# raise combined interrupts
if interrupts:
@@ -530,7 +533,6 @@ def _call(
[PregelExecutableTask, int, Optional[Call]], Optional[PregelExecutableTask]
],
submit: weakref.ref[Submit],
reraise: bool,
) -> concurrent.futures.Future[Any]:
if asyncio.iscoroutinefunction(func):
raise RuntimeError("In an sync context async tasks cannot be called")
@@ -582,14 +584,16 @@ def _call(
callbacks=callbacks,
schedule_task=schedule_task,
submit=submit,
reraise=reraise,
),
},
__reraise_on_exit__=reraise,
__reraise_on_exit__=False,
# starting a new task in the next tick ensures
# updates from this tick are committed/streamed first
__next_tick__=True,
)
# exceptions for call() tasks are raised into the parent task
# so we should not re-raise at the end of the tick
SKIP_RERAISE_SET.add(fut)
futures()[fut] = next_task # type: ignore[index]
fut = cast(Union[asyncio.Future, concurrent.futures.Future], fut)
# return a chained future to ensure commit() callback is called
@@ -613,7 +617,6 @@ def _acall(
],
submit: weakref.ref[Submit],
loop: asyncio.AbstractEventLoop,
reraise: bool = False,
stream: bool = False,
) -> Union[asyncio.Future[Any], concurrent.futures.Future[Any]]:
# return a chained future to ensure commit() callback is called
@@ -643,7 +646,6 @@ def _acall(
schedule_task=schedule_task,
submit=submit,
loop=loop,
reraise=reraise,
stream=stream,
),
loop,
@@ -669,7 +671,6 @@ async def _acall_impl(
],
submit: weakref.ref[Submit],
loop: asyncio.AbstractEventLoop,
reraise: bool = False,
stream: bool = False,
) -> None:
try:
@@ -726,17 +727,19 @@ async def _acall_impl(
schedule_task=schedule_task,
submit=submit,
loop=loop,
reraise=reraise,
),
},
__name__=task().name, # type: ignore[union-attr]
__name__=next_task.name,
__cancel_on_exit__=True,
__reraise_on_exit__=reraise,
__reraise_on_exit__=False,
# starting a new task in the next tick ensures
# updates from this tick are committed/streamed first
__next_tick__=True,
),
)
# exceptions for call() tasks are raised into the parent task
# so we should not re-raise at the end of the tick
SKIP_RERAISE_SET.add(fut)
futures()[fut] = next_task # type: ignore[index]
if fut is not None:
chain_future(fut, destination)
+2 -2
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "langgraph"
version = "0.4.5"
version = "0.4.10"
description = "Building stateful, multi-actor applications with LLMs"
authors = []
requires-python = ">=3.9"
@@ -15,7 +15,7 @@ dependencies = [
"langchain-core>=0.1",
"langgraph-checkpoint>=2.0.26",
"langgraph-sdk>=0.1.42",
"langgraph-prebuilt>=0.1.8",
"langgraph-prebuilt>=0.2.0",
"xxhash>=3.5.0",
"pydantic>=2.7.4",
]
+32 -1
View File
@@ -15,7 +15,7 @@ from pydantic import BaseModel
from typing_extensions import TypedDict
from langgraph.graph import add_messages
from langgraph.graph.message import REMOVE_ALL_MESSAGES, MessagesState
from langgraph.graph.message import REMOVE_ALL_MESSAGES, MessagesState, push_message
from langgraph.graph.state import END, START, StateGraph
from tests.messages import _AnyIdHumanMessage
@@ -332,3 +332,34 @@ def test_remove_all_messages():
assert result == [
_AnyIdHumanMessage(content="Updated hi there"),
]
def test_push_messages_in_graph():
class MessagesState(TypedDict):
messages: Annotated[list[AnyMessage], add_messages]
def chat(_: MessagesState) -> MessagesState:
with pytest.raises(ValueError, match="Message ID is required"):
push_message(AIMessage(content="No ID"))
push_message(AIMessage(content="First", id="1"))
push_message(HumanMessage(content="Second", id="2"))
push_message(AIMessage(content="Third", id="3"))
builder = StateGraph(MessagesState)
builder.add_node(chat)
builder.add_edge(START, "chat")
graph = builder.compile()
messages, values = [], None
for event, chunk in graph.stream(
{"messages": []}, stream_mode=["messages", "values"]
):
if event == "values":
values = chunk
elif event == "messages":
message, _ = chunk
messages.append(message)
assert values["messages"] == messages
+79 -3
View File
@@ -5514,8 +5514,11 @@ def test_runnable_passthrough_node_graph() -> None:
assert graph.get_graph(xray=True).to_json() == graph.get_graph(xray=False).to_json()
@pytest.mark.parametrize("subgraph_persist", [True, False])
@pytest.mark.parametrize("checkpointer_name", ALL_CHECKPOINTERS_SYNC)
def test_parent_command(request: pytest.FixtureRequest, checkpointer_name: str) -> None:
def test_parent_command(
request: pytest.FixtureRequest, checkpointer_name: str, subgraph_persist: bool
) -> None:
from langchain_core.messages import BaseMessage
from langchain_core.tools import tool
@@ -5527,7 +5530,7 @@ def test_parent_command(request: pytest.FixtureRequest, checkpointer_name: str)
subgraph_builder = StateGraph(MessagesState)
subgraph_builder.add_node("tool", get_user_name)
subgraph_builder.add_edge(START, "tool")
subgraph = subgraph_builder.compile()
subgraph = subgraph_builder.compile(checkpointer=subgraph_persist)
class CustomParentState(TypedDict):
messages: Annotated[list[BaseMessage], add_messages]
@@ -6873,7 +6876,7 @@ def test_sync_streaming_with_functional_api() -> None:
should be greater than the time delay between the two tasks.
"""
time_delay = 0.01
time_delay = 0.05
@task()
def slow() -> dict:
@@ -8769,3 +8772,76 @@ def test_get_graph_root_channel(snapshot: SnapshotAssertion) -> None:
assert json.dumps(graph.get_graph().to_json(), indent=2) == snapshot
assert graph.get_graph().draw_mermaid(with_styles=False) == snapshot
def test_imp_exception(
sync_checkpointer: BaseCheckpointSaver,
) -> None:
@task()
def my_task(number: int):
time.sleep(0.1)
return number * 2
@task()
def task_with_exception(number: int):
time.sleep(0.1)
raise Exception("This is a test exception")
@entrypoint(checkpointer=sync_checkpointer)
def my_workflow(number: int):
my_task(number).result()
try:
task_with_exception(number).result()
except Exception as e:
print(f"Exception caught: {e}")
my_task(number).result()
return "done"
thread1 = {"configurable": {"thread_id": "1"}}
assert my_workflow.invoke(1, thread1) == "done"
assert [c for c in my_workflow.stream(1, thread1)] == [
{"my_task": 2},
{"my_task": 2},
{"my_workflow": "done"},
]
@pytest.mark.parametrize("subgraph_persist", [True, False])
def test_parent_command_goto(
sync_checkpointer: BaseCheckpointSaver, subgraph_persist: bool
) -> None:
class State(TypedDict):
dialog_state: Annotated[list[str], operator.add]
def node_a_child(state):
return {"dialog_state": ["a_child_state"]}
def node_b_child(state):
return Command(
graph=Command.PARENT,
goto="node_b_parent",
update={"dialog_state": ["b_child_state"]},
)
sub_builder = StateGraph(State)
sub_builder.add_node(node_a_child)
sub_builder.add_node(node_b_child)
sub_builder.add_edge(START, "node_a_child")
sub_builder.add_edge("node_a_child", "node_b_child")
sub_graph = sub_builder.compile(checkpointer=subgraph_persist)
def node_b_parent(state):
return {"dialog_state": ["node_b_parent"]}
main_builder = StateGraph(State)
main_builder.add_node(node_b_parent)
main_builder.add_edge(START, "subgraph_node")
main_builder.add_node("subgraph_node", sub_graph, destinations=("node_b_parent",))
main_graph = main_builder.compile(sync_checkpointer, name="parent")
config = {"configurable": {"thread_id": 1}}
assert main_graph.invoke(input={"dialog_state": ["init_state"]}, config=config) == {
"dialog_state": ["init_state", "b_child_state", "node_b_parent"]
}
+341 -2
View File
@@ -6772,8 +6772,9 @@ async def test_debug_nested_subgraphs(async_checkpointer: BaseCheckpointSaver):
assert stream_task.get("state") == history_task.state
@pytest.mark.parametrize("subgraph_persist", [True, False])
@pytest.mark.parametrize("checkpointer_name", ALL_CHECKPOINTERS_ASYNC)
async def test_parent_command(checkpointer_name: str) -> None:
async def test_parent_command(checkpointer_name: str, subgraph_persist: bool) -> None:
from langchain_core.messages import BaseMessage
from langchain_core.tools import tool
@@ -6785,7 +6786,7 @@ async def test_parent_command(checkpointer_name: str) -> None:
subgraph_builder = StateGraph(MessagesState)
subgraph_builder.add_node("tool", get_user_name)
subgraph_builder.add_edge(START, "tool")
subgraph = subgraph_builder.compile()
subgraph = subgraph_builder.compile(checkpointer=subgraph_persist)
class CustomParentState(TypedDict):
messages: Annotated[list[BaseMessage], add_messages]
@@ -9148,3 +9149,341 @@ async def test_draw_invalid():
{"source": "nothing", "target": "__end__"},
],
}
@NEEDS_CONTEXTVARS
async def test_imp_exception(
async_checkpointer: BaseCheckpointSaver,
) -> None:
@task()
async def my_task(number: int):
await asyncio.sleep(0.1)
return number * 2
@task()
async def task_with_exception(number: int):
await asyncio.sleep(0.1)
raise Exception("This is a test exception")
@entrypoint(checkpointer=async_checkpointer)
async def my_workflow(number: int):
await my_task(number)
try:
await task_with_exception(number)
except Exception as e:
print(f"Exception caught: {e}")
await my_task(number)
return "done"
thread1 = {"configurable": {"thread_id": "1"}}
assert await my_workflow.ainvoke(1, thread1) == "done"
assert [c async for c in my_workflow.astream(1, thread1)] == [
{"my_task": 2},
{"my_task": 2},
{"my_workflow": "done"},
]
assert [c async for c in my_workflow.astream_events(1, thread1)] == [
{
"event": "on_chain_start",
"data": {"input": 1},
"name": "LangGraph",
"tags": [],
"run_id": AnyStr(),
"metadata": {"thread_id": "1"},
"parent_ids": [],
},
{
"event": "on_chain_start",
"data": {"input": 1},
"name": "my_workflow",
"tags": ["graph:step:4"],
"run_id": AnyStr(),
"metadata": {
"thread_id": "1",
"langgraph_step": 4,
"langgraph_node": "my_workflow",
"langgraph_triggers": ("__start__",),
"langgraph_path": ("__pregel_pull", "my_workflow"),
"langgraph_checkpoint_ns": AnyStr(),
},
"parent_ids": [AnyStr()],
},
{
"event": "on_chain_start",
"data": {"input": {"number": 1}},
"name": "my_task",
"tags": ["seq:step:1"],
"run_id": AnyStr(),
"metadata": {
"thread_id": "1",
"langgraph_step": 4,
"langgraph_node": "my_task",
"langgraph_triggers": ("__pregel_push",),
"langgraph_path": (
"__pregel_push",
("__pregel_pull", "my_workflow"),
2,
True,
),
"langgraph_checkpoint_ns": AnyStr(),
},
"parent_ids": [
AnyStr(),
AnyStr(),
],
},
{
"event": "on_chain_stream",
"run_id": AnyStr(),
"name": "my_task",
"tags": ["seq:step:1"],
"metadata": {
"thread_id": "1",
"langgraph_step": 4,
"langgraph_node": "my_task",
"langgraph_triggers": ("__pregel_push",),
"langgraph_path": (
"__pregel_push",
("__pregel_pull", "my_workflow"),
2,
True,
),
"langgraph_checkpoint_ns": AnyStr(),
},
"data": {"chunk": 2},
"parent_ids": [
AnyStr(),
AnyStr(),
],
},
{
"event": "on_chain_end",
"data": {"output": 2, "input": {"number": 1}},
"run_id": AnyStr(),
"name": "my_task",
"tags": ["seq:step:1"],
"metadata": {
"thread_id": "1",
"langgraph_step": 4,
"langgraph_node": "my_task",
"langgraph_triggers": ("__pregel_push",),
"langgraph_path": (
"__pregel_push",
("__pregel_pull", "my_workflow"),
2,
True,
),
"langgraph_checkpoint_ns": AnyStr(),
},
"parent_ids": [
AnyStr(),
AnyStr(),
],
},
{
"event": "on_chain_stream",
"run_id": AnyStr(),
"name": "LangGraph",
"tags": [],
"metadata": {"thread_id": "1"},
"data": {"chunk": {"my_task": 2}},
"parent_ids": [],
},
{
"event": "on_chain_start",
"data": {"input": {"number": 1}},
"name": "task_with_exception",
"tags": ["seq:step:1"],
"run_id": AnyStr(),
"metadata": {
"thread_id": "1",
"langgraph_step": 4,
"langgraph_node": "my_task",
"langgraph_triggers": ("__pregel_push",),
"langgraph_path": (
"__pregel_push",
("__pregel_pull", "my_workflow"),
2,
True,
),
"langgraph_checkpoint_ns": AnyStr(),
},
"parent_ids": [
AnyStr(),
AnyStr(),
],
},
{
"event": "on_chain_start",
"data": {"input": {"number": 1}},
"name": "my_task",
"tags": ["seq:step:1"],
"run_id": AnyStr(),
"metadata": {
"thread_id": "1",
"langgraph_step": 4,
"langgraph_node": "my_task",
"langgraph_triggers": ("__pregel_push",),
"langgraph_path": (
"__pregel_push",
("__pregel_pull", "my_workflow"),
2,
True,
),
"langgraph_checkpoint_ns": AnyStr(),
},
"parent_ids": [
AnyStr(),
AnyStr(),
],
},
{
"event": "on_chain_stream",
"run_id": AnyStr(),
"name": "my_task",
"tags": ["seq:step:1"],
"metadata": {
"thread_id": "1",
"langgraph_step": 4,
"langgraph_node": "my_task",
"langgraph_triggers": ("__pregel_push",),
"langgraph_path": (
"__pregel_push",
("__pregel_pull", "my_workflow"),
2,
True,
),
"langgraph_checkpoint_ns": AnyStr(),
},
"data": {"chunk": 2},
"parent_ids": [
AnyStr(),
AnyStr(),
],
},
{
"event": "on_chain_end",
"data": {"output": 2, "input": {"number": 1}},
"run_id": AnyStr(),
"name": "my_task",
"tags": ["seq:step:1"],
"metadata": {
"thread_id": "1",
"langgraph_step": 4,
"langgraph_node": "my_task",
"langgraph_triggers": ("__pregel_push",),
"langgraph_path": (
"__pregel_push",
("__pregel_pull", "my_workflow"),
2,
True,
),
"langgraph_checkpoint_ns": AnyStr(),
},
"parent_ids": [
AnyStr(),
AnyStr(),
],
},
{
"event": "on_chain_stream",
"run_id": AnyStr(),
"name": "my_workflow",
"tags": ["graph:step:4"],
"metadata": {
"thread_id": "1",
"langgraph_step": 4,
"langgraph_node": "my_workflow",
"langgraph_triggers": ("__start__",),
"langgraph_path": ("__pregel_pull", "my_workflow"),
"langgraph_checkpoint_ns": AnyStr(),
},
"data": {"chunk": "done"},
"parent_ids": [AnyStr()],
},
{
"event": "on_chain_stream",
"run_id": AnyStr(),
"name": "LangGraph",
"tags": [],
"metadata": {"thread_id": "1"},
"data": {"chunk": {"my_task": 2}},
"parent_ids": [],
},
{
"event": "on_chain_end",
"data": {"output": "done", "input": 1},
"run_id": AnyStr(),
"name": "my_workflow",
"tags": ["graph:step:4"],
"metadata": {
"thread_id": "1",
"langgraph_step": 4,
"langgraph_node": "my_workflow",
"langgraph_triggers": ("__start__",),
"langgraph_path": ("__pregel_pull", "my_workflow"),
"langgraph_checkpoint_ns": AnyStr(),
},
"parent_ids": [AnyStr()],
},
{
"event": "on_chain_stream",
"run_id": AnyStr(),
"name": "LangGraph",
"tags": [],
"metadata": {"thread_id": "1"},
"data": {"chunk": {"my_workflow": "done"}},
"parent_ids": [],
},
{
"event": "on_chain_end",
"data": {"output": "done"},
"run_id": AnyStr(),
"name": "LangGraph",
"tags": [],
"metadata": {"thread_id": "1"},
"parent_ids": [],
},
]
@pytest.mark.parametrize("subgraph_persist", [True, False])
async def test_parent_command_goto(
async_checkpointer: BaseCheckpointSaver, subgraph_persist: bool
) -> None:
class State(TypedDict):
dialog_state: Annotated[list[str], operator.add]
async def node_a_child(state):
return {"dialog_state": ["a_child_state"]}
async def node_b_child(state):
return Command(
graph=Command.PARENT,
goto="node_b_parent",
update={"dialog_state": ["b_child_state"]},
)
sub_builder = StateGraph(State)
sub_builder.add_node(node_a_child)
sub_builder.add_node(node_b_child)
sub_builder.add_edge(START, "node_a_child")
sub_builder.add_edge("node_a_child", "node_b_child")
sub_graph = sub_builder.compile(checkpointer=subgraph_persist)
async def node_b_parent(state):
return {"dialog_state": ["node_b_parent"]}
main_builder = StateGraph(State)
main_builder.add_node(node_b_parent)
main_builder.add_edge(START, "subgraph_node")
main_builder.add_node("subgraph_node", sub_graph, destinations=("node_b_parent",))
main_graph = main_builder.compile(async_checkpointer, name="parent")
config = {"configurable": {"thread_id": 1}}
assert await main_graph.ainvoke(
input={"dialog_state": ["init_state"]}, config=config
) == {"dialog_state": ["init_state", "b_child_state", "node_b_parent"]}
+1568 -1566
View File
File diff suppressed because it is too large Load Diff
@@ -140,7 +140,9 @@ def _get_prompt_runnable(prompt: Optional[Prompt]) -> Runnable:
return prompt_runnable
def _should_bind_tools(model: LanguageModelLike, tools: Sequence[BaseTool]) -> bool:
def _should_bind_tools(
model: LanguageModelLike, tools: Sequence[BaseTool], num_builtin: int = 0
) -> bool:
if isinstance(model, RunnableSequence):
model = next(
(
@@ -158,9 +160,10 @@ def _should_bind_tools(model: LanguageModelLike, tools: Sequence[BaseTool]) -> b
return True
bound_tools = model.kwargs["tools"]
if len(tools) != len(bound_tools):
if len(tools) != len(bound_tools) - num_builtin:
raise ValueError(
"Number of tools in the model.bind_tools() and tools passed to create_react_agent must match"
f" Got {len(tools)} tools, expected {len(bound_tools) - num_builtin}"
)
tool_names = set(tool.name for tool in tools)
@@ -240,7 +243,7 @@ def _validate_chat_history(
def create_react_agent(
model: Union[str, LanguageModelLike],
tools: Union[Sequence[Union[BaseTool, Callable]], ToolNode],
tools: Union[Sequence[Union[BaseTool, Callable, dict[str, Any]]], ToolNode],
*,
prompt: Optional[Prompt] = None,
response_format: Optional[
@@ -420,12 +423,13 @@ def create_react_agent(
else AgentState
)
llm_builtin_tools: list[dict] = []
if isinstance(tools, ToolNode):
tool_classes = list(tools.tools_by_name.values())
tool_node = tools
else:
tool_node = ToolNode(tools)
# get the tool functions wrapped in a tool class from the ToolNode
llm_builtin_tools = [t for t in tools if isinstance(t, dict)]
tool_node = ToolNode([t for t in tools if not isinstance(t, dict)])
tool_classes = list(tool_node.tools_by_name.values())
if isinstance(model, str):
@@ -442,8 +446,11 @@ def create_react_agent(
tool_calling_enabled = len(tool_classes) > 0
if _should_bind_tools(model, tool_classes) and tool_calling_enabled:
model = cast(BaseChatModel, model).bind_tools(tool_classes)
if (
_should_bind_tools(model, tool_classes, num_builtin=len(llm_builtin_tools))
and len(tool_classes) > 0
):
model = cast(BaseChatModel, model).bind_tools(tool_classes + llm_builtin_tools) # type: ignore[operator]
model_runnable = _get_prompt_runnable(prompt) | model
@@ -670,13 +677,16 @@ def create_react_agent(
# This means that this node is the first one called
workflow.set_entry_point(entrypoint)
agent_paths = ["tools", END]
post_model_hook_paths = [entrypoint, "tools", END]
agent_paths = []
post_model_hook_paths = [entrypoint, "tools"]
# Add a post model hook node if post_model_hook is provided
if post_model_hook is not None:
workflow.add_node("post_model_hook", post_model_hook)
agent_paths.append("post_model_hook")
workflow.add_edge("agent", "post_model_hook")
else:
agent_paths.append("tools")
# Add a structured output node if response_format is provided
if response_format is not None:
@@ -690,6 +700,11 @@ def create_react_agent(
post_model_hook_paths.append("generate_structured_response")
else:
agent_paths.append("generate_structured_response")
else:
if post_model_hook is not None:
post_model_hook_paths.append(END)
else:
agent_paths.append(END)
if post_model_hook is not None:
@@ -714,6 +729,10 @@ def create_react_agent(
]
if pending_tool_calls:
pending_tool_calls = [
tool_node.inject_tool_args(call, state, store) # type: ignore[arg-type]
for call in pending_tool_calls
]
return [Send("tools", [tool_call]) for tool_call in pending_tool_calls]
elif isinstance(messages[-1], ToolMessage):
return entrypoint
+1 -162
View File
@@ -1,12 +1,7 @@
from copy import deepcopy
from typing import Any, Literal, Optional, Union, cast
from typing import Literal, Optional, Union
from langchain_core.messages import ToolCall, ToolMessage
from typing_extensions import TypedDict
from langgraph.types import Command, interrupt
from langgraph.utils.runnable import RunnableCallable
class HumanInterruptConfig(TypedDict):
"""Configuration that defines what actions are allowed for a human interrupt.
@@ -93,159 +88,3 @@ class HumanResponse(TypedDict):
type: Literal["accept", "ignore", "response", "edit"]
args: Union[None, str, ActionRequest]
class InterruptToolNode(RunnableCallable):
"""Prebuilt post model hook node used to enable common patterns for tool interrupts.
For any tools with specified policies, an interrupt will be raised when the LLM returns
a tool call for said tool. The interrupt policy will be used to determine what sort of resume logic is allowed.
Any of the following resume patterns are supported:
* accept: the tool call is executed as planned
* edit: the args for the tool call are edited and then the tool call is executed
* response: text response/feedback is fed back into the LLM
* ignore: the current tool call is ignored / skipped
Args:
**interrupt_policy: a mapping of tool names to [`HumanInterruptConfig`][prebuilt.interrupt.HumanInterruptConfig] dictionaries
specifying which interrupt patterns to enable for said tool.
Example:
```python
from langgraph.prebuilt import create_react_agent
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.prebuilt.interrupt import HumanInterruptConfig, InterruptToolNode
from langgraph.types import Command
def book_hotel(hotel_name: str) -> str:
'''Book a room at the provided hotel.'''
# Some hotel API calls, a sensitive / expensive operation
return f"Booked a hotel at {hotel_name}."
agent = create_react_agent(
"openai:gpt-4.1",
tools=[book_hotel],
prompt="You are a hotel booking assistant.",
post_model_hook=InterruptToolNode(
book_hotel=HumanInterruptConfig(
allow_accept=True,
allow_edit=True,
allow_ignore=True,
allow_respond=True,
)
),
checkpointer=InMemorySaver(),
)
config = {"configurable": {"thread_id": 1}}
response = agent.invoke(
{"messages": [{"role": "user", "content": "please book a hotel at the hilton inn in boston."}]},
config=config,
)
response = agent.invoke(Command(resume={"type": "accept"}), config=config)
```
"""
def __init__(self, **interrupt_policy: HumanInterruptConfig):
super().__init__(self._func, self._afunc)
self.interrupt_policy = interrupt_policy
def _interrupt(
self,
tool_call: ToolCall,
interrupt_config: HumanInterruptConfig,
) -> Union[ToolCall, ToolMessage]:
"""Interrupt before a tool call and ask for human input."""
call_id = tool_call["id"]
tool_name = tool_call["name"]
request = HumanInterrupt(
action_request=ActionRequest(
action=tool_name,
args=tool_call["args"],
),
config=interrupt_config,
description=f"Please review tool call for `{tool_name}` before execution.",
)
response = interrupt([request])
# resume provided by agent inbox as a list
response = response[0] if isinstance(response, list) else response
try:
response_type = response.get("type")
except AttributeError:
raise TypeError(
f"Unexpected resume value: {response}."
f"Expected a dict with `'type'` key."
)
if response_type == "accept" and interrupt_config["allow_accept"]:
return tool_call
elif response_type == "edit" and interrupt_config["allow_edit"]:
return ToolCall(
args=cast(ActionRequest, response)["args"]["args"],
name=tool_name,
id=call_id,
type="tool_call",
)
elif response_type == "response" and interrupt_config["allow_respond"]:
return ToolMessage(
content=cast(str, response["args"]),
name=tool_name,
tool_call_id=call_id,
status="error",
)
elif response_type == "ignore" and interrupt_config["allow_ignore"]:
return ToolMessage(
content=f"User ignored the tool call for `{tool_name}` with id {call_id}",
name=tool_name,
tool_call_id=call_id,
status="success",
)
allowed_types = [
type_name
for type_name, is_allowed in {
"accept": interrupt_config["allow_accept"],
"edit": interrupt_config["allow_edit"],
"response": interrupt_config["allow_respond"],
"ignore": interrupt_config["allow_ignore"],
}.items()
if is_allowed
]
raise ValueError(
f"Unexpected human response: {response}. "
f"Expected one with `'type'` in {allowed_types} based on {tool_name}'s interrupt configuration."
)
def _func(self, input: dict[str, Any]) -> Command:
ai_msg = input["messages"][-1]
tool_calls: list[ToolCall] = deepcopy(ai_msg.tool_calls) or []
tool_messages: list[ToolMessage] = []
for idx, tool_call in enumerate(tool_calls):
if interrupt_config := self.interrupt_policy.get(tool_call["name"]):
interrupt_result = self._interrupt(
tool_call=tool_call, interrupt_config=interrupt_config
)
if isinstance(interrupt_result, ToolMessage):
tool_messages.append(interrupt_result)
else:
tool_calls[idx] = interrupt_result
updated_ai_msg = ai_msg.copy(update={"tool_calls": tool_calls})
# conditional routing logic for post_model_hook will direct to the tools node
# or agent node depending on if there are pending tool calls
return {"messages": [updated_ai_msg, *tool_messages]}
async def _afunc(self, input: dict[str, Any]) -> Command:
return self._func(input)
+2 -1
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "langgraph-prebuilt"
version = "0.1.8"
version = "0.2.3"
description = "Library with high-level APIs for creating and executing LangGraph agents and tools."
authors = []
requires-python = ">=3.9"
@@ -32,6 +32,7 @@ dev = [
"langgraph-checkpoint",
"langgraph-checkpoint-sqlite",
"langgraph-checkpoint-postgres",
"syrupy",
]
[tool.uv]
@@ -0,0 +1,173 @@
# serializer version: 1
# name: test_react_agent_graph_structure[None-None-None-tools0]
'''
graph TD;
__start__ --> agent;
agent --> __end__;
'''
# ---
# name: test_react_agent_graph_structure[None-None-None-tools1]
'''
graph TD;
__start__ --> agent;
agent -.-> __end__;
agent -.-> tools;
tools --> agent;
'''
# ---
# name: test_react_agent_graph_structure[None-None-pre_model_hook-tools0]
'''
graph TD;
__start__ --> pre_model_hook;
pre_model_hook --> agent;
agent --> __end__;
'''
# ---
# name: test_react_agent_graph_structure[None-None-pre_model_hook-tools1]
'''
graph TD;
__start__ --> pre_model_hook;
agent -.-> __end__;
agent -.-> tools;
pre_model_hook --> agent;
tools --> pre_model_hook;
'''
# ---
# name: test_react_agent_graph_structure[None-post_model_hook-None-tools0]
'''
graph TD;
__start__ --> agent;
agent --> post_model_hook;
post_model_hook --> __end__;
'''
# ---
# name: test_react_agent_graph_structure[None-post_model_hook-None-tools1]
'''
graph TD;
__start__ --> agent;
agent --> post_model_hook;
post_model_hook -.-> __end__;
post_model_hook -.-> agent;
post_model_hook -.-> tools;
tools --> agent;
'''
# ---
# name: test_react_agent_graph_structure[None-post_model_hook-pre_model_hook-tools0]
'''
graph TD;
__start__ --> pre_model_hook;
agent --> post_model_hook;
pre_model_hook --> agent;
post_model_hook --> __end__;
'''
# ---
# name: test_react_agent_graph_structure[None-post_model_hook-pre_model_hook-tools1]
'''
graph TD;
__start__ --> pre_model_hook;
agent --> post_model_hook;
post_model_hook -.-> __end__;
post_model_hook -.-> pre_model_hook;
post_model_hook -.-> tools;
pre_model_hook --> agent;
tools --> pre_model_hook;
'''
# ---
# name: test_react_agent_graph_structure[ResponseFormat-None-None-tools0]
'''
graph TD;
__start__ --> agent;
agent --> generate_structured_response;
generate_structured_response --> __end__;
'''
# ---
# name: test_react_agent_graph_structure[ResponseFormat-None-None-tools1]
'''
graph TD;
__start__ --> agent;
agent -.-> generate_structured_response;
agent -.-> tools;
tools --> agent;
generate_structured_response --> __end__;
'''
# ---
# name: test_react_agent_graph_structure[ResponseFormat-None-pre_model_hook-tools0]
'''
graph TD;
__start__ --> pre_model_hook;
agent --> generate_structured_response;
pre_model_hook --> agent;
generate_structured_response --> __end__;
'''
# ---
# name: test_react_agent_graph_structure[ResponseFormat-None-pre_model_hook-tools1]
'''
graph TD;
__start__ --> pre_model_hook;
agent -.-> generate_structured_response;
agent -.-> tools;
pre_model_hook --> agent;
tools --> pre_model_hook;
generate_structured_response --> __end__;
'''
# ---
# name: test_react_agent_graph_structure[ResponseFormat-post_model_hook-None-tools0]
'''
graph TD;
__start__ --> agent;
agent --> post_model_hook;
post_model_hook --> generate_structured_response;
generate_structured_response --> __end__;
'''
# ---
# name: test_react_agent_graph_structure[ResponseFormat-post_model_hook-None-tools1]
'''
graph TD;
__start__ --> agent;
agent --> post_model_hook;
post_model_hook -.-> agent;
post_model_hook -.-> generate_structured_response;
post_model_hook -.-> tools;
tools --> agent;
generate_structured_response --> __end__;
'''
# ---
# name: test_react_agent_graph_structure[ResponseFormat-post_model_hook-pre_model_hook-tools0]
'''
graph TD;
__start__ --> pre_model_hook;
agent --> post_model_hook;
post_model_hook --> generate_structured_response;
pre_model_hook --> agent;
generate_structured_response --> __end__;
'''
# ---
# name: test_react_agent_graph_structure[ResponseFormat-post_model_hook-pre_model_hook-tools1]
'''
graph TD;
__start__ --> pre_model_hook;
agent --> post_model_hook;
post_model_hook -.-> generate_structured_response;
post_model_hook -.-> pre_model_hook;
post_model_hook -.-> tools;
pre_model_hook --> agent;
tools --> pre_model_hook;
generate_structured_response --> __end__;
'''
# ---
+4 -1
View File
@@ -73,9 +73,12 @@ class FakeToolCallingModel(BaseChatModel):
tool_dicts = []
for tool in tools:
if isinstance(tool, dict):
tool_dicts.append(tool)
continue
if not isinstance(tool, BaseTool):
raise TypeError(
"Only BaseTool is supported by FakeToolCallingModel.bind_tools"
"Only BaseTool and dict is supported by FakeToolCallingModel.bind_tools"
)
# NOTE: this is a simplified tool spec for testing purposes only
@@ -1,191 +0,0 @@
import pytest
from langchain_core.messages import ToolMessage
from langchain_core.runnables import RunnableConfig
from langgraph.checkpoint.base import BaseCheckpointSaver
from langgraph.prebuilt import create_react_agent
from langgraph.prebuilt.interrupt import HumanInterruptConfig, InterruptToolNode
from langgraph.types import Command
from tests.model import FakeToolCallingModel
def hello_tool(name: str) -> str:
"""Return a greeting for the provided person."""
return f"Hello, {name}!"
post_model_hook = InterruptToolNode(
hello_tool=HumanInterruptConfig(
allow_accept=True,
allow_edit=True,
allow_ignore=True,
allow_respond=True,
)
)
default_model = FakeToolCallingModel(
tool_calls=[
[
{
"name": "hello_tool",
"args": {"name": "lady gaga"},
"id": "some-random-id",
}
]
]
)
def test_interrupt_surfaced(
request: pytest.FixtureRequest,
sync_checkpointer: BaseCheckpointSaver,
) -> None:
agent = create_react_agent(
default_model,
[hello_tool],
checkpointer=sync_checkpointer,
post_model_hook=post_model_hook,
)
config: RunnableConfig = {"configurable": {"thread_id": "1"}}
result = agent.invoke({"messages": [("user", "Say hi to lady gaga!")]}, config)
interrupt_data = result["__interrupt__"]
assert interrupt_data[0].value == [
{
"action_request": {"action": "hello_tool", "args": {"name": "lady gaga"}},
"config": {
"allow_accept": True,
"allow_edit": True,
"allow_ignore": True,
"allow_respond": True,
},
"description": "Please review tool call for `hello_tool` before execution.",
}
]
response = agent.invoke(Command(resume={"type": "accept"}), config=config)
tool_message: ToolMessage = response["messages"][-2]
assert tool_message.content == "Hello, lady gaga!"
assert tool_message.name == "hello_tool"
@pytest.mark.parametrize(
"resume, expected_content",
[
({"type": "accept"}, "Hello, lady gaga!"),
(
{"type": "ignore"},
"User ignored the tool call for `hello_tool` with id some-random-id",
),
(
{
"type": "edit",
"args": {"action": "hello_tool", "args": {"name": "bruno mars"}},
},
"Hello, bruno mars!",
),
],
)
def test_interrupt_resume_variants(
request: pytest.FixtureRequest,
sync_checkpointer: BaseCheckpointSaver,
resume: dict,
expected_content: str,
) -> None:
agent = create_react_agent(
default_model,
[hello_tool],
checkpointer=sync_checkpointer,
post_model_hook=post_model_hook,
)
config: RunnableConfig = {"configurable": {"thread_id": "1"}}
agent.invoke({"messages": [("user", "Say hi to lady gaga!")]}, config)
response = agent.invoke(Command(resume=resume), config=config)
tool_message: ToolMessage = response["messages"][-2]
assert tool_message.name == "hello_tool"
assert tool_message.content == expected_content
if resume["type"] == "edit":
ai_msg = response["messages"][-1]
assert ai_msg.tool_calls == [
{
"name": "hello_tool",
"args": {"name": "lady gaga"},
"id": "some-random-id",
"type": "tool_call",
}
]
def test_resume_with_response(
request: pytest.FixtureRequest,
sync_checkpointer: BaseCheckpointSaver,
) -> None:
model = FakeToolCallingModel(
tool_calls=[
[
{
"name": "hello_tool",
"args": {"name": "lady gaga"},
"id": "some-random-id",
}
],
[
{
"name": "hello_tool",
"args": {"name": "bruno mars"},
"id": "some-random-id-2",
}
],
]
)
agent = create_react_agent(
model,
[hello_tool],
checkpointer=sync_checkpointer,
post_model_hook=post_model_hook,
)
config: RunnableConfig = {"configurable": {"thread_id": "1"}}
agent.invoke({"messages": [("user", "Say hi to lady gaga!")]}, config)
# Provide user response
agent.invoke(
Command(
resume={
"type": "response",
"args": "actually, please say hello to bruno mars",
}
),
config=config,
)
# Accept the updated call
response = agent.invoke(Command(resume={"type": "accept"}), config=config)
assert len(response["messages"]) == 6
tool_message: ToolMessage = response["messages"][-2]
assert tool_message.name == "hello_tool"
assert tool_message.content == "Hello, bruno mars!"
def test_resume_with_type_not_allowed(sync_checkpointer: BaseCheckpointSaver) -> None:
agent = create_react_agent(
default_model,
[hello_tool],
checkpointer=sync_checkpointer,
post_model_hook=post_model_hook,
)
config: RunnableConfig = {"configurable": {"thread_id": "1"}}
agent.invoke({"messages": [("user", "Say hi to lady gaga!")]}, config)
with pytest.raises(ValueError) as exc_info:
agent.invoke(Command(resume={"type": "not-allowed"}), config=config)
assert (
str(exc_info.value)
== "Unexpected human response: {'type': 'not-allowed'}. Expected one with `'type'` in ['accept', 'edit', 'response', 'ignore'] based on hello_tool's interrupt configuration."
)
+81 -3
View File
@@ -275,7 +275,8 @@ async def test_prompt_with_store_async():
@pytest.mark.parametrize("tool_style", ["openai", "anthropic"])
@pytest.mark.parametrize("version", REACT_TOOL_CALL_VERSIONS)
def test_model_with_tools(tool_style: str, version: str):
@pytest.mark.parametrize("include_builtin", [True, False])
def test_model_with_tools(tool_style: str, version: str, include_builtin: bool):
model = FakeToolCallingModel(tool_style=tool_style)
@dec_tool
@@ -288,10 +289,27 @@ def test_model_with_tools(tool_style: str, version: str):
"""Tool 2 docstring."""
return f"Tool 2: {some_val}"
tools = [tool1, tool2]
if include_builtin:
tools.append(
{
"type": "mcp",
"server_label": "atest_sever",
"server_url": "https://some.mcp.somewhere.com/sse",
"headers": {"foo": "bar"},
"allowed_tools": [
"mcp_tool_1",
"set_active_account",
"get_url_markdown",
"get_url_screenshot",
],
"require_approval": "never",
}
)
# check valid agent constructor
agent = create_react_agent(
model.bind_tools([tool1, tool2]),
[tool1, tool2],
model.bind_tools(tools),
tools,
version=version,
)
result = agent.nodes["tools"].invoke(
@@ -1540,3 +1558,63 @@ def test_post_model_hook_with_structured_output() -> None:
}
},
]
@pytest.mark.parametrize(
"state_schema", [AgentStateExtraKey, AgentStateExtraKeyPydantic]
)
def test_create_react_agent_inject_vars_with_post_model_hook(
state_schema: StateSchemaType,
) -> None:
store = InMemoryStore()
namespace = ("test",)
store.put(namespace, "test_key", {"bar": 3})
if issubclass(state_schema, AgentStatePydantic):
def tool1(
some_val: int,
state: Annotated[AgentStateExtraKeyPydantic, InjectedState],
store: Annotated[BaseStore, InjectedStore()],
) -> str:
"""Tool 1 docstring."""
store_val = store.get(namespace, "test_key").value["bar"]
return some_val + state.foo + store_val
else:
def tool1(
some_val: int,
state: Annotated[dict, InjectedState],
store: Annotated[BaseStore, InjectedStore()],
) -> str:
"""Tool 1 docstring."""
store_val = store.get(namespace, "test_key").value["bar"]
return some_val + state["foo"] + store_val
tool_call = {
"name": "tool1",
"args": {"some_val": 1},
"id": "some 0",
"type": "tool_call",
}
def post_model_hook(state: dict) -> None:
return
model = FakeToolCallingModel(tool_calls=[[tool_call], []])
agent = create_react_agent(
model,
[tool1],
state_schema=state_schema,
store=store,
post_model_hook=post_model_hook,
)
input_message = HumanMessage("hi")
result = agent.invoke({"messages": [input_message], "foo": 2})
assert result["messages"] == [
input_message,
AIMessage(content="hi", tool_calls=[tool_call], id="0"),
_AnyIdToolMessage(content="6", name="tool1", tool_call_id="some 0"),
AIMessage("hi-hi-6", id="1"),
]
assert result["foo"] == 2
@@ -0,0 +1,52 @@
from typing import Callable, Union
import pytest
from pydantic import BaseModel
from syrupy import SnapshotAssertion
from langgraph.prebuilt import create_react_agent
from tests.model import FakeToolCallingModel
model = FakeToolCallingModel()
def tool() -> None:
"""Testing tool."""
...
def pre_model_hook() -> None:
"""Pre-model hook."""
...
def post_model_hook() -> None:
"""Post-model hook."""
...
class ResponseFormat(BaseModel):
"""Response format for the agent."""
result: str
@pytest.mark.parametrize("tools", [[], [tool]])
@pytest.mark.parametrize("pre_model_hook", [None, pre_model_hook])
@pytest.mark.parametrize("post_model_hook", [None, post_model_hook])
@pytest.mark.parametrize("response_format", [None, ResponseFormat])
def test_react_agent_graph_structure(
snapshot: SnapshotAssertion,
tools: list[Callable],
pre_model_hook: Union[Callable, None],
post_model_hook: Union[Callable, None],
response_format: Union[type[BaseModel], None],
) -> None:
agent = create_react_agent(
model,
tools=tools,
pre_model_hook=pre_model_hook,
post_model_hook=post_model_hook,
response_format=response_format,
)
assert agent.get_graph().draw_mermaid(with_styles=False) == snapshot

Some files were not shown because too many files have changed in this diff Show More