添加其他工具#
既然您已经构建了一个功能强大的 Agent,我们希望您对其能力感到兴奋。扩展 Agent 能力的核心在于可用的工具,这里有个好消息:来自 LlamaIndex 的 LlamaHub 拥有数百个集成,包括 数十个您可以立即使用的现有 Agent 工具。我们将向您展示如何使用其中一个现有工具,以及如何构建和贡献您自己的工具。
使用 LlamaHub 中的现有工具#
在本示例中,我们将使用来自 LlamaHub 的 Yahoo Finance 工具。它提供了一组六个 Agent 工具,用于查找股票代码的各种信息。
首先我们需要安装该工具
pip install llama-index-tools-yahoo-finance
我们的依赖项与之前的示例相同,只需要添加 Yahoo Finance 工具即可
from llama_index.tools.yahoo_finance import YahooFinanceToolSpec
为了展示如何将自定义工具与 LlamaHub 工具结合使用,即使在此处不需要它们,我们也会保留 add
和 multiply
函数。我们将引入我们的工具
finance_tools = YahooFinanceToolSpec().to_tool_list()
工具列表只是一个数组,因此我们可以使用 Python 的 extend
方法将我们自己的工具添加到其中
finance_tools.extend([multiply, add])
我们将提出一个与上次不同的问题,这需要使用新的工具
workflow = FunctionAgent(
name="Agent",
description="Useful for performing financial operations.",
llm=OpenAI(model="gpt-4o-mini"),
tools=finance_tools,
system_prompt="You are a helpful assistant.",
)
async def main():
response = await workflow.run(
user_msg="What's the current stock price of NVIDIA?"
)
print(response)
我们得到以下响应
The current stock price of NVIDIA Corporation (NVDA) is $128.41.
(这有点投机取巧,因为我们的模型已经知道 NVIDIA 的股票代码。如果是一家不太知名的公司,您将需要添加一个像 Tavily 这样的搜索工具来查找股票代码。)
就是这样!您现在可以在 Agent 中使用 LlamaHub 中的任何工具了。
一如既往,您可以查看仓库,在一个地方查看所有这些代码。
构建和贡献您自己的工具#
我们非常欢迎新的工具开源贡献!您可以看到Yahoo Finance 工具代码示例的样子:* 继承自 BaseToolSpec
的类 * 一组任意的 Python 函数 * 一个将函数映射到工具 API 的 spec_functions
列表
一旦您构建的工具可以工作,请遵循我们的贡献指南,以获取正确设置元数据和提交拉取请求的说明。
接下来我们将看看如何在 Agent 中维护状态。