Validates a single state key-value pair against a Pydantic schema. Raises StateSchemaError if the key is not in the schema or the value does not match the field's type annotation. Prefixed keys (any key containing ``:``) bypass validation.
(
schema: type[BaseModel],
key: str,
value: Any,
)
| 26 | |
| 27 | |
| 28 | def _validate_state_entry( |
| 29 | schema: type[BaseModel], |
| 30 | key: str, |
| 31 | value: Any, |
| 32 | ) -> None: |
| 33 | """Validates a single state key-value pair against a Pydantic schema. |
| 34 | |
| 35 | Raises StateSchemaError if the key is not in the schema or the value |
| 36 | does not match the field's type annotation. Prefixed keys (any key |
| 37 | containing ``:``) bypass validation. |
| 38 | """ |
| 39 | if ":" in key: |
| 40 | return |
| 41 | |
| 42 | fields = schema.model_fields |
| 43 | if key not in fields: |
| 44 | raise StateSchemaError( |
| 45 | f"Key '{key}' is not declared in state schema " |
| 46 | f"'{schema.__name__}'. Declared fields: {sorted(fields.keys())}" |
| 47 | ) |
| 48 | |
| 49 | from pydantic import TypeAdapter |
| 50 | from pydantic import ValidationError as PydanticValidationError |
| 51 | |
| 52 | try: |
| 53 | TypeAdapter(fields[key].annotation).validate_python(value) |
| 54 | except PydanticValidationError as e: |
| 55 | raise StateSchemaError( |
| 56 | f"Value for '{key}' does not match type " |
| 57 | f"'{fields[key].annotation}' in '{schema.__name__}': {e}" |
| 58 | ) from e |
| 59 | |
| 60 | |
| 61 | class State: |
no test coverage detected