微信扫码
与创始人交个朋友
我要投稿
ContextChatEngine 类是一个上下文聊天引擎,目的是:通过检索聊天的上下文信息、设置系统提示使用语言模型(LLM)生成响应,从而提供流畅的聊天体验。
它是一种简单的聊天模式,构建在数据检索器(retriever)之上。对于每个聊天交互:
首先使用用户消息从索引中检索文本
将检索到的文本设置为系统提示中的上下文
返回用户消息的答案
这种方法很简单,适用于与知识库和一般交互直接相关的问题。
构建和使用本地大模型。这里使用的是gemma2这个模型,也可以配置其他的大模型。
从文档中构建索引
定义一个memory buffer用来保存历史的聊天内容
把索引转换成查询引擎:index.as_chat_engine
,并设置chat_mode,和历史消息的内存buffer。
注意:由于检索到的上下文可能会占用大量可用的 LLM 上下文,因此我们要确保为聊天历史记录配置较小的限制:
memory = ChatMemoryBuffer.from_defaults(token_limit=1500)
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)
from llama_index.core.memory import ChatMemoryBuffer
memory = ChatMemoryBuffer.from_defaults(token_limit=1500)
# 构建聊天引擎
chat_engine = index.as_chat_engine(
chat_mode="context",
memory=memory,
system_prompt=(
"You are a chatbot, able to have normal interactions, as well as talk"
" about an essay discussing Paul Grahams life."
),
)
# 测试效果
response = chat_engine.chat("Hello!")
print(response)
response = chat_engine.chat("What did Paul Graham do growing up?")
print(response)
response = chat_engine.chat("Can you tell me more?")
print(response)
print("--------------reset chat-------------------------")
chat_engine.reset()
response = chat_engine.chat("Hello! What do you know?")
print(response)
从以下输出可以看到,不同大模型的输出不太相同。这和我们的
about Paul Graham that you
通过对历史消息的缓存,这样可以得到上下文相关的一些信息,可以让大模型的回答更加准确。当然,我认为不能完全依赖这个缓存机制,毕竟这个机制能够缓存的数据是有限的,而且查找相关的上下文内容,也可能有误差。
53AI,企业落地大模型首选服务商
产品:场景落地咨询+大模型应用平台+行业解决方案
承诺:免费场景POC验证,效果验证后签署服务协议。零风险落地应用大模型,已交付160+中大型企业
2025-01-11
LlamaIndex :企业级知识助理,万物可知
2024-12-26
深入了解 LlamaIndex 工作流程:事件驱动的 LLM 架构
2024-12-23
LlamaIndex工作流详解:提升数据处理效率的关键
2024-12-01
LlamaIndex,让AI唤醒你的数据
2024-11-29
llamaindex实战-Agent-自定义工具函数
2024-11-22
llamaindex实战-Agent-让Agent调用多个工具函数(本地部署)
2024-11-19
llamaindex实战-Workflow:工作流入门(本地部署断网运行)
2024-11-15
llamaindex实战-Agent-在Agent中使用RAG查询(本地部署)
2024-07-09
2024-04-20
2024-04-25
2024-06-05
2024-04-28
2024-05-09
2024-07-20
2024-06-19
2024-04-26
2024-04-19