给聊天机器人装“短期记忆“: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})
相关推荐
青莳吖5 分钟前
使用 SseEmitter 实现 Spring Boot 后端的流式传输和前端的数据接收
前端·spring boot·后端
Amo Xiang21 分钟前
Python 解释器安装全攻略(适用于 Linux / Windows / macOS)
linux·windows·python·环境安装
程序员杰哥22 分钟前
接口自动化测试之pytest 运行方式及前置后置封装
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
我的golang之路果然有问题1 小时前
ElasticSearch+Gin+Gorm简单示例
大数据·开发语言·后端·elasticsearch·搜索引擎·golang·gin
浩皓素1 小时前
用Python开启游戏开发之旅
python
hello kitty w1 小时前
Python学习(6) ----- Python2和Python3的区别
开发语言·python·学习
mldong2 小时前
我的全栈工程师之路:全栈学习路线分享
前端·后端
无声旅者3 小时前
n8n:解锁自动化工作流的无限可能
ai·自动化·oneapi·ai大模型·n8n
互联网杂货铺3 小时前
功能测试、性能测试、安全测试详解
自动化测试·软件测试·python·功能测试·测试工具·性能测试·安全性测试
噼里啪啦啦.3 小时前
SpringBoot统一功能处理
java·spring boot·后端