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)
相关推荐
吴佳浩19 分钟前
Run:ai 开源了,我把 GPU 编排摆回 AI 栈里看了一遍
人工智能
IT_Octopus2 小时前
【零基础入门 LLM 开发 · Day 13】:LangChain 的对话记忆——Message 对象版
人工智能·python·langchain
2603_965148112 小时前
社区与学习资源:从入门到精通的API选品学习路径
数据库·人工智能·python·学习·数据挖掘
LiuPig刘皮哥2 小时前
2026年开源3D陪玩对比:xiaoke.ai、AIRI、Open-LLM-VTuber、Amica 有什么、没有什么
人工智能·3d·开源
西柚小萌新2 小时前
【岗位面试】--成都博维数孪 - 工业 AI 解决方案顾问
人工智能·面试·职场和发展
Luminbox紫创测控3 小时前
车载LiDAR强光测试的实验设计方法与数据分析
人工智能·数据挖掘·数据分析·车载系统·安全性测试·太阳光模拟器
CCblandy4 小时前
令牌桶在 0.9 倍负载超发 19%、固定窗口边界放行 20 个:四种限流算法同构实测
后端·python·算法·性能优化·架构
建筑工程企业管理系统4 小时前
工程进度统计管理系统自动化汇总数据,解决施工企业手工对账误差难题
大数据·人工智能·自动化
唠点键盘之外的4 小时前
27 存量系统接大模型:旁挂一个 AI 微服务,老架构一行不改
人工智能·微服务·架构
kaixin_啊啊4 小时前
【用于更准确 G×E 基因组预测的大规模作物数据集与基于深度学习的多模态融合框架】论文学习
人工智能·深度学习·学习