LlamaIndex 实现 React Agent

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 integers and returns the result integer"""
    return a * b


multiply_tool = FunctionTool.from_defaults(fn=multiply)

def add(a: int, b: int) -> int:
    """Add two integers and returns the result integer"""
    return a + b


add_tool = FunctionTool.from_defaults(fn=add)


init_model()


agent = ReActAgent.from_tools([multiply_tool, add_tool], verbose=True)

response = agent.chat("What is 20+(2*4)? Calculate step by step ")

实现 Agent 主要通过 FunctionTool 和 ReactAgent,分别看一下两个类的主要作用。

FunctionTool

FunctionTool 用来定义外部工具,包括 Function 的详细信息,功能描述、入参和出参等信息,通过跟踪可以看到,代码首先创建了两个 FunctionTool,ToolMetadata 定义了工具的详细信息。


ReactAgent

创建 ReactAgent,传入 tools、llm,max_iteration 是指最大推理次数,默认为 10 次。

调用 self._react_chat_formatter 准备提示词,提示词准备完成之后,调用 LLM大模型进行处理。

解析大模型返回结果并调用对应 Function。

每一步的结果都会存储在 Memory 中,作为历史在下一步中传给 LLM 进行处理。

总结

LlamaIndex 通过提示词将问题与工具进行关联,通过多轮推理得到最终答案。核心还是在提示词,无论 RAG 还是 Agent,都是作为桥梁,底层逻辑还是通过提示词的方式把大模型的能力外部应用能力打通并进行整合。

相关推荐
uuukashiro6 小时前
数据湖可以进行Upsert吗?腾讯云DLC用Serverless架构破解实时数据更新难题
ai·架构·serverless·腾讯云
爱吃烤鸡翅的酸菜鱼7 小时前
深度解析《AI+Java编程入门》:一本为零基础重构的Java学习路径
java·人工智能·后端·ai
uuukashiro8 小时前
多模态数据管理挑战重重?腾讯云数据湖计算DLC以Serverless架构破局
ai·架构·serverless·腾讯云
寒秋丶10 小时前
Milvus:Json字段详解(十)
数据库·人工智能·python·ai·milvus·向量数据库·rag
仙人掌_lz18 小时前
Multi-Agent的编排模式总结/ Parlant和LangGraph差异对比
人工智能·ai·llm·原型模式·rag·智能体
武子康1 天前
AI研究-120 DeepSeek-OCR 从 0 到 1:上手路线、实战要点
人工智能·深度学习·机器学习·ai·ocr·deepseek·deepseek-ocr
ApacheSeaTunnel1 天前
LLM 时代,DataAgent × WhaleTunnel 如何将数据库变更瞬时 “转译” 为洞察?
大数据·ai·开源·llm·数据同步·白鲸开源·whaletunnel
武子康1 天前
AI研究-118 具身智能 Mobile-ALOHA 解读:移动+双臂模仿学习的开源方案(含论文/代码/套件链接)
人工智能·深度学习·学习·机器学习·ai·开源·模仿学习
Geo_V1 天前
提示词工程
人工智能·python·算法·ai
开水好喝1 天前
Rovo Automation - TestRail Agent设计支持用例编写
ai·自然语言处理·ask rovo