AI学习_06_短期记忆与长期记忆

短期记忆

  • 就是存储在内存当中的
python 复制代码
from langchain_community.chat_models import ChatOpenAI
from langchain_core.chat_history import InMemoryChatMessageHistory
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import PromptTemplate, ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables import RunnableLambda, RunnableWithMessageHistory

module = ChatOpenAI(
    model="deepseek-v4-flash",  # 也可以使用 "deepseek-coder" 专门处理代码任务
    openai_api_key='',  # DeepSeek 的 OpenAI 兼容接口地址
    openai_api_base="https://api.deepseek.com",  # DeepSeek 的 OpenAI 兼容接口地址
)

# first_template = PromptTemplate.from_template("")
template = ChatPromptTemplate([
    ("system", "请更具历史会话,来简单回答问题,历史如下:"),
    MessagesPlaceholder("chain_history"),
    ("user", "请回答如下问题:{input}"),
])


def print_prompt(prompt):
    print("=" * 20, prompt.to_string(), "=" * 20)
    return prompt


parser = StrOutputParser()

base_chain = template | print_prompt | module | parser

store = {}


def get_history_session(session_id):
    if session_id not in store:
        store[session_id] = InMemoryChatMessageHistory()

    return store[session_id]


history_chain = RunnableWithMessageHistory(base_chain, get_history_session, input_messages_key="input",
                                           history_messages_key="chain_history")

if __name__ == '__main__':
    config = {
        "configurable": {
            "session_id": "001",
        }
    }
    res = history_chain.invoke({"input": "小明有两只孔雀"}, config)
    print("第1次执行:", res)

    res = history_chain.invoke({"input": "小红有5只老虎"}, config)
    print("第2次执行:", res)

    res = history_chain.invoke({"input": "现在一共有多少宠物?"}, config)
    print("第3次执行:", res)

长期记忆

  • 把历史记录放在了文件当中
python 复制代码
import json
import os
from typing import Sequence

from langchain_community.chat_models import ChatOpenAI
from langchain_core.chat_history import BaseChatMessageHistory
from langchain_core.messages import BaseMessage, messages_from_dict, message_to_dict
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables import RunnableWithMessageHistory


class FileChatMessageHistory(BaseChatMessageHistory):
    def __init__(self, session_id, storage_path):
        self.session_id = session_id
        self.storage_path = storage_path

        self.file_path = os.path.join(storage_path, session_id)
        os.makedirs(os.path.dirname(self.file_path), exist_ok=True)

    @property
    def messages(self) -> list[BaseMessage]:
        try:
            with open(
                    os.path.join(self.storage_path, self.session_id),
                    "r",
                    encoding="utf-8",
            ) as f:
                messages_data = json.load(f)
            return messages_from_dict(messages_data)
        except FileNotFoundError:
            return []

    def add_messages(self, messages: Sequence[BaseMessage]) -> None:
        all_messages = list(self.messages)  # Existing messages
        all_messages.extend(messages)  # Add new messages

        serialized = [message_to_dict(message) for message in all_messages]
        file_path = os.path.join(self.storage_path, self.session_id)
        os.makedirs(os.path.dirname(file_path), exist_ok=True)
        with open(file_path, "w", encoding="utf-8") as f:
            json.dump(serialized, f)

    def clear(self) -> None:
        file_path = os.path.join(self.storage_path, self.session_id)
        os.makedirs(os.path.dirname(file_path), exist_ok=True)
        with open(file_path, "w", encoding="utf-8") as f:
            json.dump([], f)


module = ChatOpenAI(
    model="deepseek-v4-flash",  # 也可以使用 "deepseek-coder" 专门处理代码任务
    openai_api_key='',  # DeepSeek 的 OpenAI 兼容接口地址
    openai_api_base="https://api.deepseek.com",  # DeepSeek 的 OpenAI 兼容接口地址
)

# first_template = PromptTemplate.from_template("")
template = ChatPromptTemplate([
    ("system", "请更具历史会话,来简单回答问题,历史如下:"),
    MessagesPlaceholder("chain_history"),
    ("user", "请回答如下问题:{input}"),
])


def print_prompt(prompt):
    print("=" * 20, prompt.to_string(), "=" * 20)
    return prompt


parser = StrOutputParser()

base_chain = template | print_prompt | module | parser

store = {}


def get_history_session(session_id):
    return FileChatMessageHistory(session_id, storage_path='./history')


history_chain = RunnableWithMessageHistory(base_chain, get_history_session, input_messages_key="input",
                                           history_messages_key="chain_history")

if __name__ == '__main__':
    config = {
        "configurable": {
            "session_id": "001",
        }
    }
    res = history_chain.invoke({"input": "小明有两只孔雀"}, config)
    print("第1次执行:", res)

    res = history_chain.invoke({"input": "小红有5只老虎"}, config)
    print("第2次执行:", res)

    res = history_chain.invoke({"input": "现在一共有多少宠物?"}, config)
    print("第3次执行:", res)
相关推荐
回眸&啤酒鸭2 天前
【回眸】Minicart 电商购物车核心功能落地指南
人工智能
一隅论数智2 天前
给AI一张“业务概念地图“:本体如何从哲学走向企业智能
大数据·人工智能·经验分享·笔记·学习·学习方法·政务
默_笙2 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
AI的探索之旅2 天前
97 个 OpenCV 实例(三十):双目立体,从标定到点云
人工智能·opencv·计算机视觉
AlbertZein2 天前
Step-5-Preview 上手实测:3D 游戏、金融分析、网页设计一次跑完
人工智能·aigc
XiHongShi20162 天前
STM32F407 RTC定时器例程,建议保存
stm32·单片机·学习
LaughingZhu2 天前
Product Hunt 每日热榜 | 2026-09-19
人工智能·深度学习·神经网络·搜索引擎·百度
qq_426003962 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫2 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas