给聊天机器人装“短期记忆“:Flask版实现指南

📌 实现思路图解

是 否 用户发送消息 是否新会话? 创建session_id 读取历史文件 初始化空历史 保留最近3轮对话 生成AI回复 保存最新历史 返回带记忆的回复

核心实现代码

python 复制代码
def debug(self, app_id: UUID):
    # 1.提取从接口中获取的输入
    req = CompletionReq()
    if not req.validate():
        return validate_error_json(req.errors)

    # 2.创建prompt与memory
    prompt = ChatPromptTemplate.from_messages([
        ("system", "你是一个强大的聊天机器人,能根据用户的提问回复对应的问题"),
        MessagesPlaceholder("history"),
        ("human", "{query}"),
    ])
    memory = ConversationBufferWindowMemory(
        k=3,
        input_key="query",
        output_key="output",
        return_messages=True,
        chat_memory=FileChatMessageHistory("./storage/memory/chat_history.txt"),
    )

    # 3.构建llm应用
    llm = ChatOpenAI(model="gpt-3.5-turbo-16k")

    # 4.创建链应用
    chain = RunnablePassthrough.assign(
        history=RunnableLambda(memory.load_memory_variables) | itemgetter("history")
    ) | prompt | llm | StrOutputParser()

    # 5.调用链生成内容
    chain_input = {"query": req.query.data}
    content = chain.invoke(chain_input)

    # 6.存储链状态
    memory.save_context(chain_input, {"output": content})

    return success_json({"content": content})
相关推荐
sun_tao1几秒前
LlamaIndex + Qwen3.5-4B 关闭 Thinking 模式调试记录
python·llamaindex·qwen3.5-4b·huggingfacellm
小兔崽子去哪了8 分钟前
Docker 安装 PostgreSQL
数据库·后端·postgresql
野犬寒鸦12 分钟前
Redis热点key问题解析与实战解决方案(附大厂实际方案讲解)
服务器·数据库·redis·后端·缓存·bootstrap
书到用时方恨少!18 分钟前
Python os 模块使用指南:系统交互的瑞士军刀
开发语言·python
snakeshe10101 小时前
深入理解 Java 注解:从原理到实战
后端
Lucaju1 小时前
吃透 Spring AI Alibaba 多智能体|四大协同模式+完整代码
后端
Nyarlathotep01131 小时前
Redis的对象(5):有序集合对象
redis·后端
Java水解1 小时前
Spring Boot 消息队列与异步处理
spring boot·后端
带娃的IT创业者1 小时前
WeClaw_40_系统监控与日志体系:多层次日志架构与Trace追踪
java·开发语言·python·架构·系统监控·日志系统·链路追踪