{"record":{"id":"22076b5f278a0ca3","repo":"langchain-ai/langchain","slug":"unexpected-input-message-template","errorCode":null,"errorMessage":"Unexpected input: {message_template}","messagePattern":"Unexpected input: (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"libs/core/langchain_core/prompts/chat.py","lineNumber":1199,"sourceCode":"        Raises:\n            ValueError: If messages are of unexpected types.\n\n        Returns:\n            List of formatted messages.\n        \"\"\"\n        kwargs = self._merge_partial_and_user_variables(**kwargs)\n        result = []\n        for message_template in self.messages:\n            if isinstance(message_template, BaseMessage):\n                result.extend([message_template])\n            elif isinstance(\n                message_template, (BaseMessagePromptTemplate, BaseChatPromptTemplate)\n            ):\n                message = message_template.format_messages(**kwargs)\n                result.extend(message)\n            else:\n                msg = f\"Unexpected input: {message_template}\"  # type: ignore[unreachable]\n                raise ValueError(msg)  # noqa: TRY004\n        return result\n\n    async def aformat_messages(self, **kwargs: Any) -> list[BaseMessage]:\n        \"\"\"Async format the chat template into a list of finalized messages.\n\n        Args:\n            **kwargs: Keyword arguments to use for filling in template variables\n                in all the template messages in this chat template.\n\n        Returns:\n            List of formatted messages.\n\n        Raises:\n            ValueError: If unexpected input.\n        \"\"\"\n        kwargs = self._merge_partial_and_user_variables(**kwargs)\n        result = []\n        for message_template in self.messages:","sourceCodeStart":1181,"sourceCodeEnd":1217,"githubUrl":"https://github.com/langchain-ai/langchain/blob/e32fa9a52eab3b61ad7a45399bfde59b3e580fc4/libs/core/langchain_core/prompts/chat.py#L1181-L1217","documentation":"ChatPromptTemplate.format_messages iterates self.messages and accepts BaseMessage instances, BaseMessagePromptTemplate, or BaseChatPromptTemplate; anything else is rejected with ValueError('Unexpected input: ...'). Type checkers mark the raise unreachable because the messages field is typed to those classes — hitting it at runtime means the field holds an untyped/foreign object, usually injected by direct construction or mutation bypassing validation.","triggerScenarios":"Building ChatPromptTemplate(messages=[42]) via model_construct or by mutating .messages after validation; inserting a plain string or custom object into the messages list of an existing template; deserializing a corrupted prompt representation.","commonSituations":"Dynamic prompt pipelines that append to prompt.messages at runtime; model_construct(...) fast paths that skip validators; interop code that loads prompt state from JSON without re-validation.","solutions":["Keep messages to BaseMessage / message-template objects; convert strings with HumanMessagePromptTemplate.from_template(s) before inserting","Avoid mutating .messages after construction — build a new ChatPromptTemplate via from_messages","If loading from external data, revalidate: reconstruct through from_messages rather than assigning raw lists"],"exampleFix":"# before\nprompt.messages.append(\"Summarize the above\")  # later format_messages -> ValueError\n\n# after\nfrom langchain_core.prompts import HumanMessagePromptTemplate\nprompt.messages.append(HumanMessagePromptTemplate.from_template(\"Summarize the above\"))","handlingStrategy":"validation","validationCode":"from langchain_core.messages import BaseMessage\nfrom langchain_core.prompts import BaseMessagePromptTemplate, BaseChatPromptTemplate\n\ndef valid_messages(msgs) -> bool:\n    return all(\n        isinstance(m, (BaseMessage, BaseMessagePromptTemplate, BaseChatPromptTemplate))\n        for m in msgs\n    )","typeGuard":"def is_valid_chat_prompt_message(m) -> bool:\n    return isinstance(m, (BaseMessage, BaseMessagePromptTemplate, BaseChatPromptTemplate))","tryCatchPattern":null,"preventionTips":["Never append raw strings/objects to prompt.messages; convert via HumanMessagePromptTemplate.from_template","Rebuild prompts with from_messages instead of mutating .messages after construction"],"tags":["prompts","chat","messages","validation","core"],"backgroundTag":null,"analyzedSha":"e32fa9a52eab3b61ad7a45399bfde59b3e580fc4","analyzedAt":"2026-08-14T18:42:09.092Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}