React Agent 是指 LLM 对问题自行推理并调用外部工具解决问题,如下图所示,通过一些推理步骤最终找到想要的答案。
LlamaIndex 提供了实现 React Agent 的框架,通过框架可以轻松的实现上图中的步骤。那么,如果不用 LlamaIndex 应该如何实现一个 Agent 呢?首先,需要将需要调用的外部 API 和问题提供给LLM,LLM 判断得到结果是否需要调用API,如果需要调用,将 API 名称和参数相关信息返回到应用端,应用端执行API 并将结果再次传给 LLM,LLM 再次判断是否需要调用外部工具,这是个循环的过程,直到 LLM 得到答案。通过代码,分析一下 LlamaIndex 是如何实现 ReactAgent 多轮对话的。
用 LlamaIndex 实现 ReactAgent 代码如下:
from llama_index.core.agent import ReActAgent
from llama_index.llms.openai import OpenAI
from llama_index.core.tools import BaseTool, FunctionTool
from utils import init_model
import sys, os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'parent_directory')))
def multiply(a: int, b: int) -> int:
"""Multiply two intege