-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathvalidation_helpers.py
More file actions
executable file
·58 lines (45 loc) · 1.66 KB
/
validation_helpers.py
File metadata and controls
executable file
·58 lines (45 loc) · 1.66 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
57
58
"""Helpers for non-fatal validation warnings and validation error formatting."""
from __future__ import annotations
import logging
from typing import Callable
from validation_models import ValidationError
ValidationWarnFn = Callable[[str], None]
def build_validation_warning_handler(
*,
enabled: bool,
logger: logging.Logger | None = None,
) -> ValidationWarnFn:
"""Return a warning emitter for non-fatal validation issues."""
target_logger = logger or logging.getLogger(__name__)
def warn(message: str) -> None:
if enabled:
target_logger.warning("Validation warning: %s", message)
return warn
def warn_from_validation_error(
context: str,
exc: ValidationError,
warn: ValidationWarnFn | None,
) -> None:
"""Emit one warning line per structured validation error."""
if warn is None:
return
for error in exc.errors():
location = ".".join(str(part) for part in error.get("loc", ()))
message = error.get("msg", "invalid value")
if location:
warn(f"{context}: {location}: {message}")
else:
warn(f"{context}: {message}")
def format_validation_error(context: str, exc: ValidationError) -> str:
"""Return a user-facing one-line validation summary for fatal tool input errors."""
parts = []
for error in exc.errors():
location = ".".join(str(part) for part in error.get("loc", ()))
message = error.get("msg", "invalid value")
if location:
parts.append(f"{location}: {message}")
else:
parts.append(message)
if not parts:
return context
return f"{context}: " + "; ".join(parts)