1. LangChain代理系统概述
LangChain框架中的代理(Agents)是一种利用大型语言模型(LLM)作为推理引擎的智能系统,它能够自主决定需要采取的行动以及如何处理输入信息。与传统的LLM调用不同,代理系统具备以下核心特征:
- 动态决策能力:根据当前上下文决定是否需要调用工具以及调用哪些工具
- 多轮交互:支持复杂的多步骤问题解决流程
- 记忆机制:可保留对话历史实现上下文感知
- 工具集成:无缝对接各种外部API和功能模块
典型的代理工作流程包含四个关键阶段:
- 接收用户输入
- LLM推理决策
- 执行工具调用(如需要)
- 整合结果并生成响应
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 代理系统核心组件解析
2.1 语言模型选择与配置
LangChain支持多种主流LLM作为代理的推理引擎,包括但不限于:
python复制# Anthropic Claude配置示例
from langchain_anthropic import ChatAnthropic
model = ChatAnthropic(model="claude-3-sonnet-20240229")
# OpenAI GPT配置示例
from langchain_openai import ChatOpenAI
model = ChatOpenAI(model="gpt-4")
# Google Gemini配置示例
from langchain_google_vertexai import ChatVertexAI
model = ChatVertexAI(model="gemini-1.5-flash")
选择模型时需考虑:
- 输入/输出token成本
- 上下文窗口大小
- 工具调用支持程度
- 响应延迟要求
2.2 工具系统设计与实现
工具(Tools)是代理扩展能力的核心机制。创建自定义工具的基本模式:
python复制from langchain.tools import BaseTool
from typing import Optional
class CustomSearchTool(BaseTool):
name = "custom_search"
description = "用于特定领域的专业搜索引擎"
def _run(self, query: str) -> str:
# 实现工具逻辑
return search_api(query)
工具集成最佳实践:
- 为每个工具编写清晰的描述文本
- 限制单个工具的最大返回结果数
- 实现错误处理和超时机制
- 考虑添加使用权限控制
2.3 记忆管理系统
代理的记忆机制使其能够维护对话状态:
python复制from langgraph.checkpoint.memory import MemorySaver
memory = MemorySaver() # 创建内存检查点
config = {"configurable": {"thread_id": "abc123"}} # 对话线程ID
# 使用记忆的代理调用
agent_executor.invoke(
{"messages": [HumanMessage(content="hi im bob!")]},
config=config
)
记忆系统的关键参数:
max_token_limit:控制记忆缓存大小return_messages:决定返回原始消息还是摘要memory_key:指定记忆存储的变量名
3. 代理构建全流程实现
3.1 基础代理创建
使用LangGraph构建完整代理:
python复制from langgraph.prebuilt import create_react_agent
from langchain_community.tools.tavily_search import TavilySearchResults
# 1. 准备工具
search = TavilySearchResults(max_results=2)
tools = [search]
# 2. 创建代理执行器
agent_executor = create_react_agent(
model=model,
tools=tools,
checkpointer=memory
)
# 3. 执行代理
response = agent_executor.invoke(
{"messages": [HumanMessage(content="旧金山天气如何?")]}
)
3.2 流式响应处理
对于长时间运行的任务,实现流式响应:
python复制for chunk in agent_executor.stream(
{"messages": [HumanMessage(content="实时股票行情查询")]}
):
print(chunk)
print("----")
流式处理的关键状态:
on_chain_start:代理开始处理on_tool_start:工具调用开始on_tool_end:工具返回结果on_chain_end:代理完成响应
3.3 高级事件追踪
使用LangSmith进行深度监控:
python复制import os
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_API_KEY"] = "your_api_key"
async for event in agent_executor.astream_events(
{"messages": [...]},
version="v1"
):
# 解析不同事件类型
if event["event"] == "on_tool_start":
print(f"工具调用开始: {event['name']}")
4. 生产环境最佳实践
4.1 性能优化技巧
- 工具调用批处理:
python复制agent = create_react_agent(
model,
tools,
max_iterations=5, # 限制最大迭代次数
parallelize=True # 启用并行工具调用
)
- 缓存策略:
python复制from langchain.cache import SQLiteCache
import langchain
langchain.llm_cache = SQLiteCache(database_path=".langchain.db")
- 超时控制:
python复制from langchain.utils import timeout
with timeout(30): # 30秒超时
agent_executor.invoke(...)
4.2 常见问题排查
问题1:代理陷入无限循环
- 检查
max_iterations参数 - 验证工具描述是否准确
- 添加显式终止条件
问题2:工具调用失败
python复制try:
tool_output = tool.run(input)
except Exception as e:
return f"工具调用失败: {str(e)}"
问题3:上下文窗口溢出
- 启用自动记忆修剪
- 使用摘要代替完整历史
- 切换更大上下文窗口的模型
4.3 安全注意事项
- 输入验证:
python复制from langchain.schema import HumanMessage
def sanitize_input(content: str) -> str:
# 实现输入清洗逻辑
return cleaned_content
- 工具权限控制:
python复制class RestrictedTool(BaseTool):
allowed_users: List[str] = []
def _run(self, input: str) -> str:
if self.current_user not in self.allowed_users:
raise PermissionError("未授权访问此工具")
- 输出过滤:
python复制from langchain.output_parsers import RegexParser
safe_parser = RegexParser(
regex=r"^(?!.*(敏感词1|敏感词2)).*$",
default_output="内容已过滤"
)
5. 高级应用场景
5.1 多代理协作系统
构建协同工作的代理网络:
python复制from langgraph.graph import Graph
workflow = Graph()
# 定义不同角色的代理
research_agent = create_research_agent()
writing_agent = create_writing_agent()
review_agent = create_review_agent()
# 构建工作流
workflow.add_node("research", research_agent)
workflow.add_node("write", writing_agent)
workflow.add_node("review", review_agent)
# 设置边关系
workflow.add_edge("research", "write")
workflow.add_edge("write", "review")
workflow.add_edge("review", "write") # 反馈循环
# 编译执行
chain = workflow.compile()
5.2 自定义推理逻辑
覆盖默认的ReAct逻辑:
python复制from langchain.agents import AgentExecutor
from typing import List, Tuple
class CustomAgentExecutor(AgentExecutor):
def _get_next_action(self, full_inputs: Dict[str, str]) -> Tuple[str, str, str]:
# 实现自定义决策逻辑
if should_use_tool_A(full_inputs):
return "tool_a", {...}
return super()._get_next_action(full_inputs)
5.3 混合型代理架构
结合规划器和执行器的混合架构:
python复制planner = create_planner_agent()
executor = create_executor_agent()
def hybrid_agent(query):
plan = planner.invoke({"input": query})
for step in plan["steps"]:
result = executor.invoke(step)
yield result
