要在Redis中实现7天自动过期,可以通过设置ttl(Time To Live)参数来实现。以下是优化后的代码,包含Redis Key的7天自动过期功能:

from langchain_ollama import ChatOllama
from langchain_core.prompts import ChatPromptTemplate
from langchain_community.chat_message_histories import RedisChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory
from datetime import timedelta

# 初始化Ollama
model = ChatOllama(
    base_url="http://10.80.0.212:11434",
    model="deepseek-r1:8b",
    temperature=0.7
)

# 定义提示模板
prompt = ChatPromptTemplate.from_template(
    """你是一个智能助手,可以回答通用问题和编写代码。请根据上下文自然交流。
    
    历史对话:
    {history}
    
    新问题: {input}"""
)

# Redis配置
REDIS_URL = "redis://:OceanXECM!@10.80.0.212:6379/0"
REDIS_KEY_PREFIX = "message_store"
TTL_DAYS = 7  # 设置7天有效期

class CustomRedisChatMessageHistory(RedisChatMessageHistory):
    """自定义Redis存储,自动设置TTL"""
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 每次初始化时刷新TTL
        if self.redis_client.exists(self.key):
            self.redis_client.expire(self.key, timedelta(days=TTL_DAYS))

def get_message_history(conversation_id: str) -> CustomRedisChatMessageHistory:
    """获取带TTL的Redis消息历史"""
    return CustomRedisChatMessageHistory(
        session_id=f"{REDIS_KEY_PREFIX}:{conversation_id}",
        url=REDIS_URL,
        socket_connect_timeout=10
    )

# 创建带历史记录的链
with_message_history = RunnableWithMessageHistory(
    runnable=prompt | model,
    get_message_history=get_message_history,
    input_messages_key="input",
    history_messages_key="history"
)

def chat(conversation_id: str, user_input: str):
    """带自动清理的对话函数"""
    response = with_message_history.invoke(
        input={"knowledge_base": "general", "input": user_input},
        config={"configurable": {"conversation_id": conversation_id}}
    )
    print(f"用户: {user_input}\nAI: {response.content}\n")

# 示例对话
if __name__ == "__main__":
    chat("abc123", "你好,你是谁?")
    chat("abc123", "请解释下量子计算")

关键优化点:

  1. TTL实现

    • 创建了CustomRedisChatMessageHistory子类,自动设置7天过期时间
    • 每次访问对话历史时都会刷新TTL计数器
  2. 过期机制

    • 使用Redis的expire命令设置键的生命周期
    • timedelta(days=7)确保7天后自动删除
  3. 维护策略

    • 每次调用对话时都会检查并刷新TTL
    • 如果7天内没有任何对话活动,数据会自动清除
  4. 代码结构

    • 将TTL天数定义为常量TTL_DAYS方便修改
    • 保持原有接口不变,兼容现有代码

注意:Redis的过期精度是秒级,实际删除可能稍有延迟。如需精确控制,可以额外添加定时任务清理过期会话。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐