LangGraph Router Detailed interpretation
📚 Overview
This document explains in detail the Router mode in LangGraph. This is the underlying concept of the Agent system, where LLM intelligently determines the execution path: respond directly to the user or invoke a tool. Router is a key introductory case for understanding LangGraph's conditional edges and dynamic control flow.
🎯 Core Concept
What is Router?
Router is a design pattern that lets LLM act as a "traffic commander":
- Receive Input - User sends query
- Intelligent Judgment - Whether tools are needed for LLM analysis
- Dynamic Routing - Automatically select execution path:
- Path A: direct answer (no tools required)
- Path B: Call the tool to obtain information and then answer
Why is Router important?
This is the essence of Agent:
- Agent ≠ simple function call
- Agent = LLM autonomous decision-making + dynamic execution path
- Router is the simplest but most core Agent mode
Classic application scenarios
- Intelligent Customer Service: Answer simple questions directly, query the database for complex questions
- Math Assistant: answer text questions directly, call the calculator for calculation questions
- Information Query: Direct answers to basic knowledge, real-time information call search API
- Multifunctional Bot: Automatically select function modules based on intent
🎭 Practical case: Intelligent Math Assistant
We will build a mathematical assistant that can "think" and demonstrate the complete process of Router:
Requirements:
- The user asks "Hello" → LLM answers directly without tools
- The user asks "What is 2 times 3?" → LLM calls the
multiplytool to calculate
System architecture diagram
用户输入消息
↓
[tool_calling_llm] ← LLM 分析并决策
↓
(条件判断)
↓
/ \
/ \
↓ ↓
直接回答 [tools] 调用工具
↓ ↓
END ENDKey Design:
- A node:
tool_calling_llm(LLM with tool bound) - A conditional edge:
tools_condition(automatically determine whether tools are needed) - A tool node:
tools(performs the actual calculation)
🔧 Detailed explanation of code implementation
1. Environment preparation
# 安装依赖
%pip install --quiet -U langchain_openai langchain_core langgraph langgraph-prebuilt
# 设置 API Key
import os, getpass
def _set_env(var: str):
if not os.environ.get(var):
os.environ[var] = getpass.getpass(f"{var}: ")
_set_env("OPENAI_API_KEY")Description:
langgraph-prebuilt: Contains pre-built components such asToolNodeandtools_conditiongetpass: Enter sensitive information securely (API Key will not be displayed on the screen)
2. Define tools and LLM
from langchain_openai import ChatOpenAI
def multiply(a: int, b: int) -> int:
"""Multiply a and b.
Args:
a: first int
b: second int
"""
return a * b
llm = ChatOpenAI(model="gpt-4o")
llm_with_tools = llm.bind_tools([multiply])Python knowledge points: functions as tools
In LangChain, ordinary Python functions can be directly converted into LLM tools:
Key elements:
- Function name: LLM is used to identify tools (such as
multiply) - Docstring: LLM is used to understand the purpose of the tool (very important!)
- Type hint: LLM is used to understand parameter types (
a: int, b: int) - Return type: LLM is used to understand the output type (
-> int)
Example:
def multiply(a: int, b: int) -> int:
"""Multiply a and b.""" # ← LLM 看到这个描述
return a * b
# LLM 内部理解为:
# {
# "name": "multiply",
# "description": "Multiply a and b.",
# "parameters": {
# "a": {"type": "integer"},
# "b": {"type": "integer"}
# }
# }LangChain knowledge points: bind_tools
llm_with_tools = llm.bind_tools([multiply])Function:
- "Bind" tools to LLM so LLM knows it can call them
- LLM will not automatically execute the tool, but will only return the command "I want to call this tool"
- Actual execution is done by
ToolNode
Workflow:
用户: "2 乘以 3 是多少?"
↓
llm_with_tools.invoke(...)
↓
LLM 返回:AIMessage(tool_calls=[{
"name": "multiply",
"args": {"a": 2, "b": 3},
"id": "call_123"
}])
↓
ToolNode 执行 multiply(2, 3)
↓
返回:ToolMessage(content="6", tool_call_id="call_123")3. Define status
from langgraph.graph import MessagesState
# MessagesState 是预定义的状态类
# 等价于:
# class MessagesState(TypedDict):
# messages: Annotated[list[BaseMessage], add_messages]LangGraph knowledge point: MessagesState
MessagesState is the standard message state provided by LangGraph:
Features:
messagesfield: stores conversation history- Automatically use
add_messagesreducer: intelligently merge new messages
The smart thing about add_messages:
# 场景 1:追加新消息
state = {"messages": [HumanMessage("你好")]}
update = {"messages": [AIMessage("你好!")]}
# 结果:[HumanMessage("你好"), AIMessage("你好!")]
# 场景 2:更新现有消息(通过 ID)
state = {"messages": [AIMessage("思考中...", id="msg1")]}
update = {"messages": [AIMessage("2 * 3 = 6", id="msg1")]}
# 结果:[AIMessage("2 * 3 = 6", id="msg1")] # 替换而不是追加4. Build core nodes
def tool_calling_llm(state: MessagesState):
return {"messages": [llm_with_tools.invoke(state["messages"])]}Function details:
- Input:
state["messages"]- Current conversation history - Processing:
llm_with_tools.invoke(...)- LLM analysis and decision-making - Output:
{"messages": [...]}- response returned by LLM
Possible output types:
Case A: Direct answer (no tool call)
AIMessage(content="你好!我能帮你什么?")Case B: Calling Tools
AIMessage(
content="", # 内容为空
tool_calls=[{
"name": "multiply",
"args": {"a": 2, "b": 3},
"id": "call_abc123"
}]
)5. Use pre-built components: ToolNode and tools_condition
from langgraph.prebuilt import ToolNode, tools_condition
# 创建工具节点
tool_node = ToolNode([multiply])
# tools_condition 是预构建的条件函数LangGraph knowledge point: ToolNode
The role of ToolNode:
- Automate tool calls for LLM requests
- Receive
AIMessagewithtool_calls - Return
ToolMessagecontaining execution results
Internal implementation logic:
# ToolNode 内部类似这样:
def tool_node(state: MessagesState):
results = []
last_message = state["messages"][-1]
for tool_call in last_message.tool_calls:
# 找到对应的工具函数
tool = find_tool(tool_call["name"]) # 如 multiply
# 执行工具
result = tool(**tool_call["args"]) # multiply(a=2, b=3)
# 创建 ToolMessage
results.append(ToolMessage(
content=str(result), # "6"
tool_call_id=tool_call["id"]
))
return {"messages": results}LangGraph knowledge point: tools_condition
The role of tools_condition:
- Automatically check if the last message contains
tool_calls - If there is a tool call → route to tool node
- If no tool is called → route to END
Internal implementation logic:
# tools_condition 内部类似这样:
def tools_condition(state: MessagesState):
last_message = state["messages"][-1]
# 检查是否有工具调用
if hasattr(last_message, "tool_calls") and last_message.tool_calls:
return "tools" # 路由到工具节点
else:
return END # 直接结束6. Build the diagram
from langgraph.graph import StateGraph, START, END
# 创建图
builder = StateGraph(MessagesState)
# 添加节点
builder.add_node("tool_calling_llm", tool_calling_llm)
builder.add_node("tools", ToolNode([multiply]))
# 添加边
builder.add_edge(START, "tool_calling_llm")
# 添加条件边
builder.add_conditional_edges(
"tool_calling_llm",
tools_condition,
)
builder.add_edge("tools", END)
# 编译
graph = builder.compile()LangGraph knowledge points: Detailed explanation of conditional edges
builder.add_conditional_edges(
"tool_calling_llm", # 源节点
tools_condition, # 条件函数
)How it works:
tool_calling_llmnode execution completed- Call
tools_condition(state)to determine routing - The return value of
tools_conditiondetermines the next step:- Return to
"tools"→ Entertoolsnode - Return to
END→ end execution
- Return to
Complete execution process:
Scenario A: Simple greeting
用户: "你好"
↓
[tool_calling_llm] → AIMessage(content="你好!")
↓
tools_condition 检测:无 tool_calls
↓
路由到 ENDScenario B: Math Calculation
用户: "2 乘以 3 是多少?"
↓
[tool_calling_llm] → AIMessage(tool_calls=[multiply(2,3)])
↓
tools_condition 检测:有 tool_calls
↓
路由到 [tools]
↓
[tools] 执行 multiply(2,3) → ToolMessage(content="6")
↓
ENDGraph structure visualization:
START
↓
[tool_calling_llm]
↓
(条件判断)
/ \
/ \
↓ ↓
END [tools]
↓
END7. Execution diagram
Test scenario 1: Tool call
from langchain_core.messages import HumanMessage
messages = [HumanMessage(content="Hello, what is 2 multiplied by 2?")]
result = graph.invoke({"messages": messages})
for m in result['messages']:
m.pretty_print()Output:
================================ Human Message =================================
Hello, what is 2 multiplied by 2?
================================== Ai Message ==================================
Tool Calls:
multiply (call_abc123)
Call ID: call_abc123
Args:
a: 2
b: 2
================================= Tool Message =================================
Name: multiply
4Execution process analysis:
- HumanMessage Enter the system
- AIMessage returns the tool call request
- ToolMessage returns the calculation result
4
Test Scenario 2: Direct Answer
messages = [HumanMessage(content="Hello world.")]
result = graph.invoke({"messages": messages})
for m in result['messages']:
m.pretty_print()Output:
================================ Human Message =================================
Hello world.
================================== Ai Message ==================================
Hello! How can I assist you today?Execution process analysis:
- HumanMessage Enter the system
- AIMessage Direct answer, no tool call
- Go directly to END
🎓 Summary of core knowledge points
LangGraph-specific concepts
1. Router mode
Definition: LLM serves as a decision-making center and dynamically selects execution paths
Implementation method:
- Node:
tool_calling_llm(LLM for binding tool) - Conditional edge:
tools_condition(auto routing) - Tool Node:
ToolNode(execution tool)
Compare traditional process:
| Features | Traditional Process | Router Mode |
|---|---|---|
| Path decision | Hard-coded rules | LLM intelligent judgment |
| Flexibility | Low | High |
| Scalability | Poor (needs to modify the code) | Strong (just add tools) |
| Adaptability | Fixed scene | Dynamic adaptation |
2. Conditional Edge
builder.add_conditional_edges(
source_node, # 源节点
condition_func, # 条件函数:state → 目标节点名称
)Return value of conditional function:
- String (such as
"tools"): route to the specified node END: end execution- List (advanced usage): multiple possible targets
Example: Custom Conditional Function
def my_condition(state: MessagesState):
last_msg = state["messages"][-1]
if last_msg.content == "结束":
return END
elif "计算" in last_msg.content:
return "calculator"
else:
return "chat"
builder.add_conditional_edges("start", my_condition)3. ToolNode
Function: Automatically execute the tool and return the results
Key Features:
- Receive
tool_callsinAIMessage - Automatic matching and execution of corresponding tools
- Return
ToolMessagecontaining results -Support concurrent execution of multiple tools
Equivalent code for manually implementing ToolNode:
def manual_tool_node(state: MessagesState):
last_message = state["messages"][-1]
tool_calls = last_message.tool_calls
tool_messages = []
for call in tool_calls:
if call["name"] == "multiply":
result = multiply(**call["args"])
tool_messages.append(ToolMessage(
content=str(result),
tool_call_id=call["id"]
))
return {"messages": tool_messages}4. tools_condition
Function: Standardized tool call detection function
Equivalent implementation:
def tools_condition(state: MessagesState):
last_msg = state["messages"][-1]
if hasattr(last_msg, "tool_calls") and last_msg.tool_calls:
return "tools"
return END**Why use pre-built functions? **
- Fully tested
- Handle edge cases (such as empty messages, format errors, etc.)
- Keep your code simple
Python-specific knowledge points
1. The role of type hints in tools
def multiply(a: int, b: int) -> int:
"""Multiply a and b."""
return a * bImportance of type hints:
- LLM generates correct parameters based on type hints
- Runtime verification (with Pydantic)
- IDE code completion and inspection
Comparison:
# ❌ 不好的实践
def multiply(a, b): # 没有类型提示
return a * b
# ✅ 好的实践
def multiply(a: int, b: int) -> int:
"""Multiply a and b."""
return a * b2. The key role of Docstring
**Docstring is the only way LLM understands tools! **
def multiply(a: int, b: int) -> int:
"""Multiply a and b.
Args:
a: first int
b: second int
"""
return a * bLLM will read:
- Line 1: A short description of the tool ("Multiply a and b.")
- Args part: detailed description of parameters
Example: Good vs Bad Docstring
# ❌ 不好
def process_data(x, y):
"""Process data.""" # 太模糊
return x + y
# ✅ 好
def calculate_total_price(unit_price: float, quantity: int) -> float:
"""Calculate the total price by multiplying unit price and quantity.
Args:
unit_price: Price per unit in USD
quantity: Number of units to purchase
Returns:
Total price in USD
"""
return unit_price * quantity3. getpass module
import getpass
os.environ["OPENAI_API_KEY"] = getpass.getpass("OPENAI_API_KEY: ")Function:
- Enter sensitive information securely
- It will not be displayed on the screen when typing (similar to entering a password)
- Prevent API Key from being accidentally leaked
💡 Best Practices
1. Well-designed tools
Principle 1: Single Responsibility
# ✅ 好的设计 - 每个工具只做一件事
def multiply(a: int, b: int) -> int:
"""Multiply two numbers."""
return a * b
def add(a: int, b: int) -> int:
"""Add two numbers."""
return a + b
# ❌ 不好的设计 - 一个工具做多件事
def calculate(operation: str, a: int, b: int) -> int:
"""Perform various calculations."""
if operation == "multiply":
return a * b
elif operation == "add":
return a + b**Why? ** LLM makes it easier to understand and choose focused tools.
Principle 2: Clear naming and documentation
# ✅ 好
def get_current_weather(location: str, unit: str = "celsius") -> dict:
"""Get the current weather for a specific location.
Args:
location: City name or zip code
unit: Temperature unit ('celsius' or 'fahrenheit')
Returns:
Dictionary with temperature, humidity, and conditions
"""
pass
# ❌ 不好
def get_data(loc: str, u: str = "c") -> dict:
"""Get data."""
passPrinciple 3: Return structured data
# ✅ 好 - 返回结构化数据
def multiply(a: int, b: int) -> int:
return a * b # 返回数字
# 或者
def get_user_info(user_id: str) -> dict:
return {
"name": "Alice",
"age": 30,
"email": "alice@example.com"
}
# ❌ 不好 - 返回非结构化字符串
def get_user_info(user_id: str) -> str:
return "Name: Alice, Age: 30, Email: alice@example.com"2. Design skills of conditional edges
Tip 1: Clear conditional logic
# ✅ 好 - 逻辑清晰
def route_decision(state: MessagesState):
last_msg = state["messages"][-1]
# 明确的条件检查
if hasattr(last_msg, "tool_calls") and last_msg.tool_calls:
return "tools"
return END
# ❌ 不好 - 逻辑复杂
def route_decision(state: MessagesState):
return "tools" if state["messages"][-1].tool_calls if hasattr(state["messages"][-1], "tool_calls") else False else ENDTip 2: Handle edge cases
def safe_route_decision(state: MessagesState):
# 检查消息列表是否为空
if not state["messages"]:
return END
last_msg = state["messages"][-1]
# 检查是否为 AI 消息
if not isinstance(last_msg, AIMessage):
return END
# 检查是否有工具调用
if hasattr(last_msg, "tool_calls") and last_msg.tool_calls:
return "tools"
return END3. Best practices for state management
Practice 1: Keep message history intact
# ✅ 好 - 保留完整对话历史
def tool_calling_llm(state: MessagesState):
# 传递所有历史消息
return {"messages": [llm_with_tools.invoke(state["messages"])]}
# ❌ 不好 - 只使用最后一条消息
def tool_calling_llm(state: MessagesState):
# 丢失了上下文
return {"messages": [llm_with_tools.invoke([state["messages"][-1]])]}**Why is it important? ** LLM requires full context to make correct decisions.
Practice 2: Correctly return the message list
# ✅ 正确 - 返回列表
def my_node(state: MessagesState):
response = llm.invoke(...)
return {"messages": [response]} # 注意是列表
# ❌ 错误 - 返回单个消息
def my_node(state: MessagesState):
response = llm.invoke(...)
return {"messages": response} # 会出错🚀 Advanced skills
1. Multi-tool Router
Expand to multiple tools:
def add(a: int, b: int) -> int:
"""Add two numbers."""
return a + b
def multiply(a: int, b: int) -> int:
"""Multiply two numbers."""
return a * b
def divide(a: float, b: float) -> float:
"""Divide a by b."""
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
# 绑定多个工具
llm_with_tools = llm.bind_tools([add, multiply, divide])
# ToolNode 自动处理所有工具
tool_node = ToolNode([add, multiply, divide])LLM automatically selects the correct tool:
- "2 plus 3" → call
add - "4 times 5" → call
multiply - "10 divided by 2" → call
divide
2. Tool chain call
LLM can call multiple tools in succession:
# 用户:"先计算 2*3,然后把结果加 5"
# 第一轮
# LLM → multiply(2, 3)
# Tool → 6
# 第二轮(LLM 看到结果 6)
# LLM → add(6, 5)
# Tool → 11
# 第三轮(LLM 看到结果 11)
# LLM → "结果是 11"Implementation method: Add edge loop
# 修改图结构
builder.add_edge("tools", "tool_calling_llm") # 工具执行后回到 LLM
# 现在流程变成:
# START → tool_calling_llm → tools → tool_calling_llm → tools → ... → END3. Router with error handling
class SafeToolNode:
def __init__(self, tools):
self.tool_node = ToolNode(tools)
def __call__(self, state: MessagesState):
try:
return self.tool_node(state)
except Exception as e:
# 返回错误消息
return {"messages": [ToolMessage(
content=f"Error executing tool: {str(e)}",
tool_call_id=state["messages"][-1].tool_calls[0]["id"]
)]}
# 使用
builder.add_node("tools", SafeToolNode([multiply]))4. Customize tool execution logic
def custom_tool_node(state: MessagesState):
last_message = state["messages"][-1]
tool_calls = last_message.tool_calls
results = []
for call in tool_calls:
# 记录工具调用
print(f"Calling tool: {call['name']} with args: {call['args']}")
# 执行工具
if call["name"] == "multiply":
result = multiply(**call["args"])
# 添加额外信息
results.append(ToolMessage(
content=f"Result: {result} (computed at {datetime.now()})",
tool_call_id=call["id"]
))
return {"messages": results}📊 Router mode comparison
Router vs simple LLM call
| Features | Simple LLM call | Router mode |
|---|---|---|
| Tool support | None | Yes |
| Dynamic decision-making | None | Yes |
| Scalability | Low | High |
| Complexity | Low | Medium |
| Applicable scenarios | Pure dialogue | Scenarios that require tools |
Router vs ReAct Agent
| Features | Router | ReAct Agent |
|---|---|---|
| Loop execution | None (single) | Yes (multiple rounds of inference) |
| Complexity | Simple | Complex |
| Applicable tasks | Single-step tool call | Multi-step reasoning tasks |
| Status Management | Simple | Complex |
Router is the basis of ReAct:
- ReAct = Router + Loop + Reasoning State
🎯 Practical application cases
Case 1: Intelligent customer service
def search_knowledge_base(query: str) -> str:
"""Search internal knowledge base for answers."""
# 实现知识库搜索
pass
def create_ticket(issue: str, priority: str) -> str:
"""Create a support ticket."""
# 实现工单创建
pass
llm_with_tools = llm.bind_tools([search_knowledge_base, create_ticket])
# 用户问题:
# "如何重置密码?" → search_knowledge_base
# "我的账号被锁定了,请帮我处理" → create_ticket
# "你好" → 直接回答Case 2: Data Analysis Assistant
def query_database(sql: str) -> list:
"""Execute SQL query on the database."""
pass
def generate_chart(data: list, chart_type: str) -> str:
"""Generate a chart from data."""
pass
def calculate_statistics(data: list) -> dict:
"""Calculate basic statistics."""
pass
llm_with_tools = llm.bind_tools([query_database, generate_chart, calculate_statistics])
# 用户请求:
# "查询上个月的销售数据" → query_database
# "用这些数据生成柱状图" → generate_chart
# "计算平均值和标准差" → calculate_statisticsCase 3: Multi-language translation tool
def translate_text(text: str, target_language: str) -> str:
"""Translate text to target language."""
pass
def detect_language(text: str) -> str:
"""Detect the language of the text."""
pass
llm_with_tools = llm.bind_tools([translate_text, detect_language])
# 用户输入:
# "Translate 'hello' to Chinese" → translate_text
# "What language is 'Bonjour'?" → detect_language
# "How do I say goodbye in Spanish?" → 直接回答(LLM 知识)🔍 Frequently Asked Questions
Q1: Why use bind_tools instead of calling the function directly?
Answer: bind_tools lets LLM know about the available tools, but does not execute them automatically:
# 错误理解 ❌
llm_with_tools.invoke(...) # LLM 不会自动执行 multiply
# 正确理解 ✅
llm_with_tools.invoke(...) # LLM 返回"我想调用 multiply"
# 然后由 ToolNode 实际执行Benefits of this design:
- LLM is responsible for decision-making (which tool to call, what parameters to pass)
- The system is responsible for execution (safe and controllable)
- Clear separation of responsibilities
Q2: How does tools_condition know where to route?
A: It checks the last message:
def tools_condition(state):
last_msg = state["messages"][-1]
# 如果有 tool_calls 属性且不为空
if hasattr(last_msg, "tool_calls") and last_msg.tool_calls:
return "tools" # 字符串 "tools" 匹配节点名称
return ENDKey Points:
- The return value
"tools"must match an added node name - If a non-existent node name is returned, an error will be reported
Q3: What happens if LLM calls a tool that does not exist?
Answer: ToolNode will throw an error:
# 如果只绑定了 multiply
llm_with_tools = llm.bind_tools([multiply])
# 但 LLM 尝试调用 divide
AIMessage(tool_calls=[{"name": "divide", ...}])
# ToolNode 会报错:Tool 'divide' not foundSolution:
- Make sure the bound tools are consistent with the tools in the ToolNode
- Use error handling to wrap ToolNode
Q4: Will the messages in MessagesState keep growing?
Answer: Yes, messages will continue to accumulate by default:
# 第 1 轮
messages = [HumanMessage("你好")]
# 第 2 轮
messages = [
HumanMessage("你好"),
AIMessage("你好!"),
HumanMessage("2*3=?"),
]
# 第 3 轮
messages = [
HumanMessage("你好"),
AIMessage("你好!"),
HumanMessage("2*3=?"),
AIMessage(tool_calls=[...]),
ToolMessage("6"),
]Manage message history:
# 方法 1:限制消息数量
def trim_messages(state: MessagesState):
# 只保留最近 10 条消息
return {"messages": state["messages"][-10:]}
# 方法 2:使用 LangChain 的 trim_messages
from langchain_core.messages import trim_messages
trimmed = trim_messages(
messages,
max_tokens=1000,
strategy="last",
token_counter=llm
)📖 Further reading
- LangGraph official documentation - Router
- LangChain Tools Concept
- Detailed description of conditional edges
- MessagesState and Message Management
🎓 Learning Path
After mastering Router, it is recommended to learn in depth in the following order:
Current stage: Router ✅
- Understand conditional edges
- Master tool calls
- Familiar with MessagesState
Next step: Agent with Memory
- Add memory function
- Multiple rounds of dialogue
- State persistence
Advanced: ReAct Agent
- Circular reasoning
- Multi-step planning
- Break down complex tasks
Advanced: Multi-Agent System
- Multiple Agent collaboration
- Task assignment
- Parallel execution
Summary: Router is the cornerstone of the LangGraph Agent system. Through LLM intelligent decision-making + conditional edge dynamic routing, we can build an intelligent system that can choose tools autonomously. This is a crucial step from a simple chatbot to a powerful AI Agent!