在 langchain 中 initialize_agent 被禁用后,应该如何进行替代?

在 langchain 中 initialize_agent 被禁用后,应该如何进行替代?

Langchain initialize_agent 函数已被弃用后的替代方案

Langchain 的 initialize_agent 函数已被弃用,这是为了提升框架的灵活性及模块化程度。本文将介绍如何使用更细粒度的 API 调用来替代它。

主要替代方法有两种:

1. 使用 AgentExecutor:

AgentExecutorinitialize_agent 的直接替代品,它允许更灵活地构建和管理 Agent。以下是一个使用 ZeroShotAgentAgentExecutor 的示例:

from langchain.agents import AgentExecutor, ZeroShotAgentfrom langchain import LLMChain, PromptTemplatefrom langchain.llms import OpenAI  # 或者其他LLMllm = OpenAI(temperature=0) # 使用OpenAI模型,可替换为其他LLMprompt = PromptTemplate(    input_variables=["input", "agent_scratchpad"],    template="Answer the following question: {input}nn{agent_scratchpad}")llm_chain = LLMChain(llm=llm, prompt=prompt)tools = [...]  # 你的工具列表,例如搜索工具、计算工具等agent = ZeroShotAgent(llm_chain=llm_chain, tools=tools)agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True)# 使用 agent_executor 执行任务result = agent_executor.run("你的问题或任务")print(result)

2. 自定义 Agent:

对于更复杂的场景,你可以自定义 Agent。这需要你手动组合不同的工具和链,以满足特定需求。

from langchain.agents import Tool, AgentExecutorfrom langchain.chains import LLMChainfrom langchain.llms import OpenAI # 或者其他LLMfrom langchain.prompts import PromptTemplatellm = OpenAI(temperature=0) # 使用OpenAI模型,可替换为其他LLM# 定义工具tool1 = Tool(name="tool1", func=lambda x: "tool1 的结果", description="tool1 的描述")tool2 = Tool(name="tool2", func=lambda x: "tool2 的结果", description="tool2 的描述")tools = [tool1, tool2]# 定义提示模板 (根据你的Agent类型调整)prompt_template = """Use the following tools to answer the question.{tools}Question: {input}{agent_scratchpad}"""prompt = PromptTemplate(    input_variables=["input", "agent_scratchpad", "tools"],    template=prompt_template,)# 创建 LLM 链llm_chain = LLMChain(llm=llm, prompt=prompt)# 创建自定义 Agent (根据你的需求选择合适的Agent类型,例如ZeroShotAgent,  ConversationAgent等)#  agent = ZeroShotAgent(llm_chain=llm_chain, tools=tools)  # 例如ZeroShotAgent#  agent = ... # 其他Agent类型# 创建 AgentExecutoragent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True)# 运行 agentresult = agent_executor.run("你的问题或任务")print(result)

记住替换代码中的 ...你的问题或任务 为你实际的工具和问题。 选择哪种方法取决于你的应用场景和复杂度。 AgentExecutor 提供了更简便的途径,而自定义 Agent 则提供了更大的灵活性。 确保安装必要的 Langchain 包以及选择的LLM。

以上就是在 langchain 中 initialize_agent 被禁用后,应该如何进行替代?的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1359519.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月13日 22:48:22
下一篇 2025年12月13日 22:48:35

相关推荐

发表回复

登录后才能评论
关注微信