Skip to content

LangGraph Deployment Detailed interpretation 🚀 ​

📚 Overview ​

This document explains LangGraph’s deployment process in detail. Deployment is a critical step in pushing the Agent we build from the local development environment to the production environment. With LangGraph Cloud and LangGraph Studio, we can easily test, monitor, and manage our AI applications.

🎯 Core Concept ​

Why do we need to deploy? ​

In previous lessons, we have learned:

  • ✅ Build Agent (act) with tools
  • ✅ Processing tool output (observe)
  • ✅ Let Agent perform reasoning (reason)
  • ✅ Use memory to maintain state (persist state)

But these are all run in a local Jupyter Notebook. To make Agent truly serve users, we need to:

  • 🌐 Accessibility: accessible to other apps via API
  • 📊 Observability: Monitor running status and performance
  • 🔄 Scalability: Support concurrent access by multiple users
  • 🛡️ Reliability: error handling, retries, persistence

This is what deployment is all about!


🏗️ LangGraph ecological architecture ​

Core component relationship diagram ​

┌─────────────────────────────────────────────────────────┐
│                    开发者 (You)                          │
└─────────────────────────────────────────────────────────┘
                        │
        ┌───────────────┼───────────────┐
        ↓               ↓               ↓
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│  LangGraph   │ │  LangGraph   │ │  LangGraph   │
│   Library    │ │    Studio    │ │     SDK      │
│ (构建图代码)   │ │  (可视化IDE)  │ │  (程序化调用)  │
└──────────────┘ └──────────────┘ └──────────────┘
        │               │               │
        └───────────────┼───────────────┘
                        ↓
┌─────────────────────────────────────────────────────────┐
│                  LangGraph API                           │
│        (任务队列 + 持久化 + 异步处理)                      │
└─────────────────────────────────────────────────────────┘
                        │
        ┌───────────────┴───────────────┐
        ↓                               ↓
┌──────────────┐                ┌──────────────┐
│ 本地运行      │                │ LangGraph    │
│ (开发测试)    │                │   Cloud      │
└──────────────┘                │  (生产部署)   │
                               └──────────────┘

1. LangGraph Library ​

Role: Core Python/JavaScript library for building Agent workflows

python
from langgraph.graph import StateGraph, START, END

# 使用 LangGraph 定义图
graph = StateGraph(State)
graph.add_node("agent", call_model)
graph.add_edge(START, "agent")
graph.add_edge("agent", END)
app = graph.compile()

Features:

  • Provide graph construction API
  • Define status management
  • Supports advanced functions such as conditional edges and loops

2. LangGraph API ​

Function: Package graph code into deployable services

Core features:

  • 🔄 Task Queue: Manage asynchronous operations and handle concurrent requests
  • 💾 Persistence: Save conversation history and status (across sessions)
  • 🔌 HTTP API: Provides RESTful interface

**Why is it needed? **

There are limitations to running graph code directly:

python
# 本地直接运行 - 只能单次执行
app = graph.compile()
result = app.invoke({"messages": [HumanMessage("Hello")]})

Using LangGraph API:

python
# 通过 API - 支持流式、异步、多线程
async for chunk in client.runs.stream(
    thread_id="user-123",
    assistant_id="agent",
    input={"messages": [HumanMessage("Hello")]}
):
    print(chunk)

3. LangGraph Cloud ​

Role: Hosting service for LangGraph API

Core Features:

  • ☁️ Deploy from GitHub: Push code to deploy automatically
  • 🔍 Monitoring and Tracking: View detailed logs of each run
  • 🌐 Unique URL: Each deployment gets its own access address
  • 🔑 API Key Management: Securely manage environment variables

Deployment process:

GitHub Repo → LangSmith → LangGraph Cloud → 生产 URL

4. LangGraph Studio ​

Role: Visual IDE, used for testing and debugging graphs

Two operating modes:

bash
# 在项目目录运行
langgraph dev

# 输出:
# 🚀 API: http://127.0.0.1:2024
# 🎨 Studio UI: https://smith.langchain.com/studio/?baseUrl=http://127.0.0.1:2024
# 📚 API Docs: http://127.0.0.1:2024/docs

Features:

  • Real-time preview of image structure
  • Interactive test dialogue
  • View status changes at each step
  • Backend uses native LangGraph API

Cloud mode (for testing production deployments) ​

  • Connect to LangGraph Cloud deployment
  • Collaborate and share online
  • Access production environment data

5. LangGraph SDK ​

Role: Python client library for programmatic interaction

python
from langgraph_sdk import get_client

# 创建客户端(本地或云端)
client = get_client(url="http://127.0.0.1:2024")

# 列出所有助手
assistants = await client.assistants.search()

# 创建对话线程
thread = await client.threads.create()

# 运行图
async for chunk in client.runs.stream(
    thread['thread_id'],
    "agent",
    input={"messages": [...]},
    stream_mode="values"
):
    process(chunk)

Main API:

  • client.assistants - Management Assistant (Graph Definition)
  • client.threads - Manage conversation threads (state container)
  • client.runs - Execution graph operation (calling logic)

🛠️ Local deployment practice ​

Preparation ​

1. Project structure ​

Make sure your project contains the following files:

module-1/
├── studio/
│   ├── agent.py              # 图定义代码
│   ├── langgraph.json        # 配置文件
│   └── .env                  # 环境变量(不要提交到 Git!)
└── deployment.ipynb          # 测试代码

2. langgraph.json configuration file ​

json
{
  "dependencies": ["."],
  "graphs": {
    "agent": "./agent.py:graph"
  },
  "env": ".env"
}

Field description:

  • dependencies: Python package dependency path
  • graphs: graph definitions, using the format "graph_id": "file_path:variable_name"
  • env: environment variable file path

3. agent.py example ​

python
from typing import Annotated
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool

# 定义工具
@tool
def multiply(a: int, b: int) -> int:
    """Multiply two numbers."""
    return a * b

# 定义状态
class State(TypedDict):
    messages: Annotated[list, add_messages]

# 定义节点
def call_model(state: State):
    llm = ChatOpenAI(model="gpt-4o")
    llm_with_tools = llm.bind_tools([multiply])
    response = llm_with_tools.invoke(state["messages"])
    return {"messages": [response]}

# 构建图
graph_builder = StateGraph(State)
graph_builder.add_node("agent", call_model)
graph_builder.add_edge(START, "agent")
graph_builder.add_edge("agent", END)
graph = graph_builder.compile()

Start local development server ​

Step 1: Enter the project directory ​

bash
cd /Users/brycewang/langchain-academy/module-1/studio

Step 2: Start the service ​

bash
langgraph dev

Example output:

✓ Configuration loaded from langgraph.json
✓ Environment variables loaded from .env
✓ Graph 'agent' loaded successfully

- 🚀 API: http://127.0.0.1:2024
- 🎨 Studio UI: https://smith.langchain.com/studio/?baseUrl=http://127.0.0.1:2024
- 📚 API Docs: http://127.0.0.1:2024/docs

Watching for changes...

IMPORTANT NOTE:

  • Keep the terminal running (don't close it!)
  • Code modifications will be automatically reloaded
  • Visit API Docs to see full API documentation

Step 3: Open Studio in the browser ​

Visit: https://smith.langchain.com/studio/?baseUrl=http://127.0.0.1:2024

Studio interface features:

  • 📊 Graph visualization: View the connections of nodes and edges
  • 💬 Interactive test: enter a message and view the Agent response
  • 🔍 Status Check: Check the status changes after each step is executed
  • 🐛 Debug Tools: View error stacks and logs

💻 Use SDK to call local API ​

Install dependencies ​

python
%pip install --quiet -U langgraph_sdk langchain_core

Code Example ​

1. Connect to local server ​

python
from langgraph_sdk import get_client

# 本地开发服务器地址
URL = "http://127.0.0.1:2024"
client = get_client(url=URL)

Python knowledge points: async/await

LangGraph SDK uses asynchronous programming:

python
# ❌ 错误 - 同步调用会报错
assistants = client.assistants.search()

# ✅ 正确 - 异步调用
assistants = await client.assistants.search()

**Why use asynchronous? **

  • Non-blocking I/O to improve concurrency performance
  • Support streaming response
  • Better handling of long-running tasks

**How ​​to use it in Jupyter? ** Jupyter Notebook supports top-level await by default:

python
# 直接使用 await(仅在 Notebook 中)
result = await client.runs.stream(...)

# 在普通 Python 脚本中需要:
import asyncio
asyncio.run(main())

2. Search for available assistants (picture) ​

python
# 搜索所有已部署的图
assistants = await client.assistants.search()

# 查看第一个助手
print(assistants[0])

Example output:

python
{
    'assistant_id': 'fe096781-5601-53d2-b2f6-0d3403f7e9ca',
    'graph_id': 'agent',
    'config': {},
    'metadata': {'created_by': 'system'},
    'name': 'agent',
    'created_at': '2025-03-04T22:57:28.424565+00:00',
    'updated_at': '2025-03-04T22:57:28.424565+00:00',
    'version': 1
}

Field description:

  • assistant_id: unique identifier (UUID)
  • graph_id: name of the graph (from langgraph.json)
  • config: configuration options (such as model parameters)
  • version: version number (supports multi-version deployment)

3. Create a conversation thread ​

python
# 创建新线程用于跟踪状态
thread = await client.threads.create()

print(thread['thread_id'])
# 输出:'1ef6c123-4567-89ab-cdef-0123456789ab'

LangGraph knowledge point: Thread (thread)

Thread is the state container in LangGraph:

Thread = 独立的对话会话 = 独立的状态快照

**Why do you need Thread? ** -Support multi-user concurrency (one Thread per user)

  • Persist conversation history (keep state across requests) -Isolate different sessions (avoid state confusion)

Example scenario:

python
# 用户 A 的对话
thread_a = await client.threads.create()
client.runs.stream(thread_a['thread_id'], "agent", input={"messages": [...]})

# 用户 B 的对话(完全独立)
thread_b = await client.threads.create()
client.runs.stream(thread_b['thread_id'], "agent", input={"messages": [...]})

4. Run the graph and stream the output ​

python
from langchain_core.messages import HumanMessage

# 输入消息
input = {"messages": [HumanMessage(content="Multiply 3 by 2.")]}

# 流式运行图
async for chunk in client.runs.stream(
    thread['thread_id'],     # 线程 ID
    "agent",                 # 图 ID
    input=input,             # 输入数据
    stream_mode="values",    # 流模式
):
    if chunk.data and chunk.event != "metadata":
        print(chunk.data['messages'][-1])

Parameter details:

ParametersDescriptionExample
thread_idThread identifier'1ef6c123-...'
assistant_idAssistant ID (picture name)'agent'
inputInput status{"messages": [...]}
stream_modeStreaming mode"values" / "updates"

LangGraph knowledge point: Stream Modes

LangGraph supports multiple streaming modes:

  1. stream_mode="values" - Complete state flow

    python
    # 每步后返回完整状态
    {'messages': [msg1]}
    {'messages': [msg1, msg2]}
    {'messages': [msg1, msg2, msg3]}
  2. stream_mode="updates" - Incremental update stream

    python
    # 每步只返回新增的状态
    {'messages': [msg1]}
    {'messages': [msg2]}
    {'messages': [msg3]}
  3. stream_mode="messages" - Message flow (messages only)

    python
    # 直接返回消息对象
    AIMessage(content="...")
    ToolMessage(content="...")

Example of run output:

python
# 第 1 步:用户消息
{'content': 'Multiply 3 by 2.', 'type': 'human', 'id': 'cdbd7bd8-...'}

# 第 2 步:AI 调用工具
{'content': '', 'type': 'ai', 'tool_calls': [{'name': 'multiply', 'args': {'a': 3, 'b': 2}}]}

# 第 3 步:工具执行结果
{'content': '6', 'type': 'tool', 'name': 'multiply', 'tool_call_id': 'call_iIPry...'}

# 第 4 步:AI 最终响应
{'content': 'The result of multiplying 3 by 2 is 6.', 'type': 'ai'}

Code analysis:

python
async for chunk in client.runs.stream(...):
    # chunk 是流式响应的片段

    if chunk.data and chunk.event != "metadata":
        # chunk.data:包含状态数据
        # chunk.event:事件类型(如 "values", "metadata")

        print(chunk.data['messages'][-1])
        # 打印最新消息(列表最后一项)

☁️ Cloud deployment practice ​

Deployment process overview ​

1. GitHub 创建仓库
         ↓
2. 推送代码到 GitHub
         ↓
3. LangSmith 连接仓库
         ↓
4. 配置部署参数
         ↓
5. 自动部署到 LangGraph Cloud
         ↓
6. 获得生产 URL

Step 1: Create a GitHub repository ​

1.1 Create a new repository on GitHub ​

  • Login GitHub
  • Click "+" in the upper right corner → "New repository"
  • Warehouse name: langchain-academy
  • Set to Private (recommended to avoid leaking API keys)
  • DO NOT initialize README, .gitignore or License

1.2 Add remote warehouse ​

bash
# 进入本地项目目录
cd /Users/brycewang/langchain-academy

# 添加远程仓库
git remote add origin https://github.com/your-username/langchain-academy.git

# 查看远程仓库
git remote -v

Git knowledge point: remote

bash
git remote add <名称> <URL>
#              ^^^^^  ^^^^^^
#              别名    仓库地址

# 常见别名:
# origin - 默认主仓库
# upstream - 上游仓库(fork 时使用)

1.3 Push code ​

bash
# 确保所有文件已提交
git add .
git commit -m "Add LangGraph agent"

# 推送到 GitHub
git push -u origin main

**Important warning: Do not submit .env files! **

Make sure .gitignore contains:

.env
*.env
.env.local

Verification:

bash
# 检查是否误提交了敏感文件
git log --all --full-history -- "*.env"

Step 2: Configure deployment in LangSmith ​

2.1 Visit LangSmith ​

  • Open LangSmith
  • Log in (use the same account as LangChain)

2.2 Create a new deployment ​

  1. Click the "Deployments" tab in the left navigation bar
  2. Click the "+ New Deployment" button
  3. Select "Deploy from GitHub"

2.3 Connect to GitHub repository ​

  1. Authorize GitHub:

    • First time use requires authorizing LangSmith to access GitHub
    • Choose to authorize all warehouses or specific warehouses
  2. Select warehouse:

    • Repository: your-username/langchain-academy
    • Branch: main
  3. Configuration map path:

    • LangGraph API config file: module-1/studio/langgraph.json
    • This is the path of the langgraph.json file in the warehouse

2.4 Set environment variables ​

**Why is it needed? **

  • The cloud cannot access your local .env file
  • Requires manual configuration of API keys and other environment variables

**How ​​to set it up? **

Method 1: Copy from local .env

bash
# 查看本地环境变量
cat module-1/studio/.env

# 输出示例:
# OPENAI_API_KEY=sk-proj-...
# TAVILY_API_KEY=tvly-...

Method 2: Add in LangSmith UI

  • Click "Environment Variables"
  • Add each variable:
    Name: OPENAI_API_KEY
    Value: sk-proj-...
    
    Name: TAVILY_API_KEY
    Value: tvly-...

Safety Tips:

  • ✅ Use dedicated production environment keys
  • ✅ Rotate keys regularly
  • ❌ Don’t hardcode keys in your code
  • ❌ Don't print keys in logs

2.5 Deployment ​

  1. Check that the configuration is correct
  2. Click the "Deploy" button
  3. Wait for deployment to complete (usually 1-2 minutes)

Deployment process:

[1/5] 克隆 GitHub 仓库
[2/5] 安装 Python 依赖
[3/5] 加载图定义
[4/5] 运行健康检查
[5/5] 分配 URL

2.6 Get deployment URL ​

After successful deployment, you will get a unique URL:

https://langchain-academy-8011c561878d50b1883f7ed11b32d720.default.us.langgraph.app

URL format:

https://<project-name>-<deployment-id>.<region>.langgraph.app
        ^^^^^^^^^^^^^^  ^^^^^^^^^^^^^^^  ^^^^^^^^
        项目名称         唯一标识符        区域

Step 3: Use SDK to call cloud deployment ​

3.1 Set LangSmith API Key ​

python
import os
import getpass

def _set_env(var: str):
    if not os.environ.get(var):
        os.environ[var] = getpass.getpass(f"{var}: ")

# 设置 LangSmith API 密钥(用于身份验证)
_set_env("LANGSMITH_API_KEY")

Python knowledge point: getpass module

getpass is used to enter password securely:

python
import getpass

# 普通 input - 密码会显示
password = input("Password: ")  # 输入: abc123 → 屏幕显示 abc123

# getpass - 密码隐藏
password = getpass.getpass("Password: ")  # 输入: abc123 → 屏幕显示 ******

**Why do you need LANGSMITH_API_KEY? **

  • Cloud deployment requires authentication
  • Prevent unauthorized access
  • Link to your LangSmith account

**How ​​to get it? **

  1. Visit LangSmith Settings
  2. Click "API Keys"
  3. Create a new key or copy an existing key

3.2 Connect to cloud service ​

python
from langgraph_sdk import get_client

# 替换为你的部署 URL
URL = "https://langchain-academy-8011c561878d50b1883f7ed11b32d720.default.us.langgraph.app"
client = get_client(url=URL)

# 搜索助手
assistants = await client.assistants.search()

IMPORTANT NOTE:

  • Cloud URL and local URL use the same SDK
  • To switch environments, just change the url parameters
  • The API calling method is exactly the same

3.3 Running Cloud Agent ​

python
from langchain_core.messages import HumanMessage

# 选择助手
agent = assistants[0]

# 创建线程
thread = await client.threads.create()

# 输入消息
input = {"messages": [HumanMessage(content="Multiply 3 by 2.")]}

# 流式运行(与本地完全相同!)
async for chunk in client.runs.stream(
    thread['thread_id'],
    "agent",
    input=input,
    stream_mode="values",
):
    if chunk.data and chunk.event != "metadata":
        print(chunk.data['messages'][-1])

Example output:

python
{'content': 'Multiply 3 by 2.', 'type': 'human', 'id': '8ea04559-...'}
{'content': '', 'type': 'ai', 'tool_calls': [{'name': 'multiply', 'args': {'a': 3, 'b': 2}}]}
{'content': '6', 'type': 'tool', 'name': 'multiply', 'tool_call_id': 'call_EQool...'}
{'content': '3 multiplied by 2 equals 6.', 'type': 'ai'}

Step 4: Access cloud deployment in Studio ​

4.1 Open LangGraph Studio ​

4.2 Select cloud deployment ​

  • Switch to "Cloud" mode at the top
  • Choose your deployment (eg langchain-academy)

4.3 Interactive testing ​

Studio provides the same functionality as native:

  • Visual graph structure
  • Enter message test
  • View status changes
  • Monitor performance metrics

Extra features of Cloud Studio:

  • 📊 Run History: View all historical running records
  • 🔍 Tracking details: token usage, latency, etc. for each LLM call
  • 👥 Team Collaboration: share with team members
  • 📈 Usage statistics: API call volume, costs, etc.

🎓 Summary of core knowledge points ​

LangGraph-specific concepts ​

1. Deployment ​

Definition: The process of migrating a LangGraph application from a development environment to a production environment

Key components:

  • langgraph.json: Configuration file, defining graph path and dependencies
  • LangGraph API: Provides HTTP interface and task queue
  • Thread: state container, supports multi-user sessions
  • Assistant: Runtime instance of the graph

2. Thread vs Assistant ​

ConceptFunctionAnalogyPersistence
AssistantGraph definition (code)Program executable fileYes
ThreadState instance (data)The running process of the programYes
python
# 一个 Assistant(图)可以有多个 Thread(会话)
assistant_id = "agent"

thread1 = await client.threads.create()  # 用户 A 的会话
thread2 = await client.threads.create()  # 用户 B 的会话

# 同一个 Assistant,不同的 Thread
client.runs.stream(thread1['thread_id'], assistant_id, ...)
client.runs.stream(thread2['thread_id'], assistant_id, ...)

3. Stream Modes comparison ​

python
# 场景 1:需要完整状态(如 UI 渲染)
stream_mode="values"
# → {'messages': [msg1, msg2, msg3]}

# 场景 2:只关心新增数据(如增量更新)
stream_mode="updates"
# → {'messages': [msg3]}

# 场景 3:只处理消息(如聊天应用)
stream_mode="messages"
# → AIMessage(content="...")

4. Local vs cloud deployment ​

FeaturesLocal development (langgraph dev)Cloud deployment (LangGraph Cloud)
PurposeDevelopment and TestingProduction Environment
URLhttp://127.0.0.1:2024https://xxx.langgraph.app
Environment Variables.env FileLangSmith UI Configuration
Hot Reload✅ Support❌ Redeploy required
PersistenceMemory (lost on restart)Database (permanent)
MonitoringBasic logsComplete tracking and analysis
CostFreePay per usage

Python-specific knowledge points ​

1. Asynchronous programming (async/await) ​

**Why use asynchronous? **

Synchronous call (blocking):

python
# 调用 API → 等待响应 → 继续执行
result1 = call_api_1()  # 等待 2 秒
result2 = call_api_2()  # 等待 2 秒
# 总耗时:4 秒

Asynchronous call (non-blocking):

python
# 同时发起多个请求,并发等待
result1 = await call_api_1()  # 异步等待 2 秒
result2 = await call_api_2()  # 异步等待 2 秒
# 总耗时:2 秒(并发执行)

Basic syntax:

python
# 定义异步函数
async def fetch_data():
    result = await some_async_operation()
    return result

# 调用异步函数
# 方式 1:在 Jupyter Notebook 中
data = await fetch_data()

# 方式 2:在普通 Python 脚本中
import asyncio
data = asyncio.run(fetch_data())

Applications in LangGraph SDK:

python
# ✅ 所有 SDK 方法都是异步的
await client.assistants.search()
await client.threads.create()
async for chunk in client.runs.stream(...):
    process(chunk)

2. Asynchronous iterator (async for) ​

Normal iterator:

python
# 同步迭代
for item in [1, 2, 3]:
    print(item)

Asynchronous iterator:

python
# 异步迭代
async for chunk in async_generator():
    print(chunk)

Usage in LangGraph:

python
# client.runs.stream() 返回异步生成器
async for chunk in client.runs.stream(thread_id, assistant_id, input=...):
    # 每次 yield 一个新的状态片段
    if chunk.data:
        print(chunk.data)

Equivalent synchronization writing method (for understanding):

python
# 如果 stream() 是同步的,代码会是这样:
for chunk in client.runs.stream_sync(...):  # 假设有同步版本
    print(chunk.data)

3. getpass secure input ​

python
import getpass

# 安全输入密码(不显示)
api_key = getpass.getpass("API Key: ")

# 常见使用模式
def _set_env(var: str):
    if not os.environ.get(var):
        os.environ[var] = getpass.getpass(f"{var}: ")

_set_env("OPENAI_API_KEY")

Security Advantages:

  • Input will not be displayed on the screen
  • Will not be logged
  • Prevent shoulder surfing attacks (Shoulder Surfing)

4. Environment variable management ​

Read environment variables:

python
import os

# 方式 1:直接获取(可能返回 None)
api_key = os.environ.get("OPENAI_API_KEY")

# 方式 2:必须存在(不存在会报错)
api_key = os.environ["OPENAI_API_KEY"]

# 方式 3:提供默认值
api_key = os.environ.get("OPENAI_API_KEY", "default-key")

Set environment variables:

python
# 方式 1:代码中设置(临时,仅当前进程)
os.environ["OPENAI_API_KEY"] = "sk-proj-..."

# 方式 2:.env 文件(推荐)
# 文件:.env
# 内容:OPENAI_API_KEY=sk-proj-...

# 加载 .env 文件
from dotenv import load_dotenv
load_dotenv()

Best Practices:

python
# .env 文件
OPENAI_API_KEY=sk-proj-...
TAVILY_API_KEY=tvly-...
LANGSMITH_API_KEY=lsv2_...

# Python 代码
from dotenv import load_dotenv
import os

load_dotenv()  # 加载 .env

# 验证必需的环境变量
required_vars = ["OPENAI_API_KEY", "TAVILY_API_KEY"]
for var in required_vars:
    if not os.environ.get(var):
        raise ValueError(f"Missing required environment variable: {var}")

💡 Best Practices ​

1. Project structure specification ​

Recommended structure:

my-langgraph-project/
├── .gitignore              # 忽略敏感文件
├── README.md               # 项目说明
├── requirements.txt        # Python 依赖
├── .env.example            # 环境变量模板(不含真实密钥)
├── src/
│   ├── agent.py           # 图定义
│   ├── tools.py           # 工具定义
│   └── utils.py           # 工具函数
├── tests/
│   └── test_agent.py      # 单元测试
└── deployment/
    ├── langgraph.json     # 部署配置
    └── .env               # 环境变量(不提交!)

.gitignore Required Content:

# 环境变量
.env
.env.local
*.env

# Python
__pycache__/
*.pyc
.venv/
venv/

# LangGraph
.langraph/

2. Environment variable management ​

.env.example template ​

bash
# OpenAI API
OPENAI_API_KEY=your_openai_key_here

# Tavily Search API
TAVILY_API_KEY=your_tavily_key_here

# LangSmith (for tracing)
LANGSMITH_API_KEY=your_langsmith_key_here
LANGSMITH_PROJECT=my-project

Usage process:

  1. Copy .env.example to .env
  2. Fill in the real API key
  3. .env is not committed to Git (via .gitignore)

Multiple environment configuration ​

.env.development    # 开发环境
.env.staging        # 预发布环境
.env.production     # 生产环境

Load the specified environment:

python
import os
from dotenv import load_dotenv

env = os.getenv("ENV", "development")
load_dotenv(f".env.{env}")

3. Version management ​

langgraph.json version control ​

json
{
  "dependencies": ["."],
  "graphs": {
    "agent": "./agent.py:graph"
  },
  "env": ".env",
  "version": "1.0.0"
}

Git tag (Tag) ​

bash
# 创建版本标签
git tag -a v1.0.0 -m "Release version 1.0.0"

# 推送标签到 GitHub
git push origin v1.0.0

# LangSmith 部署时可以指定标签
# 部署配置 → Git Ref → v1.0.0

4. Monitoring and Debugging ​

Enable LangSmith tracing ​

python
import os

# 启用追踪
os.environ["LANGSMITH_TRACING"] = "true"
os.environ["LANGSMITH_PROJECT"] = "my-agent-deployment"

# 运行 Agent
# 所有调用会自动记录到 LangSmith

View Tracking:

  1. Visit LangSmith
  2. Select item my-agent-deployment
  3. View detailed logs for each run:
    • LLM call (prompt word, response, token usage)
    • Tool call (parameters, results)
    • State changes (state snapshot for each step)

Local debugging skills ​

python
# 添加详细日志
import logging
logging.basicConfig(level=logging.DEBUG)

# 在节点中打印状态
def call_model(state: State):
    print(f"Current state: {state}")  # 调试日志
    response = llm.invoke(state["messages"])
    return {"messages": [response]}

5. Error handling ​

Elegant error recovery ​

python
def call_model(state: State):
    try:
        response = llm.invoke(state["messages"])
        return {"messages": [response]}
    except Exception as e:
        # 记录错误
        logging.error(f"Error in call_model: {e}")

        # 返回错误消息
        return {"messages": [AIMessage(content=f"Sorry, an error occurred: {str(e)}")]}

Retry mechanism ​

python
from tenacity import retry, stop_after_attempt, wait_exponential

@retry(
    stop=stop_after_attempt(3),
    wait=wait_exponential(multiplier=1, min=2, max=10)
)
def call_model_with_retry(state: State):
    response = llm.invoke(state["messages"])
    return {"messages": [response]}

6. Performance optimization ​

Use streaming responses ​

python
# ❌ 等待完整响应(慢)
response = await client.runs.invoke(thread_id, assistant_id, input=...)

# ✅ 流式获取(快,用户体验好)
async for chunk in client.runs.stream(thread_id, assistant_id, input=...):
    display(chunk)  # 实时显示

Cache common results ​

python
from functools import lru_cache

@lru_cache(maxsize=100)
def expensive_computation(input_data):
    # 昂贵的计算
    return result

🚀 Advanced skills ​

1. Multi-version deployment ​

Scenario: Running multiple versions of Agent at the same time (such as A/B testing)

accomplish:

python
# 部署 v1
await client.assistants.create(
    graph_id="agent",
    config={"model": "gpt-4o"},
    version="v1"
)

# 部署 v2
await client.assistants.create(
    graph_id="agent",
    config={"model": "gpt-4o-mini"},
    version="v2"
)

# 用户随机分配版本
import random
version = random.choice(["v1", "v2"])
await client.runs.stream(thread_id, f"agent-{version}", input=...)

2. Custom configuration ​

langgraph.json advanced configuration:

json
{
  "dependencies": ["."],
  "graphs": {
    "agent": {
      "module": "./agent.py",
      "graph": "graph",
      "config": {
        "model": "gpt-4o",
        "temperature": 0.7,
        "max_tokens": 1000
      }
    }
  },
  "env": ".env",
  "python_version": "3.11"
}

Use configuration in code:

python
from langgraph.graph import StateGraph
from langgraph.config import get_config

def call_model(state: State):
    config = get_config()
    model_name = config.get("model", "gpt-4o")
    temperature = config.get("temperature", 0)

    llm = ChatOpenAI(model=model_name, temperature=temperature)
    response = llm.invoke(state["messages"])
    return {"messages": [response]}

3. Interruption and recovery ​

Usage scenario: Workflow that requires manual approval

python
from langgraph.checkpoint.memory import MemorySaver

# 编译时添加 checkpointer
checkpointer = MemorySaver()
app = graph.compile(checkpointer=checkpointer)

# 运行到中断点
config = {"configurable": {"thread_id": "thread-1"}}
result = app.invoke(input, config=config)

# 稍后恢复(从上次状态继续)
result = app.invoke(None, config=config)

4. Integrate into production applications ​

FastAPI integration ​

python
from fastapi import FastAPI
from langgraph_sdk import get_client

app = FastAPI()
client = get_client(url="http://127.0.0.1:2024")

@app.post("/chat")
async def chat(message: str, thread_id: str):
    input_data = {"messages": [HumanMessage(content=message)]}

    response = ""
    async for chunk in client.runs.stream(
        thread_id,
        "agent",
        input=input_data,
        stream_mode="values"
    ):
        if chunk.data:
            response = chunk.data['messages'][-1]['content']

    return {"response": response}

Streamlit front-end ​

python
import streamlit as st
from langgraph_sdk import get_client

st.title("My AI Assistant")

# 初始化客户端
client = get_client(url="http://127.0.0.1:2024")

# 创建或获取 thread
if "thread_id" not in st.session_state:
    thread = asyncio.run(client.threads.create())
    st.session_state.thread_id = thread['thread_id']

# 聊天界面
user_input = st.text_input("You:", "")

if user_input:
    input_data = {"messages": [HumanMessage(content=user_input)]}

    async for chunk in client.runs.stream(
        st.session_state.thread_id,
        "agent",
        input=input_data,
        stream_mode="values"
    ):
        if chunk.data:
            st.write("AI:", chunk.data['messages'][-1]['content'])

🔍 Frequently Asked Questions ​

Q1: When developing locally, do I need to restart the server after modifying the code? ​

Answer: No need! langgraph dev supports hot reload.

bash
# 启动服务器
langgraph dev

# 修改 agent.py
# 保存文件后,终端会显示:
✓ Detected changes in agent.py
✓ Reloading graph...
✓ Graph reloaded successfully

Note: If langgraph.json or .env is modified, manual restart is required.

Q2: How to switch between local and cloud? ​

Answer: Just modify the URL parameters.

python
# 本地
client = get_client(url="http://127.0.0.1:2024")

# 云端
client = get_client(url="https://xxx.langgraph.app")

# 其他代码完全相同!

Best Practice: Use environment variables

python
import os

URL = os.getenv("LANGGRAPH_URL", "http://127.0.0.1:2024")
client = get_client(url=URL)

Q3: How long will the state of Thread persist? ​

Local:

  • Use memory storage (MemorySaver)
  • Lost after restarting the server
  • Suitable for development testing

Cloud:

  • Use database storage
  • Default retention is 30 days
  • Configurable retention time

Query Thread status:

python
# 获取 Thread 的历史记录
thread_state = await client.threads.get_state(thread_id)
print(thread_state.values)  # 当前状态
print(thread_state.next)    # 下一步节点

Q4: How to debug cloud deployment errors? ​

Method 1: View LangSmith logs

  1. Visit LangSmith → Deployments
  2. Choose your deployment
  3. Click on the "Logs" tab
  4. View error stack and call details

Method 2: Enable detailed tracking

python
# 在 langgraph.json 中添加
{
  "env": ".env",
  "tracing": {
    "enabled": true,
    "project": "my-project"
  }
}

Method 3: Local reproduction

python
# 使用相同的输入在本地测试
async for chunk in client.runs.stream(
    thread_id,
    "agent",
    input=problematic_input,  # 导致错误的输入
    stream_mode="values"
):
    print(chunk)

Q5: How to update the code after deployment? ​

Method 1: Push to GitHub (recommended)

bash
# 修改代码
vim agent.py

# 提交并推送
git add .
git commit -m "Update agent logic"
git push origin main

# LangGraph Cloud 会自动检测并重新部署

Method 2: Manually trigger deployment

  1. Visit LangSmith → Deployments
  2. Choose your deployment
  3. Click the "Redeploy" button

Note: There will be a few minutes of downtime for redeployment.

Q6: How to limit the API call rate? ​

Scenario: Prevent malicious users from abusing or exceeding OpenAI quotas

Method 1: Add a rate limit to the graph

python
from ratelimit import limits, sleep_and_retry

# 每分钟最多 10 次调用
@sleep_and_retry
@limits(calls=10, period=60)
def call_model(state: State):
    response = llm.invoke(state["messages"])
    return {"messages": [response]}

Method 2: Using LangGraph Cloud Configuration

json
{
  "rate_limits": {
    "per_user": {
      "requests": 100,
      "window": "1h"
    }
  }
}

Q7: What is the practical difference between stream_mode="values" and "updates"? ​

Example scenario: Chat application showing Agent thought process

Use "values":

python
async for chunk in client.runs.stream(thread_id, "agent", input=..., stream_mode="values"):
    # 每次获得完整状态
    all_messages = chunk.data['messages']

    # UI 需要每次重新渲染整个对话
    display_all_messages(all_messages)

Use "updates":

python
async for chunk in client.runs.stream(thread_id, "agent", input=..., stream_mode="updates"):
    # 只获得新增消息
    new_messages = chunk.data['messages']

    # UI 只需要追加新消息
    append_messages(new_messages)

Selection suggestions:

  • "values": suitable for simple UI, fully updated every time
  • "updates": suitable for complex UI that requires incremental updates (more efficient)

📊 Comparison summary of local vs. cloud ​

DimensionsLocal developmentCloud deployment
Start Commandlanggraph devBy LangSmith UI
URLhttp://127.0.0.1:2024https://xxx.langgraph.app
Environment Variables.env FileLangSmith UI Configuration
Code UpdateJust save the file (hot reload)Push Git → Automatic deployment
State persistenceMemory (lost on restart)Database (permanent)
Applicable scenariosDevelopment, testing, debuggingProduction, multi-user, long-term operation
CostFree (local resources only)Pay per usage
ObservabilityBasic logsComplete tracking, monitoring, and alerting

🎯 Practical exercises ​

Exercise 1: Deploy a simple Agent locally ​

Task: Create a calculator Agent that supports addition, subtraction, multiplication and division

  1. Create project structure
  2. Define tools and diagrams
  3. Configure langgraph.json
  4. Start langgraph dev
  5. Test using SDK

Tip:

python
@tool
def add(a: int, b: int) -> int:
    """Add two numbers."""
    return a + b

@tool
def subtract(a: int, b: int) -> int:
    """Subtract b from a."""
    return a - b

# 绑定工具到 LLM
tools = [add, subtract]
llm_with_tools = ChatOpenAI(model="gpt-4o").bind_tools(tools)

Exercise 2: Deploy to LangGraph Cloud ​

Task: Deploy the Agent from Exercise 1 to the cloud

  1. Create a GitHub repository
  2. Push code
  3. Configure deployment in LangSmith
  4. Get the production URL
  5. Use SDK to call cloud API

Exercise 3: Multithreaded Conversations ​

Task: Create 3 independent conversation threads to test state isolation

python
# 创建 3 个线程
threads = [await client.threads.create() for _ in range(3)]

# 每个线程发送不同消息
messages = [
    "What is 3 + 5?",
    "What is 10 - 2?",
    "What is 4 * 6?"
]

# 并发运行
for thread, message in zip(threads, messages):
    asyncio.create_task(
        client.runs.stream(thread['thread_id'], "agent", input={"messages": [HumanMessage(message)]})
    )

📖 Further reading ​


Summary: Through this tutorial, you have mastered the complete deployment process of LangGraph! From local development and testing to production deployment in the cloud to programmatic calls using the SDK. These skills are the building blocks for building scalable, reliable AI applications. Keep practicing and explore more advanced features! 🚀

English translation of community learning materials. MIT licensed.