Skip to content

LangChain智能体

LangChain智能体

介绍

在 LangChain 中,Agents(智能体) 是能够自主推理、调用工具、并迭代解决问题的高级系统。它将语言模型(Model)与外部能力(Tools)结合,使 LLM 能够“行动”而不仅仅是“回答”。

  • Agent = 模型(Model) + 工具(Tools) + 推理循环(ReAct Loop) + 状态管理(State)
  • Agent 的核心思想源自论文 ReAct: Synergizing Reasoning and Acting in Language Models,其行为模式为:
    • Thought:模型推理下一步该做什么
    • Action:调用一个或多个工具
    • Observation:接收工具返回的结果
    • 循环直到得出最终答案或达到最大步数
  • 减少幻觉、过程可审计、支持复杂任务分解
mermaid
graph TD
    A[User Input] --> B{Model Node}
    B -->|Thought + Tool Call| C[Tool Node]
    C -->|Observation| D{Stop?}
    D -- No --> B
    D -- Yes --> E[Final Answer]

核心组件

(1) Model(模型)

  • 是智能体的“大脑”,负责推理。
  • 支持两种配置方式:
    • 静态模型:创建时固定,例如 create_agent("openai:gpt-4o", tools=...)
    • 动态模型:根据对话状态在运行时选择不同模型(如短对话用便宜模型,长对话用更强模型)

(2) Tools(工具)

  • 赋予智能体“动手”能力,如调用 API、执行代码、查数据库等。
  • 可以传入:
    • 工具列表(@tool 装饰的函数)
    • 预配置的 ToolNode(支持自定义错误处理等)

(3) Prompt(提示词)

  • 控制智能体的行为风格,如“你是客服助手,请礼貌回答”。
  • 支持字符串、SystemMessage 或动态中间件(middleware),后者可根据用户角色等上下文动态调整提示。

(4) Memory(记忆)

  • 默认通过 messages 自动维护对话历史。
  • 可扩展为自定义状态(state schema),例如记录用户偏好、任务进度等。

(5) Hooks(钩子)

  • Pre-model hook:在调用模型前处理状态(如裁剪过长对话)。
  • Post-model hook:在模型输出后、执行工具前做校验(如过滤敏感内容)。

(6) Structured Output(结构化输出)

  • 可指定 Pydantic 模型作为输出格式,确保结果符合预期结构

(7) Streaming(流式响应)

  • 支持 .stream() 方法,实时返回每一步的推理或工具调用,适合前端展示进度。

参考资料

智能体实战

创建智能体

create_agent 自动构建一个 ReAct 风格的图(Graph),包含:

  • Model Node:调用 LLM 进行推理
  • Tool Node:执行工具并返回结果
  • Pre/Post Hooks:可选的预处理/后处理逻辑
python
from langchain.tools import tool
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model

# 创建LLM模型实例
MODEL = "deepseek-v3.2"
API_KEY = "sk-"
BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
model = init_chat_model(
    model=MODEL, model_provider="openai", api_key=API_KEY, base_url=BASE_URL
)


# 创建工具
@tool
def get_weather(city: str) -> str:
    """
    Get the weather in a city
    Args:
        city: The city to get the weather for
    """
    return f"The weather in {city} is nice. The temperature is 20 degrees, and it feels like 22 degrees."


# 创建智能体
tools = [get_weather]
system_prompt = "You are a helpful assistant"
agent = create_agent(model=model, tools=tools, system_prompt=system_prompt)

运行智能体

python
query = "北京今天天气怎样?"
# 非流式响应
# response = agent.invoke(
#     {"messages": [{"role": "user", "content": query}]}
# )
# result = response["messages"][-1].content
# print(f"结果:{result}")
# for message in response["messages"]:
#     # 打印所有消息,便于调试
#     message.pretty_print()

# 流式响应:实时显示 Agent 的思考和行动过程
for step in agent.stream(
    {"messages": [{"role": "user", "content": query}]},
    stream_mode="values",
):
    latest_message = step["messages"][-1]
    latest_message.pretty_print()

流式输出结果示例

bash
================================ Human Message =================================

北京今天天气怎样?
================================== Ai Message ==================================

我来帮您查询北京今天的天气情况。
Tool Calls:
  get_weather (call_c7570e0086bf487f8934c929)
 Call ID: call_c7570e0086bf487f8934c929
  Args:
    city: 北京
================================= Tool Message =================================
Name: get_weather

The weather in 北京 is nice. The temperature is 20 degrees, and it feels like 22 degrees.
================================== Ai Message ==================================

北京今天天气不错!气温是20度,体感温度22度。天气条件比较宜人。

结构化输出

结构化输出

通过 response_format 参数强制 Agent 返回特定格式:

python
from pydantic import BaseModel

class WeatherReport(BaseModel):
    location: str
    temperature: float
    unit: str

agent = create_agent(
    model,
    tools=[get_weather],
    response_format=WeatherReport
)

result = agent.invoke({"messages": [...]})
report = result["structured_response"]  # WeatherReport 实例

最佳实践

建议说明
✅ 使用 create_agent()而非旧版 initialize_agent
✅ 提供清晰的工具描述帮助模型正确选择工具
✅ 设置 temperature=0保证工具调用的确定性
✅ 使用 stream() 提升 UX尤其在 Web 应用中
✅ 用 response_format 约束输出避免解析自由文本
❌ 避免无限循环合理设置 max_iterations(默认已限制)
  • 默认最大迭代次数:10 步
  • 停止条件:模型返回非工具调用的 content,或达到最大步数