Skip to content

Python: SerializationMixin.from_dict silently accepts mismatched type identifiers #7255

Description

@moonbox3

Description

SerializationMixin.from_dict() silently accepts payloads whose type identifier does not match the target class, despite documenting that a mismatch raises ValueError.

Reproduction

from agent_framework import Message

message = Message.from_dict(
    {
        "type": "function_tool",
        "role": "user",
        "contents": [],
    }
)

print(message.to_dict())

Actual behavior

A Message is returned successfully, and serializing it rewrites the payload type:

{
    "type": "message",
    "role": "user",
    "contents": [],
    "additional_properties": {},
}

Expected behavior

Message.from_dict() should raise ValueError because function_tool is not the type identifier for Message.

Root cause

In packages/core/agent_framework/_serialization.py, from_dict() derives the expected type by passing the input payload to _get_type_identifier():

type_id = cls._get_type_identifier(value)

_get_type_identifier(value) returns value["type"] first. Consequently, this validation compares the supplied type to itself and can never reject a non-empty mismatched type:

if (supplied_type := value.get("type")) and supplied_type != type_id:
    raise ValueError(...)

This can also select dependency injection entries using the incorrect incoming type.

The expected identifier should be derived independently from the target class, with a regression test covering a mismatched non-empty type value.

Metadata

Metadata

Assignees

Labels

pythonUsage: [Issues, PRs], Target: Python

Type

Projects

Status
No status

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions