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)

相关推荐
染指11108 小时前
61.RAG-RAG存在的问题
人工智能·llama·rag·llama_index·llamaindex
染指11105 天前
56.llama_index-查询引擎
人工智能·llama·rag·llama_index·llamaindex
染指11108 天前
53.llama_index-向量存储、索引存储
数据库·redis·llama_index·llamaindex
染指111011 天前
50.llama_index-文档分割器(文本)
llama·rag·llamaindex
染指111015 天前
46.llama_index-提示词模板(富提示词模板、jinja2静态和动态模板)
llama·rag·llamaindex
weigangwin15 天前
LlamaIndex 第一次试用:别先写 RAG Demo,先验上下文合同
python·ai·agent·rag·检索·llamaindex·观测性
染指111016 天前
45.llama_index-全局配置(Settings)
llama·llamaindex
li星野2 个月前
LlamaIndex 核心模块详解:从数据连接到智能代理,构建生产级 RAG 系统
大模型·llamaindex·学习记录