网站内容建设和运营工作,企业网站设计方案书,项目可行性研究报告,互联网推广计划概述
ReAct 是一种基于Agent的聊天模式#xff0c;构建在数据查询引擎之上。对于每次聊天交互#xff0c;代理都会进入一个 ReAct 循环#xff1a; 首先决定是否使用查询引擎工具并提出适当的输入 #xff08;可选#xff09;使用查询引擎工具并观察其输出 决定是否重复…概述
ReAct 是一种基于Agent的聊天模式构建在数据查询引擎之上。对于每次聊天交互代理都会进入一个 ReAct 循环 首先决定是否使用查询引擎工具并提出适当的输入 可选使用查询引擎工具并观察其输出 决定是否重复或给出最终答复
这种方法很灵活因为它可以灵活地选择是否查询知识库它是基于Agent来实现的。然而表现也更依赖于LLM的质量。您可能需要进行更多强制以确保它选择在正确的时间查询知识库而不是产生幻觉答案。 实现逻辑 构建和使用本地大模型。这里使用的是gemma2这个模型也可以配置其他的大模型。 从文档中构建索引 把索引转换成查询引擎index.as_chat_engine并设置chat_mode为react。 注意我这里使用的是本地大模型gemm2效果可能没有openai的好。 实现代码
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Settings
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.llms.ollama import Ollamalocal_model /opt/models/BAAI/bge-base-en-v1.5# bge-base embedding model
Settings.embed_model HuggingFaceEmbedding(model_namelocal_model)
# ollama
Settings.llm Ollama(modelgemma2, request_timeout360.0)from llama_index.core import VectorStoreIndex, SimpleDirectoryReaderdata SimpleDirectoryReader(input_dir./data/paul_graham/).load_data()
index VectorStoreIndex.from_documents(data)# 设置使用react模式
chat_engine index.as_chat_engine(chat_modereact, llmSettings.llm, verboseTrue)response chat_engine.chat( Use the tool to answer what did Paul Graham do in the summer of 1995?)输出
从以下输出可以看到不同大模型的输出不太相同。Agent通过查询引擎获取到了对应的索引和文本信息。
$ 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. Ill use the users language to answer
Answer: In the summer of 1995, Paul Graham worked on his Lisp-based web server.
实现分析
从以下实现代码中可以看到当聊天模式是REACT模式时会创建一个AgentRunner并把查询引擎作为工具放入Agent工具列表中。 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 importfrom llama_index.core.agent import AgentRunnerfrom llama_index.core.tools.query_engine import QueryEngineTool
# convert query engine to toolquery_engine_tool QueryEngineTool.from_defaults(query_enginequery_engine)
return AgentRunner.from_llm(tools[query_engine_tool],llmllm,**kwargs,) 小结
通过REACT模式会创建一个Agent并把查询引擎作为工具放到该Agent中。然后通过查询引擎的能力来查询想要的内容。