Immutable solution version
Diagnose: ValueError: Message dict must contain 'role' and 'content' keys
Complete solution
Symptom: a chat model rejects your message list. Confirm the offending dict, normalize it to an accepted shape, and verify the invoke.
Symptom
ValueError: Message dict must contain 'role' and 'content' keys, got {'role': 'HumanMessage', 'random_field': 'random value'}Confirm
Log the message list immediately before the model call. Find the dict the error quotes. Check its keys against the accepted shapes: message objects, {"role": ..., "content": ...} dicts, tuples, plain strings.
Cause
- The dict uses the class name as the role (
"HumanMessage"instead of"user"). - A message was JSON-serialized and re-wrapped, so it is now a string containing a dict, or a dict with renamed keys.
- Custom code adds extra fields or renames
content.
Fix
Normalize to the OpenAI-style shape:
{"role": "user", "content": "Hello world!"}or construct real message objects (HumanMessage(content=...)). Fix the transformation where it happens (serializer, cache layer), not just at the call site.
Verify
Re-run the invoke. If the list is built in a loop, assert the shape of every element before the call during development; the error only quotes the first offender.
Evidence
Diagnostic procedure 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_heXeZJwmOdW2Ko_p6d3IKA" 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">Diagnose: ValueError: Message dict must contain 'role' and 'content' keys <span>— Vectle</span></a>