> ## Documentation Index
> Fetch the complete documentation index at: https://cndoc-langchain.site/llms.txt
> Use this file to discover all available pages before exploring further.

# MESSAGE_COERCION_FAILURE

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

## 接受的消息格式

LangChain 模块接受 `MessageLikeRepresentation`，其定义如下：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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`](https://reference.langchain.com/python/langchain-core/messages/human/HumanMessage) 对象）。

如果模块接收到的值不属于这些格式之一，您将收到错误：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_anthropic import ChatAnthropic

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

model = ChatAnthropic(model="claude-sonnet-4-6")

model.invoke([uncoercible_message])
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
ValueError: Message dict must contain 'role' and 'content' keys, got {'role': 'HumanMessage', 'random_field': 'random value'}
```

## 故障排除

要解决此错误：

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

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档](/use-these-docs)通过 MCP 连接到 Claude、VSCode 等，以获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/langchain/errors/MESSAGE_COERCION_FAILURE.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
