LangChain 消息类型
系统解析 LangChain 1.x 消息体系(Human/AI/System/Tool/AIMessageChunk/RemoveMessage)、标准化 ContentBlock 与多模态图片、trim_messages 裁剪规则及 LangGraph add_messages 归并,并实测纠正 AIMessageChunk.type 与 strategy='first' 约束。
学完这一章,你能够
- 系统解析 LangChain 1.x 消息体系(Human/AI/System/Tool/AIMessageChunk/RemoveMessage)、标准化 ContentBlock 与多模态图片、trim_messages 裁剪规则及 LangGraph add_messages 归并,并实测纠正 AIMessageChunk.type 与 strategy='first' 约束。
核心消息类型与 HumanMessage / 快捷写法
在 LangChain 中,聊天模型与 Agent 的一切交互都围绕消息(Message)列表展开,涵盖纯文本、系统指令、工具调用与结果及多模态内容。四大基础消息类型见表 1:普通对话通常由 SystemMessage → HumanMessage → AIMessage 构成;引入工具后扩展为 HumanMessage → AIMessage(tool_calls) → ToolMessage → 最终 AIMessage。
HumanMessage 代表用户输入,核心属性为 content、type='human' 与 id(手动构造默认 None,可显式指定)。关键区别:LangChain 消息对象使用 .type 标识角色,不存在 .role 属性(访问 message.role 会抛 AttributeError),而 OpenAI 风格消息字典使用 'role' 键。除消息类外,框架也接受 ('user', '你好') 元组与 {'role': 'user', 'content': '你好'} 字典快捷写法——但它们本身仍是原生 tuple/dict,仅在传入接受 MessageLike 的 API(或 convert_to_messages)时按需转换。本站离线实测已全部核验。
AIMessage、SystemMessage 与 ToolMessage 详解
AIMessage(type='ai')承载模型输出及附加字段(详见表 2):普通文本回复时 tool_calls 为空列表;模型请求工具时在 tool_calls 列出调用名称、参数与 ID(出现 tool_calls 不代表工具已执行);解析失败项落入 invalid_tool_calls;response_metadata 随提供商异构,usage_metadata 提供标准化 Token 统计。
SystemMessage(type='system')通常置于消息列表首位,用于约定语言、长度、风格与参考资料优先级;但系统提示词不具备强安全隔离保证,用户权限、文件边界与支付校验等硬性规则必须在应用代码中强制执行。
ToolMessage(type='tool')保存工具执行返回,必须通过 tool_call_id 与前序 AIMessage.tool_calls 中的 id 一一匹配(一条 AIMessage 含多个调用时须配齐全部 ToolMessage,孤立发送或 ID 失配可能被服务端拒收)。此外可选 artifact 字段用于携带仅供应用程序读取、无需直接暴露给模型的完整结构化载荷(本站离线实测 artifact 保留 3 条数据库记录)。
AIMessageChunk 流式片段、消息速查表与版本实测勘误
调用 stream() 时模型逐段产出 AIMessageChunk,通过 chunk.text 读取文本并使用 + 运算符累积合并文本、工具调用参数片段与统计信息(切勿将未合并的半截 tool_call_chunks 当作完整 JSON 解析)。重要版本实测勘误:来源表格将 AIMessageChunk 的 type 列记为 'ai',但本站在 langchain 1.4.9 / langchain-core 1.7.6 实测确认 AIMessageChunk 虽继承自 AIMessage(isinstance 为 True 且非同一精确类),其 .type 属性实际值为 'AIMessageChunk';表 3 已同步标明该实测值。本站同时实测将两段分段 JSON tool_call_chunks 用 + 合并后,成功还原出 {'city': '杭州'}。另可扩展使用 ChatMessage 自定义角色。
ContentBlock 标准化内容块、多模态图片与 ToolCall 检查
LangChain 1.x 引入标准化 ContentBlock 机制统一跨提供商的多模态与推理内容(七类常见块见表 4),需区分普通聊天文本 TextContentBlock 与纯文本文件资源 PlainTextContentBlock,且 ToolCall 仍归口于 AIMessage.tool_calls。构造 HumanMessage(content_blocks=[{'type': 'text', 'text': '...'}]) 后可通过 .content_blocks 读取统一列表。
面向支持视觉输入的模型(如 openai:gpt-4o,注意并非所有模型支持图片输入),既可使用 OpenAI 风格的 image_url 块,也可使用跨厂商标准化的 ImageContentBlock(type='image',支持 url、base64+mime_type 或文件 ID)。本站离线在内存中构造 69 字节有效 1x1 PNG 并编码为 92 字符 Base64 拼入 content_blocks,验证 len(content_blocks) == 2 且完整保留 mime_type='image/png'。注意图片通常产生额外 Token 计费。
判断模型是否请求工具必须检查 if response.tool_calls:(并按需检查 response.invalid_tool_calls),切不可仅用 if not response.content: 推断,因为空文本也可能是其他非文本块或异常响应。
消息裁剪 trim_messages()、RemoveMessage 与 BaseMessage 通用接口
多轮历史增长超窗时可使用 trim_messages() 裁剪(8 项核心参数见表 5)。本站对 10 条历史消息(1 条 System + 4 轮问答 + 1 条最新提问)离线实测:(1)以 token_counter=len、max_tokens=5、strategy='last'、include_system=True、start_on='human' 裁剪后精确保留 4 条 ['system', 'human', 'ai', 'human'](起于最近可完整保留的提问,而非简单截断在 AI 回复上);(2)token_counter='approximate' 在 max_tokens=100 下保留全部 10 条,收紧至 45 后裁为 4 条;(3)重要实测边界:在 langchain-core 1.7.6 中 strategy='first' 不可搭配 include_system=True(会抛出 ValueError),因 'first' 本身即从首条系统消息起保留。裁剪含工具调用历史时务必保持 AIMessage(tool_calls) 与 ToolMessage 成对完整。
RemoveMessage(id='msg_3') 的 type 为 'remove',用于在支持状态归并的工作流(如 LangGraph add_messages reducer)中表达删除指令。实例化 RemoveMessage 不会自动修改普通 Python 列表,也不会删除数据库持久化记录。本站离线实测:创建 RemoveMessage 后原列表仍为 3 条,交由 langgraph.graph.message.add_messages 归并后精确剩余 ['msg_1', 'msg_2']。
所有核心消息均继承自 BaseMessage,共享 content、content_blocks、type、id、text(注意 1.x 中 text 为属性而非历史旧版方法)与 pretty_repr() 等属性方法(见表 6),本站实测 pretty_repr() 首行输出带标题分隔符便于终端调试。
多轮消息列表对话实战、常见问题与总结
将 SystemMessage 与每轮 HumanMessage / AIMessage 持续追加至 messages 列表即可构建基础多轮对话(本站离线 3 轮实测历史平滑增长至 7 条,第 3 轮模型可见前 6 条上下文)。生产环境须警惕:内存列表重启即失、超长会触窗限,且严禁多用户共享同一全局列表造成会话串扰,应配合独立会话存储或 LangGraph checkpointer。
八大常见疑问归纳:HumanMessage 表用户输入、AIMessage 表模型输出;对象用 .type 而字典用 'role';空 content 须联合查 tool_calls/invalid_tool_calls/content_blocks;ToolMessage 不可脱离匹配请求孤立发送;多模态支持取决于目标模型能力;历史超窗用 trim_messages() 并保护工具对完整;手动消息默认 id=None,需跟踪时显式赋值;RemoveMessage 仅改工作流内存状态不删数据库。理清消息对象与字典、工具请求与结果、原始 content 与标准 content_blocks 三组边界,是深入 Agent 与 LangGraph 的关键基石。
LangChain 四种核心消息类型
| 消息类型 | 角色 | 主要用途 |
|---|---|---|
| HumanMessage | 用户 | 表示用户发送的问题或输入内容 |
| AIMessage | AI 助手 | 表示模型回复,亦可能携带 tool_calls 与元数据 |
| SystemMessage | 系统 | 向模型提供角色定位、风格与任务约束 |
| ToolMessage | 工具 | 封装工具执行结果并通过 tool_call_id 关联请求 |
AIMessage 常用附加属性说明
| 属性 | 说明 |
|---|---|
| content | 模型生成的原始文本或内容块列表 |
| tool_calls | 已成功解析的标准化工具调用请求列表 |
| invalid_tool_calls | JSON 或格式解析失败的工具调用记录 |
| response_metadata | 具体模型提供商返回的异构响应元数据 |
| usage_metadata | LangChain 标准化 Token 使用统计字典 |
| id | 消息唯一标识(手动构造默认 None) |
LangChain 消息类型与属性速查表(含 1.7.6 实测修正)
| 消息类型 | type | 常用属性 | 主要用途 |
|---|---|---|---|
| HumanMessage | human | content、id | 用户输入消息 |
| AIMessage | ai | content、tool_calls、usage_metadata | 模型完整回复 |
| SystemMessage | system | content | 系统级指令 |
| ToolMessage | tool | content、tool_call_id、name、artifact | 工具执行结果 |
| AIMessageChunk | AIMessageChunk(实测;部分资料按父类写作 ai) | content、tool_call_chunks | 流式模型消息片段(支持 + 合并) |
| RemoveMessage | remove | id | 配合 add_messages 从状态中移除指定消息 |
LangChain 1.x 常见标准化 ContentBlock 类型
| 类型 | 说明 |
|---|---|
| TextContentBlock | 普通聊天文本内容(type='text') |
| ImageContentBlock | 标准化图片内容块(type='image',支持 URL/Base64/文件 ID) |
| AudioContentBlock | 音频多模态内容块 |
| VideoContentBlock | 视频多模态内容块 |
| FileContentBlock | PDF、Word 等二进制文档内容块 |
| PlainTextContentBlock | 纯文本文件或文本资源内容块(区别于普通对话文本) |
| ReasoningContentBlock | 推理模型返回的标准化思考推理内容块 |
trim_messages() 常用裁剪参数
| 参数 | 说明 |
|---|---|
| messages | 待裁剪的原始消息列表 |
| max_tokens | 长度预算上限,单位由 token_counter 决定 |
| token_counter | 计数函数(如 len)、模型对象或 'approximate' |
| strategy | 'first' 保留最早消息,'last' 保留最近消息 |
| include_system | 仅配合 strategy='last' 有效,保留开头系统消息 |
| start_on | 要求裁剪后非系统首条消息必须为指定类型(如 'human') |
| allow_partial | 是否允许截断单条超长消息的部分内容 |
| end_on | 要求裁剪结果以指定消息类型结尾 |
BaseMessage 常用通用属性与方法
| 属性或方法 | 作用 |
|---|---|
| content | 原始消息内容(字符串或内容块列表) |
| content_blocks | 统一标准化后的内容块列表 |
| type | LangChain 消息类型标识字符串 |
| id | 消息唯一标识(可能为 None) |
| text | 提取消息内纯文本内容的只读属性(1.x 属性写法) |
| pretty_repr() | 生成带消息类型标题栏的终端调试文本 |
离线实测核心消息类、AIMessageChunk 合并与 type 勘误、Base64 多模态块、trim_messages 与 RemoveMessage
"""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()
- 核对 .type 与无 .role 属性、AIMessageChunk.type=='AIMessageChunk' 及分段工具调用合并、69B PNG Base64 多模态块、trim_messages 裁为 4 条与 strategy='first'+include_system=True 抛 ValueError,以及 add_messages 执行 RemoveMessage。
所需环境:Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。
当前源码 SHA256:03b8ee0294d6e06f8dec6c6f58b6ce90d10217410c0df48ab26399a3b74e6121
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。
ZIP SHA256:2ee27c6e2d9455aea53ab78e09969e224aea1a84220903bdf49d252f61d69d89
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么直接访问 HumanMessage(content='你好').role 会报错?仅创建 RemoveMessage(id='msg_3') 为什么不会改变原消息列表长度?
展开参考解答
LangChain 消息对象使用 .type(如 'human')区分角色,不提供 .role 属性('role' 仅用于 OpenAI 风格消息字典);RemoveMessage 只是一条声明删除意图的状态操作消息,必须交给 LangGraph 的 add_messages 等状态归并器处理才会真正从状态列表移除对应 ID 消息。