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)

相关推荐
2601_9623815818 小时前
VSCode如何配置LlamaIndex RAG(检索增强生成)应用开发环境
vscode·开发环境·rag·llamaindex·检索增强生成
练习两年半的攻城狮2 天前
【RAG实战】知识库 BGE-M3 稀疏向量混合检索方案
python·fastapi·llamaindex
uncle_ll5 天前
LlamaIndex 全栈实战指南:架构解构、RAG 核心原理与私有知识库工程化落地方案
架构·llm·agent·rag·llamaindex
练习两年半的攻城狮6 天前
RAG 系统中 Excel/表格数据的正确处理方式
python·llamaindex
练习两年半的攻城狮7 天前
FastAPI + LlamaIndex Agent 流式对话踩坑实录
fastapi·llamaindex
云烟成雨TD8 天前
LlamaIndex 系列【5】智能体开发:大语言模型接入与基础调用
ai·agent·rag·llamaindex
云烟成雨TD9 天前
LlamaIndex 系列【3】上下文增强驱动的 LLM 应用开发框架
ai·agent·rag·llamaindex
云烟成雨TD9 天前
LlamaIndex 系列【4】入门案例(阿里云百炼适配)
ai·agent·rag·llamaindex
gis分享者10 天前
LangChain 和 LlamaIndex 有什么区别?各自适合什么场景?
人工智能·ai·langchain·场景·区别·llamaindex
练习两年半的攻城狮19 天前
LlamaIndex ResponseMode 深度解析
python·llamaindex