Skip to content

LangGraph Agent Detailed interpretation ​

📚 Overview ​

This document explains in detail the Agent architecture in LangGraph. This is the core pattern for building intelligent AI applications. It enables automated processing of complex tasks by allowing the AI ​​model to make autonomous decisions, call tools, and continue reasoning based on the results.

🎯 Core Concept ​

What is Agent? ​

Agent is an AI system that can make decisions and act autonomously. In LangGraph, Agent has the following characteristics:

  1. Autonomous decision-making

    • The AI model decides by itself whether it needs to call tools
    • Determine next steps based on the results returned by the tool
    • Can continuously call multiple tools to complete complex tasks
  2. Tool call

    • Call external functions to obtain information or perform operations
    • Transfer tool results back to the model to continue processing -Support multiple rounds of tool calls
  3. Circular Reasoning

    • The model can continue to think based on the tool results
    • Decide whether to continue calling the tool or answer directly
    • Form a "think-act-observe" cycle

ReAct Architecture ​

ReAct (Reasoning + Acting) is a classic Agent architecture pattern:

  • Reason: The model analyzes the problem and decides what tools need to be called
  • Act: Call the selected tool
  • Observe: Get the results returned by the tool
  • Loop: Based on the observations, decide whether to continue action or give the final answer

Differences from Router ​

In previous Router mode:

  • After the model calls the tool, it directly returns ToolMessage to the user
  • This is a one-time tool call, no looping

In Agent mode:

  • After the model calls the tool, ToolMessage is passed back to the model
  • Models can decide based on results:
    • Continue to call other tools
    • Or answer the user directly

Key Difference: Flow of Tool Results

Router:  用户 → 模型 → 工具 → 用户
Agent:   用户 → 模型 → 工具 → 模型 → ... → 用户
                    ↑____________↓
                      循环反馈

🎭 Practical case: Mathematical calculation Agent ​

We will build a mathematical calculation assistant that demonstrates the complete workflow of the Agent.

Requirements: Given a multi-step math problem, the agent needs:

  1. Understand what computational steps are required for the problem
  2. Call the corresponding tools in sequence (addition, multiplication, division)
  3. Based on the results of each step, decide the next step
  4. Finally give the answer

System architecture diagram ​

用户输入: "Add 3 and 4. Multiply the output by 2. Divide the output by 5"
        ↓
   [assistant] 分析:需要先做加法
        ↓
    (tools_condition 判断:需要调用工具)
        ↓
    [tools] 调用 add(3, 4) → 返回 7
        ↓
   [assistant] 收到结果 7,分析:需要乘以 2
        ↓
    (tools_condition 判断:需要调用工具)
        ↓
    [tools] 调用 multiply(7, 2) → 返回 14
        ↓
   [assistant] 收到结果 14,分析:需要除以 5
        ↓
    (tools_condition 判断:需要调用工具)
        ↓
    [tools] 调用 divide(14, 5) → 返回 2.8
        ↓
   [assistant] 收到结果 2.8,生成最终答案
        ↓
    (tools_condition 判断:不需要工具)
        ↓
       END → 返回结果给用户

🔧 Detailed explanation of code implementation ​

1. Define tool functions ​

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

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

def add(a: int, b: int) -> int:
    """Adds a and b.

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

def divide(a: int, b: int) -> float:
    """Divide a and b.

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

tools = [add, multiply, divide]

Python knowledge point: function documentation string (Docstring)

A function's docstring is more than just a comment, it's a first-class citizen of Python:

python
def add(a: int, b: int) -> int:
    """Adds a and b.    # ← 简短描述

    Args:               # ← 参数说明
        a: first int
        b: second int
    """
    return a + b

# 可以通过 __doc__ 属性访问
print(add.__doc__)

LangChain’s Magic: LangChain parses these docstrings and passes them to LLM as tool descriptions:

python
# LLM 会看到类似这样的工具描述:
# Tool: add
# Description: Adds a and b.
# Parameters:
#   - a: first int
#   - b: second int

That's why LLM "understands" what the tool does!


2. Bind the tool to the model ​

python
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-4o")
llm_with_tools = llm.bind_tools(tools, parallel_tool_calls=False)

Key parameters: parallel_tool_calls=False

This parameter controls whether the model can call multiple tools at the same time:

python
# parallel_tool_calls=True(默认)
# 模型可能同时调用:add(3, 4) 和 multiply(7, 2)
# 适合:并行、独立的任务

# parallel_tool_calls=False
# 模型必须依次调用:先 add(3, 4),等结果,再调用 multiply
# 适合:数学计算等需要顺序执行的任务

**Why should math calculations be set to False? **

Mathematical calculations often have dependencies:

第一步:3 + 4 = 7
第二步:7 × 2 = 14  ← 依赖第一步的结果!
第三步:14 ÷ 5 = 2.8  ← 依赖第二步的结果!

If parallel calls are allowed, the model may try to perform the second step without knowing the results of the first step, causing an error.


3. Define status ​

python
from langgraph.graph import MessagesState
from langchain_core.messages import HumanMessage, SystemMessage

# System message
sys_msg = SystemMessage(content="You are a helpful assistant tasked with performing arithmetic on a set of inputs.")

LangGraph knowledge point: MessagesState

MessagesState is LangGraph’s built-in status class, specifically used in chat scenarios:

python
class MessagesState(TypedDict):
    messages: Annotated[list[BaseMessage], add_messages]

Core Features:

  1. Automatic Message Management: Maintain conversation history
  2. Message Append: Use add_messages reducer to automatically append new messages
  3. Type Safety: Supports different types of messages (HumanMessage, AIMessage, ToolMessage, etc.)

Message type:

python
from langchain_core.messages import (
    HumanMessage,    # 用户消息
    AIMessage,       # AI 回复
    SystemMessage,   # 系统提示
    ToolMessage      # 工具返回结果
)

4. Define Assistant node ​

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

Code analysis:

python
[sys_msg] + state["messages"]
# 构建完整的消息列表:
# [
#   SystemMessage("You are a helpful assistant..."),  # 系统提示
#   HumanMessage("Add 3 and 4..."),                   # 用户问题
#   AIMessage(tool_calls=[...]),                       # AI 的工具调用
#   ToolMessage(content="7"),                          # 工具返回结果
#   ...
# ]

**Why do you add sys_msg every time? **

Each time LLM is called, the full context needs to be provided:

  • System prompts to define the role and behavior of the AI
  • Historical messages provide conversation context
  • This way the AI can understand where it is in the conversation

Return format:

python
return {"messages": [new_message]}
# 返回的消息会被追加到 state["messages"] 中
# 因为 MessagesState 使用了 add_messages reducer

5. Build Agent graph ​

python
from langgraph.graph import START, StateGraph
from langgraph.prebuilt import tools_condition
from langgraph.prebuilt import ToolNode

# 创建图
builder = StateGraph(MessagesState)

# 添加节点
builder.add_node("assistant", assistant)
builder.add_node("tools", ToolNode(tools))

# 添加边
builder.add_edge(START, "assistant")

# 条件边:根据 assistant 的输出决定路由
builder.add_conditional_edges(
    "assistant",
    tools_condition,  # 条件函数
)

# 关键:从 tools 回到 assistant 形成循环
builder.add_edge("tools", "assistant")

# 编译
react_graph = builder.compile()

LangGraph knowledge point: ToolNode

ToolNode is a pre-built node provided by LangGraph for performing tool calls:

python
ToolNode(tools)
# 自动处理:
# 1. 解析 AIMessage 中的 tool_calls
# 2. 调用对应的工具函数
# 3. 将结果包装成 ToolMessage
# 4. 返回给下一个节点

Equivalent manual implementation:

python
def tools_node(state: MessagesState):
    # 获取最后一条消息(AI 的工具调用)
    last_message = state["messages"][-1]

    # 执行所有工具调用
    tool_messages = []
    for tool_call in last_message.tool_calls:
        # 找到对应的工具
        tool = next(t for t in tools if t.name == tool_call["name"])
        # 调用工具
        result = tool.invoke(tool_call["args"])
        # 包装成 ToolMessage
        tool_messages.append(ToolMessage(
            content=str(result),
            tool_call_id=tool_call["id"]
        ))

    return {"messages": tool_messages}

LangGraph knowledge point: tools_condition

tools_condition is a pre-built conditional function used to determine whether a tool needs to be called:

python
def tools_condition(state: MessagesState) -> str:
    # 获取最后一条消息
    last_message = state["messages"][-1]

    # 如果是 AIMessage 且包含 tool_calls
    if hasattr(last_message, "tool_calls") and last_message.tool_calls:
        return "tools"  # 路由到 tools 节点
    else:
        return END  # 结束图执行

Workflow of conditional edges:

python
builder.add_conditional_edges("assistant", tools_condition)

# 完整流程:
# assistant 节点执行完毕
#    ↓
# tools_condition 检查输出
#    ↓
# 如果有 tool_calls → 路由到 "tools"
# 如果没有 tool_calls → 路由到 END

Key to Agent loop:

python
builder.add_edge("tools", "assistant")  # ← 这条边创建了循环!

# 完整循环:
# assistant → (有工具调用) → tools → assistant → ...
#          → (无工具调用) → END

6. Execute Agent ​

python
messages = [HumanMessage(content="Add 3 and 4. Multiply the output by 2. Divide the output by 5")]
messages = react_graph.invoke({"messages": messages})

Detailed explanation of the execution process:

步骤 1:assistant 节点
输入:[HumanMessage("Add 3 and 4. Multiply the output by 2. Divide the output by 5")]
输出:AIMessage(tool_calls=[ToolCall(name="add", args={"a": 3, "b": 4})])
tools_condition:检测到 tool_calls → 路由到 "tools"

步骤 2:tools 节点
输入:[HumanMessage(...), AIMessage(tool_calls=[...])]
执行:add(3, 4) = 7
输出:ToolMessage(content="7", tool_call_id="...")
自动路由:→ "assistant"

步骤 3:assistant 节点
输入:[HumanMessage(...), AIMessage(...), ToolMessage("7")]
分析:看到结果是 7,需要乘以 2
输出:AIMessage(tool_calls=[ToolCall(name="multiply", args={"a": 7, "b": 2})])
tools_condition:检测到 tool_calls → 路由到 "tools"

步骤 4:tools 节点
执行:multiply(7, 2) = 14
输出:ToolMessage(content="14")
自动路由:→ "assistant"

步骤 5:assistant 节点
输入:包含 ToolMessage("14") 的完整对话历史
分析:看到结果是 14,需要除以 5
输出:AIMessage(tool_calls=[ToolCall(name="divide", args={"a": 14, "b": 5})])
tools_condition:检测到 tool_calls → 路由到 "tools"

步骤 6:tools 节点
执行:divide(14, 5) = 2.8
输出:ToolMessage(content="2.8")
自动路由:→ "assistant"

步骤 7:assistant 节点
输入:包含所有历史消息和最终结果 2.8
分析:所有计算完成,可以给出最终答案
输出:AIMessage(content="The final result is 2.8")  # 注意:没有 tool_calls
tools_condition:没有 tool_calls → 路由到 END

图执行结束

7. View the output ​

python
for m in messages['messages']:
    m.pretty_print()

Output parsing:

================================ Human Message =================================
Add 3 and 4. Multiply the output by 2. Divide the output by 5

================================== Ai Message ==================================
Tool Calls:
  add (call_i8zDfMTdvmIG34w4VBA3m93Z)
 Call ID: call_i8zDfMTdvmIG34w4VBA3m93Z
  Args:
    a: 3
    b: 4

Explanation:

  • AI understands the task and decides to call the add tool first
  • Call ID is a unique identifier used to track the correspondence between tool calls and results
  • Args is the parameter passed to the tool
================================= Tool Message =================================
Name: add
7

Explanation:

  • Tool execution result: 3 + 4 = 7
  • This result will be passed back to the assistant node
================================== Ai Message ==================================
Tool Calls:
  multiply (call_nE62D40lrGQC7b67nVOzqGYY)
 Call ID: call_nE62D40lrGQC7b67nVOzqGYY
  Args:
    a: 7
    b: 2

Explanation:

  • AI receives the result 7 and decides to call multiply next
  • Note the parameter a: 7 from the previous step!
================================= Tool Message =================================
Name: multiply
14

Explanation: 7 × 2 = 14

================================== Ai Message ==================================
Tool Calls:
  divide (call_6Q9SjxD2VnYJqEBXFt7O1moe)
 Call ID: call_6Q9SjxD2VnYJqEBXFt7O1moe
  Args:
    a: 14
    b: 5

Explanation:

  • AI continues reasoning and calls divide
  • Parameter a: 14 comes from the result of the previous step
================================= Tool Message =================================
Name: divide
2.8

Explanation: 14 ÷ 5 = 2.8

================================== Ai Message ==================================
The final result after performing the operations (3 + 4) × 2 ÷ 5 is 2.8.

Explanation:

  • All calculations are completed and AI gives the final answer
  • This message does not have tool_calls, so the graph execution ends

Key observation points:

  1. AI independently determines the tool calls at each step
  2. Make inferences based on the results of the previous step each time
  3. Finally gave a natural language answer
  4. The entire process is automated and requires no manual intervention

🎓 Summary of core knowledge points ​

LangGraph-specific concepts ​

1. Agent vs Router ​

FeaturesRouterAgent
Number of tool callsOnceMultiple times (loop)
Tool result flowReturn directly to the userReturn to the model to continue processing
Number of decisionsOnceMultiple times (decisions are made in each cycle)
Applicable scenariosSimple classification, single queryComplex tasks, multi-step reasoning

2. ReAct loop ​

python
while True:
    # Reason: AI 分析当前状态,决定行动
    ai_message = assistant(state)

    # 判断:需要工具吗?
    if no_tool_calls(ai_message):
        break  # 不需要,返回答案

    # Act: 调用工具
    tool_result = tools(state)

    # Observe: 更新状态,将结果传回 AI
    state = update_state(tool_result)

3. Conditional edges and loops ​

python
# 条件边:根据输出动态路由
builder.add_conditional_edges("assistant", tools_condition)

# 返回边:创建循环
builder.add_edge("tools", "assistant")

# 组合效果:
# assistant → [有工具调用] → tools → assistant → ...
#          → [无工具调用] → END

4. MessagesState ​

python
class MessagesState(TypedDict):
    messages: Annotated[list[BaseMessage], add_messages]

# 特点:
# 1. 自动维护对话历史
# 2. 支持多种消息类型
# 3. 使用 add_messages reducer 追加消息

5. ToolNode ​

python
ToolNode(tools)

# 自动处理:
# - 解析 tool_calls
# - 调用函数
# - 包装结果为 ToolMessage
# - 追踪 tool_call_id

Python-specific knowledge points ​

1. Function type annotation ​

python
def add(a: int, b: int) -> int:
    """Adds a and b."""
    return a + b

# a: int        ← 参数类型注解
# -> int        ← 返回类型注解
# """..."""     ← 文档字符串

Function:

  • IDE provides smart prompts
  • Type checking tool (mypy) to verify code
  • LangChain parsing for tool description

2. Docstring specification (Google style) ​

python
def multiply(a: int, b: int) -> int:
    """Multiply a and b.          # 简短描述(必须)

    Args:                          # 参数列表(可选)
        a: first int
        b: second int

    Returns:                       # 返回值(可选)
        The product of a and b

    Raises:                        # 异常(可选)
        ValueError: If a or b is negative
    """
    return a * b

3. List splicing ​

python
[sys_msg] + state["messages"]

# 等价于:
result = []
result.append(sys_msg)
result.extend(state["messages"])

4. Object attribute inspection ​

python
hasattr(obj, "attribute_name")

# 示例:
hasattr(last_message, "tool_calls")
# 检查 last_message 对象是否有 tool_calls 属性

💡 Best Practices ​

1. When to use Agent? ​

✅ Applicable scenarios:

  • Tasks that require multi-step reasoning (such as mathematical calculations, data analysis)
  • Need to dynamically adjust strategies based on intermediate results
  • The order of tool calling is not fixed and requires AI to make independent decisions
  • The task is highly complex and requires flexible response

❌ Not applicable scenarios:

  • Simple single tool call (just use Router)
  • Tasks with fixed processes (just use ordinary diagrams)
  • Scenarios that do not require circular reasoning

2. Selection of parallel tool calls ​

python
# 场景 1:数学计算 → parallel_tool_calls=False
llm_with_tools = llm.bind_tools([add, multiply, divide], parallel_tool_calls=False)
# 原因:步骤有依赖关系,必须顺序执行

# 场景 2:信息收集 → parallel_tool_calls=True(默认)
llm_with_tools = llm.bind_tools([search_web, query_db, call_api])
# 原因:三个工具可以同时调用,提高效率

3. The importance of system prompts ​

python
# ✅ 好的系统提示
sys_msg = SystemMessage(content="""
You are a helpful assistant tasked with performing arithmetic on a set of inputs.
- Break down complex calculations into steps
- Use the appropriate tool for each operation
- Show your reasoning
""")

# ❌ 不好的系统提示
sys_msg = SystemMessage(content="You are helpful.")
# 太模糊,AI 可能不知道如何使用工具

4. Prevent infinite loops ​

Agent may fall into an infinite loop and needs to set limits:

python
# 方法 1:使用 recursion_limit
react_graph = builder.compile(recursion_limit=10)
# 最多执行 10 次循环

# 方法 2:在状态中计数
class MessagesStateWithCount(TypedDict):
    messages: Annotated[list[BaseMessage], add_messages]
    iterations: int

def assistant(state: MessagesStateWithCount):
    if state.get("iterations", 0) > 10:
        return {"messages": [AIMessage(content="Reached maximum iterations")]}
    # ... 正常逻辑
    return {
        "messages": [llm_with_tools.invoke(...)],
        "iterations": state.get("iterations", 0) + 1
    }

5. Tool function design principles ​

python
# ✅ 好的工具设计
def search_database(query: str, limit: int = 10) -> list[dict]:
    """Search the database for matching records.

    Args:
        query: Search query string
        limit: Maximum number of results (default: 10)

    Returns:
        List of matching records
    """
    # 实现...
    return results

# 特点:
# - 清晰的文档字符串
# - 类型注解
# - 默认参数值
# - 返回结构化数据
python
# ❌ 不好的工具设计
def search(q):  # 没有类型注解
    """搜索"""  # 文档不清楚
    # AI 不知道如何使用这个工具

🚀 Advanced skills ​

1. Agent with memory ​

python
class MessagesStateWithMemory(TypedDict):
    messages: Annotated[list[BaseMessage], add_messages]
    user_preferences: dict  # 存储用户偏好
    conversation_summary: str  # 对话摘要

def assistant(state: MessagesStateWithMemory):
    # 可以访问历史偏好
    preferences = state.get("user_preferences", {})

    # 构建带上下文的提示
    context = f"User preferences: {preferences}\n"
    prompt = context + "\n".join([m.content for m in state["messages"]])

    response = llm_with_tools.invoke(prompt)
    return {"messages": [response]}

2. Dynamic tool selection ​

python
def assistant(state: MessagesState):
    # 根据对话内容动态选择可用工具
    last_message = state["messages"][-1].content

    if "weather" in last_message:
        tools = [get_weather, get_forecast]
    elif "database" in last_message:
        tools = [query_db, insert_db, update_db]
    else:
        tools = all_tools

    llm_with_selected_tools = llm.bind_tools(tools)
    response = llm_with_selected_tools.invoke(state["messages"])
    return {"messages": [response]}

3. Error handling ​

python
def tools_node(state: MessagesState):
    last_message = state["messages"][-1]
    tool_messages = []

    for tool_call in last_message.tool_calls:
        try:
            tool = next(t for t in tools if t.name == tool_call["name"])
            result = tool.invoke(tool_call["args"])
            tool_messages.append(ToolMessage(
                content=str(result),
                tool_call_id=tool_call["id"]
            ))
        except Exception as e:
            # 返回错误信息给 AI
            tool_messages.append(ToolMessage(
                content=f"Error: {str(e)}",
                tool_call_id=tool_call["id"],
                status="error"
            ))

    return {"messages": tool_messages}

4. Streaming output ​

python
# 使用 stream 方法查看实时执行过程
for chunk in react_graph.stream({"messages": [HumanMessage("Calculate...")]}):
    print(chunk)

# 输出:
# {'assistant': {'messages': [AIMessage(tool_calls=[...])]}}
# {'tools': {'messages': [ToolMessage(content="7")]}}
# {'assistant': {'messages': [AIMessage(tool_calls=[...])]}}
# ...

📊 Agent variant comparison ​

1. Basic Agent (this tutorial) ​

python
builder.add_edge("tools", "assistant")  # 工具结果总是回到 assistant

Features: Simple, direct, suitable for most scenarios

2. Conditional return to Agent ​

python
def should_continue(state: MessagesState):
    last_message = state["messages"][-1]
    # 可以根据工具结果决定是否继续
    if "error" in last_message.content:
        return END
    return "assistant"

builder.add_conditional_edges("tools", should_continue, ["assistant"])

Features: Can be terminated early to handle error conditions

3. Multipath Agent ​

python
def route_after_tool(state: MessagesState):
    last_message = state["messages"][-1]

    if "final" in last_message.content:
        return "summarize"  # 去总结节点
    elif "error" in last_message.content:
        return "error_handler"  # 去错误处理节点
    else:
        return "assistant"  # 继续推理

builder.add_conditional_edges("tools", route_after_tool,
                             ["assistant", "summarize", "error_handler"])

Features: More complex control flow, suitable for large applications


🎯 Practical application cases ​

Case 1: Research Assistant ​

python
tools = [
    search_web,          # 搜索网络
    read_paper,          # 读取论文
    summarize_text,      # 总结文本
    save_notes           # 保存笔记
]

# 用户:Research recent advances in quantum computing
# Agent 工作流:
# 1. search_web("quantum computing 2024")
# 2. read_paper(paper_url_1)
# 3. summarize_text(paper_content_1)
# 4. read_paper(paper_url_2)
# 5. summarize_text(paper_content_2)
# 6. save_notes(combined_summary)
# 7. 返回研究总结

Case 2: Data Analysis Assistant ​

python
tools = [
    query_database,      # 查询数据库
    calculate_stats,     # 计算统计
    create_chart,        # 生成图表
    export_report        # 导出报告
]

# 用户:Analyze sales data for Q4 and create a report
# Agent 工作流:
# 1. query_database("SELECT * FROM sales WHERE quarter = 'Q4'")
# 2. calculate_stats(sales_data)
# 3. create_chart(stats, type="bar")
# 4. create_chart(stats, type="pie")
# 5. export_report(charts, stats)
# 6. 返回报告链接

Case 3: Customer Support Assistant ​

python
tools = [
    search_knowledge_base,  # 搜索知识库
    check_order_status,     # 查询订单
    create_ticket,          # 创建工单
    send_email              # 发送邮件
]

# 用户:I haven't received my order #12345
# Agent 工作流:
# 1. check_order_status("12345")
# 2. search_knowledge_base("delayed shipping")
# 3. 发现问题:物流延误
# 4. create_ticket(order_id="12345", issue="shipping_delay")
# 5. send_email(user, "Your order is delayed, ticket created")
# 6. 返回解决方案和工单号

🔍 Frequently Asked Questions ​

Q1: When will Agent stop looping? ​

Answer: When the AIMessage returned by the assistant node does not contain tool_calls:

python
# 会继续循环
AIMessage(tool_calls=[ToolCall(name="add", ...)])

# 会停止(进入 END)
AIMessage(content="The answer is 42")

Q2: How to let Agent call specific tools? ​

Answer: Boot through system prompts:

python
sys_msg = SystemMessage(content="""
You are a helpful assistant.
When the user asks about weather, ALWAYS use the get_weather tool.
When the user asks about time, ALWAYS use the get_time tool.
""")

Or use the tool_choice parameter:

python
# 强制使用特定工具
llm_with_tools = llm.bind_tools(tools, tool_choice="get_weather")

# 强制调用任意工具(不能直接回答)
llm_with_tools = llm.bind_tools(tools, tool_choice="any")

# 禁止调用工具
llm_with_tools = llm.bind_tools(tools, tool_choice="none")

Q3: How to view the execution process of Agent? ​

Method 1: Using stream

python
for chunk in graph.stream(input_data):
    print(chunk)

Method 2: Using LangSmith

python
import os
os.environ["LANGSMITH_TRACING"] = "true"
os.environ["LANGSMITH_PROJECT"] = "my-agent"

# 在 LangSmith 网站查看详细 trace

Method 3: Custom Log

python
def assistant(state: MessagesState):
    print(f"[Assistant] Processing {len(state['messages'])} messages")
    response = llm_with_tools.invoke(state["messages"])
    print(f"[Assistant] Response: {response}")
    return {"messages": [response]}

Q4: What should I do if the tool call fails? ​

Answer: Handle exceptions in ToolNode:

python
def custom_tools_node(state: MessagesState):
    last_message = state["messages"][-1]
    tool_messages = []

    for tool_call in last_message.tool_calls:
        try:
            result = execute_tool(tool_call)
            tool_messages.append(ToolMessage(
                content=str(result),
                tool_call_id=tool_call["id"]
            ))
        except Exception as e:
            # 将错误返回给 AI,让它重试或换方法
            tool_messages.append(ToolMessage(
                content=f"Error: {str(e)}. Please try a different approach.",
                tool_call_id=tool_call["id"]
            ))

    return {"messages": tool_messages}

Q5: How to limit the execution cost of Agent? ​

Method 1: Limit the number of loops

python
graph = builder.compile(recursion_limit=5)

Method 2: Limit token usage

python
class TokenTrackingState(MessagesState):
    total_tokens: int

def assistant(state: TokenTrackingState):
    if state.get("total_tokens", 0) > 10000:
        return {"messages": [AIMessage(content="Token limit reached")]}

    # 调用 LLM 并记录 token
    response = llm_with_tools.invoke(state["messages"])
    tokens_used = response.response_metadata.get("token_usage", {}).get("total_tokens", 0)

    return {
        "messages": [response],
        "total_tokens": state.get("total_tokens", 0) + tokens_used
    }

📖 Further reading ​


Summary: Agent is the core mode of LangGraph, which allows AI to complete complex tasks autonomously through the cycle of "reasoning-action-observation". Mastering the construction method of Agent is the basis for developing powerful AI applications!

English translation of community learning materials. MIT licensed.