能否为create_react_agent()与工具分别使用不同大语言模型?
为LangChain React智能体与工具配置不同大语言模型
完全可以为LangChain的React智能体和工具链分别使用不同的大语言模型。LangChain的组件化设计允许你独立为智能体决策层、各工具内部的LLM调用指定不同模型,适配不同场景的需求(比如智能体用擅长推理的模型,工具用擅长特定任务的模型)。
代码示例
以下是一个简单实现:
from langchain.agents import create_react_agent, AgentExecutor from langchain.prompts import PromptTemplate from langchain_core.output_parsers import StrOutputParser from langchain_openai import ChatOpenAI from langchain_anthropic import ChatAnthropic # 1. 定义两个不同的LLM # 智能体决策用的LLM(比如GPT-3.5) agent_llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0) # 工具链用的LLM(比如Claude 2) tool_llm = ChatAnthropic(model="claude-2", temperature=0) # 2. 定义使用独立LLM的工具 def custom_tool(input_text): # 工具内部使用tool_llm处理任务 prompt = PromptTemplate( template="请详细分析以下文本的核心观点:{text}", input_variables=["text"] ) chain = prompt | tool_llm | StrOutputParser() return chain.invoke({"text": input_text}) # 包装工具为LangChain格式 tools = [ { "name": "文本分析工具", "description": "用于分析文本的核心观点,输入为需要分析的文本内容", "func": custom_tool } ] # 3. 创建React智能体(使用agent_llm做决策) agent_prompt = PromptTemplate.from_template(""" 你是一个智能助手,根据用户的问题选择合适的工具处理。 工具列表:{tools} 请按照以下格式思考和输出: Thought: 我需要使用哪个工具? Action: 工具名称 Action Input: 工具输入内容 Observation: 工具返回结果 ...(重复思考-行动-观察步骤) Thought: 我已经得到答案了 Final Answer: 最终答案 用户问题:{input} """) agent = create_react_agent(agent_llm, tools, agent_prompt) agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True) # 测试调用 result = agent_executor.invoke({"input": "请分析以下文本的核心观点:人工智能正在改变各行各业的生产方式,尤其是在制造业的自动化和服务业的客户交互场景中,效率提升明显。"}) print(result["output"])
交互流程示意图
sequenceDiagram participant 用户 participant 智能体决策层(agent_llm: GPT-3.5) participant 工具链(tool_llm: Claude 2) 用户->>智能体决策层: 提交问题 智能体决策层->>智能体决策层: 分析问题,判断需要调用"文本分析工具" 智能体决策层->>工具链: 传递待分析文本 工具链->>工具链: 使用Claude 2处理文本,生成分析结果 工具链->>智能体决策层: 返回分析结果 智能体决策层->>智能体决策层: 确认结果足够回答问题 智能体决策层->>用户: 返回最终答案
内容的提问来源于stack exchange,提问作者Kt Student
相关产品推荐
相关产品推荐

