llamaindex实战-ChatEngine-ReAct Agent模式

概述

ReAct 是一种基于Agent的聊天模式,构建在数据查询引擎之上。对于每次聊天交互,代理都会进入一个 ReAct 循环:

  • 首先决定是否使用查询引擎工具并提出适当的输入

  • (可选)使用查询引擎工具并观察其输出

  • 决定是否重复或给出最终答复

这种方法很灵活,因为它可以灵活地选择是否查询知识库,它是基于Agent来实现的。然而,表现也更依赖于LLM的质量。您可能需要进行更多强制,以确保它选择在正确的时间查询知识库,而不是产生幻觉答案。

实现逻辑

  1. 构建和使用本地大模型。这里使用的是gemma2这个模型,也可以配置其他的大模型。

  2. 从文档中构建索引

  3. 把索引转换成查询引擎:index.as_chat_engine,并设置chat_mode为react。

注意:我这里使用的是本地大模型gemm2,效果可能没有openai的好。

实现代码

python 复制代码
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Settings
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.llms.ollama import Ollama

local_model = "/opt/models/BAAI/bge-base-en-v1.5"

# bge-base embedding model
Settings.embed_model = HuggingFaceEmbedding(model_name=local_model)
# ollama
Settings.llm = Ollama(model="gemma2", request_timeout=360.0)

from llama_index.core import VectorStoreIndex, SimpleDirectoryReader

data = SimpleDirectoryReader(input_dir="./data/paul_graham/").load_data()
index = VectorStoreIndex.from_documents(data)

# 设置使用react模式
chat_engine = index.as_chat_engine(chat_mode="react", llm=Settings.llm, verbose=True)

response = chat_engine.chat( "Use the tool to answer what did Paul Graham do in the summer of 1995?")

输出

从以下输出可以看到,不同大模型的输出不太相同。Agent通过查询引擎获取到了对应的索引和文本信息。

bash 复制代码
$ python chat_react.py 
> Running step 3e748b23-a1bb-4807-89f6-7bda3b418b86. Step input: Use the tool to answer what did Paul Graham do in the summer of 1995?
Thought: The current language of the user is: English. I need to use a tool to help me answer the question.
Action: query_engine_tool
Action Input: {'input': 'What did Paul Graham do in the summer of 1995?'}
Observation: He worked on his Lisp-based web server.  
​
> Running step 5f4592b6-f1d0-4fcf-8b03-a50d46641ef2. Step input: None
Thought: I can answer without using any more tools. I'll use the user's language to answer
Answer: In the summer of 1995, Paul Graham worked on his Lisp-based web server.

实现分析

从以下实现代码中可以看到,当聊天模式是REACT模式时,会创建一个AgentRunner,并把查询引擎作为工具放入Agent工具列表中。

python 复制代码
  def as_chat_engine(
        self,
        chat_mode: ChatMode = ChatMode.BEST,
        llm: Optional[LLMType] = None,
        **kwargs: Any,
    ) -> BaseChatEngine:    
    
           if chat_mode in [ChatMode.REACT, ChatMode.OPENAI, ChatMode.BEST]:
            # use an agent with query engine tool in these chat modes
            # NOTE: lazy import
            from llama_index.core.agent import AgentRunner
            from llama_index.core.tools.query_engine import QueryEngineTool
​
            # convert query engine to tool
            query_engine_tool = QueryEngineTool.from_defaults(query_engine=query_engine)
​
            return AgentRunner.from_llm(
                tools=[query_engine_tool],
                llm=llm,
                **kwargs,
            )

小结

通过REACT模式,会创建一个Agent,并把查询引擎作为工具放到该Agent中。然后,通过查询引擎的能力来查询想要的内容。

相关推荐
青松@FasterAI40 分钟前
【程序员 NLP 入门】词嵌入 - 上下文中的窗口大小是什么意思? (★小白必会版★)
人工智能·自然语言处理
AIGC大时代1 小时前
高效使用DeepSeek对“情境+ 对象 +问题“型课题进行开题!
数据库·人工智能·算法·aigc·智能写作·deepseek
硅谷秋水1 小时前
GAIA-2:用于自动驾驶的可控多视图生成世界模型
人工智能·机器学习·自动驾驶
偶尔微微一笑1 小时前
AI网络渗透kali应用(gptshell)
linux·人工智能·python·自然语言处理·编辑器
Want5951 小时前
从ChatGPT到GPT-4:大模型如何重塑人类认知边界?
chatgpt·aigc
深度之眼1 小时前
2025时间序列都有哪些创新点可做——总结篇
人工智能·深度学习·机器学习·时间序列
晓数2 小时前
【硬核干货】JetBrains AI Assistant 干货笔记
人工智能·笔记·jetbrains·ai assistant
jndingxin2 小时前
OpenCV 图形API(60)颜色空间转换-----将图像从 YUV 色彩空间转换为 RGB 色彩空间函数YUV2RGB()
人工智能·opencv·计算机视觉
Sherlock Ma2 小时前
PDFMathTranslate:基于LLM的PDF文档翻译及双语对照的工具【使用教程】
人工智能·pytorch·语言模型·pdf·大模型·机器翻译·deepseek
知舟不叙2 小时前
OpenCV中的SIFT特征提取
人工智能·opencv·计算机视觉