
Langchain 中 initialize_agent 的替代方案:AgentExecutor
由于 Langchain 中的 initialize_agent 函数已被弃用,推荐使用更灵活强大的 AgentExecutor 类来替代。AgentExecutor 提供更精细的代理任务管理和执行能力。
以下步骤演示如何使用 AgentExecutor:
-
定义工具 (Tools): 首先,创建代理将使用的工具列表。每个工具使用
Tool类定义,例如使用 Google 搜索 API:from langchain.agents import Tool from langchain.utilities import GoogleSearchAPIWrapper search = GoogleSearchAPIWrapper() tools = [ Tool( name="Google Search", func=search.run, description="Useful for answering questions about current events." ) ] -
选择语言模型 (LLM): 选择合适的语言模型,例如
ChatOpenAI:from langchain.chat_models import ChatOpenAI llm = ChatOpenAI(temperature=0)
-
创建代理 (Agent): 使用
ZeroShotAgent或其他合适的代理类型,并配置提示词 (prompt):
盛世企业网站管理系统1.1.2下载免费 盛世企业网站管理系统(SnSee)系统完全免费使用,无任何功能模块使用限制,在使用过程中如遇到相关问题可以去官方论坛参与讨论。开源 系统Web代码完全开源,在您使用过程中可以根据自已实际情况加以调整或修改,完全可以满足您的需求。强大且灵活 独创的多语言功能,可以直接在后台自由设定语言版本,其语言版本不限数量,可根据自已需要进行任意设置;系统各模块可在后台自由设置及开启;强大且适用的后台管理支
from langchain.agents import ZeroShotAgent, AgentExecutor prompt = ZeroShotAgent.create_prompt( tools, prefix="Answer the following questions as best you can. You have access to the following tools:", suffix="Begin!" ) agent = ZeroShotAgent(llm=llm, allowed_tools=tools, prompt=prompt) -
初始化
AgentExecutor: 使用AgentExecutor.from_agent_and_tools将代理和工具整合:agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True)
-
执行代理任务: 调用
agent_executor.run()执行任务:response = agent_executor.run("What's the weather like today in Beijing?") print(response)
通过以上步骤,您可以有效地替代 initialize_agent,并利用 AgentExecutor 的优势来构建和运行更强大的 Langchain 代理。 AgentExecutor 提供了更精细的控制和更清晰的执行流程,从而提升了开发效率和代码可读性。









