LangChain Agent 会话持久化系统(Redis版)

1. 项目概述

1.1 项目简介

本项目是一个基于 LangChain 框架构建的智能 Agent 系统,集成了多种工具(百科检索、实时搜索),并使用 Redis 实现会话历史的持久化存储。系统支持多用户、多对话的会话管理,具备完整的降级机制,在网络受限环境下也能正常运行。

1.2 核心功能

功能模块描述状态
百科检索工具基于向量数据库的文档检索,支持本地知识库查询✅ 已实现
实时搜索工具集成 Tavily 搜索引擎,支持实时信息获取✅ 已实现
智能 Agent基于 GPT-3.5 的工具调用决策引擎✅ 已实现
Redis 会话存储使用 Redis 持久化会话历史✅ 已实现
多轮对话支持支持同一用户的多轮上下文对话✅ 已实现
降级机制网络异常时自动切换到模拟数据模式✅ 已实现

2. 技术架构

2.1 系统架构图

┌─────────────────────────────────────────────────────────────────────────────┐
│                            用户查询入口                                      │
│              user_id + conversation_id + input                              │
└─────────────────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│                    RunnableWithMessageHistory                               │
│              (会话历史管理 + 自动保存/加载)                                  │
└─────────────────────────────────────────────────────────────────────────────┘
                              │
              ┌───────────────┼───────────────┐
              ▼               ▼               ▼
    ┌───────────────┐ ┌───────────────┐ ┌───────────────┐
    │   Redis 存储   │ │   Agent       │ │    LLM        │
    │  (会话历史)   │ │  Executor     │ │   GPT-3.5-turbo     │
    └───────────────┘ └───────────────┘ └───────────────┘
              │               │
              ▼               ▼
    ┌───────────────┐ ┌───────────────┐
    │   Redis DB    │ │   Tool Set    │
    │   127.0.0.1   │ │  百科/搜索    │
    └───────────────┘ └───────────────┘

2.2 技术栈

类别技术版本要求用途
核心框架LangChain1.0+构建 Agent 和工具链
LLMOpenAI ChatGPTgpt-3.5-turbo智能决策和回答生成
向量数据库FAISS最新文档向量存储和检索
搜索引擎Tavily最新实时信息搜索
会话存储Redis6.0+会话历史持久化
文档加载WebBaseLoader最新网页内容抓取
文本分块RecursiveCharacterTextSplitter最新长文本分块处理
向量化FakeEmbeddings最新模拟向量(无 token 消耗)

3. 核心模块详解

3.1 向量化模块

设计目的: 使用 FakeEmbeddings 进行模拟向量化,完全不消耗 token,适合开发测试环境。

参数说明
size1536向量维度,与 OpenAI Embeddings 保持一致

使用示例:

from langchain_core.embeddings import FakeEmbeddings
embeddings = FakeEmbeddings(size=1536)

向量化降级策略:

步骤方案条件代码行
1FakeEmbeddings默认使用L6
2备用 FakeEmbeddings主方案失败时L35-L36

3.2 百科检索工具

核心流程:

步骤组件作用代码行
1WebBaseLoader加载网页内容L21-L26
2RecursiveCharacterTextSplitter文本分块L28-L29
3FakeEmbeddings生成模拟向量L32
4FAISS向量存储L32
5create_retriever_tool创建检索工具L38-L39

分块参数配置:

参数说明
chunk_size1000每个文本块的最大字符数
chunk_overlap200相邻文本块的重叠字符数

降级机制:

异常场景处理方式代码行
网页加载失败使用预定义的模拟文档L21-L26
向量化失败使用备用 FakeEmbeddingsL31-L36

3.3 实时搜索工具

核心流程:

步骤组件作用代码行
1langchain_tavily.TavilySearch初始化搜索工具L50-L54
2max_results=1配置返回结果数量L53

降级机制:

异常场景处理方式代码行
API Key 缺失/无效创建模拟工具函数L55-L60

模拟工具定义:

@tool
def tavily_search_tool(query: str) -> str:
    return f"搜索结果: {query} - 模拟数据"

3.4 智能 Agent

核心组件:

组件类名作用代码行
LLMChatOpenAI大语言模型L87
PromptChatPromptTemplate对话模板L80-L85
Agentcreate_tool_calling_agent创建工具调用 AgentL88
ExecutorAgentExecutorAgent 执行器L89

Prompt 结构:

消息类型内容说明
system“你是一个专业的助手,使用提供的工具回答用户问题。”系统角色定义
historyMessagesPlaceholder(variable_name=“history”)会话历史
human“{input}”用户输入
agent_scratchpadMessagesPlaceholder(variable_name=“agent_scratchpad”)Agent 思考过程

3.5 Redis 会话存储(核心模块)

3.5.1 Redis 连接配置
参数说明
redis_urlredis://localhost:6379/2Redis 连接地址,使用第 2 个数据库
hostlocalhostRedis 服务器地址
port6379Redis 默认端口
db2使用的数据库编号

连接测试:

import redis
r = redis.Redis.from_url(redis_url)
r.ping()  # 返回 True 表示连接成功
3.5.2 会话历史获取函数
def get_history(user_id: str, conversation_id: str) -> RedisChatMessageHistory:
    return RedisChatMessageHistory(
        session_id=f"{user_id}:{conversation_id}",
        url=redis_url
    )
参数类型说明
user_idstr用户唯一标识符
conversation_idstr对话唯一标识符
session_idstr组合键 {user_id}:{conversation_id}
3.5.3 RunnableWithMessageHistory 配置

配置字段:

字段ID类型默认值说明
User IDuser_idstr“”用户的唯一标识符
Conversation IDconversation_idstr“”对话的唯一标识符

配置参数:

参数说明
input_messages_key“input”用户输入的键名
history_messages_key“history”历史消息的键名
is_sharedTrue配置是否在多次调用间共享

4. 工具注册与调用

4.1 工具列表

工具名称变量名类型描述
search_baikeretriever_toolRetrieverTool百科检索,基于向量数据库
tavily_searchtavily_search_toolTavilySearch/Tool实时搜索,基于 Tavily API

4.2 多轮对话调用流程

┌─────────────────────────────────────────────────────────────────────┐
│  第一次调用                                                          │
│  input: "Hi,我的名字是Cyber"                                        │
│  config: {"user_id": "user01", "conversation_id": "conversation_1"} │
└─────────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────────┐
│  Redis 存储: "user01:conversation_1" → [HumanMessage, AIMessage]     │
└─────────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────────┐
│  第二次调用                                                          │
│  input: "我叫什么名字?"                                             │
│  config: {"user_id": "user01", "conversation_id": "conversation_1"} │
└─────────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────────┐
│  Redis 读取历史 → Agent 理解上下文 → 回答: "你叫Cyber"                 │
└─────────────────────────────────────────────────────────────────────┘

4.3 调用示例

# 第一次对话
response = with_agent_history.invoke(
    {"input": "Hi,我的名字是Cyber"},
    config={"configurable": {"user_id": "user01", "conversation_id": "conversation_1"}}
)

# 第二次对话(同一会话)
response = with_agent_history.invoke(
    {"input": "我叫什么名字?"},
    config={"configurable": {"user_id": "user01", "conversation_id": "conversation_1"}}
)

5. 环境变量配置

5.1 必需环境变量

环境变量说明获取方式
OPENAI_API_KEYOpenAI API Keyhttps://platform.openai.com/
TAVILY_API_KEYTavily 搜索 API Keyhttps://tavily.com/

5.2 Redis 配置

参数默认值说明
redis_urlredis://localhost:6379/2Redis 连接地址
REDIS_HOSTlocalhostRedis 服务器地址
REDIS_PORT6379Redis 端口
REDIS_DB2数据库编号

5.3 设置方法

Windows PowerShell:

# 临时设置(当前终端有效)
$env:OPENAI_API_KEY="your-key"
$env:TAVILY_API_KEY="your-key"

# 永久设置(用户级别)
[Environment]::SetEnvironmentVariable("OPENAI_API_KEY", "your-key", "User")
[Environment]::SetEnvironmentVariable("TAVILY_API_KEY", "your-key", "User")

6. 依赖安装

6.1 核心依赖

依赖包安装命令用途
langchainpip install langchain核心框架
langchain-openaipip install langchain-openaiOpenAI 集成
langchain-communitypip install langchain-community社区工具集
langchain-tavilypip install langchain-tavilyTavily 搜索
faiss-cpupip install faiss-cpu向量数据库
redispip install redisRedis 客户端
python-dotenvpip install python-dotenv环境变量加载

6.2 一键安装

pip install langchain langchain-openai langchain-community langchain-tavily faiss-cpu redis python-dotenv

7. Redis 安装与配置

7.1 Windows 安装

方式一:使用 Chocolatey

choco install redis-64

方式二:手动安装

  1. 下载 Redis: https://github.com/tporadowski/redis/releases
  2. 解压到 D:\Redis
  3. 添加到 PATH 环境变量

7.2 启动 Redis

# 启动 Redis 服务器
redis-server.exe

# 连接测试
redis-cli.exe ping
# 返回 PONG 表示成功

在这里插入图片描述

7.3 Redis 数据结构

键名格式存储内容数据类型
user_id:conversation_id会话消息列表List

在这里插入图片描述

8. 运行说明

8.1 前提条件

条件说明
Redis 服务必须运行在 localhost:6379
Python 环境3.10+
环境变量已设置 OPENAI_API_KEY

8.2 运行步骤

# 1. 启动 Redis(如果未运行)
redis-server.exe

# 2. 切换到项目目录
cd e:\AI-Study\AI-demo\day-07\agent

# 3. 设置环境变量
$env:OPENAI_API_KEY="your-key"

# 4. 运行脚本
python agent_tools_llm_memory_redis.py

8.3 预期输出

正常模式:

✅ Redis 连接成功!
True

> Entering new AgentExecutor chain...
你好,Cyber,很高兴见到你!有什么我可以帮助你的吗?

> Finished chain.
{'input': 'Hi,我的名字是Cyber', 'history': [...], 'output': '你好,Cyber...'}

> Entering new AgentExecutor chain...
你说你的名字是Cyber。有什么我可以帮你的吗,Cyber?

> Finished chain.
{'input': '我叫什么名字?', 'history': [...], 'output': '你说你的名字是Cyber...'}

Redis 连接失败:

❌ Redis 连接失败: Connection refused

实战演示:
在这里插入图片描述

9. 代码优化建议

9.1 改进方向

建议当前状态优先级
添加 .env 文件支持未实现
Redis 连接配置外部化硬编码
添加日志系统使用 print
添加会话管理 API未实现
支持 Redis 密码认证未实现
添加配置文件硬编码

9.2 待修复的废弃警告

警告来源当前使用建议替换
langchain-communityWebBaseLoader, FAISS, RedisChatMessageHistory使用独立包

10. 故障排除

10.1 常见问题

错误信息原因解决方案
Connection refusedRedis 服务未启动运行 redis-server.exe
Request timed out网络无法访问外网检查网络连接
Invalid API keyAPI Key 无效确认 API Key 正确性
ModuleNotFoundError: redis未安装 Redis 依赖pip install redis
PydanticValidationErrorRedis URL 格式错误检查 redis_url 格式

10.2 调试命令

# 检查 Redis 连接
redis-cli.exe ping

# 查看 Redis 中的会话数据
redis-cli.exe -n 2 keys "*"

# 查看会话历史
redis-cli.exe -n 2 lrange user01:conversation_1 0 -1

11. 版本历史

版本日期修改内容
v1.02026-07-03初始版本,实现基本功能
v1.12026-07-03添加 Redis 会话持久化
v1.22026-07-03使用 FakeEmbeddings 减少 token 消耗

12. 附录

12.1 Redis 会话管理命令

# 获取会话历史
history = get_history("user01", "conversation_1")
messages = history.messages

# 手动添加消息
history.add_user_message("Hello")
history.add_ai_message("Hi there!")

# 清空会话历史
history.clear()

# 删除会话
import redis
r = redis.Redis.from_url("redis://localhost:6379/2")
r.delete("user01:conversation_1")

12.2 多用户多对话示例

# 用户1 - 对话1
response = with_agent_history.invoke(
    {"input": "今天天气怎么样?"},
    config={"configurable": {"user_id": "user01", "conversation_id": "conv_001"}}
)

# 用户1 - 对话2(独立会话)
response = with_agent_history.invoke(
    {"input": "推荐一些电影"},
    config={"configurable": {"user_id": "user01", "conversation_id": "conv_002"}}
)

# 用户2 - 对话1(完全独立)
response = with_agent_history.invoke(
    {"input": "你好"},
    config={"configurable": {"user_id": "user02", "conversation_id": "conv_001"}}
)

想要获取源代码,有三种路径:记得给个star哦!
访问我的gitee仓库(推荐)https://gitee.com/weh_coder/weh-langchain-agent-demo/blob/master/agent_tools_llm_memory_redis.py

更多推荐