contiai / apps /api /app /core /models.py
aliabozahra315's picture
Claude Opus 5.5
Deploy: three rounds of the 2026-10 bag review and the cost work
8cf6d7a
Raw History Blame Contribute Delete
4.35 kB
"""Rebuild a Pydantic model with some constraints dropped.
Two places need the same awkward operation: take a model tree and produce a twin
of it that keeps every field, type, default and description but loses a chosen
subset of the validation constraints. Doing it by hand means a second copy of
the models that drifts the first time somebody adds a field, so it is derived.
The callers differ only in which constraints they drop:
* :mod:`app.services.blueprint.relax` drops the production quotas, so a
blueprint a designer supplies is not judged by how much an agent was told to
generate;
* :mod:`app.agents.schema_compat` drops what model providers refuse to accept
in a structured-output schema.
"""
from __future__ import annotations
from collections.abc import Callable
from types import UnionType
from typing import Annotated, Any, Union, get_args, get_origin
from pydantic import BaseModel, Field, create_model
_COLLECTIONS = (list, tuple, set, frozenset)
# Given one constraint and whether its field is a collection, return True to
# keep it.
KeepRule = Callable[[Any, bool], bool]
def is_collection(annotation: Any) -> bool:
"""True for list/tuple/set fields, including inside Optional."""
origin = get_origin(annotation)
if origin in _COLLECTIONS:
return True
if origin is Union:
return any(is_collection(arg) for arg in get_args(annotation))
return False
def _rewrite(
annotation: Any, keep: KeepRule, prefix: str, cache: dict, base: Any = None
) -> Any:
"""Point a type expression at the rebuilt versions of its nested models."""
if isinstance(annotation, type) and issubclass(annotation, BaseModel):
return rebuild_model(annotation, keep, prefix=prefix, cache=cache, base=base)
origin = get_origin(annotation)
if origin is None:
return annotation
args = tuple(_rewrite(arg, keep, prefix, cache, base) for arg in get_args(annotation))
if not args:
return annotation
# Union - and so Optional - cannot be rebuilt by subscripting its origin.
# Written this way rather than as `X | Y` because the members are a runtime
# tuple, which the operator form cannot take.
# `X | None` arrives with `types.UnionType` as its origin - a model built
# with `create_model` from another model's field annotations carries it -
# and that origin cannot be subscripted either.
if origin is Union or origin is UnionType:
return Union[args] # noqa: UP007
return origin[args if len(args) > 1 else args[0]]
def rebuild_model(
model: type[BaseModel],
keep: KeepRule,
*,
prefix: str,
cache: dict[type, type] | None = None,
base: type[BaseModel] | None = None,
) -> type[BaseModel]:
"""A copy of ``model`` holding only the constraints ``keep`` approves.
``cache`` keeps one twin per source model, so a shape reached down two paths
does not become two classes that reject each other's values. Pass the same
dict when rebuilding related models together.
``base`` is given to every model in the tree, not just the root - a hook that
shapes JSON Schema has to reach the nested definitions too, since that is
where most of a schema's keywords live.
"""
cache = {} if cache is None else cache
if model in cache:
return cache[model]
fields: dict[str, tuple[Any, Any]] = {}
for name, info in model.model_fields.items():
annotation = _rewrite(info.annotation, keep, prefix, cache, base)
collection = is_collection(info.annotation)
kept = [c for c in info.metadata if keep(c, collection)]
if kept:
annotation = Annotated[tuple([annotation, *kept])]
if info.is_required():
spec = Field(..., description=info.description)
elif info.default_factory is not None:
spec = Field(default_factory=info.default_factory, description=info.description)
else:
spec = Field(info.default, description=info.description)
fields[name] = (annotation, spec)
rebuilt = create_model( # type: ignore[call-overload]
f"{prefix}{model.__name__}", __base__=base, **fields
) if base is not None else create_model(f"{prefix}{model.__name__}", **fields)
rebuilt.__doc__ = model.__doc__
cache[model] = rebuilt
return rebuilt