蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线实测 InMemorySaver 多轮记忆、线程隔离、历史快照回读、update_state 与 RemoveMessage

PYTHONWindows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。explore-checkpointer.py
explore-checkpointer.py305 行
"""Offline runtime lab for LangChain Ch 26: checkpointer."""
from __future__ import annotations

import asyncio
import importlib.util
import json
import platform
from typing import Any
from typing_extensions import NotRequired

from langchain.agents import AgentState, create_agent
from langchain.messages import AIMessage, RemoveMessage
from langchain.tools import tool
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.outputs import ChatGeneration, ChatResult
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph.message import REMOVE_ALL_MESSAGES
from pydantic import Field


class HistoryAwareChatModel(BaseChatModel):
    responses: list[Any] = Field(default_factory=list)
    cursor: list[int] = Field(default_factory=lambda: [0])
    seen_counts: list[int] = Field(default_factory=list)

    @property
    def _llm_type(self) -> str:
        return "history-aware-offline"

    def bind_tools(self, tools: Any, **kwargs: Any) -> "HistoryAwareChatModel":
        return self.model_copy()

    def _generate(self, messages: list[Any], stop: Any = None, run_manager: Any = None, **kwargs: Any) -> ChatResult:
        self.seen_counts.append(len(messages))
        idx = self.cursor[0]
        self.cursor[0] += 1
        if idx < len(self.responses):
            item = self.responses[idx]
            msg = item(messages) if callable(item) else item
        else:
            all_text = " ".join(str(m.content) for m in messages if m.type == "human")
            if "小明" in all_text and "名字" in str(messages[-1].content):
                msg = AIMessage(content="你叫小明,正在学习 Python。")
            elif "名字" in str(messages[-1].content):
                msg = AIMessage(content="你还没有告诉我你的名字。")
            else:
                msg = AIMessage(content=f"已收到({len(messages)}条上下文)")
        return ChatResult(generations=[ChatGeneration(message=msg)])

    async def _agenerate(self, messages: list[Any], stop: Any = None, run_manager: Any = None, **kwargs: Any) -> ChatResult:
        return self._generate(messages, stop=stop, run_manager=run_manager, **kwargs)


def case_stateless_vs_inmemory_saver_and_thread_isolation() -> dict[str, Any]:
    m_stateless = HistoryAwareChatModel()
    ag_stateless = create_agent(model=m_stateless, tools=[])
    ag_stateless.invoke({"messages": [{"role": "user", "content": "我叫小明,正在学习 Python。"}]})
    r_stateless_2 = ag_stateless.invoke({"messages": [{"role": "user", "content": "我叫什么名字?"}]})

    m_mem = HistoryAwareChatModel()
    ag_mem = create_agent(model=m_mem, tools=[], checkpointer=InMemorySaver())
    cfg = {"configurable": {"thread_id": "learning-001"}}
    ag_mem.invoke({"messages": [{"role": "user", "content": "我叫小明,正在学习 Python。"}]}, config=cfg)
    r_mem_2 = ag_mem.invoke({"messages": [{"role": "user", "content": "我叫什么名字?"}]}, config=cfg)

    alice_cfg = {"configurable": {"thread_id": "alice-chat-001"}}
    bob_cfg = {"configurable": {"thread_id": "bob-chat-001"}}
    ag_mem.invoke({"messages": [{"role": "user", "content": "我是 Alice。"}]}, config=alice_cfg)
    ag_mem.invoke({"messages": [{"role": "user", "content": "我是 Bob。"}]}, config=bob_cfg)
    alice_state = ag_mem.get_state(alice_cfg)
    bob_state = ag_mem.get_state(bob_cfg)

    actual = {
        "stateless_seen_counts": m_stateless.seen_counts,
        "stateless_turn2_reply": r_stateless_2["messages"][-1].content,
        "memory_seen_counts": m_mem.seen_counts[:2],
        "memory_turn2_reply": r_mem_2["messages"][-1].content,
        "alice_first_msg": alice_state.values["messages"][0].content,
        "bob_first_msg": bob_state.values["messages"][0].content,
        "alice_bob_isolated": (
            len(alice_state.values["messages"]) == 2
            and len(bob_state.values["messages"]) == 2
            and alice_state.values["messages"][0].content != bob_state.values["messages"][0].content
        ),
    }
    expected = {
        "stateless_seen_counts": [1, 1],
        "stateless_turn2_reply": "你还没有告诉我你的名字。",
        "memory_seen_counts": [1, 3],
        "memory_turn2_reply": "你叫小明,正在学习 Python。",
        "alice_first_msg": "我是 Alice。",
        "bob_first_msg": "我是 Bob。",
        "alice_bob_isolated": True,
    }
    return {
        "name": "stateless_vs_inmemory_saver_and_thread_isolation",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_state_snapshot_and_three_turn_progression() -> dict[str, Any]:
    @tool
    def lookup_topic(name: str) -> str:
        """查询课程主题。"""
        return f"主题:{name}"

    m = HistoryAwareChatModel()
    ag = create_agent(model=m, tools=[], checkpointer=InMemorySaver())
    cfg = {"configurable": {"thread_id": "demo-003"}}
    counts: list[int] = []
    nexts: list[tuple[str, ...]] = []
    for q in ("我叫小明。", "我正在学习 Python。", "总结一下刚才介绍过的我的信息。"):
        ag.invoke({"messages": [{"role": "user", "content": q}]}, config=cfg)
        snap = ag.get_state(cfg)
        counts.append(len(snap.values["messages"]))
        nexts.append(snap.next)

    snap_attrs = sorted(k for k in ("values", "next", "config", "metadata", "created_at", "tasks") if hasattr(snap, k))

    # Tool-calling turn adds 4 messages (not always 2)
    m_tool = HistoryAwareChatModel(
        responses=[
            AIMessage(
                content="",
                tool_calls=[{"name": "lookup_topic", "args": {"name": "装饰器"}, "id": "tc_1", "type": "tool_call"}],
            ),
            AIMessage(content="装饰器用于扩展函数行为。"),
        ]
    )
    ag_tool = create_agent(model=m_tool, tools=[lookup_topic], checkpointer=InMemorySaver())
    cfg_tool = {"configurable": {"thread_id": "tool-turn-001"}}
    ag_tool.invoke({"messages": [{"role": "user", "content": "查装饰器"}]}, config=cfg_tool)
    tool_turn_msgs = len(ag_tool.get_state(cfg_tool).values["messages"])

    actual = {
        "three_turn_counts": counts,
        "all_next_empty": all(n == () for n in nexts),
        "snapshot_attrs": snap_attrs,
        "has_checkpoint_id": bool(snap.config["configurable"].get("checkpoint_id")),
        "tool_turn_msg_count": tool_turn_msgs,
    }
    expected = {
        "three_turn_counts": [2, 4, 6],
        "all_next_empty": True,
        "snapshot_attrs": ["config", "created_at", "metadata", "next", "tasks", "values"],
        "has_checkpoint_id": True,
        "tool_turn_msg_count": 4,
    }
    return {
        "name": "state_snapshot_and_three_turn_progression",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_state_history_and_checkpoint_id_lookup() -> dict[str, Any]:
    m = HistoryAwareChatModel()
    ag = create_agent(model=m, tools=[], checkpointer=InMemorySaver())
    cfg = {"configurable": {"thread_id": "hist-001"}}
    for q in ("第一轮", "第二轮", "第三轮"):
        ag.invoke({"messages": [{"role": "user", "content": q}]}, config=cfg)

    history = list(ag.get_state_history(cfg))
    hist_msg_counts = [len(s.values.get("messages", [])) for s in history]
    # Fetch an older checkpoint explicitly via checkpoint_id
    older_snap = next(s for s in history if len(s.values.get("messages", [])) == 2)
    fetched = ag.get_state(older_snap.config)

    actual = {
        "history_len_gt_turns": len(history) > 3,
        "latest_msg_count": hist_msg_counts[0],
        "non_increasing_order": all(a >= b for a, b in zip(hist_msg_counts, hist_msg_counts[1:])),
        "fetched_old_msg_count": len(fetched.values.get("messages", [])),
        "fetched_matches_checkpoint_id": (
            fetched.config["configurable"]["checkpoint_id"] == older_snap.config["configurable"]["checkpoint_id"]
        ),
    }
    expected = {
        "history_len_gt_turns": True,
        "latest_msg_count": 6,
        "non_increasing_order": True,
        "fetched_old_msg_count": 2,
        "fetched_matches_checkpoint_id": True,
    }
    return {
        "name": "state_history_and_checkpoint_id_lookup",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_update_state_and_remove_messages() -> dict[str, Any]:
    class LearningState(AgentState):
        current_topic: NotRequired[str]
        user_level: NotRequired[str]

    m = HistoryAwareChatModel()
    ag = create_agent(model=m, tools=[], state_schema=LearningState, checkpointer=InMemorySaver())
    cfg = {"configurable": {"thread_id": "learning-state-001"}}
    ag.invoke(
        {"messages": [{"role": "user", "content": "我正在学习 Python。"}], "current_topic": "变量", "user_level": "入门"},
        config=cfg,
    )
    hist_before = len(list(ag.get_state_history(cfg)))

    ag.update_state(cfg, {"current_topic": "装饰器"})
    hist_after_update = len(list(ag.get_state_history(cfg)))
    updated_topic = ag.get_state(cfg).values["current_topic"]

    # Empty list does NOT clear add_messages
    ag.update_state(cfg, {"messages": []})
    len_after_empty_list = len(ag.get_state(cfg).values["messages"])

    # Remove single message by ID
    first_id = ag.get_state(cfg).values["messages"][0].id
    ag.update_state(cfg, {"messages": [RemoveMessage(id=first_id)]})
    len_after_remove_one = len(ag.get_state(cfg).values["messages"])

    # Clear all messages with REMOVE_ALL_MESSAGES while preserving custom fields & old checkpoints
    ag.update_state(cfg, {"messages": [RemoveMessage(id=REMOVE_ALL_MESSAGES)]})
    final_snap = ag.get_state(cfg)
    history_after_clear = list(ag.get_state_history(cfg))

    actual = {
        "update_creates_new_checkpoint": hist_after_update == hist_before + 1,
        "updated_topic": updated_topic,
        "empty_list_did_not_clear": len_after_empty_list,
        "after_remove_one": len_after_remove_one,
        "after_remove_all": len(final_snap.values.get("messages", [])),
        "custom_field_preserved": final_snap.values.get("current_topic"),
        "old_checkpoints_retained": any(len(s.values.get("messages", [])) == 2 for s in history_after_clear),
    }
    expected = {
        "update_creates_new_checkpoint": True,
        "updated_topic": "装饰器",
        "empty_list_did_not_clear": 2,
        "after_remove_one": 1,
        "after_remove_all": 0,
        "custom_field_preserved": "装饰器",
        "old_checkpoints_retained": True,
    }
    return {
        "name": "update_state_and_remove_messages",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_async_ainvoke_and_aget_state_memory_checkpointer() -> dict[str, Any]:
    async def run_async() -> dict[str, Any]:
        m = HistoryAwareChatModel()
        ag = create_agent(model=m, tools=[], checkpointer=InMemorySaver())
        cfg = {"configurable": {"thread_id": "async-001"}}
        await ag.ainvoke({"messages": [{"role": "user", "content": "我叫小明,正在学习 Python。"}]}, config=cfg)
        r2 = await ag.ainvoke({"messages": [{"role": "user", "content": "我叫什么名字?"}]}, config=cfg)
        snap = await ag.aget_state(cfg)
        return {
            "async_turn2_reply": r2["messages"][-1].content,
            "async_state_msg_count": len(snap.values["messages"]),
            "async_next_empty": snap.next == (),
            "sqlite_pkg_installed": importlib.util.find_spec("langgraph.checkpoint.sqlite") is not None,
            "postgres_pkg_installed": importlib.util.find_spec("langgraph.checkpoint.postgres") is not None,
        }

    actual = asyncio.run(run_async())
    expected = {
        "async_turn2_reply": "你叫小明,正在学习 Python。",
        "async_state_msg_count": 4,
        "async_next_empty": True,
        "sqlite_pkg_installed": False,
        "postgres_pkg_installed": False,
    }
    return {
        "name": "async_ainvoke_and_aget_state_memory_checkpointer",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main() -> None:
    cases = [
        case_stateless_vs_inmemory_saver_and_thread_isolation(),
        case_state_snapshot_and_three_turn_progression(),
        case_state_history_and_checkpoint_id_lookup(),
        case_update_state_and_remove_messages(),
        case_async_ainvoke_and_aget_state_memory_checkpointer(),
    ]
    print(
        json.dumps(
            {"version": platform.python_version(), "system": platform.system(), "cases": cases},
            ensure_ascii=False,
            indent=2,
        )
    )


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。

入口文件:projects/langchain-checkpointer-lab/explore-checkpointer.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-checkpointer.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:LangChain

课程关联工程包(登记关联37章) · 含当前章节或实例 · mbskycom202612a509.zip

下载课程关联工程包:LangChain

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a512.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习