
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中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                 
                                
                                 收藏
收藏
                                                                             
                                
                                 收藏
收藏
                                                                             
                                
                                 收藏
收藏
                                                                            Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号