{"record":{"id":"0022c11937249ba5","repo":"huggingface/smolagents","slug":"incorrect-role-role-only-messagerole-roles","errorCode":null,"errorMessage":"Incorrect role {role}, only {MessageRole.roles()} are supported for now.","messagePattern":"Incorrect role (.+?), only (.+?) are supported for now\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"src/smolagents/models.py","lineNumber":355,"sourceCode":") -> list[dict[str, Any]]:\n    \"\"\"\n    Creates a list of messages to give as input to the LLM. These messages are dictionaries and chat template compatible with transformers LLM chat template.\n    Subsequent messages with the same role will be concatenated to a single message.\n\n    Args:\n        message_list (`list[ChatMessage | dict]`): List of chat messages. Mixed types are allowed.\n        role_conversions (`dict[MessageRole, MessageRole]`, *optional* ): Mapping to convert roles.\n        convert_images_to_image_urls (`bool`, default `False`): Whether to convert images to image URLs.\n        flatten_messages_as_text (`bool`, default `False`): Whether to flatten messages as text.\n    \"\"\"\n    output_message_list: list[dict[str, Any]] = []\n    message_list = deepcopy(message_list)  # Avoid modifying the original list\n    for message in message_list:\n        if isinstance(message, dict):\n            message = ChatMessage.from_dict(message)\n        role = message.role\n        if role not in MessageRole.roles():\n            raise ValueError(f\"Incorrect role {role}, only {MessageRole.roles()} are supported for now.\")\n\n        if role in role_conversions:\n            message.role = role_conversions[role]  # type: ignore\n        # encode images if needed\n        if isinstance(message.content, list):\n            for element in message.content:\n                assert isinstance(element, dict), \"Error: this element should be a dict:\" + str(element)\n                if element[\"type\"] == \"image\":\n                    assert not flatten_messages_as_text, f\"Cannot use images with {flatten_messages_as_text=}\"\n                    if convert_images_to_image_urls:\n                        element.update(\n                            {\n                                \"type\": \"image_url\",\n                                \"image_url\": {\"url\": make_image_url(encode_image_base64(element.pop(\"image\")))},\n                            }\n                        )\n                    else:\n                        element[\"image\"] = encode_image_base64(element[\"image\"])","sourceCodeStart":337,"sourceCodeEnd":373,"githubUrl":"https://github.com/huggingface/smolagents/blob/30bb1161095dbae2271e6bc3cc4c219cc3897a57/src/smolagents/models.py#L337-L373","documentation":"get_clean_message_list normalizes a chat history into provider-ready messages; every message's role must be one of MessageRole.roles() (system/user/assistant/tool). Dict messages are converted via ChatMessage.from_dict, and then the role is checked before role conversion and image encoding. Any other role string (including None, empty string, or 'function') raises ValueError listing the valid roles.","triggerScenarios":"Passing a message list containing a dict or ChatMessage with an invalid role, e.g. {'role': 'tool_call', ...}, {'role': None}, or history built from another library's role names, to model methods or _prepare_completion_kwargs via agent.run([...]).","commonSituations":"Building message history manually or porting it from OpenAI/LangChain formats where roles differ; deserializing stored history with missing/corrupted role fields; typos like 'assitant'.","solutions":["Map your history's roles to MessageRole members (system/user/assistant/tool) before passing it in","Use ChatMessage.from_dict on well-formed dicts and validate early","Inspect the failing message (role printed in the error) and fix or drop it"],"exampleFix":"# before\nmessages = [{\"role\": \"function\", \"content\": \"42\"}]\nmodel.get_clean_message_list(messages)\n\n# after\nmessages = [{\"role\": \"tool\", \"content\": \"42\"}]\nmodel.get_clean_message_list(messages)","handlingStrategy":"type-guard","validationCode":"from smolagents.messages import MessageRole\nVALID = set(MessageRole.roles())\nhistory = [m if m.get('role') in VALID else {**m, 'role': 'user'} for m in history]","typeGuard":"from smolagents.messages import MessageRole\n\ndef has_valid_roles(messages) -> bool:\n    roles = set(MessageRole.roles())\n    return all((m['role'] if isinstance(m, dict) else m.role) in roles for m in messages)","tryCatchPattern":"try:\n    clean = model.get_clean_message_list(messages)\nexcept ValueError as e:\n    if 'Incorrect role' in str(e):\n        messages = sanitize_roles(messages)  # map unknown roles to 'user'","preventionTips":["Build history with ChatMessage and MessageRole enums instead of raw dicts","Map roles from other frameworks (function->tool) when importing history","Validate roles before agent.run/model calls"],"tags":["smolagents","chat-messages","role-validation","message-history"],"backgroundTag":"invalid-message-role","analyzedSha":"30bb1161095dbae2271e6bc3cc4c219cc3897a57","analyzedAt":"2026-08-28T18:52:54.169Z","schemaVersion":2},"datasetVersion":"2026-08-28T21:17:43.275Z"}