langgraph Documentation

Python agents & ai repository by @langchain-ai. AI agent rules & system prompts with 40k stars.

39,559 stars Python Python 1 file Β· ~11,971 tokens #agents#ai#ai-agents#chatgpt#deepagents#enterprise#framework#gemini
RAW Doc

Docker & Self-Hosted Deployment Verified OCI

Deploy langgraph on any server, homelab, or cloud container platform.

1-Click Terminal Command
bash (docker run)
docker run -d --name langgraph -p 5443:5443 --restart always langgraph-v3-integration-api:local
Configured Services & Ports
βš™οΈ postgres
image: pgvector/pgvector:pg16
πŸ”Œ Ports: 5443:5432
βš™οΈ redis
image: redis:7-alpine
πŸ”Œ Ports: 6380:6379
βš™οΈ api
image: langgraph-v3-integration-api:local
πŸ”Œ Ports: 2024:8000
docker-compose.yml
yaml (docker-compose.yml)
name: langgraph-v3-integration

services:
  postgres:
    image: pgvector/pgvector:pg16
    environment:
      POSTGRES_DB: postgres
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
    command: ["postgres", "-c", "shared_preload_libraries=vector", "-c", "max_connections=150"]
    ports:
      - "5443:5432"
    healthcheck:
      test: pg_isready -U postgres
      interval: 5s
      timeout: 1s
      retries: 5
      start_period: 10s
    tmpfs:
      - /var/lib/postgresql/data

  redis:
    image: redis:7-alpine
    command: redis-server --maxmemory 256mb --maxmemory-policy allkeys-lru
    ports:
      - "6380:6379"
    healthcheck:
      test: redis-cli ping
      interval: 5s
      timeout: 1s
      retries: 5
      start_period: 2s
    tmpfs:
      - /data

  api:
    # Thin layer on top of langchain/langgraph-api:latest-py3.12 β€”
    # see ./Dockerfile. The base image bundles langgraph-api +
    # langgraph_runtime_postgres + langgraph_license + the Go core-server;
    # on top we add graph deps (deepagents), the graph files, and this
    # monorepo's local langgraph *core* and *checkpoint* (so the server runs
    # the code under test, not the released langgraph).
    build:
      context: .
      dockerfile: Dockerfile
      additional_contexts:
        # The monorepo's local langgraph core (libs/langgraph) and checkpoint
        # (libs/checkpoint), installed over the base image so the server runs
        # the langgraph under test. See the Dockerfile for why.
        langgraph_src: ../../langgraph
        checkpoint_src: ../../checkpoint
    image: langgraph-v3-integration-api:local
    depends_on:
      postgres:
        condition: service_healthy
      redis:
        condition: service_healthy
    environment:
      # Database + cache (the production-shape postgres+redis runtime).
      # Recent langgraph-api reads DATABASE_URI first and falls back to
      # POSTGRES_URI; set both so older code paths also work.
      DATABASE_URI: postgres://postgres:postgres@postgres:5432/postgres?sslmode=disable
      POSTGRES_URI: postgres://postgres:postgres@postgres:5432/postgres?sslmode=disable
      REDIS_URI: redis://redis:6379
      LANGGRAPH_RUNTIME_EDITION: postgres

      LANGGRAPH_AUTH_TYPE: noop
      LANGSMITH_TRACING: "false"

      PORT: "8000"

      # Required for the v3 thread-centric streaming protocol. Without this
      # flag the API falls back to the legacy v2 streaming surface and the
      # client's v3 endpoints (POST /threads/{id}/stream/events, /commands,
      # etc.) won't be exposed.
      FF_OPTIMIZED_STREAMING: "true"

      # Tell langgraph-api which graphs to register. The langgraph CLI sets
      # this from langgraph.json; we're bypassing the CLI (running uvicorn
      # directly) so we set it manually.
      LANGSERVE_GRAPHS: '{"agent":"/app/graph/streaming_graph.py:graph","tools_agent":"/app/graph/tools_agent.py:graph","deep_agent":"/app/graph/deep_agent.py:graph","factory_agent":"/app/graph/factory_graph.py:make_graph"}'

      # The published langgraph-api image is the `licensed` variant and
      # requires a real LANGSMITH_API_KEY (or LANGGRAPH_CLOUD_LICENSE_KEY)
      # at runtime. Passed through from the host shell / CI secrets.
      LANGSMITH_API_KEY: ${LANGSMITH_API_KEY:-}
      LANGGRAPH_CLOUD_LICENSE_KEY: ${LANGGRAPH_CLOUD_LICENSE_KEY:-}
    # Mount the graph + config so edits don't require a rebuild.
    volumes:
      - ./graph:/app/graph:ro
      - ./langgraph.json:/app/langgraph.json:ro
    ports:
      - "2024:8000"
    healthcheck:
      test: ["CMD-SHELL", "wget -q -O- http://localhost:8000/ok || exit 1"]
      interval: 5s
      timeout: 3s
      retries: 30
      start_period: 30s

1. Project Overview & Quickstart (langchain-ai/langgraph)

File: README.md

Trusted by companies shaping the future of agents – including Klarna, Replit, Elastic, and more – LangGraph is a low-level orchestration framework for building, managing, and deploying long-running, stateful agents.

bash
pip install -U langgraph

[!TIP]
If you're looking to quickly build agents, check out Deep Agents β€” a higher-level package built on LangGraph for agents that can plan, use subagents, and leverage file systems for complex tasks.

For an equivalent JS/TS library, check out LangGraph.js and the JS docs.

Why use LangGraph?

LangGraph provides low-level supporting infrastructure for any long-running, stateful workflow or agent:

  • Durable execution β€” Build agents that persist through failures and can run for extended periods, automatically resuming from exactly where they left off.
  • Human-in-the-loop β€” Seamlessly incorporate human oversight by inspecting and modifying agent state at any point during execution.
  • Comprehensive memory β€” Create truly stateful agents with both short-term working memory for ongoing reasoning and long-term persistent memory across sessions.
  • Debugging with LangSmith β€” Gain deep visibility into complex agent behavior with visualization tools that trace execution paths, capture state transitions, and provide detailed runtime metrics.
  • Production-ready deployment β€” Deploy sophisticated agent systems confidently with scalable infrastructure designed to handle the unique challenges of stateful, long-running workflows.

[!TIP]
For developing, debugging, and deploying AI agents and LLM applications, see LangSmith.

LangGraph ecosystem

While LangGraph can be used standalone, it also integrates seamlessly with any LangChain product, giving developers a full suite of tools for building agents.

To improve your LLM application development, pair LangGraph with:

  • Deep Agents – Build agents that can plan, use subagents, and leverage file systems for complex tasks.
  • LangChain – Provides integrations and composable components to streamline LLM application development.
  • LangSmith – Helpful for agent evals and observability. Debug poor-performing LLM app runs, evaluate agent trajectories, gain visibility in production, and improve performance over time.
  • LangSmith Deployment – Deploy and scale agents effortlessly with a purpose-built deployment platform for long-running, stateful workflows. Discover, reuse, configure, and share agents across teams – and iterate quickly with visual prototyping in LangSmith Studio.

Documentation

Discussions: Visit the LangChain Forum to connect with the community and share all of your technical questions, ideas, and feedback.

Additional resources

  • Guides – Quick, actionable code snippets for topics such as streaming, adding memory & persistence, and design patterns (e.g. branching, subgraphs, etc.).
  • LangChain Academy – Learn the basics of LangGraph in our free, structured course.
  • Case studies – Hear how industry leaders use LangGraph to ship AI applications at scale.
  • Contributing Guide – Learn how to contribute to LangChain projects and find good first issues.
  • Code of Conduct – Our community guidelines and standards for participation.

Acknowledgements

LangGraph is inspired by Pregel and Apache Beam. The public interface draws inspiration from NetworkX. LangGraph is built by LangChain Inc, the creators of LangChain, but can be used without LangChain.


File: examples/README.md

LangGraph examples

This directory is retained purely for archival purposes and is no longer updated.

πŸ€” What is this?

The examples previously found here have been moved to the consolidated LangChain documentation. This directory remains available for historical reference, but new examples and usage guidance are published in the docs.

πŸ“– Documentation

For up-to-date LangGraph examples, tutorials, and guides, see the LangGraph Docs. Get started with the LangGraph Quickstart.


File: libs/sdk-py/README.md

LangGraph Python SDK




To help you ship LangGraph apps to production faster, check out LangSmith.
LangSmith is a unified developer platform for building, testing, and monitoring LLM applications.

Quick Install

bash
uv add langgraph-sdk

πŸ€” What is this?

This library provides the Python SDK for interacting with the LangGraph API. Use it to connect to a running LangGraph API server, manage assistants and threads, and stream runs from Python applications.

You will need a running LangGraph API server. If you're running a server locally using langgraph-cli, the SDK will automatically point at http://localhost:8123; otherwise, specify the server URL when creating a client.

πŸ“– Documentation

For full documentation, see the API reference. For conceptual guides and tutorials, see the LangGraph Docs.

Quick Start

python
from langgraph_sdk import get_client

# If you're using a remote server, initialize the client with `get_client(url=REMOTE_URL)`
client = get_client()

# List all assistants
assistants = await client.assistants.search()

# We auto-create an assistant for each graph you register in config.
agent = assistants[0]

# Start a new thread
thread = await client.threads.create()

# Start a streaming run
input = {"messages": [{"role": "human", "content": "what's the weather in la"}]}
async for chunk in client.runs.stream(
    thread["thread_id"], agent["assistant_id"], input=input
):
    print(chunk)

Known Limitations

  • WebSocket transport requires websockets>=14 and is only available on the async client (AsyncThreadStream). The sync client (SyncThreadStream) uses SSE exclusively.
  • thread.extensions[name] opens a new subscription each time the same name is accessed. Assign the projection to a variable and reuse it within a single session rather than re-indexing across multiple iterations.
  • Sync streaming drives the lifecycle watcher in a background thread. Long-lived sync sessions will hold that thread open until the context manager exits.
  • Reconnect attempts are limited to 5 by default for both the shared SSE fan-out and the lifecycle watcher. Persistent network partitions will surface as RuntimeError on in-flight projections.

Thread-Centric Streaming (v3)

client.threads.stream() returns a context manager that owns the SSE session for one thread. Typed projections β€” values snapshots, message streams, tool calls, custom events β€” all share the same underlying connection.

python
from langgraph_sdk import get_client
import asyncio

client = get_client()

async with client.threads.stream(
    thread_id="my-thread",
    assistant_id="agent",
) as thread:
    await thread.run.start(input={"messages": [{"role": "user", "content": "hi"}]})

    # Start all consumers concurrently so they share one SSE connection.
    async def get_messages():
        return [s async for s in thread.messages]

    async def get_tool_calls():
        return [c async for c in thread.tool_calls]

    messages, tool_calls = await asyncio.gather(get_messages(), get_tool_calls())

    for stream in messages:
        print(await stream.text)  # accumulated text

    final = await thread.output  # terminal state values

πŸ“• Releases & Versioning

See our Releases and Versioning policies.

πŸ’ Contributing

As an open-source project in a rapidly developing field, we are extremely open to contributions, whether it be in the form of a new feature, improved infrastructure, or better documentation.

For detailed information on how to contribute, see the Contributing Guide.


File: libs/sdk-js/README.md

LangGraph JavaScript SDK

Looking for the JS/TS version? Check out LangGraph.js.

πŸ€” What is this?

This package has moved to langchain-ai/langgraphjs.

πŸ“– Documentation

For JavaScript and TypeScript documentation, see the LangGraph.js docs.


File: libs/prebuilt/README.md

LangGraph Prebuilt




To help you ship LangGraph apps to production faster, check out LangSmith.
LangSmith is a unified developer platform for building, testing, and monitoring LLM applications.

Quick Install

bash
uv add langgraph

πŸ€” What is this?

This library defines high-level APIs for creating and executing LangGraph agents and tools. It includes prebuilt components such as create_react_agent, ToolNode, validation helpers, and Agent Inbox schemas.

πŸ“– Documentation

For full documentation, see the API reference. For conceptual guides and tutorials, see the LangGraph Docs.

[!IMPORTANT]
This library is bundled with langgraph; most users should install langgraph instead of installing langgraph-prebuilt directly.

Agents

langgraph-prebuilt provides an implementation of a tool-calling ReAct-style agent - create_react_agent:

bash
uv add langchain-anthropic
python
from langchain_anthropic import ChatAnthropic
from langgraph.prebuilt import create_react_agent


# Define the tools for the agent to use
def search(query: str):
    """Call to surf the web."""
    # This is a placeholder, but don't tell the LLM that...
    if "sf" in query.lower() or "san francisco" in query.lower():
        return "It's 60 degrees and foggy."
    return "It's 90 degrees and sunny."


tools = [search]
model = ChatAnthropic(model="claude-3-7-sonnet-latest")

app = create_react_agent(model, tools)
# run the agent
app.invoke(
    {"messages": [{"role": "user", "content": "what is the weather in sf"}]},
)

Tools

ToolNode

langgraph-prebuilt provides an implementation of a node that executes tool calls - ToolNode:

python
from langgraph.prebuilt import ToolNode
from langchain_core.messages import AIMessage


def search(query: str):
    """Call to surf the web."""
    # This is a placeholder, but don't tell the LLM that...
    if "sf" in query.lower() or "san francisco" in query.lower():
        return "It's 60 degrees and foggy."
    return "It's 90 degrees and sunny."


tool_node = ToolNode([search])
tool_calls = [
    {"name": "search", "args": {"query": "what is the weather in sf"}, "id": "1"}
]
ai_message = AIMessage(content="", tool_calls=tool_calls)
# execute tool call
tool_node.invoke({"messages": [ai_message]})

ValidationNode

langgraph-prebuilt provides an implementation of a node that validates tool calls against a pydantic schema - ValidationNode:

python
from pydantic import BaseModel, field_validator
from langgraph.prebuilt import ValidationNode
from langchain_core.messages import AIMessage


class SelectNumber(BaseModel):
    a: int

    @field_validator("a")
    def a_must_be_meaningful(cls, v):
        if v != 37:
            raise ValueError("Only 37 is allowed")
        return v


validation_node = ValidationNode([SelectNumber])
validation_node.invoke(
    {
        "messages": [
            AIMessage(
                "", tool_calls=[{"name": "SelectNumber", "args": {"a": 42}, "id": "1"}]
            )
        ]
    }
)

Agent Inbox

The library contains schemas for using the Agent Inbox with LangGraph agents. Learn more about how to use Agent Inbox here.

python
from langgraph.types import interrupt
from langgraph.prebuilt.interrupt import HumanInterrupt, HumanResponse

def my_graph_function():
    # Extract the last tool call from the `messages` field in the state
    tool_call = state["messages"][-1].tool_calls[0]
    # Create an interrupt
    request: HumanInterrupt = {
        "action_request": {
            "action": tool_call['name'],
            "args": tool_call['args']
        },
        "config": {
            "allow_ignore": True,
            "allow_respond": True,
            "allow_edit": False,
            "allow_accept": False
        },
        "description": _generate_email_markdown(state) # Generate a detailed markdown description.
    }
    # Send the interrupt request inside a list, and extract the first response
    response = interrupt([request])[0]
    if response['type'] == "response":
        # Do something with the response
    ...

πŸ“• Releases & Versioning

See our Releases and Versioning policies.

πŸ’ Contributing

As an open-source project in a rapidly developing field, we are extremely open to contributions, whether it be in the form of a new feature, improved infrastructure, or better documentation.

For detailed information on how to contribute, see the Contributing Guide.


File: libs/langgraph/README.md

πŸ¦œπŸ•ΈοΈ LangGraph





Looking for the JS/TS version? Check out LangGraph.js.

To help you ship LangGraph apps to production faster, check out LangSmith.
LangSmith is a unified developer platform for building, testing, and monitoring LLM applications.

Quick Install

bash
uv add langgraph

πŸ€” What is this?

LangGraph is a low-level orchestration framework for building, managing, and deploying long-running, stateful agents. LangGraph provides the infrastructure for durable execution, streaming, human-in-the-loop, persistence, memory, and more.

We recommend you use LangGraph when you have advanced needs that require a combination of deterministic and agentic workflows, heavy customization, and carefully controlled latency. Use LangChain when you want to quickly build agents and applications powered by LLMs using pre-built agent architectures and model integrations.

LangChain agents are built on top of LangGraph in order to provide durable execution, streaming, human-in-the-loop, persistence, and more. (You do not need to know LangGraph for basic LangChain agent usage.)

Trusted by companies shaping the future of agents – including Klarna, Replit, Elastic, and more – LangGraph is used to ship AI applications at scale.

πŸ“– Documentation

For full documentation, see the API reference. For conceptual guides, tutorials, and examples on using LangGraph, see the LangGraph Docs. Get started with the LangGraph Quickstart.

πŸ“• Releases & Versioning

See our Releases and Versioning policies.

πŸ’ Contributing

As an open-source project in a rapidly developing field, we are extremely open to contributions, whether it be in the form of a new feature, improved infrastructure, or better documentation.

For detailed information on how to contribute, see the Contributing Guide.

Acknowledgements

LangGraph is inspired by Pregel and Apache Beam. The public interface draws inspiration from NetworkX. LangGraph is built by LangChain Inc, the creators of LangChain, but can be used without LangChain.


File: libs/cli/js-examples/README.md

New LangGraph.js Project



This template demonstrates a simple chatbot implemented using LangGraph.js, designed for LangGraph Studio. The chatbot maintains persistent chat memory, allowing for coherent conversations across multiple interactions.

The core logic, defined in src/agent/graph.ts, showcases a straightforward chatbot that responds to user queries while maintaining context from previous messages.

πŸ€” What is this?

The simple chatbot:

  1. Takes a user message as input
  2. Maintains a history of the conversation
  3. Returns a placeholder response, updating the conversation history

This template provides a foundation that can be easily customized and extended to create more complex conversational agents.

πŸ“– Documentation

For JavaScript and TypeScript documentation, see the LangGraph.js docs. LangGraph Studio also integrates with LangSmith for tracing and collaboration with teammates.

Getting Started

Assuming you have already installed LangGraph Studio, to set up:

  1. Create a .env file. This template does not require any environment variables by default, but you will likely want to add some when customizing.
bash
cp .env.example .env
  1. Open the folder in LangGraph Studio!
  2. Customize the code as needed.

How to customize

  1. Add an LLM call: You can select and install a chat model wrapper from the LangChain.js ecosystem, or use LangGraph.js without LangChain.js.
  2. Extend the graph: The core logic of the chatbot is defined in graph.ts. You can modify this file to add new nodes, edges, or change the flow of the conversation.

You can also extend this template by:

  • Adding custom tools or functions to enhance the chatbot's capabilities.
  • Implementing additional logic for handling specific types of user queries or tasks.
  • Add retrieval-augmented generation (RAG) capabilities by integrating external APIs or databases to provide more customized responses.

Development

While iterating on your graph, you can edit past state and rerun your app from previous states to debug specific nodes. Local changes will be automatically applied via hot reload. Try experimenting with:

  • Modifying the system prompt to give your chatbot a unique personality.
  • Adding new nodes to the graph for more complex conversation flows.
  • Implementing conditional logic to handle different types of user inputs.

Follow-up requests will be appended to the same thread. You can create an entirely new thread, clearing previous history, using the + button in the top right.

For more advanced features and examples, refer to the LangGraph.js documentation. These resources can help you adapt this template for your specific use case and build more sophisticated conversational agents.

LangGraph Studio also integrates with LangSmith for more in-depth tracing and collaboration with teammates, allowing you to analyze and optimize your chatbot's performance.


File: libs/cli/README.md

LangGraph CLI




To help you ship LangGraph apps to production faster, check out LangSmith.
LangSmith is a unified developer platform for building, testing, and monitoring LLM applications.

Quick Install

bash
uv add langgraph-cli

πŸ€” What is this?

The LangGraph CLI is the official command-line interface for LangGraph. It provides tools to create, develop, build, and run LangGraph applications locally or in Docker.

πŸ“– Documentation

For full documentation, see the LangGraph CLI reference. For conceptual guides and tutorials, see the LangGraph Docs.

For development mode with hot reloading:

bash
uv add "langgraph-cli[inmem]"

Commands

`langgraph new` 🌱

Create a new LangGraph project from a template.

bash
langgraph new [PATH] --template TEMPLATE_NAME

`langgraph dev` πŸƒβ€β™€οΈ

Run LangGraph API server in development mode with hot reloading.

bash
langgraph dev [OPTIONS]
  --host TEXT                 Host to bind to (default: 127.0.0.1)
  --port INTEGER             Port to bind to (default: 2024)
  --no-reload               Disable auto-reload
  --debug-port INTEGER      Enable remote debugging
  --no-browser             Skip opening browser window
  -c, --config FILE        Config file path (default: langgraph.json)

`langgraph up` πŸš€

Launch LangGraph API server in Docker.

bash
langgraph up [OPTIONS]
  -p, --port INTEGER        Port to expose (default: 8123)
  --wait                   Wait for services to start
  --watch                  Restart on file changes
  --verbose               Show detailed logs
  -c, --config FILE       Config file path
  -d, --docker-compose    Additional services file

`langgraph build`

Build a Docker image for your LangGraph application.

bash
langgraph build -t IMAGE_TAG [OPTIONS]
  --platform TEXT          Target platforms (e.g., linux/amd64,linux/arm64)
  --pull / --no-pull      Use latest/local base image
  -c, --config FILE       Config file path

`langgraph dockerfile`

Generate a Dockerfile for custom deployments.

bash
langgraph dockerfile SAVE_PATH [OPTIONS]
  -c, --config FILE       Config file path

Configuration

The CLI uses a langgraph.json configuration file with these key settings:

json
{
  "dependencies": ["langchain_openai", "./your_package"],
  "graphs": {
    "my_graph": "./your_package/file.py:graph"
  },
  "env": "./.env",
  "python_version": "3.11",
  "pip_config_file": "./pip.conf",
  "dockerfile_lines": []
}

See the full documentation for detailed configuration options.

Development

To develop the CLI itself:

  1. Clone the repository
  2. Navigate to the CLI directory: cd libs/cli
  3. Install development dependencies: uv sync
  4. Make your changes to the CLI code
  5. Test your changes:
bash
# Run CLI commands directly
uv run langgraph --help

# Or use the examples
cd examples
uv sync
uv run langgraph dev  # or other commands

πŸ“• Releases & Versioning

See our Releases and Versioning policies.

πŸ’ Contributing

As an open-source project in a rapidly developing field, we are extremely open to contributions, whether it be in the form of a new feature, improved infrastructure, or better documentation.

For detailed information on how to contribute, see the Contributing Guide.


File: libs/checkpoint-sqlite/README.md

LangGraph SQLite Checkpoint




To help you ship LangGraph apps to production faster, check out LangSmith.
LangSmith is a unified developer platform for building, testing, and monitoring LLM applications.

Quick Install

bash
uv add langgraph-checkpoint-sqlite

πŸ€” What is this?

This library provides a SQLite implementation of LangGraph's checkpoint saver, with both sync and async support via aiosqlite. Use it when you want LangGraph state persistence backed by SQLite for local development, testing, or lightweight deployments.

πŸ“– Documentation

For full documentation, see the API reference. For conceptual guides on persistence and memory, see the LangGraph Docs.

Security

[!IMPORTANT]
Set LANGGRAPH_STRICT_MSGPACK=true or pass an explicit allowed_msgpack_modules list when creating your checkpointer. This restricts checkpoint deserialization to known-safe types, preventing code execution if the database is compromised. See the langgraph-checkpoint README for details.

Usage

python
from langgraph.checkpoint.sqlite import SqliteSaver

write_config = {"configurable": {"thread_id": "1", "checkpoint_ns": ""}}
read_config = {"configurable": {"thread_id": "1"}}

with SqliteSaver.from_conn_string(":memory:") as checkpointer:
    checkpoint = {
        "v": 4,
        "ts": "2024-07-31T20:14:19.804150+00:00",
        "id": "1ef4f797-8335-6428-8001-8a1503f9b875",
        "channel_values": {
            "my_key": "meow",
            "node": "node"
        },
        "channel_versions": {
            "__start__": 2,
            "my_key": 3,
            "start:node": 3,
            "node": 3
        },
        "versions_seen": {
            "__input__": {},
            "__start__": {
                "__start__": 1
            },
            "node": {
                "start:node": 2
            }
        },
    }

    # store checkpoint
    checkpointer.put(write_config, checkpoint, {}, {})

    # load checkpoint
    checkpointer.get(read_config)

    # list checkpoints
    list(checkpointer.list(read_config))

Async

python
from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver

async with AsyncSqliteSaver.from_conn_string(":memory:") as checkpointer:
    checkpoint = {
        "v": 4,
        "ts": "2024-07-31T20:14:19.804150+00:00",
        "id": "1ef4f797-8335-6428-8001-8a1503f9b875",
        "channel_values": {
            "my_key": "meow",
            "node": "node"
        },
        "channel_versions": {
            "__start__": 2,
            "my_key": 3,
            "start:node": 3,
            "node": 3
        },
        "versions_seen": {
            "__input__": {},
            "__start__": {
                "__start__": 1
            },
            "node": {
                "start:node": 2
            }
        },
    }

    # store checkpoint
    await checkpointer.aput(write_config, checkpoint, {}, {})

    # load checkpoint
    await checkpointer.aget(read_config)

    # list checkpoints
    [c async for c in checkpointer.alist(read_config)]

πŸ“• Releases & Versioning

See our Releases and Versioning policies.

πŸ’ Contributing

As an open-source project in a rapidly developing field, we are extremely open to contributions, whether it be in the form of a new feature, improved infrastructure, or better documentation.

For detailed information on how to contribute, see the Contributing Guide.


File: libs/checkpoint-postgres/README.md

LangGraph Checkpoint Postgres




To help you ship LangGraph apps to production faster, check out LangSmith.
LangSmith is a unified developer platform for building, testing, and monitoring LLM applications.

Quick Install

bash
uv add langgraph-checkpoint-postgres

πŸ€” What is this?

This library provides a Postgres implementation of LangGraph's checkpoint saver. Use it when you want LangGraph state persistence backed by Postgres for durable, long-running workflows and agents.

By default, langgraph-checkpoint-postgres installs psycopg (Psycopg 3) without any extras. You can choose a specific installation that best suits your needs in the Psycopg installation docs, for example psycopg[binary].

πŸ“– Documentation

For full documentation, see the API reference. For conceptual guides on persistence and memory, see the LangGraph Docs.

Security

[!IMPORTANT]
Set LANGGRAPH_STRICT_MSGPACK=true or pass an explicit allowed_msgpack_modules list when creating your checkpointer. This restricts checkpoint deserialization to known-safe types, preventing code execution if the database is compromised. See the langgraph-checkpoint README for details.

Usage

[!IMPORTANT]
When using Postgres checkpointers for the first time, make sure to call .setup() method on them to create required tables. See example below.

[!IMPORTANT]
When manually creating Postgres connections and passing them to PostgresSaver or AsyncPostgresSaver, make sure to include autocommit=True and row_factory=dict_row (from psycopg.rows import dict_row). See a full example in this how-to guide.

Why these parameters are required:

  • autocommit=True: Required for the .setup() method to properly commit the checkpoint tables to the database. Without this, table creation may not be persisted.
  • row_factory=dict_row: Required because the PostgresSaver implementation accesses database rows using dictionary-style syntax (e.g., row["column_name"]). The default tuple_row factory returns tuples that only support index-based access (e.g., row[0]), which will cause TypeError exceptions when the checkpointer tries to access columns by name.

Example of incorrect usage:

python
# ❌ This will fail with TypeError during checkpointer operations
with psycopg.connect(DB_URI) as conn:  # Missing autocommit=True and row_factory=dict_row
    checkpointer = PostgresSaver(conn)
    checkpointer.setup()  # May not persist tables properly
    # Any operation that reads from database will fail with:
    # TypeError: tuple indices must be integers or slices, not str
python
from langgraph.checkpoint.postgres import PostgresSaver

write_config = {"configurable": {"thread_id": "1", "checkpoint_ns": ""}}
read_config = {"configurable": {"thread_id": "1"}}

DB_URI = "postgres://postgres:postgres@localhost:5432/postgres?sslmode=disable"
with PostgresSaver.from_conn_string(DB_URI) as checkpointer:
    # call .setup() the first time you're using the checkpointer
    checkpointer.setup()
    checkpoint = {
        "v": 4,
        "ts": "2024-07-31T20:14:19.804150+00:00",
        "id": "1ef4f797-8335-6428-8001-8a1503f9b875",
        "channel_values": {"my_key": "meow", "node": "node"},
        "channel_versions": {"__start__": 2, "my_key": 3, "start:node": 3, "node": 3},
        "versions_seen": {
            "__input__": {},
            "__start__": {"__start__": 1},
            "node": {"start:node": 2},
        },
    }

    # store checkpoint
    checkpointer.put(write_config, checkpoint, {}, {})

    # load checkpoint
    checkpointer.get(read_config)

    # list checkpoints
    list(checkpointer.list(read_config))

Async

python
from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver

async with AsyncPostgresSaver.from_conn_string(DB_URI) as checkpointer:
    checkpoint = {
        "v": 4,
        "ts": "2024-07-31T20:14:19.804150+00:00",
        "id": "1ef4f797-8335-6428-8001-8a1503f9b875",
        "channel_values": {"my_key": "meow", "node": "node"},
        "channel_versions": {"__start__": 2, "my_key": 3, "start:node": 3, "node": 3},
        "versions_seen": {
            "__input__": {},
            "__start__": {"__start__": 1},
            "node": {"start:node": 2},
        },
    }

    # store checkpoint
    await checkpointer.aput(write_config, checkpoint, {}, {})

    # load checkpoint
    await checkpointer.aget(read_config)

    # list checkpoints
    [c async for c in checkpointer.alist(read_config)]

πŸ“• Releases & Versioning

See our Releases and Versioning policies.

πŸ’ Contributing

As an open-source project in a rapidly developing field, we are extremely open to contributions, whether it be in the form of a new feature, improved infrastructure, or better documentation.

For detailed information on how to contribute, see the Contributing Guide.

2. Official Technical Reference & Guides (langchain-ai/docs)

LangChain Docs

🦜 Welcome! This repository contains the documentation build pipeline for LangChain projects.

  • 🏠 docs.langchain.com is our docs home, centralizing LangChain, LangGraph, LangSmith, and LangChain Labs (Deep Agents, Open SWE, Open Agent Platform). This site is hosted on Mintlify.
  • πŸ› οΈ reference.langchain.com hosts generated API reference for LangChain, LangGraph, LangSmith, and integration packages. That site is not built from this repository (no reference build scripts or output live here).
  • πŸ’¬ chat.langchain.com is an AI-powered assistant that can answer questions about LangChain documentation.

Table of contents:


Contribute

To run a local preview of the documentation:

bash
git clone https://github.com/langchain-ai/docs.git
bash
cd docs
bash
make install
bash
make dev

For more information on how to contribute to LangChain documentation, follow the steps outlined in the contributing guide. The contributing guide also explains our documentation types and their writing and quality standards.

For detailed information about setting up your development environment and contributing to documentation, see the documentation contributing guide.

To report issues with reference.langchain.com (missing pages, broken links, or generated API content), open a reference documentation issue on this repo so maintainers can route it.

Reference

Repository structure

text
# --- docs.langchain.com ----------------------------------------------
build/                    # Built docs (DO NOT EDIT)
packages.yml              # Package metadata (indexes, tables, downloads; not the API reference build)
pipeline/                 # Build pipeline source code
scripts/                  # Helper scripts
src/                      # Source documentation files (< EDIT CONTENT HERE)
    langsmith/            # LangSmith docs
    oss/                  # LangChain, LangGraph, Deep Agents, and integrations docs
    docs.json             # Mintlify site configuration and navigation
tests/                    # Test files for the pipeline
Makefile                  # Build targets
pyproject.toml            # Dependencies

`docs.langchain.com`

The Mintlify docs pipeline is structured with .mdx source files in /src and build artifacts in /build. Mintlify deploys from the /build folder, which is generated by preprocessing logic.

[!IMPORTANT]
Never edit /build directly.

The /src/docs.json file is used to configure the Mintlify site navigation and settings. Refer to the Mintlify documentation for detailed syntax and component usage.

Documentation changes follow a PR workflow where all tests must pass before merging. See the contributing guidelines for more details.

`reference.langchain.com`

API reference is generated and deployed outside this repo. Browse Python and JavaScript/TypeScript reference there. If something is wrong with that site, use the reference docs issue template.

File formats

  • Markdown files (.md, .mdx) - Standard documentation content
  • Snippets (src/snippets/) - Reusable MDX content that can be imported into multiple pages. Important: Snippets undergo special link preprocessing. When writing links in snippets, be careful about path segments.
  • Jupyter notebooks (.ipynb) - Converted to markdown during build, though these are not recommended for new content! Your PR will likely be rejected if you attempt to add a Jupyter notebook unless asked to by a maintainer.
  • Assets - Images and other files are copied to the build directory

Available commands

Make commands:

  • make dev - Start development mode with file watching and live rebuild
  • make build - Build documentation to ./build directory
  • make broken-links - Check for broken links in documentation
  • make broken-links-with-anchors - Check for broken links + check links with anchors
  • make install - Install all dependencies
  • make clean - Remove build artifacts
  • make test - Run the test suite
  • make lint - Check code style and formatting
  • make format - Auto-format code
  • make lint_md - Lint markdown files
  • make lint_md_fix - Lint and fix markdown files
  • make help - Show all available commands

docs CLI tool:

The docs command (installed as uv run docs) provides additional functionality:

  • docs migrate - Convert MkDocs markdown/notebook files to Mintlify format

    • --dry-run - Preview changes without writing files
    • --output - Specify output location (default: in-place)
    • Supports .md, .markdown, .ipynb files
  • docs migrate-docusaurus - Convert Docusaurus markdown/notebook files to Mintlify format

    • --dry-run - Preview changes without writing files
    • --output - Specify output location (default: in-place)
    • Supports .md, .markdown, .mdx, .ipynb files
    • Converts Docusaurus-specific syntax (admonitions, tabs, imports, etc.)
  • docs mv <old_path> <new_path> - Move files and update cross-references

    • --dry-run - Preview changes without moving files

These can be used directly using the Makefile or via the docs CLI tool:

  • docs dev - Start development mode with file watching and hot reload

    • Automatically rebuilds changed files from src/ to build/
    • Launches Mintlify dev server at http://localhost:3000
    • Provides automatic browser refresh when files change
    • --skip-build - Skip initial build and use existing build directory
  • docs build - Build documentation files

    • --watch - Watch for file changes after building

Linting

After running make install, you can use make lint_prose to ensure your writing meets our style guide rules.

Codespell

make lint runs uv run codespell src to check source documentation for common spelling errors.

Codespell is configured in pyproject.toml under [tool.codespell]:

  • Add custom accepted words to src/.codespellignore. This file is referenced by ignore-words = "src/.codespellignore".
  • Exclude generated files, vendor content, or other paths that should not be spell checked by adding glob patterns to the skip setting.
  • Keep skip patterns scoped. Prefer adding accepted words to src/.codespellignore when the word is valid documentation content, and use skip when the file or directory should not be checked at all.

You can also follow these steps to enable vale with VS Code or Cursor:

  1. Install the Vale extension (Vale by Chris Chinchilla)
  2. Install Vale CLI: brew install vale (macOS) or see Vale installation for other platforms
  3. Navigate to the Vale extension settings:
    • Set Vale CLI: Config to the absolute path to .vale.ini (in the root of this repo)
    • Set Vale CLI: Min Alert Level to suggestion (many rules are coded as suggestions)

If you cannot use the VS Code UI to configure Vale, add these settings to your settings.json:

json
"vale.valeCLI.config": "/path/to/docs/.vale.ini",
    "vale.valeCLI.minAlertLevel": "suggestion"

Note: The extension requires Vale on your PATH. If annotations don't appear (e.g., when Cursor is launched from the Dock), launch Cursor from a terminal so it inherits your PATH, or ensure Homebrew is in your shell profile.

Troubleshooting

General Mintlify errors

In some cases, we use new features that are only available in the latest Mintlify CLI. If you encounter errors, ensure you have the latest version installed:

bash
mint update

# or

npm install mint

`docs dev` not working / running

Re-do the steps to set up your dev environment, ensuring you have activated the virtual environment and installed all dependencies.

[!IMPORTANT]
Most of the time, mint update solves any docs dev / make dev issues!

Mintlify `.venv` parsing error

Problem: Running mint broken-links or other Mintlify commands from the project root causes parsing errors like:

txt
Unable to parse .venv/lib/python3.13/site-packages/soupsieve-2.7.dist-info/licenses/LICENSE.md
- 3:48: Unexpected character '@' (U+0040) in name

Root Cause: Mintlify tries to parse all files in the directory, including Python virtual environment files that contain invalid MDX syntax.

Solutions (in order of preference):

  1. Use the safe Make commands (recommended):

    bash
    make broken-links-with-anchors      # Builds docs first, then checks internal links
  2. Run Mintlify commands from the build directory:

    bash
    cd build               # Change to build directory where final docs are
    mint broken-links      # Now safe to run

Why this works: The solution ensures Mintlify commands run from the build/ directory where the final documentation is generated, which is the correct place to check for broken links. This avoids scanning the Python virtual environment in the project root.

Prevention: Always use the provided Make commands instead of running raw mint commands from the project root.

Warning: page doesn't exist

If adding a new group, ensure the root index.mdx is included in the pages array like:

json
{
  "group": "New group",
  "pages": ["new-group/index", "new-group/other-page"]
}

If the trailing /index (no extension included) is omitted, the Mintlify parser will raise a warning even though the site will still build.