github-actions[bot]
Deploy to Hugging Face Space
ba5fffb
Raw History Blame Contribute Delete
2.17 kB
from __future__ import annotations
import json
import re
from typing import TypeVar
from pydantic import BaseModel, ValidationError
T = TypeVar("T", bound=BaseModel)
_FENCE_RE = re.compile(r"^\s*```(?:json)?\s*(.*?)\s*```\s*$", re.DOTALL)
class OutputContractValidationError(ValueError):
def __init__(self, issues: list[dict[str, str]], technical_message: str):
super().__init__("The agent output did not match the required contract.")
self.issues = issues
self.technical_message = technical_message
def _field_path(location: tuple[str | int, ...]) -> str:
path = ""
for part in location:
if isinstance(part, int):
path += f"[{part}]"
else:
path += f".{part}" if path else part
return path
def extract_json_text(text: str) -> str:
match = _FENCE_RE.match(text)
return match.group(1).strip() if match else text.strip()
def parse_json_object(text: str) -> dict:
payload = extract_json_text(text)
decoder = json.JSONDecoder()
try:
obj, end = decoder.raw_decode(payload)
except json.JSONDecodeError as exc:
raise ValueError(f"Invalid JSON: {exc.msg}") from exc
if payload[end:].strip():
raise ValueError("Invalid JSON: multiple JSON values or trailing content")
if not isinstance(obj, dict):
raise ValueError("Invalid JSON: expected a JSON object")
return obj
def parse_and_validate(text: str, schema: type[T]) -> T:
obj = parse_json_object(text)
try:
return schema.model_validate(obj)
except ValidationError as exc:
issues = [
{
"field": _field_path(error["loc"]),
"problem": (
"Required field is missing."
if error["type"] == "missing"
else error["msg"].rstrip(".") + "."
),
}
for error in exc.errors(include_url=False, include_context=False, include_input=False)
]
raise OutputContractValidationError(
issues=issues,
technical_message=f"Output contract validation failed: {exc}",
) from exc