1. 概述:什么是智能体?
智能体(Agents)是将大型语言模型(LLMs)与各种**工具(Tools)**相结合的系统,能够推理复杂任务、自主决定使用何种工具,并通过迭代方式逐步解决问题。
create_agent函数提供了一个生产就绪的智能体实现。它基于LangGraph构建了一个**图结构(graph)的智能体运行时环境。这种架构由节点(nodes,即处理步骤)和边(edges,即连接关系)**组成,智能体在执行过程中会沿着这个图结构移动,执行如模型调用、工具执行等节点操作。
智能体的核心执行遵循ReAct模式(“推理+行动”):交替进行推理步骤和工具调用,并将工具执行结果作为后续决策的输入,直至达成目标或达到迭代限制。
2. 核心组件详解
2.1 模型(Model):智能体的推理引擎
模型是智能体的核心,它可以通过静态或动态方式进行配置。
2.1.1 静态模型
静态模型在创建智能体时一次性配置,执行过程中保持不变。
使用模型标识符字符串:最简单直接的方式。
fromlangchain.agentsimportcreate_agent# 模型标识符支持自动推断agent=create_agent("openai:gpt-5",tools=tools)直接实例化模型对象:提供更精细的控制。
fromlangchain.agentsimportcreate_agentfromlangchain_openaiimportChatOpenAI model=ChatOpenAI(model="gpt-5",temperature=0.1,# 控制输出随机性max_tokens=1000,# 限制生成长度timeout=30# 设置超时)agent=create_agent(model,tools=tools)
2.1.2 动态模型
动态模型允许根据运行时上下文选择不同的模型,实现复杂路由逻辑和成本优化。
fromlangchain_openaiimportChatOpenAIfromlangchain.agentsimportcreate_agentfromlangchain.agents.middlewareimportwrap_model_call,ModelRequest basic_model=ChatOpenAI(model="gpt-4o-mini")advanced_model=ChatOpenAI(model="gpt-4o")@wrap_model_calldefdynamic_model_selection(request:ModelRequest,handler):"""根据对话复杂度选择模型"""message_count=len(request.state["messages"])ifmessage_count>10:# 复杂对话使用高级模型model=advanced_modelelse:model=basic_modelreturnhandler(request.override(model=model))agent=create_agent(model=basic_model,# 默认模型tools=tools,middleware=[dynamic_model_selection])2.2 工具(Tools):智能体的行动能力
工具赋予智能体执行具体操作的能力,支持顺序调用、并行调用、动态选择和错误处理等功能。
2.2.1 定义工具
fromlangchain.toolsimporttoolfromlangchain.agentsimportcreate_agent@tooldefsearch(query:str)->str:"""搜索信息"""returnf"Results for:{query}"@tooldefget_weather(location:str)->str:"""获取指定位置的天气信息"""returnf"Weather in{location}: Sunny, 72°F"agent=create_agent(model,tools=[search,get_weather])2.2.2 工具错误处理
fromlangchain.agents.middlewareimportwrap_tool_callfromlangchain.messagesimportToolMessage@wrap_tool_calldefhandle_tool_errors(request,handler):"""处理工具执行错误的自定义中间件"""try:returnhandler(request)exceptExceptionase:# 返回自定义错误消息给模型returnToolMessage(content=f"工具错误:请检查输入后重试。({str(e)})",tool_call_id=request.tool_call["id"])agent=create_agent(model="gpt-4o",tools=[search,get_weather],middleware=[handle_tool_errors])2.2.3 ReAct循环中的工具使用示例
智能体通过ReAct循环逐步解决问题:
- 人类消息:查找当前最流行的无线耳机并检查库存
- 推理:“流行度具有时效性,我需要使用搜索工具”
- 行动:调用
search_products("wireless headphones") - 工具返回:找到5个匹配项,排名第一:WH-1000XM5
- 推理:“需要在回答前确认库存”
- 行动:调用
check_inventory("WH-1000XM5") - 工具返回:产品WH-1000XM5:库存10件
- 推理:“已获取最流行型号及库存状态,可以回答问题”
- 最终答案:生成包含具体信息的回答
2.3 系统提示(System Prompt)
系统提示用于塑造智能体的行为方式。
2.3.1 基本用法
agent=create_agent(model,tools,system_prompt="你是一个有用的助手。请保持回答简洁准确。")2.3.2 高级控制
使用SystemMessage对象可以提供更精细的控制:
fromlangchain.messagesimportSystemMessage literary_agent=create_agent(model="anthropic:claude-sonnet-4-5",system_prompt=SystemMessage(content=[{"type":"text","text":"你是一个专门分析文学作品的AI助手。"},{"type":"text","text":"<《傲慢与偏见》全书内容>","cache_control":{"type":"ephemeral"}# 启用缓存优化}]))2.3.3 动态系统提示
fromlangchain.agents.middlewareimportdynamic_prompt@dynamic_promptdefuser_role_prompt(request:ModelRequest)->str:"""根据用户角色生成系统提示"""user_role=request.runtime.context.get("user_role","user")base_prompt="你是一个有用的助手。"ifuser_role=="expert":returnf"{base_prompt}请提供详细的技术性回答。"elifuser_role=="beginner":returnf"{base_prompt}请用简单语言解释概念,避免专业术语。"returnbase_prompt agent=create_agent(model="gpt-4o",tools=[web_search],middleware=[user_role_prompt])3. 调用智能体
智能体通过向其状态(State)传递更新来调用。所有智能体都在状态中包含一系列消息。
# 基本调用result=agent.invoke({"messages":[{"role":"user","content":"旧金山现在的天气如何?"}]})# 支持流式输出# 请参考streaming guide了解流式步骤和token生成4. 高级概念
4.1 结构化输出(Structured Output)
LangChain提供两种结构化输出策略。
4.1.1 工具策略(ToolStrategy)
适用于任何支持工具调用的模型,通过“人工”工具调用来生成结构化输出。
frompydanticimportBaseModelfromlangchain.agents.structured_outputimportToolStrategyclassContactInfo(BaseModel):name:stremail:strphone:stragent=create_agent(model="gpt-4o-mini",tools=[search_tool],response_format=ToolStrategy(ContactInfo))result=agent.invoke({"messages":[{"role":"user","content":"从以下提取联系信息: John Doe, john@example.com, (555) 123-4567"}]})# 访问结构化响应print(result["structured_response"])# ContactInfo(name='John Doe', email='john@example.com', phone='(555) 123-4567')4.1.2 供应商策略(ProviderStrategy)
利用模型供应商的原生结构化输出功能,更加可靠但仅限支持此功能的供应商。
fromlangchain.agents.structured_outputimportProviderStrategy agent=create_agent(model="gpt-4o",response_format=ProviderStrategy(ContactInfo))重要提示:在LangChain 1.0中,直接传递模式(如
response_format=ContactInfo)不再支持,必须明确使用ToolStrategy或ProviderStrategy。
4.2 记忆(Memory)
智能体通过消息状态自动维护对话历史,也可以配置自定义状态模式来记住更多信息。
4.2.1 通过中间件定义状态
当自定义状态需要被特定中间件钩子和工具访问时使用。
fromlangchain.agentsimportAgentStatefromlangchain.agents.middlewareimportAgentMiddlewareclassCustomState(AgentState):user_preferences:dictclassCustomMiddleware(AgentMiddleware):state_schema=CustomState tools=[tool1,tool2]defbefore_model(self,state:CustomState,runtime):# 模型调用前的预处理逻辑passagent=create_agent(model,tools=tools,middleware=[CustomMiddleware()])result=agent.invoke({"messages":[{"role":"user","content":"我偏好技术性解释"}],"user_preferences":{"style":"technical","verbosity":"detailed"},})4.2.2 通过state_schema定义状态
作为快捷方式,当自定义状态仅在工具中使用时适用。
fromlangchain.agentsimportAgentStateclassCustomState(AgentState):user_preferences:dictagent=create_agent(model,tools=tools,state_schema=CustomState)5. 最佳实践总结
- 模型选择:简单应用使用静态模型,需要智能路由时使用动态模型
- 工具设计:为每个工具提供清晰描述和类型提示,实现适当的错误处理
- 提示工程:基础任务使用字符串提示,高级需求使用
SystemMessage或动态提示 - 输出控制:需要特定格式输出时使用结构化输出策略
- 状态管理:利用自定义状态跟踪对话上下文和用户偏好
本指南涵盖了LangChain智能体的核心概念和高级特性。实际应用中,建议从简单配置开始,逐步根据需求添加复杂度,充分利用中间件和状态管理来构建强大的智能体应用。