ReACT介绍与llama_index ReActAgent实践
Agent是大模型的重要应用方向,而ReACT是学术界提出的重要方法,本文介绍ReACT论文,然后通过llama_index ReActAgent来分析ReACT的执行过程。
ReACT
《REACT: SYNERGIZING REASONING AND ACTING IN LANGUAGE MODELS》,由Shunyu Yao等人撰写,发表在2023年的ICLR会议上。论文探讨了如何在大型语言模型(LLMs)中结合推理(reasoning)和行动(acting)的能力,以提高模型在语言理解和交互式决策制定任务中的性能。
主要观点:
- 大型语言模型(LLMs)在语言理解和交互式决策制定任务中表现出色,但它们的推理(例如链式思维提示)和行动(例如行动计划生成)能力通常被分开研究。
- 作者提出了一种新的方法ReAct,它通过交错生成推理轨迹和特定于任务的行动,使两者之间产生更大的协同效应。推理轨迹帮助模型诱导、跟踪和更新行动计划,以及处理异常情况,而行动则允许它与外部资源(如知识库或环境)接口并收集额外信息。
具体步骤:
ReAct(Reasoning and Acting)是一种结合了推理(reasoning)和行动(acting)的方法,旨在提高大型语言模型(LLMs)在解决复杂任务时的性能和可解释性。ReAct的具体步骤如下:
- 定义任务和目标:首先,明确模型需要解决的任务和目标。这可能包括问题回答、事实验证、文本游戏或网页导航等。
- 生成推理轨迹:模型生成一系列推理轨迹,这些轨迹是模型内部的思考过程,用于解决问题。这些推理轨迹可能包括分解任务目标、提取重要信息、执行常识推理、指导搜索重构、跟踪进度和处理异常等。
- 执行行动:模型根据推理轨迹执行一系列行动。在ReAct中,行动是通过与外部环境(例如Wikipedia或其他知识库)的交互来完成的。行动可以是搜索信息、选择产品、选择选项或购买等。
- 交替推理和行动:在解决任务的过程中,模型会交替进行推理和行动。这意味着模型在执行每个行动后可能会生成新的推理轨迹,然后再执行新的行动,以此往复。
- 更新上下文:每次行动后,模型会更新上下文信息,这包括之前的行动、观察结果和新生成的推理轨迹。这种上下文更新帮助模型跟踪任务的当前状态,并为未来的推理和行动提供信息。
- 生成任务解决轨迹:通过上述步骤,模型生成一个包含行动、观察和推理轨迹的任务解决轨迹。这个轨迹不仅展示了模型如何解决问题,而且提供了模型决策的透明度,使得人类用户可以理解和评估模型的行为。
- 评估和调整:在实际应用中,模型生成的任务解决轨迹可能会被人类用户评估和调整。用户提供的反馈可以用来进一步指导模型的行为,或者在模型自身无法正确解决问题时进行干预。
ReAct的核心在于通过交错的推理和行动步骤,使模型能够在执行任务时动态地进行推理和行动,从而提高任务解决的准确性和效率。这种方法特别适用于需要与外部环境交互并从中获取信息以支持决策的任务。
以llama_index ReActAgent来看ReAct 执行过程
我们编写一个简单的ReActAgent程序,计算乘法,同样的没有openai的账号,我们用google的Gemini。
from llama_index.core.agent import ReActAgent
from llama_index.core.tools import FunctionTool
from llama_index.llms.gemini import Gemini
# define sample Tool
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)
# initialize llm
llm = Gemini(api_key="AI...", transport="rest")
# initialize ReAct agent
agent = ReActAgent.from_tools([multiply_tool], llm=llm, verbose=True)
resp = agent.query("计算85乘以9")
print(resp.response)
- 第一步,将tools放入prompts,要求LLM按照要求做Thought,然后出书符合要求的response:
[ChatMessage(role=<MessageRole.SYSTEM: 'system'>, content='\nYou are designed to help with a variety of tasks, from answering questions to providing summaries to other types of analyses.\n\n## Tools\nYou have access to a wide variety of tools. You are responsible for using\nthe tools in any sequence you deem appropriate to complete the task at hand.\nThis may require breaking the task into subtasks and using different tools\nto complete each subtask.\n\nYou have access to the following tools:\n> Tool Name: multiply\nTool Description: multiply(a: int, b: int) -> int\nMultiply two integers and returns the result integer\nTool Args: {"type": "object", "properties": {"a": {"title": "A", "type": "integer"}, "b": {"title": "B", "type": "integer"}}, "required": ["a", "b"]}\n\n\n## Output Format\nPlease answer in the same language as the question and use the following format:\n\n```\nThought: The current language of the user is: (user\'s language). I need to use a tool to help me answer the question.\nAction: tool name (one of multiply) if using a tool.\nAction Input: the input to the tool, in a JSON format representing the kwargs (e.g. {"input": "hello world", "num_beams": 5})\n```\n\nPlease ALWAYS start with a Thought.\n\nPlease use a valid JSON format for the Action Input. Do NOT do this {\'input\': \'hello world\', \'num_beams\': 5}.\n\nIf this format is used, the user will respond in the following format:\n\n```\nObservation: tool response\n```\n\nYou should keep repeating the above format until you have enough information\nto answer the question without using any more tools. At that point, you MUST respond\nin the one of the following two formats:\n\n```\nThought: I can answer without using any more tools. I\'ll use the user\'s language to answer\nAnswer: [your answer here (In the same language as the user\'s question)]\n```\n\n```\nThought: I cannot answer the question with the provided tools.\nAnswer: [your answer here (In the same language as the user\'s question)]\n```\n\n## Current Conversation\nBelow is the current conversation consisting of interleaving human and assistant messages.\n\n', additional_kwargs={}), ChatMessage(role=<MessageRole.USER: 'user'>, content='计算85乘以9', additional_kwargs={})]
上述数据没有格式化,我们格式化后来看:
![[Pasted image 20240313134946.png]]
大体上就是让LLM做COT思考,然后根据用户当前的question,选择合适的tool进行计算。
- LLM 思考后,回复:
assistant: Thought: The current language of the user is: chinese. I need to use a tool to help me answer the question.
Action: multiply
Action Input: {"a": 85, "b": 9}
可以看到,给出了Action的tool,以及action的input
- llama_index 会对上面的输出进行解析
process_actions,得到:
[ActionReasoningStep(thought='The current language of the user is: chinese. I need to use a tool to help me answer the question.', action='multiply', action_input={'a': 85, 'b': 9}), ObservationReasoningStep(observation='765')]
- 得到action step后,会进行执行,调用函数计算
cur_step_output = 765
- 然后,开始next_step:
[TaskStep(task_id='1d8db1d0-f5e3-4bfa-bcef-8fc405f958ca', step_id='91e9a97a-5ae1-4900-bf77-690865976902', input=None, step_state={'is_first': False}, next_steps={}, prev_steps={}, is_ready=True)]
- 来看step如何执行,同样的拼接prompt,更新上下文,然后让大模型COT:
[ChatMessage(role=<MessageRole.SYSTEM: 'system'>, content='\nYou are designed to help with a variety of tasks, from answering questions to providing summaries to other types of analyses.\n\n## Tools\nYou have access to a wide variety of tools. You are responsible for using\nthe tools in any sequence you deem appropriate to complete the task at hand.\nThis may require breaking the task into subtasks and using different tools\nto complete each subtask.\n\nYou have access to the following tools:\n> Tool Name: multiply\nTool Description: multiply(a: int, b: int) -> int\nMultiply two integers and returns the result integer\nTool Args: {"type": "object", "properties": {"a": {"title": "A", "type": "integer"}, "b": {"title": "B", "type": "integer"}}, "required": ["a", "b"]}\n\n\n## Output Format\nPlease answer in the same language as the question and use the following format:\n\n```\nThought: The current language of the user is: (user\'s language). I need to use a tool to help me answer the question.\nAction: tool name (one of multiply) if using a tool.\nAction Input: the input to the tool, in a JSON format representing the kwargs (e.g. {"input": "hello world", "num_beams": 5})\n```\n\nPlease ALWAYS start with a Thought.\n\nPlease use a valid JSON format for the Action Input. Do NOT do this {\'input\': \'hello world\', \'num_beams\': 5}.\n\nIf this format is used, the user will respond in the following format:\n\n```\nObservation: tool response\n```\n\nYou should keep repeating the above format until you have enough information\nto answer the question without using any more tools. At that point, you MUST respond\nin the one of the following two formats:\n\n```\nThought: I can answer without using any more tools. I\'ll use the user\'s language to answer\nAnswer: [your answer here (In the same language as the user\'s question)]\n```\n\n```\nThought: I cannot answer the question with the provided tools.\nAnswer: [your answer here (In the same language as the user\'s question)]\n```\n\n## Current Conversation\nBelow is the current conversation consisting of interleaving human and assistant messages.\n\n', additional_kwargs={}), ChatMessage(role=<MessageRole.USER: 'user'>, content='计算85乘以9', additional_kwargs={}), ChatMessage(role=<MessageRole.ASSISTANT: 'assistant'>, content="Thought: The current language of the user is: chinese. I need to use a tool to help me answer the question.\nAction: multiply\nAction Input: {'a': 85, 'b': 9}", additional_kwargs={}), ChatMessage(role=<MessageRole.USER: 'user'>, content='Observation: 765', additional_kwargs={})]
- 大模型回复:
assistant: Thought: I can answer without using any more tools. I'll use the user's language to answer
Answer: 765
- 上述的回复已经没有新的action了,因此解析不出来action,next_steps就为空了,计算结束,返回答案
- 这里的计算比较简单,一步action就搞定了,对于需要多步action的,会按照下面的流程图,递归的执行,直到得到
Final Answer- 思考Thought
- 得到要执行的Action
- 执行Action,得到观测结果 Observation
- 将上下文,连同Observation,让大模型继续思考Thought
- 直到没有Action,给出最后的Filnal Answer

ReACT介绍与llama_index ReActAgent实践的更多相关文章
- immutable.js 在React、Redux中的实践以及常用API简介
immutable.js 在React.Redux中的实践以及常用API简介 学习下 这个immutable Data 是什么鬼,有什么优点,好处等等 mark : https://yq.aliyu ...
- 【前端,干货】react and redux教程学习实践(二)。
前言 这篇博文接 [前端]react and redux教程学习实践,浅显易懂的实践学习方法. ,上一篇简略的做了一个redux的初级demo,今天深入的学习了一些新的.有用的,可以在生产项目中使用的 ...
- Cmake的介绍和使用 Cmake实践【转】
本文转载自:http://www.cppblog.com/Roger/archive/2011/11/17/160368.html Cmake的介绍和使用 Cmake实践 Cmake优点: 1. ...
- Cmake的介绍和使用 Cmake实践
Cmake的介绍和使用 Cmake实践http://www.cppblog.com/Roger/archive/2011/11/17/160368.html
- react介绍、环境搭建、demo运行实例
React官网:https://reactjs.org/docs/create-a-new-react-app.html cnpm网址:http://npm.taobao.org/ 1.react介绍 ...
- 【前端】react and redux教程学习实践,浅显易懂的实践学习方法。
前言 前几天,我在博文[前端]一步一步使用webpack+react+scss脚手架重构项目 中搭建了一个react开发环境.然而在实际的开发过程中,或者是在对源码的理解中,感受到react中用的最多 ...
- Immutable.js 以及在 react+redux 项目中的实践
来自一位美团大牛的分享,相信可以帮助到你. 原文链接:https://juejin.im/post/5948985ea0bb9f006bed7472?utm_source=tuicool&ut ...
- react系列从零开始-react介绍
react算是目前最火的js MVC框架了,写一个react系列的博客,顺便回忆一下react的基础知识,新入门前端的小白,可以持续关注,我会从零开始教大家用react开发一个完整的项目,也会涉及到w ...
- 1. React介绍 React开发环境搭建 React第一个程序
什么是 React React 是 Facebook 发布的 JavaScript 库,以其高性能和独特的设计理念受到了广泛关注. React的开发背景 Faceboo ...
- React教程(一) React介绍与搭建
React的介绍: React来自于Facebook公司的开源项目 React 可以开发单页面应用 spa(单页面应用) react 组件化模块化 开发模式 React通过对DOM的模拟(虚拟dom) ...
随机推荐
- LyScriptTools 模块类API接口手册
LyScriptTools工具包是在LyScript模块基础上封装的工具包,其主要是二次封装LyScript插件实现的一些新功能,或者将特定功能组件拆分开形成的独立模块,此类模块可实现更加精细化的功能 ...
- Redis安装,数据类型及常用命令
安装 - 可以使用yum 安装,要先配置epel源 ``` yum install -y redis ``` - 可以编译安装 ``` wget http://download.redis.io/re ...
- unordered_map模拟实现|STL源码剖析系列|开散列
博主很久没有更新过STL源码剖析这个系列的文章了,主要是因为大部分STL常用的容器,博主都已经发过文章了,今天博主带着大家把哈希表也模拟实现一下. 前言 那么这里博主先安利一下一些干货满满的专栏啦! ...
- CF1515F Phoenix and Earthquake 题解
题目链接:CF 或者 洛谷 首先基于一个事实,答案一定是生成树,显然,每次我们都需要连边,每次都会 \(-x\),那么一共会减少 \((n-1)\times x\),很显然的一个必要条件为: \[\s ...
- Linux离线安装MySQL(5.7.22)
1.下载tar包 (1)Window PC下载(PC需要联网) MySQL官网地址:https://www.mysql.com/ MySQL社区版下载地址: https://dev.mysql.com ...
- C++ map自定义比较函数遵守严格弱序
C++ map自定义比较函数遵守严格弱序 问题背景及定位 背景:这个问题是在将tablesaw(一个Java的数据处理项目)迁移到C++时出现的. 问题位置:SplitOn()函数,在数据流水线中的a ...
- JS Leetcode 155. 最小栈 题解分析
壹 ❀ 引 本题来自LeetCode155. 最小栈,难度简单,题目描述如下: 设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈. push(x) -- 将元素 x ...
- Linux常用的20个命令(下)
无论你是后端程序员还是前端程序员,都避免不了和Linux打交道.上篇介绍了Linux常用的20个命令其中的10个,本文继续介绍剩下的10个命令. 11.man 命令 manual的缩写,即使用手册的意 ...
- java 从零开始手写 redis(十)缓存淘汰算法 LFU 最少使用频次
前言 java从零手写实现redis(一)如何实现固定大小的缓存? java从零手写实现redis(三)redis expire 过期原理 java从零手写实现redis(三)内存数据如何重启不丢失? ...
- 2022年3月核心库MySQL优化总结
2021年9月底到新公司,公司核心数据库,以前无专业DBA维护,问题多,隐患大,到2022年2月持续后,优化至今: 优化大项: 1,从1主3从,扩容到1主5从,将部分读放都另外新加从库 2,最大表 ...