-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvalidation.py
More file actions
56 lines (44 loc) · 1.72 KB
/
Copy pathvalidation.py
File metadata and controls
56 lines (44 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
"""Runtime validation for TypedDict shapes at untrusted-data boundaries."""
from typing import Any, cast
from models.errors import SessionValidationError
from models.session import SessionDict
_ROOT_PATH = "(root)"
def _require_field(
container: dict[str, Any],
key: str,
expected_type: type[Any],
type_label: str,
*,
path: str | None = None,
) -> Any:
field_path = path or key
if key not in container:
raise SessionValidationError(field_path, "missing required field")
return _require_value(field_path, container[key], expected_type, type_label)
def _require_value(
path: str,
val: Any,
expected_type: type[Any],
type_label: str,
) -> Any:
if val is None:
raise SessionValidationError(path, "must not be null")
if not isinstance(val, expected_type):
raise SessionValidationError(
path, f"expected {type_label}, got {type(val).__name__}"
)
return val
def validate_session_dict(data: dict[str, Any]) -> SessionDict:
"""Validate a plain dict matches SessionDict before returning it."""
# Runtime guard for dynamic callers; mypy already types the parameter as dict.
if not isinstance(data, dict):
raise SessionValidationError(_ROOT_PATH, "expected dict")
_require_field(data, "session_id", str, "str")
_require_field(data, "title", str, "str")
messages = _require_field(data, "messages", list, "list")
_require_field(data, "metadata", dict, "dict")
for index, message in enumerate(messages):
path = f"messages[{index}]"
msg_dict = _require_value(path, message, dict, "dict")
_require_field(msg_dict, "role", str, "str", path=f"{path}.role")
return cast(SessionDict, data)