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
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:
# 本地直接运行 - 只能单次执行
app = graph.compile()
result = app.invoke({"messages": [HumanMessage("Hello")]})Using LangGraph API:
# 通过 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 → 生产 URL4. LangGraph Studio
Role: Visual IDE, used for testing and debugging graphs
Two operating modes:
Local mode (recommended for development)
# 在项目目录运行
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/docsFeatures:
- 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
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
{
"dependencies": ["."],
"graphs": {
"agent": "./agent.py:graph"
},
"env": ".env"
}Field description:
dependencies: Python package dependency pathgraphs: graph definitions, using the format"graph_id": "file_path:variable_name"env: environment variable file path
3. agent.py example
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
cd /Users/brycewang/langchain-academy/module-1/studioStep 2: Start the service
langgraph devExample 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
%pip install --quiet -U langgraph_sdk langchain_coreCode Example
1. Connect to local server
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:
# ❌ 错误 - 同步调用会报错
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:
# 直接使用 await(仅在 Notebook 中)
result = await client.runs.stream(...)
# 在普通 Python 脚本中需要:
import asyncio
asyncio.run(main())2. Search for available assistants (picture)
# 搜索所有已部署的图
assistants = await client.assistants.search()
# 查看第一个助手
print(assistants[0])Example output:
{
'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 (fromlanggraph.json)config: configuration options (such as model parameters)version: version number (supports multi-version deployment)
3. Create a conversation thread
# 创建新线程用于跟踪状态
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:
# 用户 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
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:
| Parameters | Description | Example |
|---|---|---|
thread_id | Thread identifier | '1ef6c123-...' |
assistant_id | Assistant ID (picture name) | 'agent' |
input | Input status | {"messages": [...]} |
stream_mode | Streaming mode | "values" / "updates" |
LangGraph knowledge point: Stream Modes
LangGraph supports multiple streaming modes:
stream_mode="values"- Complete state flowpython# 每步后返回完整状态 {'messages': [msg1]} {'messages': [msg1, msg2]} {'messages': [msg1, msg2, msg3]}stream_mode="updates"- Incremental update streampython# 每步只返回新增的状态 {'messages': [msg1]} {'messages': [msg2]} {'messages': [msg3]}stream_mode="messages"- Message flow (messages only)python# 直接返回消息对象 AIMessage(content="...") ToolMessage(content="...")
Example of run output:
# 第 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:
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. 获得生产 URLStep 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
# 进入本地项目目录
cd /Users/brycewang/langchain-academy
# 添加远程仓库
git remote add origin https://github.com/your-username/langchain-academy.git
# 查看远程仓库
git remote -vGit knowledge point: remote
git remote add <名称> <URL>
# ^^^^^ ^^^^^^
# 别名 仓库地址
# 常见别名:
# origin - 默认主仓库
# upstream - 上游仓库(fork 时使用)1.3 Push code
# 确保所有文件已提交
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.localVerification:
# 检查是否误提交了敏感文件
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
- Click the "Deployments" tab in the left navigation bar
- Click the "+ New Deployment" button
- Select "Deploy from GitHub"
2.3 Connect to GitHub repository
Authorize GitHub:
- First time use requires authorizing LangSmith to access GitHub
- Choose to authorize all warehouses or specific warehouses
Select warehouse:
- Repository:
your-username/langchain-academy - Branch:
main
- Repository:
Configuration map path:
- LangGraph API config file:
module-1/studio/langgraph.json - This is the path of the
langgraph.jsonfile in the warehouse
- LangGraph API config file:
2.4 Set environment variables
**Why is it needed? **
- The cloud cannot access your local
.envfile - Requires manual configuration of API keys and other environment variables
**How to set it up? **
Method 1: Copy from local .env
# 查看本地环境变量
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
- Check that the configuration is correct
- Click the "Deploy" button
- Wait for deployment to complete (usually 1-2 minutes)
Deployment process:
[1/5] 克隆 GitHub 仓库
[2/5] 安装 Python 依赖
[3/5] 加载图定义
[4/5] 运行健康检查
[5/5] 分配 URL2.6 Get deployment URL
After successful deployment, you will get a unique URL:
https://langchain-academy-8011c561878d50b1883f7ed11b32d720.default.us.langgraph.appURL format:
https://<project-name>-<deployment-id>.<region>.langgraph.app
^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^
项目名称 唯一标识符 区域Step 3: Use SDK to call cloud deployment
3.1 Set LangSmith API Key
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:
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? **
- Visit LangSmith Settings
- Click "API Keys"
- Create a new key or copy an existing key
3.2 Connect to cloud service
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
urlparameters - The API calling method is exactly the same
3.3 Running Cloud Agent
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:
{'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
- Visit LangGraph Studio
- Log in to your LangSmith account
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
| Concept | Function | Analogy | Persistence |
|---|---|---|---|
| Assistant | Graph definition (code) | Program executable file | Yes |
| Thread | State instance (data) | The running process of the program | Yes |
# 一个 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
# 场景 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
| Features | Local development (langgraph dev) | Cloud deployment (LangGraph Cloud) |
|---|---|---|
| Purpose | Development and Testing | Production Environment |
| URL | http://127.0.0.1:2024 | https://xxx.langgraph.app |
| Environment Variables | .env File | LangSmith UI Configuration |
| Hot Reload | ✅ Support | ❌ Redeploy required |
| Persistence | Memory (lost on restart) | Database (permanent) |
| Monitoring | Basic logs | Complete tracking and analysis |
| Cost | Free | Pay per usage |
Python-specific knowledge points
1. Asynchronous programming (async/await)
**Why use asynchronous? **
Synchronous call (blocking):
# 调用 API → 等待响应 → 继续执行
result1 = call_api_1() # 等待 2 秒
result2 = call_api_2() # 等待 2 秒
# 总耗时:4 秒Asynchronous call (non-blocking):
# 同时发起多个请求,并发等待
result1 = await call_api_1() # 异步等待 2 秒
result2 = await call_api_2() # 异步等待 2 秒
# 总耗时:2 秒(并发执行)Basic syntax:
# 定义异步函数
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:
# ✅ 所有 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:
# 同步迭代
for item in [1, 2, 3]:
print(item)Asynchronous iterator:
# 异步迭代
async for chunk in async_generator():
print(chunk)Usage in LangGraph:
# 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):
# 如果 stream() 是同步的,代码会是这样:
for chunk in client.runs.stream_sync(...): # 假设有同步版本
print(chunk.data)3. getpass secure input
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:
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:
# 方式 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:
# .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
# 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-projectUsage process:
- Copy
.env.exampleto.env - Fill in the real API key
.envis not committed to Git (via.gitignore)
Multiple environment configuration
.env.development # 开发环境
.env.staging # 预发布环境
.env.production # 生产环境Load the specified environment:
import os
from dotenv import load_dotenv
env = os.getenv("ENV", "development")
load_dotenv(f".env.{env}")3. Version management
langgraph.json version control
{
"dependencies": ["."],
"graphs": {
"agent": "./agent.py:graph"
},
"env": ".env",
"version": "1.0.0"
}Git tag (Tag)
# 创建版本标签
git tag -a v1.0.0 -m "Release version 1.0.0"
# 推送标签到 GitHub
git push origin v1.0.0
# LangSmith 部署时可以指定标签
# 部署配置 → Git Ref → v1.0.04. Monitoring and Debugging
Enable LangSmith tracing
import os
# 启用追踪
os.environ["LANGSMITH_TRACING"] = "true"
os.environ["LANGSMITH_PROJECT"] = "my-agent-deployment"
# 运行 Agent
# 所有调用会自动记录到 LangSmithView Tracking:
- Visit LangSmith
- Select item
my-agent-deployment - 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
# 添加详细日志
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
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
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
# ❌ 等待完整响应(慢)
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
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:
# 部署 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:
{
"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:
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
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
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
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.
# 启动服务器
langgraph dev
# 修改 agent.py
# 保存文件后,终端会显示:
✓ Detected changes in agent.py
✓ Reloading graph...
✓ Graph reloaded successfullyNote: 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.
# 本地
client = get_client(url="http://127.0.0.1:2024")
# 云端
client = get_client(url="https://xxx.langgraph.app")
# 其他代码完全相同!Best Practice: Use environment variables
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:
# 获取 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
- Visit LangSmith → Deployments
- Choose your deployment
- Click on the "Logs" tab
- View error stack and call details
Method 2: Enable detailed tracking
# 在 langgraph.json 中添加
{
"env": ".env",
"tracing": {
"enabled": true,
"project": "my-project"
}
}Method 3: Local reproduction
# 使用相同的输入在本地测试
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)
# 修改代码
vim agent.py
# 提交并推送
git add .
git commit -m "Update agent logic"
git push origin main
# LangGraph Cloud 会自动检测并重新部署Method 2: Manually trigger deployment
- Visit LangSmith → Deployments
- Choose your deployment
- 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
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
{
"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":
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":
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
| Dimensions | Local development | Cloud deployment |
|---|---|---|
| Start Command | langgraph dev | By LangSmith UI |
| URL | http://127.0.0.1:2024 | https://xxx.langgraph.app |
| Environment Variables | .env File | LangSmith UI Configuration |
| Code Update | Just save the file (hot reload) | Push Git → Automatic deployment |
| State persistence | Memory (lost on restart) | Database (permanent) |
| Applicable scenarios | Development, testing, debugging | Production, multi-user, long-term operation |
| Cost | Free (local resources only) | Pay per usage |
| Observability | Basic logs | Complete 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
- Create project structure
- Define tools and diagrams
- Configure
langgraph.json - Start
langgraph dev - Test using SDK
Tip:
@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
- Create a GitHub repository
- Push code
- Configure deployment in LangSmith
- Get the production URL
- Use SDK to call cloud API
Exercise 3: Multithreaded Conversations
Task: Create 3 independent conversation threads to test state isolation
# 创建 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
- LangGraph Cloud official document
- LangGraph Studio User Guide
- LangGraph SDK API Reference
- LangSmith Tracking and Monitoring
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! 🚀