Spaces:
Running
Running
File size: 5,087 Bytes
fd5dd94 | 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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 | """Build a Pydantic input model from a (resolved, ``$ref``-free) JSON Schema object.
Tenant tools (OpenAPI operations, MCP tools, connectors) are stored as JSON Schema; the
gateway needs a Pydantic model to validate arguments. The same function runs at import and
every time a tool is loaded, so the stored schema is the single source of truth.
Deliberately conservative: unknown constructs (``anyOf``, ``oneOf``, ...) become ``Any``;
nesting deeper than ``MAX_DEPTH`` becomes ``dict[str, Any]``; extra arguments are rejected.
"""
from __future__ import annotations
import keyword
import re
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field, create_model
MAX_DEPTH = 3
MAX_PROPERTIES = 100
_IDENT = re.compile(r"[^0-9a-zA-Z_]+")
class SchemaError(ValueError):
pass
def field_name(raw: str) -> str:
"""A safe Python identifier for a JSON property name (the original stays the alias)."""
name = _IDENT.sub("_", raw).strip("_") or "field"
if name[0].isdigit():
name = f"f_{name}"
if keyword.iskeyword(name) or name.startswith("model_"):
name = f"{name}_"
return name
def _type_names(schema: dict[str, Any]) -> tuple[list[str], bool]:
t = schema.get("type")
types = [t] if isinstance(t, str) else list(t) if isinstance(t, list) else []
nullable = bool(schema.get("nullable")) or "null" in types
return [x for x in types if x != "null"], nullable
def _annotation(schema: dict[str, Any], name: str, depth: int) -> Any:
if not isinstance(schema, dict):
return Any
enum = schema.get("enum")
if isinstance(enum, list) and enum and all(isinstance(v, str | int | bool) for v in enum):
return Literal[tuple(enum)]
types, _ = _type_names(schema)
if len(types) != 1:
return Any
t = types[0]
if t == "string":
return str
if t == "integer":
return int
if t == "number":
return float
if t == "boolean":
return bool
if t == "array":
return list[_annotation(schema.get("items") or {}, f"{name}_item", depth + 1)] # type: ignore[misc]
if t == "object":
props = schema.get("properties")
if isinstance(props, dict) and props and depth < MAX_DEPTH:
return model_from_schema(schema, f"{name}_obj", depth=depth + 1)
return dict[str, Any]
return Any
def _constraints(schema: dict[str, Any]) -> dict[str, Any]:
out: dict[str, Any] = {}
for src, dst in (
("minLength", "min_length"),
("maxLength", "max_length"),
("minimum", "ge"),
("maximum", "le"),
("minItems", "min_length"),
("maxItems", "max_length"),
):
v = schema.get(src)
if isinstance(v, int | float) and not isinstance(v, bool):
out[dst] = v
return out
def model_from_schema(
schema: dict[str, Any], model_name: str, *, depth: int = 0
) -> type[BaseModel]:
"""``schema`` is an object schema with ``properties`` / ``required``."""
if not isinstance(schema, dict):
raise SchemaError("schema must be an object")
props = schema.get("properties") or {}
if not isinstance(props, dict):
raise SchemaError("properties must be an object")
if len(props) > MAX_PROPERTIES:
raise SchemaError(f"too many properties ({len(props)} > {MAX_PROPERTIES})")
required = set(schema.get("required") or [])
fields: dict[str, Any] = {}
used: set[str] = set()
for raw, sub in props.items():
sub = sub if isinstance(sub, dict) else {}
name = field_name(str(raw))
while name in used:
name = f"{name}_"
used.add(name)
ann = _annotation(sub, f"{model_name}_{name}", depth)
_, nullable = _type_names(sub)
kwargs: dict[str, Any] = _constraints(sub)
if name != raw:
kwargs["alias"] = str(raw)
desc = sub.get("description")
if isinstance(desc, str) and desc:
kwargs["description"] = desc[:300]
if raw in required:
default: Any = ...
else:
ann = ann | None
default = sub.get("default") if "default" in sub else None
if nullable and raw in required:
ann = ann | None
fields[name] = (ann, Field(default, **kwargs))
safe = _IDENT.sub("_", model_name)[:80] or "Input"
return create_model(
safe,
__config__=ConfigDict(extra="forbid", populate_by_name=True),
**fields,
)
def property_fields(schema: dict[str, Any]) -> dict[str, str]:
"""JSON property name -> Python field name, in the same order ``model_from_schema`` uses."""
out: dict[str, str] = {}
used: set[str] = set()
for raw in (schema.get("properties") or {}).keys():
name = field_name(str(raw))
while name in used:
name = f"{name}_"
used.add(name)
out[str(raw)] = name
return out
|