{"record":{"id":"4d796ae9c153c80d","repo":"langchain-ai/langchain","slug":"expected-type-to-be-a-str-got-type-result-n","errorCode":null,"errorMessage":"Expected 'type' to be a str, got {type(result).__name__}","messagePattern":"Expected 'type' to be a str, got (.+?)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"libs/core/langchain_core/messages/utils.py","lineNumber":82,"sourceCode":"\nlogger = logging.getLogger(__name__)\n\n\ndef _get_type(v: Any) -> str:\n    \"\"\"Get the type associated with the object for serialization purposes.\"\"\"\n    if isinstance(v, dict) and \"type\" in v:\n        result = v[\"type\"]\n    elif hasattr(v, \"type\"):\n        result = v.type\n    else:\n        msg = (\n            f\"Expected either a dictionary with a 'type' key or an object \"\n            f\"with a 'type' attribute. Instead got type {type(v)}.\"\n        )\n        raise TypeError(msg)\n    if not isinstance(result, str):\n        msg = f\"Expected 'type' to be a str, got {type(result).__name__}\"\n        raise TypeError(msg)\n    return result\n\n\nAnyMessage = Annotated[\n    Annotated[AIMessage, Tag(tag=\"ai\")]\n    | Annotated[HumanMessage, Tag(tag=\"human\")]\n    | Annotated[ChatMessage, Tag(tag=\"chat\")]\n    | Annotated[SystemMessage, Tag(tag=\"system\")]\n    | Annotated[FunctionMessage, Tag(tag=\"function\")]\n    | Annotated[ToolMessage, Tag(tag=\"tool\")]\n    | Annotated[AIMessageChunk, Tag(tag=\"AIMessageChunk\")]\n    | Annotated[HumanMessageChunk, Tag(tag=\"HumanMessageChunk\")]\n    | Annotated[ChatMessageChunk, Tag(tag=\"ChatMessageChunk\")]\n    | Annotated[SystemMessageChunk, Tag(tag=\"SystemMessageChunk\")]\n    | Annotated[FunctionMessageChunk, Tag(tag=\"FunctionMessageChunk\")]\n    | Annotated[ToolMessageChunk, Tag(tag=\"ToolMessageChunk\")],\n    Field(discriminator=Discriminator(_get_type)),\n]","sourceCodeStart":64,"sourceCodeEnd":100,"githubUrl":"https://github.com/langchain-ai/langchain/blob/e32fa9a52eab3b61ad7a45399bfde59b3e580fc4/libs/core/langchain_core/messages/utils.py#L64-L100","documentation":"Raised by `_get_type` when the value found at `v['type']` (or `v.type`) is not a Python `str`. The discriminator must be a string like 'human' or 'ai'; any other type (int, None, list) is rejected to keep serialization dispatch deterministic.","triggerScenarios":"A message dict like `{'type': 1, ...}` or `{'type': None, ...}`, or an object whose `.type` attribute is a non-string (e.g. an int enum or a property returning None).","commonSituations":"Programmatically generated message dicts where the type was inserted from an untyped source (JSON number); ORM rows where `type` maps to an integer column; custom message classes overriding `type` with a non-string value.","solutions":["Ensure the 'type' value is a plain string literal ('human', 'ai', 'system', 'chat', 'function', 'tool')","Coerce before passing: `{'type': str(v['type']), ...}` if the source data uses stringly-typed numbers or enums","Fix custom message classes so the `type` attribute is a `str` (langchain-core's own classes use `Literal` string values)"],"exampleFix":"# before\nmsg = {'type': None, 'content': 'hi'}\n\n# after\nmsg = {'type': 'human', 'content': 'hi'}","handlingStrategy":"validation","validationCode":"def valid_type_value(v) -> bool:\n    t = v.get('type') if isinstance(v, dict) else getattr(v, 'type', None)\n    return isinstance(t, str) and len(t) > 0","typeGuard":"def is_str_typed(v: dict) -> bool:\n    return isinstance(v.get('type'), str)","tryCatchPattern":"try:\n    result = _get_type(v)\nexcept TypeError as e:\n    if \"Expected 'type' to be a str\" in str(e):\n        if isinstance(v, dict):\n            v['type'] = str(v['type'])\n        result = _get_type(v)\n    else:\n        raise","preventionTips":["Keep 'type' as a plain lowercase string literal","Do not reuse ORM/DB columns typed as integers for the message type field","Add schema validation (e.g. pydantic) on persisted message dicts before reload"],"tags":["serialization","type-discriminator","input-validation"],"backgroundTag":null,"analyzedSha":"e32fa9a52eab3b61ad7a45399bfde59b3e580fc4","analyzedAt":"2026-08-14T18:42:09.092Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}