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

离线实测核心消息类、AIMessageChunk 合并与 type 勘误、Base64 多模态块、trim_messages 与 RemoveMessage

PYTHONWindows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。explore-messages.py
explore-messages.py409 行
"""Independent offline lab for LangChain Ch 10: LangChain Message Types & History Management."""
import base64
import json
import platform
import struct
import zlib

from langchain.messages import (
    AIMessage,
    AIMessageChunk,
    HumanMessage,
    RemoveMessage,
    SystemMessage,
    ToolMessage,
    trim_messages,
)
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.messages import ChatMessage, convert_to_messages
from langchain_core.outputs import ChatGeneration, ChatResult
from langgraph.graph.message import add_messages


def make_tiny_png_bytes() -> bytes:
    """Create a minimal valid 1x1 RGB PNG in memory without external files."""
    def chunk(tag: bytes, data: bytes) -> bytes:
        return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)

    ihdr = struct.pack(">IIBBBBB", 1, 1, 8, 2, 0, 0, 0)
    raw = b"\x00\x20\x80\xff"
    idat = zlib.compress(raw)
    return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", idat) + chunk(b"IEND", b"")


class StatefulOfflineChatModel(BaseChatModel):
    """Offline model acknowledging conversation turn count from full message history."""

    @property
    def _llm_type(self) -> str:
        return "stateful-offline-chat"

    def _generate(self, messages, stop=None, run_manager=None, **kwargs):
        human_count = sum(1 for m in messages if m.type == "human")
        last_q = messages[-1].content
        return ChatResult(
            generations=[
                ChatGeneration(
                    message=AIMessage(
                        content=f"第{human_count}轮回答(已见历史{len(messages)}条):{last_q}",
                        usage_metadata={"input_tokens": len(messages) * 10, "output_tokens": 18, "total_tokens": len(messages) * 10 + 18},
                        response_metadata={"model_name": "offline-sim", "finish_reason": "stop"},
                    )
                )
            ]
        )


def main():
    cases = []

    # 1. Core 4 message types + ChatMessage + role vs type + shortcut conversion + ToolMessage artifact
    sys_msg = SystemMessage(content="你是一名 Python 编程助手。")
    hum_msg = HumanMessage(content="蓝色天空网是什么?")
    hum_with_id = HumanMessage(content="你好", id="user_message_001")
    ai_plain = AIMessage(content="蓝色天空网是一个编程学习平台。")
    ai_tool = AIMessage(
        content="",
        tool_calls=[{"name": "get_weather", "args": {"city": "杭州"}, "id": "call_001", "type": "tool_call"}],
        invalid_tool_calls=[{"name": "broken", "args": "{", "id": "call_bad", "error": "bad json", "type": "invalid_tool_call"}],
    )
    tool_msg = ToolMessage(
        content="找到3条匹配记录",
        tool_call_id="call_search_001",
        name="search_database",
        artifact={"records": [{"id": 1, "name": "Python"}, {"id": 2, "name": "Java"}, {"id": 3, "name": "Go"}]},
    )
    custom_msg = ChatMessage(role="moderator", content="系统公告")

    # Shortcut tuple & dict remain native tuple/dict until converted by LangChain API
    msg_tuple = ("user", "你好")
    msg_dict = {"role": "user", "content": "你好"}
    converted = convert_to_messages([("system", "助手"), msg_tuple, msg_dict])

    role_attr_missing = not hasattr(hum_msg, "role")
    c1_ok = (
        sys_msg.type == "system"
        and hum_msg.type == "human"
        and hum_msg.id is None
        and hum_with_id.id == "user_message_001"
        and role_attr_missing
        and ai_plain.type == "ai"
        and ai_plain.tool_calls == []
        and ai_tool.content == ""
        and len(ai_tool.tool_calls) == 1
        and len(ai_tool.invalid_tool_calls) == 1
        and tool_msg.type == "tool"
        and tool_msg.tool_call_id == "call_search_001"
        and len(tool_msg.artifact["records"]) == 3
        and custom_msg.role == "moderator"
        and isinstance(msg_tuple, tuple)
        and isinstance(msg_dict, dict)
        and [type(m).__name__ for m in converted] == ["SystemMessage", "HumanMessage", "HumanMessage"]
    )
    cases.append(
        dict(
            name="core_message_types_and_shortcuts",
            inputs=dict(types=["SystemMessage", "HumanMessage", "AIMessage", "ToolMessage", "ChatMessage"]),
            prerequisites="构造四类核心消息、带 artifact 的 ToolMessage 及元组/字典快捷写法,并核对 role 与 type 属性差异。",
            action="验证各消息 .type 值、HumanMessage 无 role 属性且默认 id 为 None,以及 convert_to_messages 按需转换快捷写法。",
            expected=dict(
                core_types=["system", "human", "ai", "tool"],
                human_has_no_role_attr=True,
                default_id_is_none=True,
                artifact_record_count=3,
                converted_classes=["SystemMessage", "HumanMessage", "HumanMessage"],
            ),
            actual=dict(
                core_types=[sys_msg.type, hum_msg.type, ai_plain.type, tool_msg.type],
                human_has_no_role_attr=role_attr_missing,
                default_id_is_none=(hum_msg.id is None),
                artifact_record_count=len(tool_msg.artifact["records"]),
                converted_classes=[type(m).__name__ for m in converted],
            ),
            measurements=dict(
                explicit_id=hum_with_id.id,
                custom_chat_role=custom_msg.role,
            ),
            passed=c1_ok,
        )
    )

    # 2. AIMessageChunk streaming merge (+), split tool_call_chunks assembly & BaseMessage properties
    c_a = AIMessageChunk(content="Python ")
    c_b = AIMessageChunk(content="是一门")
    c_c = AIMessageChunk(content="通用编程语言。")
    merged_text_chunk = c_a + c_b + c_c

    tc_1 = AIMessageChunk(
        content="",
        tool_call_chunks=[{"name": "get_weather", "args": '{"city": ', "id": "call_s1", "index": 0, "type": "tool_call_chunk"}],
    )
    tc_2 = AIMessageChunk(
        content="",
        tool_call_chunks=[{"name": None, "args": '"杭州"}', "id": None, "index": 0, "type": "tool_call_chunk"}],
    )
    merged_tc = tc_1 + tc_2

    sample_base = HumanMessage(content="你好,蓝色天空网")
    pretty = sample_base.pretty_repr()

    c2_ok = (
        c_a.type == "AIMessageChunk"
        and isinstance(c_a, AIMessage)
        and type(c_a) is AIMessageChunk
        and type(c_a) is not AIMessage
        and isinstance(merged_text_chunk, AIMessageChunk)
        and merged_text_chunk.text == "Python 是一门通用编程语言。"
        and merged_tc.tool_calls == [{"name": "get_weather", "args": {"city": "杭州"}, "id": "call_s1", "type": "tool_call"}]
        and sample_base.text == "你好,蓝色天空网"
        and "Human Message" in pretty
    )
    cases.append(
        dict(
            name="streaming_chunks_merge_and_properties",
            inputs=dict(text_chunks=3, tool_call_chunks=2),
            prerequisites="构造文本 AIMessageChunk 与分段 JSON 的 tool_call_chunks,测试 + 合并行为与 BaseMessage.pretty_repr()。",
            action="实测 langchain-core 1.7.6 中 AIMessageChunk.type 实际为 'AIMessageChunk'(且为 AIMessage 子类),+ 运算拼接文本并还原 tool_calls。",
            expected=dict(
                chunk_type_field="AIMessageChunk",
                chunk_is_subclass_of_ai=True,
                merged_text="Python 是一门通用编程语言。",
                assembled_tool_args={"city": "杭州"},
                pretty_has_header=True,
            ),
            actual=dict(
                chunk_type_field=c_a.type,
                chunk_is_subclass_of_ai=(isinstance(c_a, AIMessage) and type(c_a) is not AIMessage),
                merged_text=merged_text_chunk.text,
                assembled_tool_args=merged_tc.tool_calls[0]["args"],
                pretty_has_header=("Human Message" in pretty),
            ),
            measurements=dict(
                merged_class=type(merged_text_chunk).__name__,
                chunk_type_value=c_a.type,
                pretty_first_line=pretty.splitlines()[0],
            ),
            passed=c2_ok,
        )
    )

    # 3. ContentBlock standardized text & multimodal image (URL and local base64 PNG)
    text_block_msg = HumanMessage(content_blocks=[{"type": "text", "text": "你好,LangChain!"}])
    img_url_msg = HumanMessage(
        content_blocks=[
            {"type": "text", "text": "请描述这张图片。"},
            {"type": "image", "url": "https://example.com/demo.png"},
        ]
    )
    png_bytes = make_tiny_png_bytes()
    png_b64 = base64.b64encode(png_bytes).decode("utf-8")
    img_b64_msg = HumanMessage(
        content_blocks=[
            {"type": "text", "text": "请描述截图中的主要内容。"},
            {"type": "image", "base64": png_b64, "mime_type": "image/png"},
        ]
    )

    c3_ok = (
        text_block_msg.content_blocks == [{"type": "text", "text": "你好,LangChain!"}]
        and len(img_url_msg.content_blocks) == 2
        and img_url_msg.content_blocks[1]["type"] == "image"
        and len(img_b64_msg.content_blocks) == 2
        and img_b64_msg.content_blocks[1]["mime_type"] == "image/png"
        and img_b64_msg.content_blocks[1]["base64"] == png_b64
        and png_bytes.startswith(b"\x89PNG")
    )
    cases.append(
        dict(
            name="content_blocks_and_multimodal_base64",
            inputs=dict(png_size_bytes=len(png_bytes)),
            prerequisites="使用 LangChain 1.x content_blocks 构造纯文本块、URL 图片块与内存生成 1x1 PNG 的 Base64 图片块。",
            action="核对 content_blocks 标准化结构包含 type='text' 与 type='image',且 Base64 与 mime_type 完整保留。",
            expected=dict(
                text_block_count=1,
                url_block_types=["text", "image"],
                b64_block_count=2,
                b64_mime="image/png",
            ),
            actual=dict(
                text_block_count=len(text_block_msg.content_blocks),
                url_block_types=[b["type"] for b in img_url_msg.content_blocks],
                b64_block_count=len(img_b64_msg.content_blocks),
                b64_mime=img_b64_msg.content_blocks[1]["mime_type"],
            ),
            measurements=dict(
                png_bytes_len=len(png_bytes),
                base64_len=len(png_b64),
            ),
            passed=c3_ok,
        )
    )

    # 4. trim_messages() with token_counter=len, token_counter="approximate", and strategy="first"/"last"
    history = [
        SystemMessage(content="你是蓝色天空网的 AI 助手。"),
        HumanMessage(content="Python 怎么入门?"),
        AIMessage(content="建议先学习基础语法。"),
        HumanMessage(content="推荐什么 IDE?"),
        AIMessage(content="可以使用 VS Code 或 PyCharm。"),
        HumanMessage(content="如何安装第三方库?"),
        AIMessage(content="可以使用 pip install。"),
        HumanMessage(content="什么是 NumPy?"),
        AIMessage(content="NumPy 是 Python 数值计算库。"),
        HumanMessage(content="pandas 和 NumPy 有什么区别?"),
    ]
    trimmed_len = trim_messages(
        history,
        max_tokens=5,
        strategy="last",
        token_counter=len,
        include_system=True,
        start_on="human",
    )
    trimmed_approx = trim_messages(
        history,
        max_tokens=100,
        strategy="last",
        token_counter="approximate",
        include_system=True,
        start_on="human",
    )
    trimmed_approx_tight = trim_messages(
        history,
        max_tokens=45,
        strategy="last",
        token_counter="approximate",
        include_system=True,
        start_on="human",
    )
    trimmed_first = trim_messages(
        history,
        max_tokens=4,
        strategy="first",
        token_counter=len,
    )
    first_with_include_system_rejected = False
    try:
        trim_messages(history, max_tokens=4, strategy="first", token_counter=len, include_system=True)
    except ValueError:
        first_with_include_system_rejected = True

    c4_ok = (
        len(history) == 10
        and len(trimmed_len) == 4  # system + last human/ai/human starting on human within 5 msgs
        and [m.type for m in trimmed_len] == ["system", "human", "ai", "human"]
        and trimmed_len[0].type == "system"
        and trimmed_len[-1].content == "pandas 和 NumPy 有什么区别?"
        and len(trimmed_approx) >= 2
        and trimmed_approx[0].type == "system"
        and trimmed_approx[1].type == "human"
        and len(trimmed_approx_tight) < len(history)
        and trimmed_approx_tight[0].type == "system"
        and len(trimmed_first) == 4
        and trimmed_first[0].type == "system"
        and trimmed_first[1].content == "Python 怎么入门?"
        and first_with_include_system_rejected
    )
    cases.append(
        dict(
            name="trim_messages_count_and_approximate",
            inputs=dict(original_count=10, count_budget=5, approx_budget=100, approx_tight_budget=45),
            prerequisites="对 10 条历史消息(1 条 System + 4 轮问答 + 1 条最新提问)分别运行按消息数 len、approximate 估算及 strategy='first' 裁剪。",
            action="验证 strategy='last' + include_system=True + start_on='human' 保留 4 条消息,紧缩近似预算 45 触发裁剪,且 strategy='first' 搭配 include_system=True 抛出 ValueError。",
            expected=dict(
                original_len=10,
                trimmed_len_count=4,
                trimmed_len_types=["system", "human", "ai", "human"],
                approx_keeps_system_first=True,
                approx_tight_trimmed=True,
                first_strategy_len=4,
                first_rejects_include_system=True,
            ),
            actual=dict(
                original_len=len(history),
                trimmed_len_count=len(trimmed_len),
                trimmed_len_types=[m.type for m in trimmed_len],
                approx_keeps_system_first=(trimmed_approx[0].type == "system" and trimmed_approx[1].type == "human"),
                approx_tight_trimmed=(len(trimmed_approx_tight) < len(history) and trimmed_approx_tight[0].type == "system"),
                first_strategy_len=len(trimmed_first),
                first_rejects_include_system=first_with_include_system_rejected,
            ),
            measurements=dict(
                trimmed_approx_100_count=len(trimmed_approx),
                trimmed_approx_45_count=len(trimmed_approx_tight),
                trimmed_len_contents=[m.content for m in trimmed_len],
            ),
            passed=c4_ok,
        )
    )

    # 5. RemoveMessage + LangGraph add_messages reducer & 3-turn stateful conversation loop
    state_msgs = [
        HumanMessage(content="你好", id="msg_1"),
        AIMessage(content="你好!", id="msg_2"),
        HumanMessage(content="查询天气", id="msg_3"),
    ]
    removal = RemoveMessage(id="msg_3")
    raw_len_after_create = len(state_msgs)
    reduced = add_messages(state_msgs, [removal])
    reduced_ids = [m.id for m in reduced]

    chat_model = StatefulOfflineChatModel()
    conv = [SystemMessage(content="你是一名 Python 编程教程助手。")]
    for q in ("什么是 Python?", "它适合初学者吗?", "给我一个简单的学习计划。"):
        conv.append(HumanMessage(content=q))
        ans = chat_model.invoke(conv)
        conv.append(ans)

    c5_ok = (
        removal.type == "remove"
        and removal.id == "msg_3"
        and raw_len_after_create == 3
        and reduced_ids == ["msg_1", "msg_2"]
        and len(conv) == 7
        and [m.type for m in conv] == ["system", "human", "ai", "human", "ai", "human", "ai"]
        and "第3轮回答(已见历史6条)" in conv[-1].text
    )
    cases.append(
        dict(
            name="remove_message_and_langgraph_add_messages",
            inputs=dict(remove_id="msg_3", chat_turns=3),
            prerequisites="构造 RemoveMessage(id='msg_3') 对比普通列表与 LangGraph add_messages reducer,并运行 3 轮多轮消息列表对话。",
            action="确认仅创建 RemoveMessage 不修改原列表(仍为 3 条),经 add_messages 归并后剩余 ['msg_1', 'msg_2'];3 轮对话累计 7 条消息。",
            expected=dict(
                removal_type="remove",
                raw_list_unchanged_len=3,
                reduced_ids=["msg_1", "msg_2"],
                three_turn_history_len=7,
                third_turn_saw_6_msgs=True,
            ),
            actual=dict(
                removal_type=removal.type,
                raw_list_unchanged_len=raw_len_after_create,
                reduced_ids=reduced_ids,
                three_turn_history_len=len(conv),
                third_turn_saw_6_msgs=("第3轮回答(已见历史6条)" in conv[-1].text),
            ),
            measurements=dict(
                final_turn_reply=conv[-1].text,
                final_turn_usage=conv[-1].usage_metadata,
            ),
            passed=c5_ok,
        )
    )

    print(
        json.dumps(
            dict(
                version=platform.python_version(),
                system=platform.system(),
                cases=cases,
            ),
            ensure_ascii=False,
        )
    )


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

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

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

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

下载课程关联工程包:LangChain

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

下载课程关联工程包:LangChain

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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