给聊天机器人装“短期记忆“: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})
相关推荐
Victor3561 小时前
MySQL(163) 如何理解MySQL的隔离级别?
后端
gc_22991 小时前
学习Python中Selenium模块的基本用法(1:简介)
python·selenium
Victor3561 小时前
MySQL(164)如何设置MySQL的隔离级别?
后端
先做个垃圾出来………2 小时前
2116. 判断一个括号字符串是否有效
python
兮℡檬,2 小时前
房价预测|Pytorch
人工智能·pytorch·python
代码老y2 小时前
ASP.NET Core 高并发万字攻防战:架构设计、性能优化与生产实践
后端·性能优化·asp.net
im_AMBER5 小时前
学习日志19 python
python·学习
武子康7 小时前
Java-80 深入浅出 RPC Dubbo 动态服务降级:从雪崩防护到配置中心秒级生效
java·分布式·后端·spring·微服务·rpc·dubbo
舒一笑7 小时前
我的开源项目-PandaCoder迎来史诗级大更新啦
后端·程序员·intellij idea
mortimer8 小时前
安装NVIDIA Parakeet时,我遇到的两个Pip“小插曲”
python·github