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:
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 提供了更精細的控制和更清晰的執行流程,從而提升了開發效率和代碼可讀性。
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END