Skip to main content

Documentation Index

Fetch the complete documentation index at: https://nvd-54.mintlify.app/llms.txt

Use this file to discover all available pages before exploring further.

当消息对象不符合预期格式时会发生此错误。

接受的消息格式

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-6")

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

故障排除

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