在 LangChain 中,如何使用 AgentExecutor 替代已被禁用的 initialize_agent 函数?

在 LangChain 中,如何使用 AgentExecutor 替代已被禁用的 initialize_agent 函数?

LangChain 中 initialize_agent 函数的替代方案:使用 AgentExecutor

LangChain 的 initialize_agent 函数已被弃用,推荐使用更灵活的 AgentExecutor 类来初始化和运行代理。 AgentExecutor 提供了更精细的控制和定制选项。 下面是使用 AgentExecutor 的步骤:

1. 导入必要的模块:

from langchain.agents import AgentExecutor from langchain.agents.tools import Tool

2. 定义工具 (Tools):

代理需要一系列工具来完成任务。这些工具可以是函数、API 调用或其他可执行单元。 例如:

def search_tool(query):     #  此处实现你的搜索逻辑,例如使用 SerpAPI 或其他搜索引擎     #  ...     return "搜索结果"  tools = [     Tool(         name="Search",         func=search_tool,         description="用于搜索信息的工具,输入查询关键词。"     ) ]

3. 创建代理 (Agent):

选择合适的代理类型,例如 ZeroShotAgent 或其他。 以下示例使用 ZeroShotAgent:

from langchain.agents import ZeroShotAgent from langchain import LLMChain, SerpAPIWrapper  # 替换为你的LLM和搜索工具  #  替换为你的LLM llm = ...   search = SerpAPIWrapper() # 或其他搜索工具 tools = [     Tool(         name="Calculator",         func=lambda x: str(eval(x)), #简单的计算器示例,实际应用中需更完善的处理         description="用于进行简单数学计算的工具,输入数学表达式。"     ),     Tool(         name="Search",         func=search.run,         description="用于搜索信息的工具,输入查询关键词。"     ) ]  prompt = ZeroShotAgent.create_prompt(     tools,     prefix="请根据以下工具回答问题:",     suffix="开始!" )  llm_chain = LLMChain(llm=llm, prompt=prompt) agent = ZeroShotAgent(llm_chain=llm_chain, tools=tools)

4. 初始化并使用 AgentExecutor:

agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True)  response = agent_executor.run("东京的人口是多少?") print(response)

通过以上步骤,你便可以使用 AgentExecutor 来替代被禁用的 initialize_agent 函数,并更有效地管理和运行你的 LangChain 代理。 记住替换示例代码中的占位符 (…) 为你实际使用的 LLM 和工具。 verbose=True 将打印代理的推理过程,方便调试。

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享