Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions python/packages/core/agent_framework/_serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -535,8 +535,10 @@ async def get_current_weather(location: Annotated[str, "The city name"]) -> str:
if dependencies is None:
dependencies = {}

# Get the type identifier
type_id = cls._get_type_identifier(value)
# Resolve the expected identifier from the class, not the payload:
# reading it from `value` makes the mismatch check tautological, so
# any supplied 'type' would silently match itself.
type_id = cls._get_type_identifier()

if (supplied_type := value.get("type")) and supplied_type != type_id:
raise ValueError(f"Type mismatch: expected '{type_id}', got '{supplied_type}'")
Comment on lines 543 to 544
Expand Down
21 changes: 21 additions & 0 deletions python/packages/core/tests/core/test_serializable_mixin.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import logging
from typing import Any

import pytest
from typing_extensions import Self

from agent_framework._serialization import SerializationMixin
Expand Down Expand Up @@ -369,6 +370,26 @@ def __init__(self, value: str):
out = obj.to_dict()
assert out["type"] == "my_custom_type"

def test_from_dict_rejects_mismatched_type(self):
"""from_dict raises ValueError when the payload type doesn't match the class."""

class TestClass(SerializationMixin):
def __init__(self, value: str):
self.value = value

with pytest.raises(ValueError, match="Type mismatch: expected 'test_class', got 'function_tool'"):
TestClass.from_dict({"type": "function_tool", "value": "x"})

def test_from_json_rejects_mismatched_type(self):
"""from_json surfaces the same mismatch error instead of silently coercing."""

class TestClass(SerializationMixin):
def __init__(self, value: str):
self.value = value

with pytest.raises(ValueError, match="Type mismatch"):
TestClass.from_json('{"type": "some_other_type", "value": "x"}')

def test_from_json(self):
"""Test from_json deserializes JSON string."""

Expand Down
Loading