Skip to content

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":

  1. Receive Input - User sends query
  2. Intelligent Judgment - Whether tools are needed for LLM analysis
  3. 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:

  1. The user asks "Hello" → LLM answers directly without tools
  2. The user asks "What is 2 times 3?" → LLM calls the multiply tool to calculate

System architecture diagram ​

用户输入消息
     ↓
[tool_calling_llm]  ← LLM 分析并决策
     ↓
  (条件判断)
     ↓
    / \
   /   \
  ↓     ↓
直接回答  [tools] 调用工具
  ↓     ↓
  END   END

Key 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 ​

python
# 安装依赖
%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 as ToolNode and tools_condition
  • getpass: Enter sensitive information securely (API Key will not be displayed on the screen)

2. Define tools and LLM ​

python
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:

  1. Function name: LLM is used to identify tools (such as multiply)
  2. Docstring: LLM is used to understand the purpose of the tool (very important!)
  3. Type hint: LLM is used to understand parameter types (a: int, b: int)
  4. Return type: LLM is used to understand the output type (-> int)

Example:

python
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 ​

python
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 ​

python
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:

  • messages field: stores conversation history
  • Automatically use add_messages reducer: intelligently merge new messages

The smart thing about add_messages:

python
# 场景 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 ​

python
def tool_calling_llm(state: MessagesState):
    return {"messages": [llm_with_tools.invoke(state["messages"])]}

Function details:

  1. Input: state["messages"] - Current conversation history
  2. Processing: llm_with_tools.invoke(...) - LLM analysis and decision-making
  3. Output: {"messages": [...]} - response returned by LLM

Possible output types:

Case A: Direct answer (no tool call)

python
AIMessage(content="你好!我能帮你什么?")

Case B: Calling Tools

python
AIMessage(
    content="",  # 内容为空
    tool_calls=[{
        "name": "multiply",
        "args": {"a": 2, "b": 3},
        "id": "call_abc123"
    }]
)

5. Use pre-built components: ToolNode and tools_condition ​

python
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 AIMessage with tool_calls
  • Return ToolMessage containing execution results

Internal implementation logic:

python
# 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:

python
# 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 ​

python
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 ​

python
builder.add_conditional_edges(
    "tool_calling_llm",  # 源节点
    tools_condition,      # 条件函数
)

How ​​it works:

  1. tool_calling_llm node execution completed
  2. Call tools_condition(state) to determine routing
  3. The return value of tools_condition determines the next step:
    • Return to "tools" → Enter tools node
    • Return to END → end execution

Complete execution process:

Scenario A: Simple greeting

用户: "你好"
  ↓
[tool_calling_llm] → AIMessage(content="你好!")
  ↓
tools_condition 检测:无 tool_calls
  ↓
路由到 END

Scenario 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")
  ↓
END

Graph structure visualization:

     START
       ↓
[tool_calling_llm]
       ↓
   (条件判断)
      / \
     /   \
    ↓     ↓
  END   [tools]
         ↓
        END

7. Execution diagram ​

Test scenario 1: Tool call ​

python
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
4

Execution process analysis:

  1. HumanMessage Enter the system
  2. AIMessage returns the tool call request
  3. ToolMessage returns the calculation result 4

Test Scenario 2: Direct Answer ​

python
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:

  1. HumanMessage Enter the system
  2. AIMessage Direct answer, no tool call
  3. 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:

FeaturesTraditional ProcessRouter Mode
Path decisionHard-coded rulesLLM intelligent judgment
FlexibilityLowHigh
ScalabilityPoor (needs to modify the code)Strong (just add tools)
AdaptabilityFixed sceneDynamic adaptation

2. Conditional Edge ​

python
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

python
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_calls in AIMessage
  • Automatic matching and execution of corresponding tools
  • Return ToolMessage containing results -Support concurrent execution of multiple tools

Equivalent code for manually implementing ToolNode:

python
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:

python
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 ​

python
def multiply(a: int, b: int) -> int:
    """Multiply a and b."""
    return a * b

Importance of type hints:

  • LLM generates correct parameters based on type hints
  • Runtime verification (with Pydantic)
  • IDE code completion and inspection

Comparison:

python
# ❌ 不好的实践
def multiply(a, b):  # 没有类型提示
    return a * b

# ✅ 好的实践
def multiply(a: int, b: int) -> int:
    """Multiply a and b."""
    return a * b

2. The key role of Docstring ​

**Docstring is the only way LLM understands tools! **

python
def multiply(a: int, b: int) -> int:
    """Multiply a and b.

    Args:
        a: first int
        b: second int
    """
    return a * b

LLM 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

python
# ❌ 不好
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 * quantity

3. getpass module ​

python
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 ​

python
# ✅ 好的设计 - 每个工具只做一件事
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 ​

python
# ✅ 好
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."""
    pass

Principle 3: Return structured data ​

python
# ✅ 好 - 返回结构化数据
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 ​

python
# ✅ 好 - 逻辑清晰
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 END

Tip 2: Handle edge cases ​

python
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 END

3. Best practices for state management ​

Practice 1: Keep message history intact ​

python
# ✅ 好 - 保留完整对话历史
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 ​

python
# ✅ 正确 - 返回列表
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:

python
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:

python
# 用户:"先计算 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

python
# 修改图结构
builder.add_edge("tools", "tool_calling_llm")  # 工具执行后回到 LLM

# 现在流程变成:
# START → tool_calling_llm → tools → tool_calling_llm → tools → ... → END

3. Router with error handling ​

python
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 ​

python
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 ​

FeaturesSimple LLM callRouter mode
Tool supportNoneYes
Dynamic decision-makingNoneYes
ScalabilityLowHigh
ComplexityLowMedium
Applicable scenariosPure dialogueScenarios that require tools

Router vs ReAct Agent ​

FeaturesRouterReAct Agent
Loop executionNone (single)Yes (multiple rounds of inference)
ComplexitySimpleComplex
Applicable tasksSingle-step tool callMulti-step reasoning tasks
Status ManagementSimpleComplex

Router is the basis of ReAct:

  • ReAct = Router + Loop + Reasoning State

🎯 Practical application cases ​

Case 1: Intelligent customer service ​

python
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 ​

python
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_statistics

Case 3: Multi-language translation tool ​

python
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:

python
# 错误理解 ❌
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:

python
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 END

Key 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:

python
# 如果只绑定了 multiply
llm_with_tools = llm.bind_tools([multiply])

# 但 LLM 尝试调用 divide
AIMessage(tool_calls=[{"name": "divide", ...}])

# ToolNode 会报错:Tool 'divide' not found

Solution:

  1. Make sure the bound tools are consistent with the tools in the ToolNode
  2. Use error handling to wrap ToolNode

Q4: Will the messages in MessagesState keep growing? ​

Answer: Yes, messages will continue to accumulate by default:

python
# 第 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:

python
# 方法 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 ​


🎓 Learning Path ​

After mastering Router, it is recommended to learn in depth in the following order:

  1. Current stage: Router ✅

    • Understand conditional edges
    • Master tool calls
    • Familiar with MessagesState
  2. Next step: Agent with Memory

    • Add memory function
    • Multiple rounds of dialogue
    • State persistence
  3. Advanced: ReAct Agent

    • Circular reasoning
    • Multi-step planning
    • Break down complex tasks
  4. 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!

English translation of community learning materials. MIT licensed.