
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:
Web Accessibility (WCAG 2 AA))下载将 WCAG 2 AA 无障碍标准应用于设计系统、UI 组件和网页——通过可运行的验证器进行对比度计算,采用设计 token 模式使颜色天生可访问,设定排版和焦点状态规则,并提供语义检查清单。适用于构建或审查 UI。
from langchain.chat_models import ChatOpenAI llm = ChatOpenAI(temperature=0)
-
创建代理 (Agent): 使用
ZeroShotAgent或其他合适的代理类型,并配置提示词 (prompt):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 提供了更精细的控制和更清晰的执行流程,从而提升了开发效率和代码可读性。

















