添加其他工具
现在你已经构建了一个功能强大的代理,我们希望你对它所能做的事情感到兴奋。扩展代理能力的核心是可用的工具,我们有好消息:LlamaIndex的LlamaHub有数百个集成,包括数十个现有的代理工具,你可以立即使用。我们将向你展示如何使用其中一个现有工具,以及如何构建和贡献你自己的工具。
使用LlamaHub中的现有工具
在我们的示例中,我们将使用LlamaHub中的Yahoo Finance工具。它提供了一组六个代理工具,用于查找有关股票代码的各种信息。
首先我们需要安装这个工具:
pip install llama-index-tools-yahoo-finance
然后我们可以设置依赖项。这与我们之前的示例完全相同,除了最后的导入:
from dotenv import load_dotenv
load_dotenv()
from llama_index.core.agent import ReActAgent
from llama_index.llms.openai import OpenAI
from llama_index.core.tools import FunctionTool
from llama_index.core import Settings
from llama_index.tools.yahoo_finance import YahooFinanceToolSpec
为了展示自定义工具和LlamaHub工具如何一起工作,我们将包含之前示例中定义“乘法”工具的代码。我们还将借此机会设置LLM:
# settings
Settings.llm = OpenAI(model="gpt-4o", temperature=0)
# function tools
def multiply(a: float, b: float) -> float:
"""Multiply two numbers and returns the product"""
return a * b
multiply_tool = FunctionTool.from_defaults(fn=multiply)
def add(a: float, b: float) -> float:
"""Add two numbers and returns the sum"""
return a + b
add_tool = FunctionTool.from_defaults(fn=add)
现在我们将进行新的步骤,即获取工具数组:
finance_tools = YahooFinanceToolSpec().to_tool_list()
这只是一个普通的数组,所以我们可以使用Python的extend方法将我们自己的工具添加到其中:
finance_tools.extend([multiply_tool, add_tool])
然后我们像往常一样设置代理,并提出一个问题:
agent = ReActAgent.from_tools(finance_tools, verbose=True)
response = agent.chat("What is the current price of NVDA?")
print(response)
响应非常冗长,所以我们截断了它:
Thought: The current language of the user is English. I need to use a tool to help me answer the question.
Action: stock_basic_info
Action Input: {'ticker': 'NVDA'}
Observation: Info:
{'address1': '2788 San Tomas Expressway'
...
'currentPrice': 135.58
...}
Thought: I have obtained the current price of NVDA from the stock basic info.
Answer: The current price of NVDA (NVIDIA Corporation) is $135.58.
The current price of NVDA (NVIDIA Corporation) is $135.58.
完美!正如你所见,使用现有工具非常简单。
像往常一样,你可以查看仓库以查看所有代码。
构建和贡献你自己的工具
我们喜欢开源的新工具贡献!你可以查看Yahoo Finance工具的代码示例:
- 一个继承自BaseToolSpec的类
- 一组任意的Python函数
- 一个将函数映射到工具API的spec_functions列表
一旦你有了一个工作的工具,请按照我们的贡献指南获取正确设置元数据和提交拉取请求的说明。
恭喜!你已经完成了我们关于使用LlamaIndex构建代理的指南。我们迫不及待地想看看你构建的用例!