跳到主要内容
当消息对象不符合预期格式时,会发生此错误。

接受的消息格式

LangChain 模块接受 MessageLikeRepresentation,其定义为
from typing import Union

from langchain_core.prompts.chat import (
    BaseChatPromptTemplate,
    BaseMessage,
    BaseMessagePromptTemplate,
)

MessageLikeRepresentation = Union[
    Union[BaseMessagePromptTemplate, BaseMessage, BaseChatPromptTemplate],
    tuple[
        Union[str, type],
        Union[str, list[dict], list[object]],
    ],
    str,
]
这些包括 OpenAI 风格的消息对象 ({ role: "user", content: "Hello world!" })、元组和纯字符串(它们被转换为 HumanMessage 对象)。 如果模块接收到的值不属于这些格式之一,您将收到一个错误:
from langchain_anthropic import ChatAnthropic

uncoercible_message = {"role": "HumanMessage", "random_field": "random value"}

model = ChatAnthropic(model="claude-sonnet-4-5-20250929")

model.invoke([uncoercible_message])
ValueError: Message dict must contain 'role' and 'content' keys, got {'role': 'HumanMessage', 'random_field': 'random value'}

故障排除

解决此错误的方法
  1. 确保格式正确:聊天模型的所有输入都必须是 LangChain 消息类数组或受支持的类似消息的格式
  2. 验证您的消息没有发生意外的字符串化或转换
  3. 检查错误的堆栈跟踪,并添加日志语句以检查消息对象在传递给模型之前的情况

以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.