{"record":{"id":"5b66c021ea34c752","repo":"langchain-ai/langchain","slug":"unsupported-operand-type-s-for-self-class","errorCode":null,"errorMessage":"unsupported operand type(s) for +: \"{self.__class__.__name__}\" and \"{other.__class__.__name__}\"","messagePattern":"unsupported operand type\\(s\\) for \\+: \"(.+?)\" and \"(.+?)\"","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"libs/core/langchain_core/messages/base.py","lineNumber":471,"sourceCode":"            content = merge_content(self.content, *(o.content for o in other))\n            additional_kwargs = merge_dicts(\n                self.additional_kwargs, *(o.additional_kwargs for o in other)\n            )\n            response_metadata = merge_dicts(\n                self.response_metadata, *(o.response_metadata for o in other)\n            )\n            return self.__class__(  # type: ignore[call-arg]\n                id=self.id,\n                content=content,\n                additional_kwargs=additional_kwargs,\n                response_metadata=response_metadata,\n            )\n        msg = (\n            'unsupported operand type(s) for +: \"'\n            f\"{self.__class__.__name__}\"\n            f'\" and \"{other.__class__.__name__}\"'\n        )\n        raise TypeError(msg)\n\n\ndef message_to_dict(message: BaseMessage) -> dict[str, Any]:\n    \"\"\"Convert a Message to a dictionary.\n\n    Args:\n        message: Message to convert.\n\n    Returns:\n        Message as a dict. The dict will have a `type` key with the message type\n        and a `data` key with the message data as a dict.\n\n    \"\"\"\n    return {\"type\": message.type, \"data\": message.model_dump()}\n\n\ndef messages_to_dict(messages: Sequence[BaseMessage]) -> list[dict[str, Any]]:\n    \"\"\"Convert a sequence of Messages to a list of dictionaries.","sourceCodeStart":453,"sourceCodeEnd":489,"githubUrl":"https://github.com/langchain-ai/langchain/blob/e32fa9a52eab3b61ad7a45399bfde59b3e580fc4/libs/core/langchain_core/messages/base.py#L453-L489","documentation":"Raised by BaseMessage.__add__ when you use the + operator on two message objects whose types are incompatible for merging. langchain-core only merges messages when one is an instance of the other's class (e.g. AIMessageChunk + AIMessageChunk); anything else falls through to this TypeError, mirroring Python's behavior for unsupported operands.","triggerScenarios":"Calling `msg1 + msg2` where the operands are different message classes, e.g. `AIMessage('a') + HumanMessage('b')`, `HumanMessage('a') + AIMessageChunk('b')`, or adding a plain string/other object to a message. Only same-class (or chunk-of-same-base) combinations merge.","commonSituations":"Accidentally building a history list and reducing it with `sum()` or `+` over mixed Human/AI messages; mixing a chunk streamed from a provider with a locally constructed message of a different type; assuming `+` concatenates any message contents like strings.","solutions":["Put messages in a list (`[msg1, msg2]`) instead of using `+` — conversation history is a list, not a merged message","If you meant to merge content, concatenate explicitly: `self.__class__(content=merge_content(msg1.content, msg2.content))`","If merging streamed chunks, ensure both operands are the same chunk class (e.g. both `AIMessageChunk`) from the same provider run","Check types before adding: `if type(other) is type(self): merged = self + other`"],"exampleFix":"# before\nmerged = HumanMessage(\"hi\") + AIMessage(\"hello\")  # TypeError\n\n# after\nhistory = [HumanMessage(\"hi\"), AIMessage(\"hello\")]","handlingStrategy":"type-guard","validationCode":"from langchain_core.messages import BaseMessage\n\ndef can_add(a: BaseMessage, b: BaseMessage) -> bool:\n    return isinstance(b, type(a)) or isinstance(a, type(b))","typeGuard":"from langchain_core.messages import BaseMessage\n\ndef is_mergeable_pair(a: BaseMessage, b: BaseMessage) -> bool:\n    \"\"\"True when a + b is defined by BaseMessage.__add__.\"\"\"\n    return isinstance(b, type(a)) or isinstance(a, type(b))","tryCatchPattern":"try:\n    merged = msg1 + msg2\nexcept TypeError as e:\n    if \"unsupported operand type(s) for +\" in str(e):\n        merged = None  # keep as separate messages\n    else:\n        raise","preventionTips":["Treat conversation history as a list of messages, never a single merged message","Only apply + between chunks of the same class from the same stream","Use merge_content() when you explicitly want content-level concatenation across types"],"tags":["messages","type-error","concatenation","langchain-core"],"backgroundTag":null,"analyzedSha":"e32fa9a52eab3b61ad7a45399bfde59b3e580fc4","analyzedAt":"2026-08-14T18:42:09.092Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}