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

碧海醫心
发布: 2025-03-17 08:24:15
原创
901人浏览过

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

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

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

主要替代方法有两种:

1. 使用 AgentExecutor:

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

from langchain.agents import AgentExecutor, ZeroShotAgent
from langchain import LLMChain, PromptTemplate
from langchain.llms import OpenAI  # 或者其他LLM

llm = OpenAI(temperature=0) # 使用OpenAI模型,可替换为其他LLM

prompt = PromptTemplate(
    input_variables=["input", "agent_scratchpad"],
    template="Answer the following question: {input}\n\n{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, AgentExecutor
from langchain.chains import LLMChain
from langchain.llms import OpenAI # 或者其他LLM
from langchain.prompts import PromptTemplate

llm = 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类型


# 创建 AgentExecutor
agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True)

# 运行 agent
result = agent_executor.run("你的问题或任务")
print(result)
登录后复制

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

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

豆包AI编程
豆包AI编程

智能代码生成与优化,高效提升开发速度与质量!

下载
相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号