0.0 LangGraph Quick Case: Getting Started with Lightspeed
Preface: Why should we "get started at the speed of light"?
Case running and debugging are the best way to get started with programming and are also the core concept of writing this book. Through case running, we can quickly see some concepts and knowledge points related to LangGraph and Python, and then we will analyze them step by step and learn repeatedly until we are proficient.
In the world of AI Agent development, the theory is the same, and the practice is different. The design concept of this chapter is: Let you run the first Agent within 5 minutes, understand the core mode within 30 minutes, and master multi-Agent collaboration within 1 hour.
We have carefully designed 5 cases ranging from simple to complex, each of which:
- ✅ Code Streamlining: The core code does not exceed 100 lines
- ✅ Works out of the box: copy and paste to run
- ✅ Step-by-step: only introduce 1-2 new concepts per case
- ✅ Practical Orientation: All cases are based on official cases or real business scenarios
Learning Path:
案例 1: 基础聊天机器人 (5 分钟)
↓ 引入状态管理
案例 2: 带记忆的聊天机器人 (10 分钟)
↓ 引入工具调用
案例 3: 工具调用 Agent (15 分钟)
↓ 引入 ReAct 推理
案例 4: ReAct 搜索 Agent (20 分钟)
↓ 引入多 Agent 协作
案例 5: 多 Agent 协作系统 (30 分钟)Environment preparation
Install dependencies
# 核心依赖
pip install langchain langchain-openai langgraph
# 工具依赖(用于后续案例)
pip install tavily-python requestsAPI key configuration
All cases in this chapter use getpass() to securely read API keys and avoid hard-coded leaks:
import getpass
import os
def _set_env(var: str):
if not os.environ.get(var):
os.environ[var] = getpass.getpass(f"{var}: ")
# 在每个案例开头调用
_set_env("OPENAI_API_KEY")Case 1: The simplest chatbot
Goal: Build a conversational chatbot in 10 lines of code Core concept: StateGraph, MessagesState, node function
Complete code
import getpass
import os
def _set_env(var: str):
if not os.environ.get(var):
os.environ[var] = getpass.getpass(f"{var}: ")
_set_env("OPENAI_API_KEY")
from langchain_openai import ChatOpenAI
from langgraph.graph import StateGraph, MessagesState, START, END
# 定义节点:调用 LLM
def chatbot(state: MessagesState):
return {"messages": [ChatOpenAI(model="gpt-4o-mini").invoke(state["messages"])]}
# 构建图
graph = StateGraph(MessagesState)
graph.add_node("chatbot", chatbot)
graph.add_edge(START, "chatbot")
graph.add_edge("chatbot", END)
# 编译并运行
app = graph.compile()
response = app.invoke({"messages": [("user", "你好,请用一句话介绍 LangGraph")]})
print(response["messages"][-1].content)Running results
LangGraph 是一个用于构建和管理复杂语言模型工作流的框架,支持状态管理和多步骤推理。Key point analysis
- StateGraph: graph container, defining workflow structure
- MessagesState: built-in state type, automatically manages conversation history
- Node function: receive
stateand return the new status update - START/END: Special nodes, marking the entrance and exit of the graph
Case 2: Chatbot with memory
Goal: Let the Agent remember the conversation history and support multiple rounds of dialogue Core concept: MemorySaver, checkpoint persistence
Complete code
import getpass
import os
def _set_env(var: str):
if not os.environ.get(var):
os.environ[var] = getpass.getpass(f"{var}: ")
_set_env("OPENAI_API_KEY")
from langchain_openai import ChatOpenAI
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.checkpoint.memory import MemorySaver
# 定义节点
def chatbot(state: MessagesState):
return {"messages": [ChatOpenAI(model="gpt-4o-mini").invoke(state["messages"])]}
# 构建图(添加记忆)
graph = StateGraph(MessagesState)
graph.add_node("chatbot", chatbot)
graph.add_edge(START, "chatbot")
graph.add_edge("chatbot", END)
# 使用 MemorySaver 保存对话历史
memory = MemorySaver()
app = graph.compile(checkpointer=memory)
# 多轮对话
config = {"configurable": {"thread_id": "user_001"}}
# 第一轮
response1 = app.invoke(
{"messages": [("user", "我的名字是小明")]},
config=config
)
print("Round 1:", response1["messages"][-1].content)
# 第二轮(Agent 应该记住名字)
response2 = app.invoke(
{"messages": [("user", "我的名字是什么?")]},
config=config
)
print("Round 2:", response2["messages"][-1].content)Running results
Round 1: 你好,小明!很高兴认识你。有什么我可以帮助你的吗?
Round 2: 你的名字是小明。Key point analysis
- MemorySaver: Memory checkpoint saver, stores conversation history
- thread_id: session identifier, different users use different IDs
- Automatic accumulation:
MessagesStatewill automatically add new messages to the history
Case 3: Tool calls Agent
Goal: Allow Agent to call external tools (calculator, weather query) Core concepts: tool binding, conditional edges, tool nodes
Complete code
import getpass
import os
def _set_env(var: str):
if not os.environ.get(var):
os.environ[var] = getpass.getpass(f"{var}: ")
_set_env("OPENAI_API_KEY")
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.prebuilt import ToolNode
# 定义工具
@tool
def calculator(expression: str) -> str:
"""执行数学计算。输入:数学表达式(如 '2+3*4')"""
try:
return str(eval(expression))
except:
return "计算错误"
@tool
def get_weather(city: str) -> str:
"""查询城市天气。输入:城市名称"""
# 模拟天气查询
weather_db = {
"北京": "晴天,15°C",
"上海": "多云,18°C",
"深圳": "阴天,22°C"
}
return weather_db.get(city, "未知城市")
tools = [calculator, get_weather]
# 定义节点
llm = ChatOpenAI(model="gpt-4o-mini")
llm_with_tools = llm.bind_tools(tools)
def chatbot(state: MessagesState):
return {"messages": [llm_with_tools.invoke(state["messages"])]}
# 条件边:判断是否需要调用工具
def should_continue(state: MessagesState):
last_message = state["messages"][-1]
if hasattr(last_message, "tool_calls") and last_message.tool_calls:
return "tools"
return END
# 构建图
graph = StateGraph(MessagesState)
graph.add_node("chatbot", chatbot)
graph.add_node("tools", ToolNode(tools))
graph.add_edge(START, "chatbot")
graph.add_conditional_edges("chatbot", should_continue, ["tools", END])
graph.add_edge("tools", "chatbot")
app = graph.compile()
# 测试
response = app.invoke({
"messages": [("user", "北京的天气怎么样?计算一下 25 * 4 + 10")]
})
print(response["messages"][-1].content)Running results
北京今天是晴天,气温 15°C。计算结果:25 * 4 + 10 = 110。Key point analysis
- @tool decorator: Convert Python functions into LLM callable tools
- bind_tools(): Bind the tools to LLM so that it knows which tools can be called
- ToolNode: A node dedicated to executing tool calls
- Conditional edge: dynamic routing based on the output of LLM (whether there are tool_calls)
- Loop: tools → chatbot forms a loop, supporting multiple tool calls
Case 4: ReAct Reasoning Agent
Goal: Build an Agent that can "think-act-observe" and integrate a real search engine Core concepts: ReAct mode, Tavily search, system prompt words
Complete code
import getpass
import os
def _set_env(var: str):
if not os.environ.get(var):
os.environ[var] = getpass.getpass(f"{var}: ")
_set_env("OPENAI_API_KEY")
_set_env("TAVILY_API_KEY") # 注册:https://tavily.com
from langchain_openai import ChatOpenAI
from langchain_community.tools.tavily_search import TavilySearchResults
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.prebuilt import ToolNode
# 初始化工具
search = TavilySearchResults(max_results=2)
tools = [search]
# 定义 Agent(添加 ReAct 系统提示词)
llm = ChatOpenAI(model="gpt-4o-mini")
llm_with_tools = llm.bind_tools(tools)
def agent(state: MessagesState):
# 添加 ReAct 提示词
system_message = """你是一个 ReAct (Reasoning + Acting) Agent。
处理用户问题时,请遵循以下步骤:
1. Thought(思考):分析问题需要什么信息
2. Action(行动):决定调用哪个工具
3. Observation(观察):分析工具返回的结果
4. Answer(回答):基于观察给出最终答案
始终展示你的推理过程。"""
messages = [{"role": "system", "content": system_message}] + state["messages"]
return {"messages": [llm_with_tools.invoke(messages)]}
def should_continue(state: MessagesState):
last_message = state["messages"][-1]
if hasattr(last_message, "tool_calls") and last_message.tool_calls:
return "tools"
return END
# 构建图
graph = StateGraph(MessagesState)
graph.add_node("agent", agent)
graph.add_node("tools", ToolNode(tools))
graph.add_edge(START, "agent")
graph.add_conditional_edges("agent", should_continue, ["tools", END])
graph.add_edge("tools", "agent")
app = graph.compile()
# 测试
response = app.invoke({
"messages": [("user", "2024年诺贝尔物理学奖获得者是谁?他们的主要贡献是什么?")]
})
print(response["messages"][-1].content)Running results
**Thought**: 用户询问 2024 年诺贝尔物理学奖的获得者,我需要搜索最新信息。
**Action**: 使用搜索工具查询 "2024 Nobel Prize Physics winner"。
**Observation**: 搜索结果显示,2024 年诺贝尔物理学奖授予了 John Hopfield 和 Geoffrey Hinton,
表彰他们在人工神经网络领域的开创性发现。
**Answer**: 2024 年诺贝尔物理学奖的获得者是 John Hopfield 和 Geoffrey Hinton。
他们的主要贡献是:
- Hopfield: 发明了 Hopfield 网络,一种可以存储和重建模式的联想记忆网络
- Hinton: 开发了反向传播算法和深度学习的关键技术,被誉为"深度学习之父"Key point analysis
- ReAct Mode: Guide LLM to display the reasoning process through system prompt words
- Tavily Search: Enterprise-level search API, optimized for AI Agent
- Circular Reasoning: Agent can call the tool multiple times to gradually improve the answer
Case 5: Multi-Agent collaboration system
Goal: Build a team collaboration system of "researcher + chart analyst + report writer" Core Concepts: Multi-Agent, message routing, subgraph
Complete code
import getpass
import os
def _set_env(var: str):
if not os.environ.get(var):
os.environ[var] = getpass.getpass(f"{var}: ")
_set_env("OPENAI_API_KEY")
from langchain_openai import ChatOpenAI
from langgraph.graph import StateGraph, MessagesState, START, END
from typing import Literal
# 定义 3 个专业 Agent
llm = ChatOpenAI(model="gpt-4o-mini")
def researcher(state: MessagesState):
"""研究员:负责信息收集"""
system_msg = "你是资深研究员,擅长收集和分析行业信息。请提供数据和趋势分析。"
messages = [{"role": "system", "content": system_msg}] + state["messages"]
response = llm.invoke(messages)
return {"messages": [response]}
def chart_analyst(state: MessagesState):
"""图表分析师:负责数据可视化建议"""
system_msg = "你是数据可视化专家,擅长将数据转化为图表建议。请推荐合适的图表类型和关键指标。"
messages = [{"role": "system", "content": system_msg}] + state["messages"]
response = llm.invoke(messages)
return {"messages": [response]}
def report_writer(state: MessagesState):
"""报告撰写员:整合信息并生成最终报告"""
system_msg = "你是专业报告撰写员,擅长将研究结果和图表建议整合成结构清晰的报告。"
messages = [{"role": "system", "content": system_msg}] + state["messages"]
response = llm.invoke(messages)
return {"messages": [response]}
# Supervisor:决定下一步调用哪个 Agent
def supervisor(state: MessagesState) -> Literal["researcher", "chart_analyst", "report_writer", "end"]:
"""管理者:协调各个 Agent 的工作流程"""
messages = state["messages"]
# 简单的状态机逻辑
user_message = messages[0].content if messages else ""
response_count = len([m for m in messages if hasattr(m, "response_metadata")])
if response_count == 0:
return "researcher" # 第一步:研究
elif response_count == 1:
return "chart_analyst" # 第二步:图表分析
elif response_count == 2:
return "report_writer" # 第三步:报告撰写
else:
return "end" # 完成
# 构建图
graph = StateGraph(MessagesState)
# 添加节点
graph.add_node("researcher", researcher)
graph.add_node("chart_analyst", chart_analyst)
graph.add_node("report_writer", report_writer)
# 添加边(串行工作流)
graph.add_edge(START, "researcher")
graph.add_edge("researcher", "chart_analyst")
graph.add_edge("chart_analyst", "report_writer")
graph.add_edge("report_writer", END)
app = graph.compile()
# 测试
response = app.invoke({
"messages": [("user", "请帮我分析一下 2024 年生成式 AI 市场的发展趋势,并给出报告")]
})
# 打印每个 Agent 的输出
print("=== 研究员输出 ===")
print(response["messages"][1].content[:200] + "...\n")
print("=== 图表分析师输出 ===")
print(response["messages"][2].content[:200] + "...\n")
print("=== 最终报告 ===")
print(response["messages"][3].content)Running results
=== 研究员输出 ===
根据市场研究,2024 年生成式 AI 市场呈现以下趋势:
1. 市场规模预计达到 500 亿美元,同比增长 150%
2. 主要应用领域:内容创作(40%)、代码生成(25%)、客户服务(20%)
3. 技术突破:多模态模型、实时推理、成本优化...
=== 图表分析师输出 ===
针对上述数据,建议使用以下可视化方案:
1. **市场规模趋势图**(折线图):展示 2022-2024 年市场增长曲线
2. **应用领域占比**(饼图):突出内容创作的主导地位
3. **技术成熟度雷达图**:对比多模态、实时推理等技术的成熟度...
=== 最终报告 ===
# 2024 年生成式 AI 市场发展趋势报告
## 一、市场概况
2024 年生成式 AI 市场规模预计达到 500 亿美元,同比增长 150%,标志着该行业进入快速发展期。
## 二、应用分布
- **内容创作**(40%):文本、图像、视频生成
- **代码生成**(25%):GitHub Copilot、Cursor 等工具
- **客户服务**(20%):智能客服、对话机器人
## 三、数据可视化建议
建议使用折线图展示市场增长曲线,饼图突出应用领域占比,雷达图对比技术成熟度。
## 四、结论与展望
生成式 AI 正在从技术创新走向商业化落地,预计 2025 年将出现更多杀手级应用。Key point analysis
- Specialized Division of Labor: Each Agent has a clear role and system prompt word
- Serial workflow: researcher → chart_analyst → report_writer
- Status Accumulation: Each Agent can see all previous conversation history
- Scalability: More professional Agents (such as data_validator, editor) can be easily added
Advanced extensions
More complex multi-agent systems can use:
- Parallel Execution: Multiple Agents work at the same time to improve efficiency
- Dynamic Routing: Supervisor dynamically selects Agents based on task complexity
- Human-computer collaboration: Add manual review breakpoints at key nodes
Selected interpretations of the official case library
The official LangGraph repository (https://github.com/langchain-ai/langgraph/tree/main/examples) contains more than 50 production-ready examples across a range of application scenarios. Selected categories include:
🤖 Agent type
1. chatbot-simulation-evaluation/
- FEATURE: Simulation framework for evaluating chatbot quality
- Applicable scenarios: Automated testing before product launch
- Core Technology: simulated user dialogue, multi-dimensional scoring
2. multi-agent/
- Function: Complete implementation of multi-Agent collaboration
- Applicable scenarios: Complex task decomposition, team collaboration simulation
- Core Technology: Supervisor mode, message routing
3. customer-support/
- Function: Enterprise-level customer service system
- Applicable scenarios: E-commerce, SaaS customer support
- Core Technology: Intent recognition, work order system integration, sentiment analysis
🧠 Advanced Technology
4. rag/
- Function: Retrieval-Augmented Generation
- Applicable scenarios: Knowledge base Q&A, document assistant
- Core Technology: Vector retrieval, context injection, reference tracing
- Recommendation Index: ⭐⭐⭐⭐⭐ (most commonly used mode)
5. reflection/
- Feature: Agent self-reflection and optimization
- Applicable scenarios: code review, content proofreading, paper writing
- Core Technology: Self-criticism, iterative improvement
6. plan-execute/
- Function: Task decomposition mode of planning first and then executing
- Applicable scenarios: complex project management, multi-step tasks
- Core Technology: Task disassembly, dependency management, dynamic adjustment
7. rewoo/
- Function: Reasoning Without Observation
- Applicable Scenarios: Tasks that require advance planning (such as travel planning)
- Core Technology: Pre-generate complete plans and batch tool calls
🔧 Technical ability
8. memory/
- Function: Implementation of multiple memory mechanisms
- Applicable scenarios: long-term dialogue, user portrait construction
- Core Technology: short-term memory, long-term memory, memory retrieval
9. tool-calling/
- Function: Various modes of tool calling
- Applicable scenarios: API integration, external service calling
- Core Technology: Parallel tool invocation, error retry, result verification
10. streaming/
- Function: Streaming output and intermediate result display
- Applicable scenarios: real-time dialogue, long text generation
- Core Technology: Token streaming, progress feedback
11. persistence/
- FEATURE: State persistence and recovery
- Applicable scenarios: long-running tasks, resumed downloads from breakpoints
- Core Technology: CheckPoint, status serialization
🌐 Professional fields
12. web-navigation/
- FEATURE: Automated web browsing and information extraction
- Applicable scenarios: web crawler, competitive product analysis, price monitoring
- Core Technology: Playwright integration, DOM parsing
13. extraction/
- Function: Structured information extraction
- Applicable scenarios: resume analysis, contract element extraction, invoice identification
- Core Technology: Schema definition, field validation, batch processing
14. code-assistant/
- FEATURE: Code generation and refactoring assistant
- Applicable scenarios: IDE plug-ins, code review, auto-completion
- Core Technology: AST parsing, syntax checking, unit test generation
📊 Assessment and Monitoring
15. llm-compiler/
- Feature: Parallel optimized Agent execution engine
- Applicable scenarios: Production environments with high performance requirements
- Core Technology: Task DAG, parallel scheduling, dependency management
16. chatbot-simulation-evaluation/
- FEATURE: Automated assessment framework
- Applicable scenarios: AB testing, model selection, prompt word optimization
- Core Technology: Simulation dialogue, indicator calculation, statistical analysis
🎯 Recommended learning path
If you are a novice, it is recommended to study the official cases in the following order:
第 1 层:基础模式
├─ chatbot/ # 基础对话
├─ tool-calling/ # 工具集成
└─ streaming/ # 流式输出
第 2 层:高级技术
├─ rag/ # 检索增强(必学)
├─ memory/ # 记忆管理
└─ reflection/ # 自我优化
第 3 层:复杂系统
├─ multi-agent/ # 多 Agent 协作
├─ plan-execute/ # 任务规划
└─ customer-support/ # 完整业务案例
第 4 层:专业领域
├─ web-navigation/ # 网页自动化
├─ extraction/ # 信息抽取
└─ code-assistant/ # 代码助手💡 Suggestions for studying official cases
Clone repository:
bashgit clone https://github.com/langchain-ai/langgraph.git cd langgraph/examplesRun on demand:
- Each case has independent README and dependency instructions
- It is recommended to read the README first to understand the design ideas
- Run the code again and observe the actual effect
Renovation Practice:
- Don't just run official code
- Try modifying prompt words, adding new tools, and adjusting workflow
- Migrate the case to your actual business scenario
Source code reading:
- The official case code is of extremely high quality and contains a large number of best practices
- Focus on error handling, logging, and performance optimization -Learn code structure and module division
Summary and next steps
Core skills you have seen
Through the 5 cases in this chapter, you have initially seen:
✅ Case 1: StateGraph basics, message flow ✅ Case 2: Checkpoint persistence, multiple rounds of dialogue ✅ Case 3: Tool calling, conditional routing ✅ Case 4: ReAct reasoning and search integration ✅ Case 5: Multi-Agent collaboration, role division
From "getting started at light speed" to "real mastery"
This chapter is designed to be a "quick start", allowing you to intuitively look at and get started with LangGraph. Obviously, the capabilities of LangGraph go far beyond this. We will also explain the core concepts of LangGraph repeatedly to help everyone fully digest it.
The following chapters will explain in depth:
- Chapter 1: The essential differences between Chain, Router and Agent
- Chapter 2: Advanced Design Patterns of State Schema
- Chapter 3: Breakpoint Debugging and Time Travel
- Chapter 4: Parallel Execution, Subgraphs, Map-Reduce
- Chapter 5-6: Production deployment, monitoring, security
Practical practice suggestions
Before continuing, it is highly recommended to complete the following exercises:
- Renovation Case 3: Add a "translation tool" to allow Agent to translate text
- Extended Case 4: Let ReAct Agent support multiple searches and information synthesis
- Optimization Case 5: Add a "Quality Inspector" Agent to review the final report
- Combined Case: Combine RAG (Retrieval Enhancement) and ReAct to build an "intelligent customer service"
Recommended resources
- Official Document: https://langchain-ai.github.io/langgraph/
- Official Case: https://github.com/langchain-ai/langgraph/tree/main/examples
- LangChain Academy: https://academy.langchain.com/courses/intro-to-langgraph
- Discord Community: https://discord.gg/langchain
Remember: Building an Agent is like building blocks. The 5 cases in this chapter are the most basic "building blocks". Once you master them, you can combine them into endless possible AI applications.
Next step: Go to Chapter 1 to gain a deeper understanding of LangGraph’s core concepts and design philosophy.