给聊天机器人装“短期记忆“: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})
相关推荐
Victor35621 小时前
Netty(19)Netty的性能优化手段有哪些?
后端
爬山算法21 小时前
Netty(15)Netty的线程模型是什么?它有哪些线程池类型?
java·后端
一世琉璃白_Y21 小时前
pg配置国内数据源安装
linux·python·postgresql·centos
liwulin05061 天前
【PYTHON】COCO数据集中的物品ID
开发语言·python
小鸡吃米…1 天前
Python - XML 处理
xml·开发语言·python·开源
我赵帅的飞起1 天前
python国密SM4加解密
python·sm4加解密·国密sm4加解密
白宇横流学长1 天前
基于SpringBoot实现的冬奥会科普平台设计与实现【源码+文档】
java·spring boot·后端
yaoh.wang1 天前
力扣(LeetCode) 1: 两数之和 - 解法思路
python·程序人生·算法·leetcode·面试·跳槽·哈希算法
Python编程学习圈1 天前
Asciinema - 终端日志记录神器,开发者的福音
后端
bing.shao1 天前
Golang 高并发秒杀系统踩坑
开发语言·后端·golang