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)
相关推荐
我爱写代码i2 分钟前
边缘计算与小模型在工业预测性维护、机器视觉质检中有哪些具体的落地实施案例与架构设计?
人工智能·边缘计算
兮动人4 分钟前
Python变量与常量
开发语言·python·机器学习·python变量与常量
CCYe、9 分钟前
新模型上线、旧模型下线:企业AI网关如何管住模型版本
java·网络·数据库·人工智能
2601_9623008112 分钟前
机器学习的理想基石
人工智能·python·机器学习·编程语言·数据处理
audyxiao00114 分钟前
优秀博士学位论文分享|神经符号系统的非确定性管理研究
人工智能·神经符号系统·优博论文
falldeep17 分钟前
kl_loss为什么用k3?该放到reward中还是loss中?
人工智能·机器学习
Java后端的Ai之路19 分钟前
21、Python - 命令模式
开发语言·人工智能·python·命令模式·外观模式
AI推荐率26 分钟前
企业归属关系:开发、运营、持有和销售主体需要按真实关系表达
人工智能
海兰27 分钟前
【应用】Firecrawl-Style Scrape Demo网页爬取效果演示及部署
人工智能·网页爬虫
2601_9620779828 分钟前
机器学习及其Python实践
pytorch·python·机器学习·tensorflow·scikit-learn