60.llama_index-记忆(记忆存储到Redis)

内容参考于:图灵AI大模型全栈

常用的数据库组件

ChatStore 类型 存储方式 主要功能与适用场景 持久化 推荐场景
SimpleChatStore 内存 + JSON 文件 基础存取、persist()/from_persist_path() 开发、测试、小项目
RedisChatStore Redis 高性能、高并发、分布式 生产、中大型应用
PostgresChatStore PostgreSQL 事务支持、SQL 查询 企业级
UpstashChatStore Serverless Redis 无服务器运维、易扩展 云原生应用
TablestoreChatStore 阿里云等云数据库 云服务集成 特定云平台

Radis存储

安装Radis库

python 复制代码
pip install llama-index-storage-chat-store-redis

使用Radis代码,如果想使用Redis只需要把下图红框位置改成RedisChatStore就可以了

如下图红框,历史记录存放到Redis中的内容

如果想看Redis怎么读写的源码,可以按着CTRL鼠标左键单击下图红框位置

如下图红框修改值和获取值的源码

如下图红框,方法名前面带a字母的表示异步

Redis存储代码

python 复制代码
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
from llama_index.core.memory import ChatMemoryBuffer
from llama_index.storage.chat_store.redis import RedisChatStore
from base_llm import llm, embed_model

# 创建RedisChatStore,也就是创建一个可以连接和操作Readis数据库的变量
chat_store = RedisChatStore(
    redis_url="redis://localhost:6379"
)

# 创建Memory,也就是创建历史记录存储空间,这里指定让它存放到Redis中
memory = ChatMemoryBuffer(
    token_limit=1500,
    chat_store=chat_store,
    chat_store_key="user1"
)

# 加载文档
documents = SimpleDirectoryReader(input_files=["./data_file/小说.txt"]).load_data()

# 创建索引
index = VectorStoreIndex.from_documents(documents, embed_model=embed_model)

# 创建ChatEngine,也就是创建聊天大模型
chat_engine = index.as_chat_engine(
    chat_mode="best",
    memory=memory,
    verbose=True,
    llm=llm
)


# 开始聊天
response = chat_engine.chat("萧炎的斗之力多少段")
print(response)
# 打印100个-,用来区分上方的回答和下方的回答
print('-'*100)
response = chat_engine.chat("萧薰儿比他高多少")
print(response)

相关推荐
云烟成雨TD11 小时前
LlamaIndex 系列【31】检索增强策略:命名实体识别(NER)
ai·agent·rag·llamaindex
云烟成雨TD1 天前
LlamaIndex 系列【29】检索增强策略:路由(Routing)机制
ai·agent·rag·llamaindex
一只小bit9 天前
LlamaIndex框架:简单RAG框架的全过程实现手册
llm·milvus·rag·llamaindex·deepseek
云烟成雨TD9 天前
LlamaIndex 系列【24】检索增强策略:交叉编码器(Cross‑Encoder)
ai·agent·rag·llamaindex
uncle_ll13 天前
智能客服实践:微调+RAG双引擎架构落地
llm·agent·智能客服·rag·llamaindex
云烟成雨TD14 天前
LlamaIndex 系列【21】语义检索(Semantic Search)
ai·agent·rag·llamaindex
云烟成雨TD14 天前
LlamaIndex 系列【20】关键词检索(Keyword Search):BM 25 算法
ai·agent·rag·llamaindex
云烟成雨TD16 天前
LlamaIndex 系列【14】数据接入流水线(IngestionPipeline)
ai·agent·rag·llamaindex
云烟成雨TD16 天前
LlamaIndex 系列【18】关键词检索(Keyword Search):TF-IDF 算法
ai·agent·llamaindex
2601_9623815821 天前
VSCode如何配置LlamaIndex RAG(检索增强生成)应用开发环境
vscode·开发环境·rag·llamaindex·检索增强生成