AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix(backend/copilot): auto-parse structured data and robust type coercion (#12390)
Zamil Majdya083493aa2b7
diff --git a/autogpt_platform/backend/backend/copilot/prompting.py b/autogpt_platform/backend/backend/copilot/prompting.pyindex bbd47b6013..8e5e047df1 100644--- a/autogpt_platform/backend/backend/copilot/prompting.py+++ b/autogpt_platform/backend/backend/copilot/prompting.py@@ -52,6 +52,11 @@ Examples:You can embed a reference inside any string argument, or use it as the entirevalue. Multiple references in one argument are all expanded.+**Type coercion**: The platform automatically coerces expanded string values+to match the block's expected input types. For example, if a block expects+`list[list[str]]` and you pass a string containing a JSON array (e.g. from+an @@agptfile: expansion), the string will be parsed into the correct type.+### Sub-agent tasks- When using the Task tool, NEVER set `run_in_background` to true.diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers.py b/autogpt_platform/backend/backend/copilot/tools/helpers.pyindex 6db28e8cb0..1c6de38a3a 100644--- a/autogpt_platform/backend/backend/copilot/tools/helpers.py+++ b/autogpt_platform/backend/backend/copilot/tools/helpers.py@@ -13,6 +13,7 @@ from backend.data.execution import ExecutionContextfrom backend.data.model import CredentialsFieldInfo, CredentialsMetaInputfrom backend.integrations.creds_manager import IntegrationCredentialsManagerfrom backend.util.exceptions import BlockError+from backend.util.type import coerce_inputs_to_schemafrom .models import BlockOutputResponse, ErrorResponse, ToolResponseBasefrom .utils import match_credentials_to_requirements@@ -111,6 +112,9 @@ async def execute_block(session_id=session_id,)+ # Coerce non-matching data types to the expected input schema.+ coerce_inputs_to_schema(input_data, block.input_schema)+# Execute the block and collect outputsoutputs: dict[str, list[Any]] = defaultdict(list)async for output_name, output_data in block.execute(diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers_test.py b/autogpt_platform/backend/backend/copilot/tools/helpers_test.pynew file mode 100644index 0000000000..4f22a5111d--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/helpers_test.py@@ -0,0 +1,333 @@+"""Tests for execute_block type coercion in helpers.py.++Verifies that execute_block() coerces string input values to match the block's+expected input types, mirroring the executor's validate_exec() logic.+This is critical for @@agptfile: expansion, where file content is always a string+but the block may expect structured types (e.g. list[list[str]]).+"""++from typing import Any+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from backend.copilot.tools.helpers import execute_block+from backend.copilot.tools.models import BlockOutputResponse+++def _make_block_schema(annotations: dict[str, Any]) -> MagicMock:+ """Create a mock input_schema with model_fields matching the given annotations."""+ schema = MagicMock()+ # coerce_inputs_to_schema uses model_fields (Pydantic v2 API)+ model_fields = {}+ for name, ann in annotations.items():+ field = MagicMock()+ field.annotation = ann+ model_fields[name] = field+ schema.model_fields = model_fields+ return schema+++def _make_block(+ block_id: str,+ name: str,+ annotations: dict[str, Any],+ outputs: dict[str, list[Any]] | None = None,+) -> MagicMock:+ """Create a mock block with typed annotations and a simple execute method."""+ block = MagicMock()+ block.id = block_id+ block.name = name+ block.input_schema = _make_block_schema(annotations)++ captured_inputs: dict[str, Any] = {}++ async def mock_execute(input_data: dict, **_kwargs: Any):+ captured_inputs.update(input_data)+ for output_name, values in (outputs or {"result": ["ok"]}).items():+ for v in values:+ yield output_name, v++ block.execute = mock_execute+ block._captured_inputs = captured_inputs+ return block+++_TEST_SESSION_ID = "test-session-coerce"+_TEST_USER_ID = "test-user-coerce"++[email protected](loop_scope="session")+async def test_coerce_json_string_to_nested_list():+ """JSON string → list[list[str]] (Google Sheets CSV import case)."""+ block = _make_block(+ "sheets-write",+ "Google Sheets Write",+ {"values": list[list[str]], "spreadsheet_id": str},+ )++ mock_workspace_db = MagicMock()+ mock_workspace_db.get_or_create_workspace = AsyncMock(+ return_value=MagicMock(id="ws-1")+ )++ with patch(+ "backend.copilot.tools.helpers.workspace_db",+ return_value=mock_workspace_db,+ ):+ response = await execute_block(+ block=block,+ block_id="sheets-write",+ input_data={+ "values": '[["Name","Score"],["Alice","90"],["Bob","85"]]',+ "spreadsheet_id": "abc123",+ },+ user_id=_TEST_USER_ID,+ session_id=_TEST_SESSION_ID,+ node_exec_id="exec-1",+ matched_credentials={},+ )++ assert isinstance(response, BlockOutputResponse)+ assert response.success is True+ # Verify the input was coerced from string to list[list[str]]+ assert block._captured_inputs["values"] == [+ ["Name", "Score"],+ ["Alice", "90"],+ ["Bob", "85"],+ ]+ assert isinstance(block._captured_inputs["values"], list)+ assert isinstance(block._captured_inputs["values"][0], list)++[email protected](loop_scope="session")+async def test_coerce_json_string_to_list():+ """JSON string → list[str]."""+ block = _make_block(+ "list-block",+ "List Block",+ {"items": list[str]},+ )++ mock_workspace_db = MagicMock()+ mock_workspace_db.get_or_create_workspace = AsyncMock(+ return_value=MagicMock(id="ws-1")+ )++ with patch(+ "backend.copilot.tools.helpers.workspace_db",+ return_value=mock_workspace_db,+ ):+ response = await execute_block(+ block=block,+ block_id="list-block",+ input_data={"items": '["a","b","c"]'},+ user_id=_TEST_USER_ID,+ session_id=_TEST_SESSION_ID,+ node_exec_id="exec-2",+ matched_credentials={},+ )++ assert isinstance(response, BlockOutputResponse)+ assert block._captured_inputs["items"] == ["a", "b", "c"]++[email protected](loop_scope="session")+async def test_coerce_json_string_to_dict():+ """JSON string → dict[str, str]."""+ block = _make_block(+ "dict-block",+ "Dict Block",+ {"config": dict[str, str]},+ )++ mock_workspace_db = MagicMock()+ mock_workspace_db.get_or_create_workspace = AsyncMock(+ return_value=MagicMock(id="ws-1")+ )++ with patch(+ "backend.copilot.tools.helpers.workspace_db",+ return_value=mock_workspace_db,+ ):+ response = await execute_block(+ block=block,+ block_id="dict-block",+ input_data={"config": '{"key": "value", "foo": "bar"}'},+ user_id=_TEST_USER_ID,+ session_id=_TEST_SESSION_ID,+ node_exec_id="exec-3",+ matched_credentials={},+ )++ assert isinstance(response, BlockOutputResponse)+ assert block._captured_inputs["config"] == {"key": "value", "foo": "bar"}++[email protected](loop_scope="session")+async def test_no_coercion_when_type_matches():+ """Already-correct types pass through without coercion."""+ block = _make_block(+ "pass-through",+ "Pass Through",+ {"values": list[list[str]], "name": str},+ )++ original_values = [["a", "b"], ["c", "d"]]+ mock_workspace_db = MagicMock()+ mock_workspace_db.get_or_create_workspace = AsyncMock(+ return_value=MagicMock(id="ws-1")+ )++ with patch(+ "backend.copilot.tools.helpers.workspace_db",+ return_value=mock_workspace_db,+ ):+ response = await execute_block(+ block=block,+ block_id="pass-through",+ input_data={"values": original_values, "name": "test"},+ user_id=_TEST_USER_ID,+ session_id=_TEST_SESSION_ID,+ node_exec_id="exec-4",+ matched_credentials={},+ )++ assert isinstance(response, BlockOutputResponse)+ assert block._captured_inputs["values"] == original_values+ assert block._captured_inputs["name"] == "test"++[email protected](loop_scope="session")+async def test_coerce_string_to_int():+ """String number → int."""+ block = _make_block(+ "int-block",+ "Int Block",+ {"count": int},+ )++ mock_workspace_db = MagicMock()+ mock_workspace_db.get_or_create_workspace = AsyncMock(+ return_value=MagicMock(id="ws-1")+ )++ with patch(+ "backend.copilot.tools.helpers.workspace_db",+ return_value=mock_workspace_db,+ ):+ response = await execute_block(+ block=block,+ block_id="int-block",+ input_data={"count": "42"},+ user_id=_TEST_USER_ID,+ session_id=_TEST_SESSION_ID,+ node_exec_id="exec-5",+ matched_credentials={},+ )++ assert isinstance(response, BlockOutputResponse)+ assert block._captured_inputs["count"] == 42+ assert isinstance(block._captured_inputs["count"], int)++[email protected](loop_scope="session")+async def test_coerce_skips_none_values():+ """None values are not coerced (they may be optional fields)."""+ block = _make_block(+ "optional-block",+ "Optional Block",+ {"data": list[str], "label": str},+ )++ mock_workspace_db = MagicMock()+ mock_workspace_db.get_or_create_workspace = AsyncMock(+ return_value=MagicMock(id="ws-1")+ )++ with patch(+ "backend.copilot.tools.helpers.workspace_db",+ return_value=mock_workspace_db,+ ):+ response = await execute_block(+ block=block,+ block_id="optional-block",+ input_data={"label": "test"},+ user_id=_TEST_USER_ID,+ session_id=_TEST_SESSION_ID,+ node_exec_id="exec-6",+ matched_credentials={},+ )++ assert isinstance(response, BlockOutputResponse)+ # 'data' was not provided, so it should not appear in captured inputs+ assert "data" not in block._captured_inputs++[email protected](loop_scope="session")+async def test_coerce_union_type_preserves_valid_member():+ """Union-typed fields should not be coerced when the value matches a member."""+ block = _make_block(+ "union-block",+ "Union Block",+ {"content": str | list[str]},+ )++ mock_workspace_db = MagicMock()+ mock_workspace_db.get_or_create_workspace = AsyncMock(+ return_value=MagicMock(id="ws-1")+ )++ with patch(+ "backend.copilot.tools.helpers.workspace_db",+ return_value=mock_workspace_db,+ ):+ response = await execute_block(+ block=block,+ block_id="union-block",+ input_data={"content": ["a", "b"]},+ user_id=_TEST_USER_ID,+ session_id=_TEST_SESSION_ID,+ node_exec_id="exec-7",+ matched_credentials={},+ )++ assert isinstance(response, BlockOutputResponse)+ # list[str] should NOT be stringified to '["a", "b"]'+ assert block._captured_inputs["content"] == ["a", "b"]+ assert isinstance(block._captured_inputs["content"], list)++[email protected](loop_scope="session")+async def test_coerce_inner_elements_of_generic():+ """Inner elements of generic containers are recursively coerced."""+ block = _make_block(+ "inner-coerce",+ "Inner Coerce",+ {"values": list[str]},+ )++ mock_workspace_db = MagicMock()+ mock_workspace_db.get_or_create_workspace = AsyncMock(+ return_value=MagicMock(id="ws-1")+ )++ with patch(+ "backend.copilot.tools.helpers.workspace_db",+ return_value=mock_workspace_db,+ ):+ response = await execute_block(+ block=block,+ block_id="inner-coerce",+ # Inner elements are ints, but target is list[str]+ input_data={"values": [1, 2, 3]},+ user_id=_TEST_USER_ID,+ session_id=_TEST_SESSION_ID,+ node_exec_id="exec-8",+ matched_credentials={},+ )++ assert isinstance(response, BlockOutputResponse)+ # Inner elements should be coerced from int to str+ assert block._captured_inputs["values"] == ["1", "2", "3"]+ assert all(isinstance(v, str) for v in block._captured_inputs["values"])diff --git a/autogpt_platform/backend/backend/executor/utils.py b/autogpt_platform/backend/backend/executor/utils.pyindex 2f7706f932..cb3548944c 100644--- a/autogpt_platform/backend/backend/executor/utils.py+++ b/autogpt_platform/backend/backend/executor/utils.py@@ -46,7 +46,7 @@ from backend.util.exceptions import ()from backend.util.logging import TruncatedLogger, is_structured_logging_enabledfrom backend.util.settings import Config-from backend.util.type import convert+from backend.util.type import coerce_inputs_to_schemaconfig = Config()logger = TruncatedLogger(logging.getLogger(__name__), prefix="[GraphExecutorUtil]")@@ -213,11 +213,8 @@ def validate_exec(if resolve_input:data = merge_execution_input(data)- # Convert non-matching data types to the expected input schema.- for name, data_type in schema.__annotations__.items():- value = data.get(name)- if (value is not None) and (type(value) is not data_type):- data[name] = convert(value, data_type)+ # Coerce non-matching data types to the expected input schema.+ coerce_inputs_to_schema(data, schema)# Input data post-merge should contain all required fields from the schema.if missing_input := schema.get_missing_input(data):diff --git a/autogpt_platform/backend/backend/util/type.py b/autogpt_platform/backend/backend/util/type.pyindex 2402011669..f22ae5a4d6 100644--- a/autogpt_platform/backend/backend/util/type.py+++ b/autogpt_platform/backend/backend/util/type.py@@ -249,6 +249,87 @@ def convert(value: Any, target_type: Any) -> Any:raise ConversionError(f"Failed to convert {value} to {target_type}") from e+def _value_satisfies_type(value: Any, target: Any) -> bool:+ """Check whether *value* already satisfies *target*, including inner elements.++ For union types this checks each member; for generic container types it+ recursively checks that inner elements satisfy the type args (e.g. every+ element in a ``list[str]`` is a ``str``). Returns ``False`` when uncertain+ so the caller falls through to :func:`convert`.+ """+ # typing.Any cannot be used with isinstance(); treat as always satisfied.+ if target is Any:+ return True++ origin = get_origin(target)++ if origin is Union or origin is types.UnionType:+ non_none = [a for a in get_args(target) if a is not type(None)]+ return any(_value_satisfies_type(value, member) for member in non_none)++ # Generic container type (e.g. list[str], dict[str, int])+ if origin is not None:+ # Guard: origin may not be a runtime type (e.g. Literal)+ if not isinstance(origin, type):+ return False+ if not isinstance(value, origin):+ return False+ args = get_args(target)+ if not args:+ return True+ # Check inner elements satisfy the type args+ if _is_type_or_subclass(origin, list):+ return all(_value_satisfies_type(v, args[0]) for v in value)+ if _is_type_or_subclass(origin, dict) and len(args) >= 2:+ return all(+ _value_satisfies_type(k, args[0]) and _value_satisfies_type(v, args[1])+ for k, v in value.items()+ )+ if (+ _is_type_or_subclass(origin, set) or _is_type_or_subclass(origin, frozenset)+ ) and args:+ return all(_value_satisfies_type(v, args[0]) for v in value)+ if _is_type_or_subclass(origin, tuple):+ # Homogeneous tuple[T, ...] — single type + Ellipsis+ if len(args) == 2 and args[1] is Ellipsis:+ return all(_value_satisfies_type(v, args[0]) for v in value)+ # Heterogeneous tuple[T1, T2, ...] — positional types+ if len(value) != len(args):+ return False+ return all(_value_satisfies_type(v, t) for v, t in zip(value, args))+ # Unhandled generic origin — fall through to convert()+ return False++ # Simple type (e.g. str, int)+ if isinstance(target, type):+ return isinstance(value, target)++ return False+++def coerce_inputs_to_schema(data: dict[str, Any], schema: type) -> None:+ """Coerce *data* values in-place to match *schema*'s field types.++ Uses ``model_fields`` (not ``__annotations__``) so inherited fields are+ included. Skips coercion when the value already satisfies the target+ type — in particular for union-typed fields where the value matches one+ member but differs from the annotation object itself.++ This is the single authoritative coercion step shared by the executor+ (``validate_exec``) and the CoPilot (``execute_block``).+ """+ for name, field_info in schema.model_fields.items():+ value = data.get(name)+ if value is None:+ continue+ target = field_info.annotation+ if target is None:+ continue+ if _value_satisfies_type(value, target):+ continue+ data[name] = convert(value, target)++class FormattedStringType(str):string_format: strdiff --git a/autogpt_platform/backend/backend/util/type_test.py b/autogpt_platform/backend/backend/util/type_test.pyindex 920776edbf..ea25270511 100644--- a/autogpt_platform/backend/backend/util/type_test.py+++ b/autogpt_platform/backend/backend/util/type_test.py@@ -1,6 +1,8 @@-from typing import List, Optional+from typing import Any, List, Literal, Optional-from backend.util.type import convert+from pydantic import BaseModel++from backend.util.type import _value_satisfies_type, coerce_inputs_to_schema, convertdef test_type_conversion():@@ -46,3 +48,343 @@ def test_type_conversion():# Test other empty list conversionsassert convert([], int) == 0 # len([]) = 0assert convert([], Optional[int]) == 0+++# ---------------------------------------------------------------------------+# _value_satisfies_type+# ---------------------------------------------------------------------------+++class TestValueSatisfiesType:+ # --- simple types ---+ def test_simple_match(self):+ assert _value_satisfies_type("hello", str) is True+ assert _value_satisfies_type(42, int) is True+ assert _value_satisfies_type(3.14, float) is True+ assert _value_satisfies_type(True, bool) is True++ def test_simple_mismatch(self):+ assert _value_satisfies_type("hello", int) is False+ assert _value_satisfies_type(42, str) is False+ assert _value_satisfies_type([1, 2], str) is False++ # --- Any ---+ def test_any_always_satisfied(self):+ assert _value_satisfies_type("hello", Any) is True+ assert _value_satisfies_type(42, Any) is True+ assert _value_satisfies_type([1, 2], Any) is True+ assert _value_satisfies_type(None, Any) is True++ # --- Optional / Union ---+ def test_optional_with_value(self):+ assert _value_satisfies_type("hello", Optional[str]) is True+ assert _value_satisfies_type(42, Optional[int]) is True++ def test_optional_mismatch(self):+ assert _value_satisfies_type(42, Optional[str]) is False++ def test_union_matches_first_member(self):+ assert _value_satisfies_type("hello", str | list[str]) is True++ def test_union_matches_second_member(self):+ assert _value_satisfies_type(["a", "b"], str | list[str]) is True++ def test_union_no_match(self):+ assert _value_satisfies_type(42, str | list[str]) is False++ # --- list[T] ---+ def test_list_str_all_match(self):+ assert _value_satisfies_type(["a", "b", "c"], list[str]) is True++ def test_list_str_inner_mismatch(self):+ assert _value_satisfies_type([1, 2, 3], list[str]) is False++ def test_list_int_all_match(self):+ assert _value_satisfies_type([1, 2, 3], list[int]) is True++ def test_list_int_inner_mismatch(self):+ assert _value_satisfies_type(["1", "2"], list[int]) is False++ def test_empty_list_satisfies_any_list_type(self):+ assert _value_satisfies_type([], list[str]) is True+ assert _value_satisfies_type([], list[int]) is True++ def test_string_does_not_satisfy_list(self):+ assert _value_satisfies_type("hello", list[str]) is False++ # --- nested list[list[str]] ---+ def test_nested_list_all_match(self):+ assert _value_satisfies_type([["a", "b"], ["c"]], list[list[str]]) is True++ def test_nested_list_inner_mismatch(self):+ assert _value_satisfies_type([["a", 1], ["c"]], list[list[str]]) is False++ def test_nested_list_outer_mismatch(self):+ assert _value_satisfies_type(["a", "b"], list[list[str]]) is False++ # --- dict[K, V] ---+ def test_dict_str_int_match(self):+ assert _value_satisfies_type({"a": 1, "b": 2}, dict[str, int]) is True++ def test_dict_str_int_value_mismatch(self):+ assert _value_satisfies_type({"a": "1", "b": "2"}, dict[str, int]) is False++ def test_dict_str_int_key_mismatch(self):+ assert _value_satisfies_type({1: 1, 2: 2}, dict[str, int]) is False++ def test_empty_dict_satisfies(self):+ assert _value_satisfies_type({}, dict[str, int]) is True++ # --- set[T] / tuple[T] ---+ def test_set_match(self):+ assert _value_satisfies_type({1, 2, 3}, set[int]) is True++ def test_set_mismatch(self):+ assert _value_satisfies_type({"a", "b"}, set[int]) is False++ def test_tuple_homogeneous_match(self):+ assert _value_satisfies_type((1, 2, 3), tuple[int, ...]) is True++ def test_tuple_homogeneous_mismatch(self):+ assert _value_satisfies_type((1, "2", 3), tuple[int, ...]) is False++ def test_tuple_heterogeneous_match(self):+ assert _value_satisfies_type(("a", 1, True), tuple[str, int, bool]) is True++ def test_tuple_heterogeneous_mismatch(self):+ assert _value_satisfies_type(("a", "b", True), tuple[str, int, bool]) is False++ def test_tuple_heterogeneous_wrong_length(self):+ assert _value_satisfies_type(("a", 1), tuple[str, int, bool]) is False++ # --- bare generics (no args) ---+ def test_bare_list(self):+ assert _value_satisfies_type([1, "a"], list) is True++ def test_bare_dict(self):+ assert _value_satisfies_type({"a": 1}, dict) is True++ # --- union with generic inner mismatch ---+ def test_union_list_with_wrong_inner_falls_through(self):+ # [1, 2] doesn't satisfy list[str] (inner mismatch), and not str either+ assert _value_satisfies_type([1, 2], str | list[str]) is False++ # --- Literal (non-runtime origin) ---+ def test_literal_does_not_crash(self):+ """Literal origins are not runtime types — should return False, not crash."""+ assert _value_satisfies_type("active", Literal["active", "inactive"]) is False+++# ---------------------------------------------------------------------------+# coerce_inputs_to_schema — using real Pydantic models+# ---------------------------------------------------------------------------+++class SampleSchema(BaseModel):+ name: str+ count: int+ items: list[str]+ config: dict[str, int] = {}+++class NestedSchema(BaseModel):+ rows: list[list[str]]+++class UnionSchema(BaseModel):+ content: str | list[str]+++class OptionalSchema(BaseModel):+ label: Optional[str] = None+ value: int = 0+++class AnyFieldSchema(BaseModel):+ data: Any+++class TestCoerceInputsToSchema:+ def test_string_to_int(self):+ data: dict[str, Any] = {"name": "test", "count": "42", "items": ["a"]}+ coerce_inputs_to_schema(data, SampleSchema)+ assert data["count"] == 42+ assert isinstance(data["count"], int)++ def test_json_string_to_list(self):+ data: dict[str, Any] = {"name": "test", "count": 1, "items": '["a","b","c"]'}+ coerce_inputs_to_schema(data, SampleSchema)+ assert data["items"] == ["a", "b", "c"]++ def test_already_correct_types_unchanged(self):+ data: dict[str, Any] = {+ "name": "test",+ "count": 42,+ "items": ["a", "b"],+ "config": {"x": 1},+ }+ coerce_inputs_to_schema(data, SampleSchema)+ assert data == {+ "name": "test",+ "count": 42,+ "items": ["a", "b"],+ "config": {"x": 1},+ }++ def test_inner_element_coercion(self):+ """list[str] with int inner elements → coerced to strings."""+ data: dict[str, Any] = {"name": "test", "count": 1, "items": [1, 2, 3]}+ coerce_inputs_to_schema(data, SampleSchema)+ assert data["items"] == ["1", "2", "3"]++ def test_dict_value_coercion(self):+ """dict[str, int] with string values → coerced to ints."""+ data: dict[str, Any] = {+ "name": "test",+ "count": 1,+ "items": [],+ "config": {"x": "10", "y": "20"},+ }+ coerce_inputs_to_schema(data, SampleSchema)+ assert data["config"] == {"x": 10, "y": 20}++ def test_nested_list_from_json_string(self):+ data: dict[str, Any] = {+ "rows": '[["Name","Score"],["Alice","90"]]',+ }+ coerce_inputs_to_schema(data, NestedSchema)+ assert data["rows"] == [["Name", "Score"], ["Alice", "90"]]++ def test_nested_list_already_correct(self):+ original = [["a", "b"], ["c", "d"]]+ data: dict[str, Any] = {"rows": original}+ coerce_inputs_to_schema(data, NestedSchema)+ assert data["rows"] == original++ def test_union_preserves_valid_list(self):+ """list[str] value should NOT be stringified for str | list[str]."""+ data: dict[str, Any] = {"content": ["a", "b"]}+ coerce_inputs_to_schema(data, UnionSchema)+ assert data["content"] == ["a", "b"]+ assert isinstance(data["content"], list)++ def test_union_preserves_valid_string(self):+ data: dict[str, Any] = {"content": "hello"}+ coerce_inputs_to_schema(data, UnionSchema)+ assert data["content"] == "hello"++ def test_union_list_with_wrong_inner_gets_coerced(self):+ """[1, 2] for str | list[str] — inner ints don't match list[str],+ so convert() is called. convert tries str first → stringifies."""+ data: dict[str, Any] = {"content": [1, 2]}+ coerce_inputs_to_schema(data, UnionSchema)+ # convert([1,2], str | list[str]) tries str first → "[1, 2]"+ # This is convert()'s union behavior — str wins over list[str]+ assert isinstance(data["content"], (str, list))++ def test_skips_none_values(self):+ data: dict[str, Any] = {"label": None, "value": "5"}+ coerce_inputs_to_schema(data, OptionalSchema)+ assert data["label"] is None+ assert data["value"] == 5++ def test_skips_missing_fields(self):+ data: dict[str, Any] = {"value": "10"}+ coerce_inputs_to_schema(data, OptionalSchema)+ assert "label" not in data+ assert data["value"] == 10++ def test_any_field_skipped(self):+ """Fields typed as Any should pass through without coercion."""+ data: dict[str, Any] = {"data": [1, "mixed", {"nested": True}]}+ coerce_inputs_to_schema(data, AnyFieldSchema)+ assert data["data"] == [1, "mixed", {"nested": True}]++ def test_preserves_all_convert_capabilities(self):+ """Verify coerce_inputs_to_schema doesn't lose any convert() capability+ that existed before the _value_satisfies_type gate was added."""++ class FullSchema(BaseModel):+ as_int: int+ as_float: float+ as_bool: bool+ as_str: str+ as_list: list[int]+ as_dict: dict[str, str]++ data: dict[str, Any] = {+ "as_int": "42",+ "as_float": "3.14",+ "as_bool": "True",+ "as_str": 123,+ "as_list": "[1,2,3]",+ "as_dict": '{"a": "b"}',+ }+ coerce_inputs_to_schema(data, FullSchema)+ assert data["as_int"] == 42+ assert data["as_float"] == 3.14+ assert data["as_bool"] is True+ assert data["as_str"] == "123"+ assert data["as_list"] == [1, 2, 3]+ assert data["as_dict"] == {"a": "b"}++ def test_inherited_fields_are_coerced(self):+ """model_fields includes inherited fields; __annotations__ does not.+ This verifies that fields from a parent schema are still coerced."""++ class ParentSchema(BaseModel):+ base_count: int++ class ChildSchema(ParentSchema):+ name: str++ # base_count is inherited — __annotations__ wouldn't include it+ assert "base_count" not in ChildSchema.__annotations__+ assert "base_count" in ChildSchema.model_fields++ data: dict[str, Any] = {"base_count": "42", "name": "test"}+ coerce_inputs_to_schema(data, ChildSchema)+ assert data["base_count"] == 42+ assert isinstance(data["base_count"], int)++ def test_nested_pydantic_model_field(self):+ """dict input for a Pydantic model-typed field passes through.+ convert() doesn't construct Pydantic models — Pydantic validation+ handles that downstream. This test documents the behavior."""++ class InnerModel(BaseModel):+ x: int++ class OuterModel(BaseModel):+ inner: InnerModel++ data: dict[str, Any] = {"inner": {"x": 1}}+ coerce_inputs_to_schema(data, OuterModel)+ # dict stays as dict — convert() doesn't construct Pydantic models+ assert data["inner"] == {"x": 1}+ assert isinstance(data["inner"], dict)++ def test_literal_field_passes_through(self):+ """Literal-typed fields should not crash coercion."""++ class LiteralSchema(BaseModel):+ status: Literal["active", "inactive"]++ data: dict[str, Any] = {"status": "active"}+ coerce_inputs_to_schema(data, LiteralSchema)+ assert data["status"] == "active"++ def test_list_of_pydantic_model_field(self):+ """list[dict] for list[PydanticModel] passes through unchanged."""++ class ItemModel(BaseModel):+ name: str++ class ContainerModel(BaseModel):+ items: list[ItemModel]++ data: dict[str, Any] = {"items": [{"name": "a"}, {"name": "b"}]}+ coerce_inputs_to_schema(data, ContainerModel)+ # Dicts stay as dicts — Pydantic validation handles construction+ assert data["items"] == [{"name": "a"}, {"name": "b"}]+ assert isinstance(data["items"][0], dict)