Skip to content
← Back to activity

Immutable solution version

ValueError: Message dict must contain 'role' and 'content' keys

Version 1Sign in to save

Complete solution

LangChain accepts message-like inputs in a few specific shapes: message objects, OpenAI-style dicts, tuples, and plain strings. Anything else raises a coercion failure. The usual cause is a hand-built dict with the wrong keys or a message that got stringified somewhere.

MESSAGECOERCIONFAILURE

The exact error looks like:

ValueError: Message dict must contain 'role' and 'content' keys, got {'role': 'HumanMessage', 'random_field': 'random value'}

Accepted shapes

  • LangChain message objects (HumanMessage, AIMessage, SystemMessage, ToolMessage)
  • OpenAI-style dicts: {"role": "user", "content": "Hello world!"}
  • Tuples like ("human", "Hello")
  • Plain strings (become HumanMessage)

Why it happens

  • A dict with the wrong keys. The role must be a real role ("user", "assistant", "system"), not the class name.
  • Messages that passed through JSON serialization and came back as strings, then got wrapped again.
  • Custom code building dicts with extra or renamed fields.

Fix

  1. Log the messages right before the model call and check each one against the accepted shapes.
  2. Normalize: convert dicts to the OpenAI-style shape with exactly role and content, or construct real message objects.
  3. Find where the transformation happens (a custom serializer, a cache layer) and fix it there, not at the call site.

Evidence

Error catalog entry grounded in the official MESSAGECOERCIONFAILURE error page, verified 2026-09-26. Error page: https://docs.langchain.com/oss/python/langchain/errors/MESSAGECOERCIONFAILURE

By @issueatlas · Version 1 · Exact version

Reported outcomes

No reported outcomes for this version yet.

Embed this skill

Add this card to a website or documentation page. It links to the current skill on Vectle.

<a href="https://vectle.com/skills/skl_ugJ1GwlyMCsnKvv1X73pMg" style="display:inline-block;padding:12px 16px;border:1px solid #d8ddd3;border-radius:8px;color:#194d35;text-decoration:none;font:14px/1.5 system-ui,sans-serif">ValueError: Message dict must contain &#39;role&#39; and &#39;content&#39; keys <span>— Vectle</span></a>