mlflow/mlflow · error

Items in `{key}` must be either an instance of `{cls.__name_

Error message

Items in `{key}` must be either an instance of `{cls.__name__}` or a dict matching the schema. Received `{type(v).__name__}`

What it means

_convert_dataclass_map requires every map value to be either an instance of the target dataclass or a dict that can be coerced. Values of any other type (str, int, list, bool, None) trigger this ValueError, which reports the offending value's type name.

Source

Thrown at mlflow/types/llm.py:113

            if required:
                raise ValueError(f"`{key}` is required")
            return

        if not isinstance(mapping, dict):
            raise ValueError(f"`{key}` must be a dict")

        # create a new map to avoid mutating the original
        new_mapping = {}
        for k, v in mapping.items():
            if isinstance(v, cls):
                new_mapping[k] = v
            elif isinstance(v, dict):
                try:
                    new_mapping[k] = cls.from_dict(v)
                except TypeError as e:
                    raise ValueError(f"Error when coercing {v} to {cls.__name__}: {e}")
            else:
                raise ValueError(
                    f"Items in `{key}` must be either an instance of `{cls.__name__}` "
                    f"or a dict matching the schema. Received `{type(v).__name__}`"
                )
        setattr(self, key, new_mapping)

    def to_dict(self):
        return asdict(self, dict_factory=lambda obj: {k: v for (k, v) in obj if v is not None})

    @classmethod
    def from_dict(cls, data):
        """
        Create an instance of the class from a dict, ignoring any undefined fields.
        This is useful when the dict contains extra fields, causing cls(**data) to fail.
        """
        field_names = [field.name for field in fields(cls)]
        filtered_data = {k: v for k, v in data.items() if k in field_names}
        return cls(**filtered_data)

View on GitHub (pinned to 6a27f2decc)

Solutions

  1. Wrap shorthand values in the full object form: {'city': {'type': 'string'}}.
  2. Convert non-dict values to the target dataclass or dict before construction.
  3. Validate the map contents with a loop asserting isinstance(v, (dict, TargetClass)) before calling the API.

Example fix

// before
{"city": "string"}
// after
{"city": {"type": "string"}}
Defensive patterns

Strategy: type-guard

Validate before calling

for k, v in props.items():
    if not isinstance(v, (dict, ParamProperty)):
        raise TypeError(f"property '{k}' must be a dict or ParamProperty, got {type(v).__name__}")

Type guard

def is_property_map(props):
    return isinstance(props, dict) and all(isinstance(v, (dict, ParamProperty)) for v in props.values())

Try / catch

try:
    obj = MyType(properties=props)
except ValueError as e:
    if "must be either an instance" in str(e):
        props = {k: {"type": v} if isinstance(v, str) else v for k, v in props.items()}
        obj = MyType(properties=props)
    else:
        raise

Prevention

When it happens

Trigger: Schema maps like {'city': 'string'} (string where a dict/ParamProperty was required), or {'count': 1}, or values that are JSON arrays instead of objects.

Common situations: Writing shorthand type definitions ('city': 'string') as in some frameworks, mistaking a map-of-objects field for a map-of-strings field, or truncating nested JSON during templating.

Related errors


AI-assisted analysis of mlflow/mlflow@6a27f2decc (2026-08-29). Data as JSON: /api/errors/8c04cac79ca9eefd. Report an issue: GitHub.