Skip to content

schemez

Class info

Re-exported classes

Class Module Description
ConfigSchema schemez.schema Schema for configuration objects that may declare required packages.
ExecutableFunction schemez.functionschema.executable Wrapper for executing functions with different calling patterns.
FunctionSchema schemez.functionschema.functionschema Schema representing an OpenAI function definition and metadata.
ImportedSchemaDef schemez.schemadef.schemadef Response definition that imports an existing Pydantic model.
InlineSchemaDef schemez.schemadef.schemadef Inline definition of schema.
JSONCode schemez.code JSON with syntax validation.
ModelStore schemez.storage.model_store Type-safe async SQLite storage for Pydantic models.
OpenAIFunctionDefinition schemez.functionschema.typedefs Schema for the function definition part of an OpenAI tool.
OpenAIFunctionTool schemez.functionschema.typedefs Complete OpenAI tool definition for function calling.
PythonCode schemez.code Python with syntax validation.
Schema schemez.schema Base class for configuration models.
SchemaField schemez.schemadef.schemadef Field definition for inline response types.
TOMLCode schemez.code TOML with syntax validation.
ToolCodeGenerator schemez.code_generation.tool_code_generator Generates code artifacts for a single tool.
ToolsetCodeGenerator schemez.code_generation.toolset_code_generator Generates code artifacts for multiple tools.
YAMLCode schemez.code YAML with syntax validation.

🛈 DocStrings

Schemez: main package.

Pydantic shim for config stuff.

ConfigSchema

Bases: Schema

Schema for configuration objects that may declare required packages.

Source code in src/schemez/schema.py
class ConfigSchema(Schema):
    """Schema for configuration objects that may declare required packages."""

    @classmethod
    def required_python_packages(cls) -> list[str]:
        """Return the Python packages this config needs. Override in subclasses."""
        return []

required_python_packages classmethod

required_python_packages() -> list[str]

Return the Python packages this config needs. Override in subclasses.

Source code in src/schemez/schema.py
@classmethod
def required_python_packages(cls) -> list[str]:
    """Return the Python packages this config needs. Override in subclasses."""
    return []

ExecutableFunction

Wrapper for executing functions with different calling patterns.

Source code in src/schemez/functionschema/executable.py
class ExecutableFunction[T_co]:
    """Wrapper for executing functions with different calling patterns."""

    def __init__(
        self,
        schema: FunctionSchema,
        func: (
            Callable[..., T_co]
            | Callable[..., Generator[T_co]]
            | Callable[..., AsyncGenerator[T_co]]
            | Callable[..., AsyncIterator[T_co]]
        ),
    ) -> None:
        """Initialize with schema and function.

        Args:
            schema: OpenAI function schema
            func: The actual function to execute
        """
        from schemez.functionschema import determine_function_type

        self.schema = schema
        self.func = func
        self.function_type: FunctionType = determine_function_type(self.func)

    def run(self, *args: Any, **kwargs: Any) -> T_co | list[T_co]:
        """Run the function synchronously.

        Args:
            *args: Positional arguments to pass to the function
            **kwargs: Keyword arguments to pass to the function

        Returns:
            Either a single result or list of results for generators

        Inside a running event loop, coroutines run on a worker thread's own loop
        (blocking the caller); use `arun` from async code.
        """
        func: Callable[..., Any] = self.func
        match self.function_type:
            case "sync":
                return func(*args, **kwargs)
            case "async":
                return _run_coroutine(lambda: func(*args, **kwargs))
            case "sync_generator":
                return list(func(*args, **kwargs))
            case "async_generator":
                return _run_coroutine(lambda: self._collect_async_gen(*args, **kwargs))
            case _ as unreachable:
                assert_never(unreachable)

    async def _collect_async_gen(self, *args: Any, **kwargs: Any) -> list[T_co]:
        """Collect async generator results into a list.

        Args:
            *args: Positional arguments to pass to the function
            **kwargs: Keyword arguments to pass to the function

        Returns:
            List of collected results
        """
        func: Callable[..., Any] = self.func
        return [x async for x in func(*args, **kwargs)]

    async def arun(self, *args: Any, **kwargs: Any) -> T_co | list[T_co]:
        """Run the function asynchronously.

        Args:
            *args: Positional arguments to pass to the function
            **kwargs: Keyword arguments to pass to the function

        Returns:
            Function result or list of results for generators

        Raises:
            ValueError: If the function type is unknown
        """
        func: Callable[..., Any] = self.func
        match self.function_type:
            case "sync":
                return func(*args, **kwargs)
            case "async":
                return await func(*args, **kwargs)
            case "sync_generator":
                return list(func(*args, **kwargs))
            case "async_generator":
                return [x async for x in func(*args, **kwargs)]
            case _:
                msg = f"Unknown function type: {self.function_type}"
                raise ValueError(msg)

    async def astream(self, *args: Any, **kwargs: Any) -> AsyncIterator[T_co]:
        """Stream results from the function.

        Args:
            *args: Positional arguments to pass to the function
            **kwargs: Keyword arguments to pass to the function

        Yields:
            Individual results as they become available

        Raises:
            ValueError: If the function type is unknown
        """
        func: Callable[..., Any] = self.func
        match self.function_type:
            case "sync_generator":
                for x in func(*args, **kwargs):
                    yield x
            case "async_generator":
                async for x in func(*args, **kwargs):
                    yield x
            case "sync":
                yield func(*args, **kwargs)
            case "async":
                yield await func(*args, **kwargs)
            case _ as unreachable:
                assert_never(unreachable)

__init__

__init__(
    schema: FunctionSchema,
    func: (
        Callable[..., T_co]
        | Callable[..., Generator[T_co]]
        | Callable[..., AsyncGenerator[T_co]]
        | Callable[..., AsyncIterator[T_co]]
    ),
) -> None

Initialize with schema and function.

Parameters:

Name Type Description Default
schema FunctionSchema

OpenAI function schema

required
func Callable[..., T_co] | Callable[..., Generator[T_co]] | Callable[..., AsyncGenerator[T_co]] | Callable[..., AsyncIterator[T_co]]

The actual function to execute

required
Source code in src/schemez/functionschema/executable.py
def __init__(
    self,
    schema: FunctionSchema,
    func: (
        Callable[..., T_co]
        | Callable[..., Generator[T_co]]
        | Callable[..., AsyncGenerator[T_co]]
        | Callable[..., AsyncIterator[T_co]]
    ),
) -> None:
    """Initialize with schema and function.

    Args:
        schema: OpenAI function schema
        func: The actual function to execute
    """
    from schemez.functionschema import determine_function_type

    self.schema = schema
    self.func = func
    self.function_type: FunctionType = determine_function_type(self.func)

arun async

arun(*args: Any, **kwargs: Any) -> T_co | list[T_co]

Run the function asynchronously.

Parameters:

Name Type Description Default
*args Any

Positional arguments to pass to the function

()
**kwargs Any

Keyword arguments to pass to the function

{}

Returns:

Type Description
T_co | list[T_co]

Function result or list of results for generators

Raises:

Type Description
ValueError

If the function type is unknown

Source code in src/schemez/functionschema/executable.py
async def arun(self, *args: Any, **kwargs: Any) -> T_co | list[T_co]:
    """Run the function asynchronously.

    Args:
        *args: Positional arguments to pass to the function
        **kwargs: Keyword arguments to pass to the function

    Returns:
        Function result or list of results for generators

    Raises:
        ValueError: If the function type is unknown
    """
    func: Callable[..., Any] = self.func
    match self.function_type:
        case "sync":
            return func(*args, **kwargs)
        case "async":
            return await func(*args, **kwargs)
        case "sync_generator":
            return list(func(*args, **kwargs))
        case "async_generator":
            return [x async for x in func(*args, **kwargs)]
        case _:
            msg = f"Unknown function type: {self.function_type}"
            raise ValueError(msg)

astream async

astream(*args: Any, **kwargs: Any) -> AsyncIterator[T_co]

Stream results from the function.

Parameters:

Name Type Description Default
*args Any

Positional arguments to pass to the function

()
**kwargs Any

Keyword arguments to pass to the function

{}

Yields:

Type Description
AsyncIterator[T_co]

Individual results as they become available

Raises:

Type Description
ValueError

If the function type is unknown

Source code in src/schemez/functionschema/executable.py
async def astream(self, *args: Any, **kwargs: Any) -> AsyncIterator[T_co]:
    """Stream results from the function.

    Args:
        *args: Positional arguments to pass to the function
        **kwargs: Keyword arguments to pass to the function

    Yields:
        Individual results as they become available

    Raises:
        ValueError: If the function type is unknown
    """
    func: Callable[..., Any] = self.func
    match self.function_type:
        case "sync_generator":
            for x in func(*args, **kwargs):
                yield x
        case "async_generator":
            async for x in func(*args, **kwargs):
                yield x
        case "sync":
            yield func(*args, **kwargs)
        case "async":
            yield await func(*args, **kwargs)
        case _ as unreachable:
            assert_never(unreachable)

run

run(*args: Any, **kwargs: Any) -> T_co | list[T_co]

Run the function synchronously.

Parameters:

Name Type Description Default
*args Any

Positional arguments to pass to the function

()
**kwargs Any

Keyword arguments to pass to the function

{}

Returns:

Type Description
T_co | list[T_co]

Either a single result or list of results for generators

Inside a running event loop, coroutines run on a worker thread's own loop (blocking the caller); use arun from async code.

Source code in src/schemez/functionschema/executable.py
def run(self, *args: Any, **kwargs: Any) -> T_co | list[T_co]:
    """Run the function synchronously.

    Args:
        *args: Positional arguments to pass to the function
        **kwargs: Keyword arguments to pass to the function

    Returns:
        Either a single result or list of results for generators

    Inside a running event loop, coroutines run on a worker thread's own loop
    (blocking the caller); use `arun` from async code.
    """
    func: Callable[..., Any] = self.func
    match self.function_type:
        case "sync":
            return func(*args, **kwargs)
        case "async":
            return _run_coroutine(lambda: func(*args, **kwargs))
        case "sync_generator":
            return list(func(*args, **kwargs))
        case "async_generator":
            return _run_coroutine(lambda: self._collect_async_gen(*args, **kwargs))
        case _ as unreachable:
            assert_never(unreachable)

FunctionSchema

Bases: BaseModel

Schema representing an OpenAI function definition and metadata.

This class encapsulates all the necessary information to describe a function to the OpenAI API, including its name, description, parameters, return type, and execution characteristics. It follows the OpenAI function calling format while adding additional metadata useful for Python function handling.

Source code in src/schemez/functionschema/functionschema.py
class FunctionSchema(pydantic.BaseModel):
    """Schema representing an OpenAI function definition and metadata.

    This class encapsulates all the necessary information to describe a function to the
    OpenAI API, including its name, description, parameters, return type, and execution
    characteristics. It follows the OpenAI function calling format while adding
    additional metadata useful for Python function handling.
    """

    name: str
    """The name of the function as it will be presented to the OpenAI API."""

    description: str | None = None
    """Optional description of what the function does."""

    parameters: ToolParameters = pydantic.Field(
        default_factory=lambda: ToolParameters(type="object", properties={}, required=[]),
    )
    """JSON Schema object describing the function's parameters."""

    required: list[str] = pydantic.Field(default_factory=list)
    """List of parameter names that are required (do not have default values)."""

    returns: dict[str, Any] = pydantic.Field(
        default_factory=lambda: {"type": "object"},
    )
    """JSON Schema object describing the function's return type."""

    model_config = pydantic.ConfigDict(frozen=True)

    def create_parameter_model(self) -> type[pydantic.BaseModel]:
        """Create a Pydantic model from the schema parameters."""
        fields: dict[str, Any] = {}
        properties = self.parameters.get("properties", {})
        required = self.parameters.get("required", self.required)

        for name, details in properties.items():
            if name.startswith("_"):  # TODO: kwarg for renaming instead perhaps?
                logger.debug("Skipping parameter %s due to leading underscore", name)
                continue
            param_type = _schema_to_python_type(details)

            # Handle optional types (if there's a default of None)
            default_value = details.get("default")
            if default_value is None and name not in required:
                param_type = param_type | None

            # Create a proper pydantic Field
            field = (
                param_type,
                pydantic.Field(default=... if name in required else default_value),
            )
            fields[name] = field

        return pydantic.create_model(f"{self.name}_params", **fields)

    def model_dump_openai(self) -> OpenAIFunctionTool:
        """Convert the schema to OpenAI's function calling format.

        Returns:
            A dictionary matching OpenAI's complete function tool definition format.
            {"type": "function", "function": {"name": ..., "description": ..., "parameters": ...}}
        """
        parameters: ToolParameters = {
            "type": "object",
            "properties": self.parameters["properties"],
            "required": self.required,
        }
        if "$defs" in self.parameters:
            parameters["$defs"] = self.parameters["$defs"]

        # First create the function definition
        function_def = OpenAIFunctionDefinition(
            name=self.name,
            description=self.description or "",
            parameters=parameters,
        )

        return OpenAIFunctionTool(type="function", function=function_def)

    def to_python_signature(self) -> inspect.Signature:
        """Convert the schema back to a Python function signature.

        This method creates a Python function signature from the OpenAI schema,
        mapping JSON schema types back to their Python equivalents.
        """
        model = self.create_parameter_model()
        param_type = TYPE_MAP.get(self.returns.get("type", "string"), Any)
        return pydantic_model_to_signature(model, param_type)

    def to_return_model_code(self, class_name: str | None = None) -> str:
        """Generate Pydantic model code for return type using datamodel-codegen.

        Args:
            class_name: Name for the generated class (default: {name}Response)

        Returns:
            Generated Python code string
        """
        name = class_name or f"{self.name.title()}Response"
        return json_schema_to_pydantic_code(
            self.returns,
            class_name=name,
            target_python_version="3.13",
        )

    def to_parameter_model_code(self, class_name: str | None = None) -> str:
        """Generate Pydantic model code for parameters using datamodel-codegen.

        Args:
            class_name: Name for the generated class (default: {name}Params)

        Returns:
            Generated Python code string
        """
        name = class_name or f"{self.name.title()}Params"
        return json_schema_to_pydantic_code(
            dict(self.parameters),
            class_name=name,
            target_python_version="3.13",
        )

    def get_annotations(self, return_type: Any = str) -> dict[str, type[Any]]:
        """Get a dictionary of parameter names to their Python types.

        This can be used directly for __annotations__ assignment.

        Returns:
            Dictionary mapping parameter names to their Python types.
        """
        model = self.create_parameter_model()
        annotations: dict[str, Any] = {}
        for name, field in model.model_fields.items():
            annotations[name] = field.annotation
        annotations["return"] = return_type
        return annotations

    @classmethod
    def from_dict(
        cls,
        schema: Mapping[str, Any],
        output_schema: dict[str, Any] | None = None,
    ) -> FunctionSchema:
        """Create a FunctionSchema from a raw schema dictionary.

        Args:
            schema: OpenAI function schema dictionary (also an ``OpenAIFunctionTool``
                or ``OpenAIFunctionDefinition``).
                Can be either a direct function definition or a tool wrapper.
            output_schema: Optional dictionary specifying the return type.
                If not provided, an object type will be set.

        Raises:
            ValueError: If schema format is invalid or missing required fields
        """
        # Handle tool wrapper format
        if "type" in schema and schema["type"] == "function":
            if "function" not in schema:
                msg = 'Tool with type "function" must have a "function" field'
                raise ValueError(msg)
            schema = schema["function"]
        elif "type" in schema and schema.get("type") != "function":
            msg = f"Unknown tool type: {schema.get('type')}"
            raise ValueError(msg)

        # Get function name
        name = schema.get("name", schema.get("function", {}).get("name"))
        if not name:
            msg = 'Schema must have a "name" field'
            raise ValueError(msg)

        # Extract parameters
        param_dict = schema.get("parameters", {"type": "object", "properties": {}})
        if not isinstance(param_dict, dict):
            msg = "Schema parameters must be a dictionary"
            raise ValueError(msg)  # noqa: TRY004

        # Clean up properties that have advanced JSON Schema features
        properties = param_dict.get("properties", {})
        cleaned_props: dict[str, Property] = {}
        for prop_name, prop in properties.items():
            cleaned_props[prop_name] = clean_property(prop)
        required = param_dict.get("required", [])
        if not isinstance(required, list):
            msg = "Schema required field must be a list"
            raise ValueError(msg)  # noqa: TRY004
        parameters: ToolParameters = {"type": "object", "properties": cleaned_props}
        if required:
            parameters["required"] = required
        return cls(
            name=name,
            description=schema.get("description"),
            parameters=parameters,
            required=required,
            returns=output_schema or {"type": "object"},
        )

description class-attribute instance-attribute

description: str | None = None

Optional description of what the function does.

name instance-attribute

name: str

The name of the function as it will be presented to the OpenAI API.

parameters class-attribute instance-attribute

parameters: ToolParameters = pydantic.Field(
    default_factory=lambda: ToolParameters(type="object", properties={}, required=[])
)

JSON Schema object describing the function's parameters.

required class-attribute instance-attribute

required: list[str] = pydantic.Field(default_factory=list)

List of parameter names that are required (do not have default values).

returns class-attribute instance-attribute

returns: dict[str, Any] = pydantic.Field(default_factory=lambda: {'type': 'object'})

JSON Schema object describing the function's return type.

create_parameter_model

create_parameter_model() -> type[BaseModel]

Create a Pydantic model from the schema parameters.

Source code in src/schemez/functionschema/functionschema.py
def create_parameter_model(self) -> type[pydantic.BaseModel]:
    """Create a Pydantic model from the schema parameters."""
    fields: dict[str, Any] = {}
    properties = self.parameters.get("properties", {})
    required = self.parameters.get("required", self.required)

    for name, details in properties.items():
        if name.startswith("_"):  # TODO: kwarg for renaming instead perhaps?
            logger.debug("Skipping parameter %s due to leading underscore", name)
            continue
        param_type = _schema_to_python_type(details)

        # Handle optional types (if there's a default of None)
        default_value = details.get("default")
        if default_value is None and name not in required:
            param_type = param_type | None

        # Create a proper pydantic Field
        field = (
            param_type,
            pydantic.Field(default=... if name in required else default_value),
        )
        fields[name] = field

    return pydantic.create_model(f"{self.name}_params", **fields)

from_dict classmethod

from_dict(schema: Mapping[str, Any], output_schema: dict[str, Any] | None = None) -> FunctionSchema

Create a FunctionSchema from a raw schema dictionary.

Parameters:

Name Type Description Default
schema Mapping[str, Any]

OpenAI function schema dictionary (also an OpenAIFunctionTool or OpenAIFunctionDefinition). Can be either a direct function definition or a tool wrapper.

required
output_schema dict[str, Any] | None

Optional dictionary specifying the return type. If not provided, an object type will be set.

None

Raises:

Type Description
ValueError

If schema format is invalid or missing required fields

Source code in src/schemez/functionschema/functionschema.py
@classmethod
def from_dict(
    cls,
    schema: Mapping[str, Any],
    output_schema: dict[str, Any] | None = None,
) -> FunctionSchema:
    """Create a FunctionSchema from a raw schema dictionary.

    Args:
        schema: OpenAI function schema dictionary (also an ``OpenAIFunctionTool``
            or ``OpenAIFunctionDefinition``).
            Can be either a direct function definition or a tool wrapper.
        output_schema: Optional dictionary specifying the return type.
            If not provided, an object type will be set.

    Raises:
        ValueError: If schema format is invalid or missing required fields
    """
    # Handle tool wrapper format
    if "type" in schema and schema["type"] == "function":
        if "function" not in schema:
            msg = 'Tool with type "function" must have a "function" field'
            raise ValueError(msg)
        schema = schema["function"]
    elif "type" in schema and schema.get("type") != "function":
        msg = f"Unknown tool type: {schema.get('type')}"
        raise ValueError(msg)

    # Get function name
    name = schema.get("name", schema.get("function", {}).get("name"))
    if not name:
        msg = 'Schema must have a "name" field'
        raise ValueError(msg)

    # Extract parameters
    param_dict = schema.get("parameters", {"type": "object", "properties": {}})
    if not isinstance(param_dict, dict):
        msg = "Schema parameters must be a dictionary"
        raise ValueError(msg)  # noqa: TRY004

    # Clean up properties that have advanced JSON Schema features
    properties = param_dict.get("properties", {})
    cleaned_props: dict[str, Property] = {}
    for prop_name, prop in properties.items():
        cleaned_props[prop_name] = clean_property(prop)
    required = param_dict.get("required", [])
    if not isinstance(required, list):
        msg = "Schema required field must be a list"
        raise ValueError(msg)  # noqa: TRY004
    parameters: ToolParameters = {"type": "object", "properties": cleaned_props}
    if required:
        parameters["required"] = required
    return cls(
        name=name,
        description=schema.get("description"),
        parameters=parameters,
        required=required,
        returns=output_schema or {"type": "object"},
    )

get_annotations

get_annotations(return_type: Any = str) -> dict[str, type[Any]]

Get a dictionary of parameter names to their Python types.

This can be used directly for annotations assignment.

Returns:

Type Description
dict[str, type[Any]]

Dictionary mapping parameter names to their Python types.

Source code in src/schemez/functionschema/functionschema.py
def get_annotations(self, return_type: Any = str) -> dict[str, type[Any]]:
    """Get a dictionary of parameter names to their Python types.

    This can be used directly for __annotations__ assignment.

    Returns:
        Dictionary mapping parameter names to their Python types.
    """
    model = self.create_parameter_model()
    annotations: dict[str, Any] = {}
    for name, field in model.model_fields.items():
        annotations[name] = field.annotation
    annotations["return"] = return_type
    return annotations

model_dump_openai

model_dump_openai() -> OpenAIFunctionTool

Convert the schema to OpenAI's function calling format.

Returns:

Type Description
OpenAIFunctionTool

A dictionary matching OpenAI's complete function tool definition format.

OpenAIFunctionTool

{"type": "function", "function": {"name": ..., "description": ..., "parameters": ...}}

Source code in src/schemez/functionschema/functionschema.py
def model_dump_openai(self) -> OpenAIFunctionTool:
    """Convert the schema to OpenAI's function calling format.

    Returns:
        A dictionary matching OpenAI's complete function tool definition format.
        {"type": "function", "function": {"name": ..., "description": ..., "parameters": ...}}
    """
    parameters: ToolParameters = {
        "type": "object",
        "properties": self.parameters["properties"],
        "required": self.required,
    }
    if "$defs" in self.parameters:
        parameters["$defs"] = self.parameters["$defs"]

    # First create the function definition
    function_def = OpenAIFunctionDefinition(
        name=self.name,
        description=self.description or "",
        parameters=parameters,
    )

    return OpenAIFunctionTool(type="function", function=function_def)

to_parameter_model_code

to_parameter_model_code(class_name: str | None = None) -> str

Generate Pydantic model code for parameters using datamodel-codegen.

Parameters:

Name Type Description Default
class_name str | None

Name for the generated class (default: {name}Params)

None

Returns:

Type Description
str

Generated Python code string

Source code in src/schemez/functionschema/functionschema.py
def to_parameter_model_code(self, class_name: str | None = None) -> str:
    """Generate Pydantic model code for parameters using datamodel-codegen.

    Args:
        class_name: Name for the generated class (default: {name}Params)

    Returns:
        Generated Python code string
    """
    name = class_name or f"{self.name.title()}Params"
    return json_schema_to_pydantic_code(
        dict(self.parameters),
        class_name=name,
        target_python_version="3.13",
    )

to_python_signature

to_python_signature() -> Signature

Convert the schema back to a Python function signature.

This method creates a Python function signature from the OpenAI schema, mapping JSON schema types back to their Python equivalents.

Source code in src/schemez/functionschema/functionschema.py
def to_python_signature(self) -> inspect.Signature:
    """Convert the schema back to a Python function signature.

    This method creates a Python function signature from the OpenAI schema,
    mapping JSON schema types back to their Python equivalents.
    """
    model = self.create_parameter_model()
    param_type = TYPE_MAP.get(self.returns.get("type", "string"), Any)
    return pydantic_model_to_signature(model, param_type)

to_return_model_code

to_return_model_code(class_name: str | None = None) -> str

Generate Pydantic model code for return type using datamodel-codegen.

Parameters:

Name Type Description Default
class_name str | None

Name for the generated class (default: {name}Response)

None

Returns:

Type Description
str

Generated Python code string

Source code in src/schemez/functionschema/functionschema.py
def to_return_model_code(self, class_name: str | None = None) -> str:
    """Generate Pydantic model code for return type using datamodel-codegen.

    Args:
        class_name: Name for the generated class (default: {name}Response)

    Returns:
        Generated Python code string
    """
    name = class_name or f"{self.name.title()}Response"
    return json_schema_to_pydantic_code(
        self.returns,
        class_name=name,
        target_python_version="3.13",
    )

ImportedSchemaDef

Bases: BaseSchemaDef

Response definition that imports an existing Pydantic model.

Allows using externally defined Pydantic models as response types. Benefits: - Reuse existing model definitions - Full Python type support - Complex validation logic - IDE support for imported types

Example

responses: AnalysisResult: type: import import_path: myapp.models.AnalysisResult

Source code in src/schemez/schemadef/schemadef.py
class ImportedSchemaDef(BaseSchemaDef):
    """Response definition that imports an existing Pydantic model.

    Allows using externally defined Pydantic models as response types.
    Benefits:
    - Reuse existing model definitions
    - Full Python type support
    - Complex validation logic
    - IDE support for imported types

    Example:
        responses:
          AnalysisResult:
            type: import
            import_path: myapp.models.AnalysisResult
    """

    type: Literal["import"] = Field("import", init=False)
    """Import-path based response definition."""

    import_path: str = Field(
        title="Import path",
        examples=[
            "myapp.models.User",
            "schemas.api:ResponseModel",
            "models.core.BaseResponse",
        ],
    )
    """The path to the pydantic model to use as the response type."""

    # mypy is confused about "type"
    # TODO: convert BaseModel to Schema?
    def get_schema(self) -> type[BaseModel]:
        """Import and return the model class."""
        try:
            model_class = helpers.import_class(self.import_path)
            if not issubclass(model_class, BaseModel):
                msg = f"{self.import_path} must be a Pydantic model"
                raise TypeError(msg)  # noqa: TRY301
        except Exception as e:
            msg = f"Failed to import response type {self.import_path}"
            raise ValueError(msg) from e
        else:
            return model_class

import_path class-attribute instance-attribute

import_path: str = Field(
    title="Import path",
    examples=["myapp.models.User", "schemas.api:ResponseModel", "models.core.BaseResponse"],
)

The path to the pydantic model to use as the response type.

type class-attribute instance-attribute

type: Literal['import'] = Field('import', init=False)

Import-path based response definition.

get_schema

get_schema() -> type[BaseModel]

Import and return the model class.

Source code in src/schemez/schemadef/schemadef.py
def get_schema(self) -> type[BaseModel]:
    """Import and return the model class."""
    try:
        model_class = helpers.import_class(self.import_path)
        if not issubclass(model_class, BaseModel):
            msg = f"{self.import_path} must be a Pydantic model"
            raise TypeError(msg)  # noqa: TRY301
    except Exception as e:
        msg = f"Failed to import response type {self.import_path}"
        raise ValueError(msg) from e
    else:
        return model_class

InlineSchemaDef

Bases: BaseSchemaDef

Inline definition of schema.

Allows defining response types directly in the configuration using: - Field definitions with types and descriptions - Optional validation constraints - Custom field descriptions - Field dependencies and relationships

Example

type: inline fields: success: {type: bool, description: "Operation success"} message: {type: str, description: "Result details"} payment_method: {type: str, description: "Payment method used"} card_number: { type: str, description: "Credit card number", dependent_required: { "payment_method": ["card_expiry", "card_cvc"] } }

Source code in src/schemez/schemadef/schemadef.py
class InlineSchemaDef(BaseSchemaDef):
    """Inline definition of schema.

    Allows defining response types directly in the configuration using:
    - Field definitions with types and descriptions
    - Optional validation constraints
    - Custom field descriptions
    - Field dependencies and relationships

    Example:
        type: inline
        fields:
            success: {type: bool, description: "Operation success"}
            message: {type: str, description: "Result details"}
            payment_method: {type: str, description: "Payment method used"}
            card_number: {
                type: str,
                description: "Credit card number",
                dependent_required: {
                "payment_method": ["card_expiry", "card_cvc"]
                }
            }
    """

    type: Literal["inline"] = Field("inline", init=False)
    """Inline response definition."""

    fields: dict[str, SchemaField] = Field(
        title="Schema fields",
        examples=[
            {
                "name": {"type": "str", "description": "User name"},
                "age": {"type": "int", "description": "User age", "ge": 0},
            }
        ],
    )
    """A dictionary containing all fields."""

    def add_field_dependency(
        self, field_name: str, dependent_on: str, required_fields: list[str]
    ) -> None:
        """Add a dependency between fields.

        Args:
            field_name: The field where to add the dependency
            dependent_on: The field that triggers the dependency
            required_fields: Fields that become required when the dependency is triggered
        """
        if field_name not in self.fields:
            msg = f"Field '{field_name}' not found in schema"
            raise ValueError(msg)

        field = self.fields[field_name]
        field.add_required_dependency(dependent_on, required_fields)

    def add_schema_dependency(
        self, field_name: str, dependent_on: str, schema: dict[str, Any]
    ) -> None:
        """Add a schema dependency between fields.

        Args:
            field_name: The field where to add the dependency
            dependent_on: The field that triggers the dependency
            schema: JSON Schema to apply when dependent_on exists
        """
        if field_name not in self.fields:
            msg = f"Field '{field_name}' not found in schema"
            raise ValueError(msg)

        field = self.fields[field_name]
        field.add_schema_dependency(dependent_on, schema)

    def get_schema(self) -> type[BaseModel]:
        """Create Pydantic model from inline definition."""
        fields: dict[str, Any] = {}
        model_dependencies: dict[str, dict[str, Any]] = {}

        # First pass: collect all field information
        for name, field in self.fields.items():
            # Initialize constraint dictionary
            field_constraints: dict[str, Any] = {}

            # Handle enum type
            if field.type == "enum":
                if not field.values:
                    msg = f"Field {name!r} has type 'enum' but no values defined"
                    raise ValueError(msg)

                enum_name = f"{name.capitalize()}Enum"  # Create dynamic Enum class
                enum_members = {}  # Create enum members dictionary
                for i, value in enumerate(field.values):
                    # If value is valid Python identifier use as is, otherwise create synthetic name
                    key = value if isinstance(value, str) and value.isidentifier() else f"VALUE_{i}"
                    enum_members[key] = value

                enum_class = Enum(enum_name, enum_members)
                python_type: Any = enum_class

                if field.default is not None:  # Handle enum default value specially
                    # Store default value as the enum value string
                    # Pydantic v2 will convert it to the enum instance
                    if field.default in list(field.values):
                        field_constraints["default"] = field.default
                    else:
                        msg = (
                            f"Default value {field.default!r} not found "
                            f"in enum values for field {name!r}"
                        )
                        raise ValueError(msg)
            else:
                python_type = helpers.resolve_type_string(field.type)
                if not python_type:
                    msg = f"Unsupported field type: {field.type}"
                    raise ValueError(msg)

            if field.literal_value is not None:  # Handle literal constraint if provided
                python_type = Literal[field.literal_value]

            if field.optional:  # Handle optional fields (allowing None)
                python_type = python_type | None

            # Add standard Pydantic constraints. Collect all constraint values
            for constraint in [
                "default",
                "title",
                "min_length",
                "max_length",
                "pattern",
                "min_length",
                "max_length",
                "gt",
                "ge",
                "lt",
                "le",
                "multiple_of",
            ]:
                value = getattr(field, constraint, None)
                if value is not None:
                    field_constraints[constraint] = value

            if field.examples:
                if field.json_schema_extra is None:
                    field.json_schema_extra = {}
                field.json_schema_extra["examples"] = field.examples

            if field.json_schema_extra:
                field_constraints["json_schema_extra"] = field.json_schema_extra

            if field.dependent_required or field.dependent_schema:
                if field.json_schema_extra is None:
                    field_constraints["json_schema_extra"] = {}

                json_extra = field_constraints.get("json_schema_extra", {})
                if field.dependent_required:
                    if "dependentRequired" not in json_extra:
                        json_extra["dependentRequired"] = {}
                    json_extra["dependentRequired"].update(field.dependent_required)

                if field.dependent_schema:
                    if "dependentSchemas" not in json_extra:
                        json_extra["dependentSchemas"] = {}
                    json_extra["dependentSchemas"].update(field.dependent_schema)

                field_constraints["json_schema_extra"] = json_extra

            field_constraints.update(field.constraints)  # Add any additional constraints
            field_info = Field(description=field.description, **field_constraints)
            fields[name] = (python_type, field_info)

            # Collect model-level dependencies for JSON Schema
            if field.dependent_required or field.dependent_schema:
                if not model_dependencies:
                    model_dependencies = {"json_schema_extra": {}}
                extra = model_dependencies["json_schema_extra"]
                if field.dependent_required:
                    if "dependentRequired" not in extra:
                        extra["dependentRequired"] = {}
                    extra["dependentRequired"].update(field.dependent_required)
                if field.dependent_schema:
                    if "dependentSchemas" not in extra:
                        extra["dependentSchemas"] = {}
                    extra["dependentSchemas"].update(field.dependent_schema)

        model = create_model(  # Create the model class
            self.description or "ResponseType",
            **fields,
            __base__=BaseModel,
            __doc__=self.description,
        )

        # Add model-level JSON Schema extras for dependencies
        if model_dependencies:
            existing_extra = model.model_config.get("json_schema_extra")
            deps_extra = model_dependencies["json_schema_extra"]

            match existing_extra:
                case None:
                    model.model_config["json_schema_extra"] = deps_extra
                case dict() as schema_extra:
                    schema_extra.update(deps_extra)
                case Callable() as callable_func:

                    def wrapped_extra(*args: Any) -> None:
                        callable_func(*args)
                        schema = args[0]
                        schema.update(deps_extra)

                    model.model_config["json_schema_extra"] = wrapped_extra

        # Return the created model
        return model

fields class-attribute instance-attribute

fields: dict[str, SchemaField] = Field(
    title="Schema fields",
    examples=[
        {
            "name": {"type": "str", "description": "User name"},
            "age": {"type": "int", "description": "User age", "ge": 0},
        }
    ],
)

A dictionary containing all fields.

type class-attribute instance-attribute

type: Literal['inline'] = Field('inline', init=False)

Inline response definition.

add_field_dependency

add_field_dependency(field_name: str, dependent_on: str, required_fields: list[str]) -> None

Add a dependency between fields.

Parameters:

Name Type Description Default
field_name str

The field where to add the dependency

required
dependent_on str

The field that triggers the dependency

required
required_fields list[str]

Fields that become required when the dependency is triggered

required
Source code in src/schemez/schemadef/schemadef.py
def add_field_dependency(
    self, field_name: str, dependent_on: str, required_fields: list[str]
) -> None:
    """Add a dependency between fields.

    Args:
        field_name: The field where to add the dependency
        dependent_on: The field that triggers the dependency
        required_fields: Fields that become required when the dependency is triggered
    """
    if field_name not in self.fields:
        msg = f"Field '{field_name}' not found in schema"
        raise ValueError(msg)

    field = self.fields[field_name]
    field.add_required_dependency(dependent_on, required_fields)

add_schema_dependency

add_schema_dependency(field_name: str, dependent_on: str, schema: dict[str, Any]) -> None

Add a schema dependency between fields.

Parameters:

Name Type Description Default
field_name str

The field where to add the dependency

required
dependent_on str

The field that triggers the dependency

required
schema dict[str, Any]

JSON Schema to apply when dependent_on exists

required
Source code in src/schemez/schemadef/schemadef.py
def add_schema_dependency(
    self, field_name: str, dependent_on: str, schema: dict[str, Any]
) -> None:
    """Add a schema dependency between fields.

    Args:
        field_name: The field where to add the dependency
        dependent_on: The field that triggers the dependency
        schema: JSON Schema to apply when dependent_on exists
    """
    if field_name not in self.fields:
        msg = f"Field '{field_name}' not found in schema"
        raise ValueError(msg)

    field = self.fields[field_name]
    field.add_schema_dependency(dependent_on, schema)

get_schema

get_schema() -> type[BaseModel]

Create Pydantic model from inline definition.

Source code in src/schemez/schemadef/schemadef.py
def get_schema(self) -> type[BaseModel]:
    """Create Pydantic model from inline definition."""
    fields: dict[str, Any] = {}
    model_dependencies: dict[str, dict[str, Any]] = {}

    # First pass: collect all field information
    for name, field in self.fields.items():
        # Initialize constraint dictionary
        field_constraints: dict[str, Any] = {}

        # Handle enum type
        if field.type == "enum":
            if not field.values:
                msg = f"Field {name!r} has type 'enum' but no values defined"
                raise ValueError(msg)

            enum_name = f"{name.capitalize()}Enum"  # Create dynamic Enum class
            enum_members = {}  # Create enum members dictionary
            for i, value in enumerate(field.values):
                # If value is valid Python identifier use as is, otherwise create synthetic name
                key = value if isinstance(value, str) and value.isidentifier() else f"VALUE_{i}"
                enum_members[key] = value

            enum_class = Enum(enum_name, enum_members)
            python_type: Any = enum_class

            if field.default is not None:  # Handle enum default value specially
                # Store default value as the enum value string
                # Pydantic v2 will convert it to the enum instance
                if field.default in list(field.values):
                    field_constraints["default"] = field.default
                else:
                    msg = (
                        f"Default value {field.default!r} not found "
                        f"in enum values for field {name!r}"
                    )
                    raise ValueError(msg)
        else:
            python_type = helpers.resolve_type_string(field.type)
            if not python_type:
                msg = f"Unsupported field type: {field.type}"
                raise ValueError(msg)

        if field.literal_value is not None:  # Handle literal constraint if provided
            python_type = Literal[field.literal_value]

        if field.optional:  # Handle optional fields (allowing None)
            python_type = python_type | None

        # Add standard Pydantic constraints. Collect all constraint values
        for constraint in [
            "default",
            "title",
            "min_length",
            "max_length",
            "pattern",
            "min_length",
            "max_length",
            "gt",
            "ge",
            "lt",
            "le",
            "multiple_of",
        ]:
            value = getattr(field, constraint, None)
            if value is not None:
                field_constraints[constraint] = value

        if field.examples:
            if field.json_schema_extra is None:
                field.json_schema_extra = {}
            field.json_schema_extra["examples"] = field.examples

        if field.json_schema_extra:
            field_constraints["json_schema_extra"] = field.json_schema_extra

        if field.dependent_required or field.dependent_schema:
            if field.json_schema_extra is None:
                field_constraints["json_schema_extra"] = {}

            json_extra = field_constraints.get("json_schema_extra", {})
            if field.dependent_required:
                if "dependentRequired" not in json_extra:
                    json_extra["dependentRequired"] = {}
                json_extra["dependentRequired"].update(field.dependent_required)

            if field.dependent_schema:
                if "dependentSchemas" not in json_extra:
                    json_extra["dependentSchemas"] = {}
                json_extra["dependentSchemas"].update(field.dependent_schema)

            field_constraints["json_schema_extra"] = json_extra

        field_constraints.update(field.constraints)  # Add any additional constraints
        field_info = Field(description=field.description, **field_constraints)
        fields[name] = (python_type, field_info)

        # Collect model-level dependencies for JSON Schema
        if field.dependent_required or field.dependent_schema:
            if not model_dependencies:
                model_dependencies = {"json_schema_extra": {}}
            extra = model_dependencies["json_schema_extra"]
            if field.dependent_required:
                if "dependentRequired" not in extra:
                    extra["dependentRequired"] = {}
                extra["dependentRequired"].update(field.dependent_required)
            if field.dependent_schema:
                if "dependentSchemas" not in extra:
                    extra["dependentSchemas"] = {}
                extra["dependentSchemas"].update(field.dependent_schema)

    model = create_model(  # Create the model class
        self.description or "ResponseType",
        **fields,
        __base__=BaseModel,
        __doc__=self.description,
    )

    # Add model-level JSON Schema extras for dependencies
    if model_dependencies:
        existing_extra = model.model_config.get("json_schema_extra")
        deps_extra = model_dependencies["json_schema_extra"]

        match existing_extra:
            case None:
                model.model_config["json_schema_extra"] = deps_extra
            case dict() as schema_extra:
                schema_extra.update(deps_extra)
            case Callable() as callable_func:

                def wrapped_extra(*args: Any) -> None:
                    callable_func(*args)
                    schema = args[0]
                    schema.update(deps_extra)

                model.model_config["json_schema_extra"] = wrapped_extra

    # Return the created model
    return model

JSONCode

Bases: BaseCode

JSON with syntax validation.

Source code in src/schemez/code.py
class JSONCode(BaseCode):
    """JSON with syntax validation."""

    @field_validator("code")
    @classmethod
    def validate_syntax(cls, code: str) -> str:
        import yamling

        try:
            yamling.load(code, mode="json")
        except yamling.ParsingError as e:
            msg = f"Invalid JSON syntax: {e}"
            raise ValueError(msg) from e
        else:
            return code

ModelStore

Type-safe async SQLite storage for Pydantic models.

Can be initialized with a model type, or opened from an existing database that has the schema stored.

Example
class User(BaseModel):
    name: str
    age: int
    email: str | None = None

# Create new database with known type
async with ModelStore(User, "users.db") as store:
    user_id = await store.insert(User(name="Alice", age=30))
    user = await store.get(user_id)
    all_users = await store.all()

# Open existing database, reconstruct type from stored schema
async with await ModelStore.open("users.db") as store:
    users = await store.all()  # Returns reconstructed model instances
Source code in src/schemez/storage/model_store.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
class ModelStore[T: BaseModel]:
    """Type-safe async SQLite storage for Pydantic models.

    Can be initialized with a model type, or opened from an existing database
    that has the schema stored.

    Example:
        ```python
        class User(BaseModel):
            name: str
            age: int
            email: str | None = None

        # Create new database with known type
        async with ModelStore(User, "users.db") as store:
            user_id = await store.insert(User(name="Alice", age=30))
            user = await store.get(user_id)
            all_users = await store.all()

        # Open existing database, reconstruct type from stored schema
        async with await ModelStore.open("users.db") as store:
            users = await store.all()  # Returns reconstructed model instances
        ```
    """

    def __init__(
        self,
        model_type: type[T] | None = None,
        path: str | Path = ":memory:",
        table_name: str | None = None,
    ) -> None:
        """Initialize the model store.

        Args:
            model_type: The Pydantic model class to store (required for new DBs)
            path: SQLite database path (":memory:" for in-memory)
            table_name: Custom table name (defaults to lowercase model name)

        Raises:
            ValueError: If model_type is None and path doesn't exist or is :memory:
        """
        self._path = str(path)
        self._connection: aiosqlite.Connection | None = None
        self._model_type: type[T] | None = model_type
        self._table_name = table_name
        self._columns: list[tuple[str, str, bool, Any]] | None = None
        self._import_path: str | None = None

        # Validate: can't create new DB without model_type
        if model_type is None:
            if self._path == ":memory:":
                msg = "model_type is required for in-memory databases"
                raise ValueError(msg)
            if not Path(self._path).exists():
                msg = f"model_type is required when database doesn't exist: {self._path}"
                raise ValueError(msg)
        else:
            self._table_name = table_name or model_type.__name__.lower()
            self._columns = self._build_column_definitions()
            module = model_type.__module__
            if module != "__main__":
                self._import_path = f"{module}.{model_type.__name__}"

    @classmethod
    async def open(cls, path: str | Path) -> ModelStore[BaseModel]:
        """Open an existing database and reconstruct the model from stored schema.

        Args:
            path: Path to existing SQLite database

        Returns:
            ModelStore with reconstructed model type

        Raises:
            FileNotFoundError: If database doesn't exist
            ValueError: If database has no stored schema
        """
        path = Path(path)
        if not path.exists():
            msg = f"Database not found: {path}"
            raise FileNotFoundError(msg)

        return cls(model_type=None, path=path)  # ty: ignore[invalid-explicit-return]

    @property
    def model_type(self) -> type[T]:
        """The model class (original or reconstructed)."""
        if self._model_type is None:
            msg = "Model type not yet available. Use async context manager first."
            raise RuntimeError(msg)
        return self._model_type

    @property
    def json_schema(self) -> dict[str, Any]:
        """Get the JSON schema for the stored model."""
        return self.model_type.model_json_schema()

    @property
    def import_path(self) -> str | None:
        """Get the import path for the stored model, if available."""
        return self._import_path

    def _build_column_definitions(self) -> list[tuple[str, str, bool, Any]]:
        """Build column definitions from model fields.

        Returns:
            List of (name, sqlite_type, is_nullable, annotation) tuples
        """
        if self._model_type is None:
            msg = "Cannot build columns without model_type"
            raise RuntimeError(msg)

        columns: list[tuple[str, str, bool, Any]] = []
        for name, field_info in self._model_type.model_fields.items():
            annotation = field_info.annotation
            sqlite_type, is_nullable = _get_sqlite_type(annotation)
            # Fields with a default may still default to None
            if not field_info.is_required() and field_info.default is None:
                is_nullable = True
            columns.append((name, sqlite_type, is_nullable, annotation))
        return columns

    def _create_table_sql(self) -> str:
        """Generate CREATE TABLE SQL statement."""
        if self._columns is None:
            msg = "Columns not initialized"
            raise RuntimeError(msg)

        column_defs = ["id INTEGER PRIMARY KEY AUTOINCREMENT"]
        for name, sqlite_type, is_nullable, _ in self._columns:
            null_clause = "" if is_nullable else " NOT NULL"
            column_defs.append(f"{_quote(name)} {sqlite_type}{null_clause}")
        columns_sql = ", ".join(column_defs)
        return f"CREATE TABLE IF NOT EXISTS {self._quoted_table} ({columns_sql})"

    def _create_meta_table_sql(self) -> str:
        """Generate CREATE TABLE SQL for metadata."""
        return f"""
            CREATE TABLE IF NOT EXISTS {META_TABLE} (
                key TEXT PRIMARY KEY,
                value TEXT NOT NULL
            )
        """

    async def _store_schema(self, conn: aiosqlite.Connection) -> None:
        """Store the model's JSON schema in the metadata table."""
        if self._model_type is None:
            return

        schema = self._model_type.model_json_schema()
        model_name = self._model_type.__name__
        module = self._model_type.__module__
        import_path = f"{module}.{model_name}" if module != "__main__" else None

        await conn.execute(
            f"INSERT OR REPLACE INTO {META_TABLE} (key, value) VALUES (?, ?)",
            ("schema", json.dumps(schema)),
        )
        await conn.execute(
            f"INSERT OR REPLACE INTO {META_TABLE} (key, value) VALUES (?, ?)",
            ("model_name", model_name),
        )
        await conn.execute(
            f"INSERT OR REPLACE INTO {META_TABLE} (key, value) VALUES (?, ?)",
            ("table_name", self._table_name),
        )
        if import_path:
            await conn.execute(
                f"INSERT OR REPLACE INTO {META_TABLE} (key, value) VALUES (?, ?)",
                ("import_path", import_path),
            )

    async def _load_schema(self, conn: aiosqlite.Connection) -> None:
        """Load and reconstruct model from stored schema."""
        from schemez.schema_to_type import json_schema_to_pydantic_class

        # Check if meta table exists
        cursor = await conn.execute(
            "SELECT name FROM sqlite_master WHERE type='table' AND name=?",
            (META_TABLE,),
        )
        if await cursor.fetchone() is None:
            msg = "Database has no metadata table. Cannot reconstruct model."
            raise ValueError(msg)

        # Load schema and model name
        cursor = await conn.execute(
            f"SELECT key, value FROM {META_TABLE} WHERE key IN (?, ?, ?, ?)",
            ("schema", "model_name", "table_name", "import_path"),
        )
        rows = await cursor.fetchall()
        meta = {row[0]: row[1] for row in rows}

        if "schema" not in meta:
            msg = "No schema found in database metadata"
            raise ValueError(msg)

        schema = json.loads(meta["schema"])
        model_name = meta.get("model_name", "DynamicModel")
        self._table_name = meta.get("table_name", model_name.lower())
        self._import_path = meta.get("import_path")

        # Reconstruct the model class
        self._model_type = json_schema_to_pydantic_class(schema, class_name=model_name)  # ty: ignore[invalid-assignment]
        self._columns = self._build_column_definitions()

    async def __aenter__(self) -> Self:
        """Open connection and create/load table."""
        import aiosqlite

        conn = await aiosqlite.connect(self._path)
        conn.row_factory = aiosqlite.Row
        try:
            if self._model_type is None:
                # Opening existing DB - reconstruct model from schema
                await self._load_schema(conn)
            else:
                # Creating new or opening with known type
                await conn.execute(self._create_meta_table_sql())
                await conn.execute(self._create_table_sql())
                await self._store_schema(conn)
                await conn.commit()
        except BaseException:
            # __aexit__ won't run; an open connection's worker thread blocks exit
            await conn.close()
            raise
        self._connection = conn
        return self

    async def __aexit__(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: object,
    ) -> None:
        """Close connection."""
        if self._connection:
            await self._connection.close()
            self._connection = None

    @property
    def _quoted_table(self) -> str:
        if self._table_name is None:
            msg = "Table name not initialized"
            raise RuntimeError(msg)
        return _quote(self._table_name)

    def _ensure_connected(self) -> aiosqlite.Connection:
        """Ensure we have an active connection."""
        if self._connection is None:
            msg = "ModelStore must be used as async context manager"
            raise RuntimeError(msg)
        return self._connection

    def _instance_to_row(self, instance: T) -> dict[str, Any]:
        """Convert model instance to row dict with serialized values."""
        if self._columns is None:
            msg = "Columns not initialized"
            raise RuntimeError(msg)

        row = {}
        for name, _, _, annotation in self._columns:
            value = getattr(instance, name)
            row[name] = _serialize_value(value, annotation)
        return row

    def _row_to_instance(self, row: aiosqlite.Row) -> T:
        """Convert database row to model instance."""
        if self._columns is None or self._model_type is None:
            msg = "Model not initialized"
            raise RuntimeError(msg)

        data = {}
        for name, _, _, annotation in self._columns:
            value = row[name]
            data[name] = _deserialize_value(value, annotation)
        return self._model_type.model_validate(data)

    async def insert(self, instance: T) -> int:
        """Insert a model instance.

        Args:
            instance: The model instance to insert

        Returns:
            The inserted row's id
        """
        conn = self._ensure_connected()
        row_id = await self._insert_row(conn, instance)
        await conn.commit()
        return row_id

    async def _insert_row(self, conn: aiosqlite.Connection, instance: T) -> int:
        row = self._instance_to_row(instance)
        columns = ", ".join(_quote(name) for name in row)
        placeholders = ", ".join("?" for _ in row)
        sql = f"INSERT INTO {self._quoted_table} ({columns}) VALUES ({placeholders})"
        cursor = await conn.execute(sql, list(row.values()))
        row_id = cursor.lastrowid
        assert row_id is not None  # always set after a successful INSERT
        return row_id

    async def insert_many(self, instances: Sequence[T]) -> list[int]:
        """Insert multiple model instances.

        Args:
            instances: The model instances to insert

        Returns:
            List of inserted row ids
        """
        conn = self._ensure_connected()
        try:  # one transaction for all rows
            ids = [await self._insert_row(conn, instance) for instance in instances]
        except BaseException:
            await conn.rollback()
            raise
        await conn.commit()
        return ids

    async def get(self, row_id: int) -> T | None:
        """Fetch a model instance by id.

        Args:
            row_id: The row id to fetch

        Returns:
            The model instance, or None if not found
        """
        conn = self._ensure_connected()
        sql = f"SELECT * FROM {self._quoted_table} WHERE id = ?"
        cursor = await conn.execute(sql, (row_id,))
        row = await cursor.fetchone()
        if row is None:
            return None
        return self._row_to_instance(row)

    async def all(self) -> list[T]:
        """Fetch all model instances.

        Returns:
            List of all model instances
        """
        conn = self._ensure_connected()
        sql = f"SELECT * FROM {self._quoted_table}"
        cursor = await conn.execute(sql)
        rows = await cursor.fetchall()
        return [self._row_to_instance(row) for row in rows]

    async def delete(self, row_id: int) -> bool:
        """Delete a model instance by id.

        Args:
            row_id: The row id to delete

        Returns:
            True if a row was deleted, False otherwise
        """
        conn = self._ensure_connected()
        sql = f"DELETE FROM {self._quoted_table} WHERE id = ?"
        cursor = await conn.execute(sql, (row_id,))
        await conn.commit()
        return cursor.rowcount > 0

    async def count(self) -> int:
        """Count total rows in the table.

        Returns:
            Number of rows
        """
        conn = self._ensure_connected()
        sql = f"SELECT COUNT(*) FROM {self._quoted_table}"
        cursor = await conn.execute(sql)
        row = await cursor.fetchone()
        return row[0] if row else 0

    async def query(self, **filters: Any) -> list[T]:
        """Query instances with simple equality filters.

        Args:
            **filters: Field-value pairs for WHERE clause (equality only)

        Returns:
            List of matching model instances

        Example:
            ```python
            users = await store.query(age=30, name="Alice")
            ```
        """
        conn = self._ensure_connected()

        if not filters:
            return await self.all()

        if self._columns is None:
            msg = "Columns not initialized"
            raise RuntimeError(msg)

        # Build WHERE clause
        conditions = []
        values = []
        annotations = {name: ann for name, _, _, ann in self._columns}

        for field, value in filters.items():
            if field not in annotations:
                msg = f"Unknown field: {field}"
                raise ValueError(msg)
            if value is None:
                conditions.append(f"{_quote(field)} IS NULL")
                continue
            conditions.append(f"{_quote(field)} = ?")
            values.append(_serialize_value(value, annotations[field]))

        where_clause = " AND ".join(conditions)
        sql = f"SELECT * FROM {self._quoted_table} WHERE {where_clause}"
        cursor = await conn.execute(sql, values)
        rows = await cursor.fetchall()
        return [self._row_to_instance(row) for row in rows]

import_path property

import_path: str | None

Get the import path for the stored model, if available.

json_schema property

json_schema: dict[str, Any]

Get the JSON schema for the stored model.

model_type property

model_type: type[T]

The model class (original or reconstructed).

__aenter__ async

__aenter__() -> Self

Open connection and create/load table.

Source code in src/schemez/storage/model_store.py
async def __aenter__(self) -> Self:
    """Open connection and create/load table."""
    import aiosqlite

    conn = await aiosqlite.connect(self._path)
    conn.row_factory = aiosqlite.Row
    try:
        if self._model_type is None:
            # Opening existing DB - reconstruct model from schema
            await self._load_schema(conn)
        else:
            # Creating new or opening with known type
            await conn.execute(self._create_meta_table_sql())
            await conn.execute(self._create_table_sql())
            await self._store_schema(conn)
            await conn.commit()
    except BaseException:
        # __aexit__ won't run; an open connection's worker thread blocks exit
        await conn.close()
        raise
    self._connection = conn
    return self

__aexit__ async

__aexit__(
    exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: object
) -> None

Close connection.

Source code in src/schemez/storage/model_store.py
async def __aexit__(
    self,
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: object,
) -> None:
    """Close connection."""
    if self._connection:
        await self._connection.close()
        self._connection = None

__init__

__init__(
    model_type: type[T] | None = None,
    path: str | Path = ":memory:",
    table_name: str | None = None,
) -> None

Initialize the model store.

Parameters:

Name Type Description Default
model_type type[T] | None

The Pydantic model class to store (required for new DBs)

None
path str | Path

SQLite database path (":memory:" for in-memory)

':memory:'
table_name str | None

Custom table name (defaults to lowercase model name)

None

Raises:

Type Description
ValueError

If model_type is None and path doesn't exist or is :memory:

Source code in src/schemez/storage/model_store.py
def __init__(
    self,
    model_type: type[T] | None = None,
    path: str | Path = ":memory:",
    table_name: str | None = None,
) -> None:
    """Initialize the model store.

    Args:
        model_type: The Pydantic model class to store (required for new DBs)
        path: SQLite database path (":memory:" for in-memory)
        table_name: Custom table name (defaults to lowercase model name)

    Raises:
        ValueError: If model_type is None and path doesn't exist or is :memory:
    """
    self._path = str(path)
    self._connection: aiosqlite.Connection | None = None
    self._model_type: type[T] | None = model_type
    self._table_name = table_name
    self._columns: list[tuple[str, str, bool, Any]] | None = None
    self._import_path: str | None = None

    # Validate: can't create new DB without model_type
    if model_type is None:
        if self._path == ":memory:":
            msg = "model_type is required for in-memory databases"
            raise ValueError(msg)
        if not Path(self._path).exists():
            msg = f"model_type is required when database doesn't exist: {self._path}"
            raise ValueError(msg)
    else:
        self._table_name = table_name or model_type.__name__.lower()
        self._columns = self._build_column_definitions()
        module = model_type.__module__
        if module != "__main__":
            self._import_path = f"{module}.{model_type.__name__}"

all async

all() -> list[T]

Fetch all model instances.

Returns:

Type Description
list[T]

List of all model instances

Source code in src/schemez/storage/model_store.py
async def all(self) -> list[T]:
    """Fetch all model instances.

    Returns:
        List of all model instances
    """
    conn = self._ensure_connected()
    sql = f"SELECT * FROM {self._quoted_table}"
    cursor = await conn.execute(sql)
    rows = await cursor.fetchall()
    return [self._row_to_instance(row) for row in rows]

count async

count() -> int

Count total rows in the table.

Returns:

Type Description
int

Number of rows

Source code in src/schemez/storage/model_store.py
async def count(self) -> int:
    """Count total rows in the table.

    Returns:
        Number of rows
    """
    conn = self._ensure_connected()
    sql = f"SELECT COUNT(*) FROM {self._quoted_table}"
    cursor = await conn.execute(sql)
    row = await cursor.fetchone()
    return row[0] if row else 0

delete async

delete(row_id: int) -> bool

Delete a model instance by id.

Parameters:

Name Type Description Default
row_id int

The row id to delete

required

Returns:

Type Description
bool

True if a row was deleted, False otherwise

Source code in src/schemez/storage/model_store.py
async def delete(self, row_id: int) -> bool:
    """Delete a model instance by id.

    Args:
        row_id: The row id to delete

    Returns:
        True if a row was deleted, False otherwise
    """
    conn = self._ensure_connected()
    sql = f"DELETE FROM {self._quoted_table} WHERE id = ?"
    cursor = await conn.execute(sql, (row_id,))
    await conn.commit()
    return cursor.rowcount > 0

get async

get(row_id: int) -> T | None

Fetch a model instance by id.

Parameters:

Name Type Description Default
row_id int

The row id to fetch

required

Returns:

Type Description
T | None

The model instance, or None if not found

Source code in src/schemez/storage/model_store.py
async def get(self, row_id: int) -> T | None:
    """Fetch a model instance by id.

    Args:
        row_id: The row id to fetch

    Returns:
        The model instance, or None if not found
    """
    conn = self._ensure_connected()
    sql = f"SELECT * FROM {self._quoted_table} WHERE id = ?"
    cursor = await conn.execute(sql, (row_id,))
    row = await cursor.fetchone()
    if row is None:
        return None
    return self._row_to_instance(row)

insert async

insert(instance: T) -> int

Insert a model instance.

Parameters:

Name Type Description Default
instance T

The model instance to insert

required

Returns:

Type Description
int

The inserted row's id

Source code in src/schemez/storage/model_store.py
async def insert(self, instance: T) -> int:
    """Insert a model instance.

    Args:
        instance: The model instance to insert

    Returns:
        The inserted row's id
    """
    conn = self._ensure_connected()
    row_id = await self._insert_row(conn, instance)
    await conn.commit()
    return row_id

insert_many async

insert_many(instances: Sequence[T]) -> list[int]

Insert multiple model instances.

Parameters:

Name Type Description Default
instances Sequence[T]

The model instances to insert

required

Returns:

Type Description
list[int]

List of inserted row ids

Source code in src/schemez/storage/model_store.py
async def insert_many(self, instances: Sequence[T]) -> list[int]:
    """Insert multiple model instances.

    Args:
        instances: The model instances to insert

    Returns:
        List of inserted row ids
    """
    conn = self._ensure_connected()
    try:  # one transaction for all rows
        ids = [await self._insert_row(conn, instance) for instance in instances]
    except BaseException:
        await conn.rollback()
        raise
    await conn.commit()
    return ids

open async classmethod

open(path: str | Path) -> ModelStore[BaseModel]

Open an existing database and reconstruct the model from stored schema.

Parameters:

Name Type Description Default
path str | Path

Path to existing SQLite database

required

Returns:

Type Description
ModelStore[BaseModel]

ModelStore with reconstructed model type

Raises:

Type Description
FileNotFoundError

If database doesn't exist

ValueError

If database has no stored schema

Source code in src/schemez/storage/model_store.py
@classmethod
async def open(cls, path: str | Path) -> ModelStore[BaseModel]:
    """Open an existing database and reconstruct the model from stored schema.

    Args:
        path: Path to existing SQLite database

    Returns:
        ModelStore with reconstructed model type

    Raises:
        FileNotFoundError: If database doesn't exist
        ValueError: If database has no stored schema
    """
    path = Path(path)
    if not path.exists():
        msg = f"Database not found: {path}"
        raise FileNotFoundError(msg)

    return cls(model_type=None, path=path)  # ty: ignore[invalid-explicit-return]

query async

query(**filters: Any) -> list[T]

Query instances with simple equality filters.

Parameters:

Name Type Description Default
**filters Any

Field-value pairs for WHERE clause (equality only)

{}

Returns:

Type Description
list[T]

List of matching model instances

Example
users = await store.query(age=30, name="Alice")
Source code in src/schemez/storage/model_store.py
async def query(self, **filters: Any) -> list[T]:
    """Query instances with simple equality filters.

    Args:
        **filters: Field-value pairs for WHERE clause (equality only)

    Returns:
        List of matching model instances

    Example:
        ```python
        users = await store.query(age=30, name="Alice")
        ```
    """
    conn = self._ensure_connected()

    if not filters:
        return await self.all()

    if self._columns is None:
        msg = "Columns not initialized"
        raise RuntimeError(msg)

    # Build WHERE clause
    conditions = []
    values = []
    annotations = {name: ann for name, _, _, ann in self._columns}

    for field, value in filters.items():
        if field not in annotations:
            msg = f"Unknown field: {field}"
            raise ValueError(msg)
        if value is None:
            conditions.append(f"{_quote(field)} IS NULL")
            continue
        conditions.append(f"{_quote(field)} = ?")
        values.append(_serialize_value(value, annotations[field]))

    where_clause = " AND ".join(conditions)
    sql = f"SELECT * FROM {self._quoted_table} WHERE {where_clause}"
    cursor = await conn.execute(sql, values)
    rows = await cursor.fetchall()
    return [self._row_to_instance(row) for row in rows]

OpenAIFunctionDefinition

Bases: TypedDict

Schema for the function definition part of an OpenAI tool.

This represents the inner "function" object that contains the actual function metadata and parameters.

Source code in src/schemez/functionschema/typedefs.py
class OpenAIFunctionDefinition(TypedDict):
    """Schema for the function definition part of an OpenAI tool.

    This represents the inner "function" object that contains the actual
    function metadata and parameters.
    """

    name: str
    description: str
    parameters: ToolParameters

OpenAIFunctionTool

Bases: TypedDict

Complete OpenAI tool definition for function calling.

This represents the top-level tool object that wraps a function definition and identifies it as a function tool type.

Source code in src/schemez/functionschema/typedefs.py
class OpenAIFunctionTool(TypedDict):
    """Complete OpenAI tool definition for function calling.

    This represents the top-level tool object that wraps a function definition
    and identifies it as a function tool type.
    """

    type: Literal["function"]
    function: OpenAIFunctionDefinition

PythonCode

Bases: BaseCode

Python with syntax validation.

Source code in src/schemez/code.py
class PythonCode(BaseCode):
    """Python with syntax validation."""

    @field_validator("code")
    @classmethod
    def validate_syntax(cls, code: str) -> str:
        try:
            ast.parse(code)
        except SyntaxError as e:
            msg = f"Invalid Python syntax: {e}"
            raise ValueError(msg) from e
        else:
            return code

Schema

Bases: BaseModel

Base class for configuration models.

Provides: - Common Pydantic settings (extra="forbid", attribute docstrings as descriptions) - YAML loading and dumping (optionally with field descriptions as comments) - Markdown documentation, Python code and test data generation - Model creation from functions, class constructors and JSON Schema - Merging and sub-model iteration

Dumps (model_dump(), model_dump_json(), YAML) put the fields of the most derived class first, then those of its bases. Pydantic itself orders base fields first, so a wrap serializer reorders the keys of every dump, nested Schema instances included. That makes dumps about 3x slower than a plain BaseModel (around 1.8 µs instead of 0.6 µs for a three-field model). This is deliberate: the order is what users read in dumped configs; the key order per class is cached, the remaining cost is the Python-level serializer call.

Source code in src/schemez/schema.py
 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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
class Schema(BaseModel):
    """Base class for configuration models.

    Provides:
    - Common Pydantic settings (`extra="forbid"`, attribute docstrings as descriptions)
    - YAML loading and dumping (optionally with field descriptions as comments)
    - Markdown documentation, Python code and test data generation
    - Model creation from functions, class constructors and JSON Schema
    - Merging and sub-model iteration

    Dumps (`model_dump()`, `model_dump_json()`, YAML) put the fields of the most derived
    class first, then those of its bases. Pydantic itself orders base fields first, so a
    wrap serializer reorders the keys of every dump, nested `Schema` instances included.
    That makes dumps about 3x slower than a plain `BaseModel` (around 1.8 µs instead of
    0.6 µs for a three-field model). This is deliberate: the order is what users read in
    dumped configs; the key order per class is cached, the remaining cost is the Python-level
    serializer call.
    """

    model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)

    @model_serializer(mode="wrap")
    def _serialize_with_subclass_fields_first(self, serializer: Any, info: Any) -> dict[str, Any]:
        """Serialize with subclass fields appearing before base class fields.

        Only reorders: keys without a known rank (computed fields, extras) keep their
        place after the fields, and aliases rank like the field they belong to.
        """
        data = serializer(self)
        # A nested field holding a plain dict (model_construct) is passed in as `self`
        if not isinstance(data, dict) or not isinstance(self, BaseModel):
            return data
        rank = _key_rank(type(self))
        end = len(rank)
        return {k: data[k] for k in sorted(data, key=lambda k: rank.get(k, end))}

    def model_dump_markdown(
        self,
        *,
        template: str | None = None,
        header_level: int = 1,
        include_defaults: bool = True,
        include_examples: bool = True,
        include_constraints: bool = True,
        include_values: bool = True,
        display_mode: Literal["table", "python_code", "yaml"] = "table",
        exclude_none: bool = True,
        exclude_defaults_yaml: bool = False,
        exclude_unset: bool = False,
        indent: int = 2,
        header_style: Literal["default", "pymdownx"] = "default",
        serialization_mode: Literal["json", "python"] = "json",
    ) -> str:
        """Dump model instance to Markdown documentation.

        Args:
            template: Custom Jinja2 template string (uses default if None)
            header_level: Starting header level (1 = h1, 2 = h2, etc.)
            include_defaults: Include default values in the table
            include_examples: Include examples section
            include_constraints: Include constraints section
            include_values: Include current instance values
            display_mode: Output format - "table", "python_code", or "yaml"
            exclude_none: Exclude None values from YAML
            exclude_defaults_yaml: Exclude default values from YAML
            exclude_unset: Exclude unset values from YAML
            indent: YAML indentation
            header_style: Code block header style - "default" or "pymdownx"
            serialization_mode: Pydantic serialization mode - "json" (default) or "python"

        Returns:
            Markdown string documenting the model
        """
        from schemez.markdown import instance_to_markdown

        return instance_to_markdown(
            self,
            template=template,
            header_level=header_level,
            include_defaults=include_defaults,
            include_examples=include_examples,
            include_constraints=include_constraints,
            include_values=include_values,
            display_mode=display_mode,
            exclude_none=exclude_none,
            exclude_defaults_yaml=exclude_defaults_yaml,
            exclude_unset=exclude_unset,
            indent=indent,
            header_style=header_style,
            serialization_mode=serialization_mode,
        )

    @classmethod
    def dump_markdown_schema(
        cls,
        *,
        template: str | None = None,
        header_level: int = 1,
        include_defaults: bool = True,
        include_examples: bool = True,
        include_constraints: bool = True,
        display_mode: Literal["table", "python_code", "yaml"] = "table",
        mode: Literal["minimal", "maximal", "default"] = "default",
        exclude_none: bool = True,
        exclude_defaults: bool = False,
        exclude_unset: bool = False,
        indent: int = 2,
        header_style: Literal["default", "pymdownx"] = "default",
        serialization_mode: Literal["json", "python"] = "json",
    ) -> str:
        """Dump model class schema to Markdown documentation.

        Args:
            template: Custom Jinja2 template string (uses default if None)
            header_level: Starting header level (1 = h1, 2 = h2, etc.)
            include_defaults: Include default values in the table
            include_examples: Include examples section
            include_constraints: Include constraints section
            display_mode: Output format - "table", "python_code", or "yaml"
            mode: Generation mode for YAML examples
            exclude_none: Exclude None values from YAML
            exclude_defaults: Exclude default values from YAML
            exclude_unset: Exclude unset values from YAML
            indent: YAML indentation
            header_style: Code block header style - "default" or "pymdownx"
            serialization_mode: Pydantic serialization mode - "json" (default) or "python"

        Returns:
            Markdown string documenting the model schema
        """
        from schemez.markdown import model_to_markdown

        return model_to_markdown(
            cls,
            template=template,
            header_level=header_level,
            include_defaults=include_defaults,
            include_examples=include_examples,
            include_constraints=include_constraints,
            display_mode=display_mode,
            mode=mode,
            exclude_none=exclude_none,
            exclude_defaults=exclude_defaults,
            exclude_unset=exclude_unset,
            indent=indent,
            header_style=header_style,
            serialization_mode=serialization_mode,
        )

    def merge(self, other: Self) -> Self:
        """Merge with another instance by overlaying its non-None values."""
        from schemez.helpers import merge_models

        return merge_models(self, other)

    def iter_submodels(self, *, recursive: bool = True) -> Iterator[tuple[str, BaseModel]]:
        """Iterate through all nested BaseModel instances in fields.

        Supports fields of type:
        - BaseModel (direct instance)
        - list[BaseModel]
        - dict[str, BaseModel]

        Args:
            recursive: If True, also iterate through submodels of submodels

        Yields:
            Tuples of (path, submodel) where path is like "field", "field[0]", "field['key']"
        """
        return _iter_submodels(self, recursive=recursive)

    @classmethod
    def iter_submodel_types(
        cls, *, recursive: bool = True, include_union_members: bool = True
    ) -> Iterator[tuple[str, type[BaseModel]]]:
        """Iterate through all nested BaseModel types in field annotations.

        Supports field types:
        - BaseModel (direct type)
        - list[BaseModel]
        - dict[str, BaseModel]
        - BaseModel | OtherModel (unions, when include_union_members=True)

        Args:
            recursive: If True, also iterate through submodel types of submodels
            include_union_members: If True, yield each union member separately

        Yields:
            Tuples of (path, model_type) where path is like "field", "field[]", "field{}"
        """
        return _iter_submodel_types(
            cls, recursive=recursive, include_union_members=include_union_members
        )

    @classmethod
    def from_yaml(cls, content: str, inherit_path: JoinablePathLike | None = None) -> Self:
        """Create from YAML string."""
        import yamling

        data = yamling.load_yaml(content, resolve_inherit=inherit_path or False)
        return cls.model_validate(data)

    @classmethod
    def for_function(cls, func: Callable[..., Any], *, name: str | None = None) -> type[Schema]:
        """Create a schema model from a function's signature.

        Args:
            func: The function to create a schema from
            name: Optional name for the model

        Returns:
            A new schema model class based on the function parameters
        """
        from schemez.convert import get_function_model

        return get_function_model(func, name=name)

    @classmethod
    def from_json_schema(cls, json_schema: dict[str, Any]) -> type[Schema]:
        """Create a schema model from a JSON schema.

        Args:
            json_schema: The JSON schema to create a schema from

        Returns:
            A new schema model class based on the JSON schema
        """
        from schemez.schema_to_type import json_schema_to_pydantic_class

        return json_schema_to_pydantic_class(
            json_schema, class_name="GeneratedSchema", base_class=cls
        )

    @classmethod
    async def from_llm(
        cls,
        *prompts: JoinablePathLike | str | UserContent,
        model: str = "google-gla:gemini-2.0-flash",
        system_prompt: str = DEFAULT_SYSTEM_PROMPT,
        user_prompt: str = DEFAULT_USER_PROMPT,
    ) -> Self:
        """Create a schema model from a text snippet using AI.

        Args:
            prompts: The text to create a schema from
            model: The AI model to use for schema extraction
            system_prompt: The system prompt to use for schema extraction
            user_prompt: The user prompt to use for schema extraction

        Returns:
            A new schema model class based on the document
        """
        from agentpool import Agent

        prompt = system_prompt.format(name=cls.__name__)
        agent = Agent(model=model, system_prompt=prompt, output_type=cls)
        chat_message = await agent.run(user_prompt, prompts)
        return chat_message.content

    @classmethod
    def for_class_ctor(cls, target_cls: type) -> type[Schema]:
        """Create a schema model from a class constructor.

        Args:
            target_cls: The class whose constructor to convert

        Returns:
            A new schema model class based on the constructor parameters
        """
        from schemez.convert import get_ctor_basemodel

        return get_ctor_basemodel(target_cls)

    def model_dump_yaml(
        self,
        exclude_none: bool = True,
        exclude_defaults: bool = False,
        exclude_unset: bool = False,
        indent: int = 2,
        default_flow_style: bool | None = None,
        allow_unicode: bool = True,
        comments: bool = False,
        sort_keys: bool = True,
        mode: Literal["json", "python"] = "python",
    ) -> str:
        """Dump configuration to YAML string.

        Args:
            exclude_none: Exclude fields with None values
            exclude_defaults: Exclude fields with default values
            exclude_unset: Exclude fields that are not set
            indent: Indentation level for YAML output
            default_flow_style: Default flow style for YAML output
            allow_unicode: Allow unicode characters in YAML output
            comments: Include descriptions as comments in the YAML output
            sort_keys: Sort keys in the YAML output
            mode: Output mode, either "json" or "python"

        Returns:
            YAML string representation of the model
        """
        import yamling

        from schemez.commented_yaml import process_yaml_lines

        data = self.model_dump(
            exclude_none=exclude_none,
            exclude_defaults=exclude_defaults,
            exclude_unset=exclude_unset,
            mode=mode,
        )
        base_yaml = yamling.dump_yaml(
            data,
            sort_keys=sort_keys,
            indent=indent,
            default_flow_style=default_flow_style,
            allow_unicode=allow_unicode,
        )
        if not comments:
            return base_yaml

        schema = self.model_json_schema()
        yaml_lines = base_yaml.strip().split("\n")
        commented_lines = process_yaml_lines(yaml_lines, schema, as_listitem=False, wrapped_in=None)

        return "\n".join(commented_lines)

    def save(self, path: JoinablePathLike, overwrite: bool = False) -> None:
        """Save configuration to a YAML file.

        Args:
            path: Path to save the configuration to
            overwrite: Whether to overwrite an existing file

        Raises:
            OSError: If file cannot be written
            ValueError: If path is invalid
        """
        yaml_str = self.model_dump_yaml()
        try:
            file_path = upath.UPath(path)
            if file_path.exists() and not overwrite:
                msg = f"File already exists: {path}"
                raise FileExistsError(msg)  # noqa: TRY301
            file_path.parent.mkdir(parents=True, exist_ok=True)
            file_path.write_text(yaml_str)
        except Exception as exc:
            msg = f"Failed to save configuration to {path}"
            raise ValueError(msg) from exc

    @classmethod
    def to_python_code(
        cls,
        *,
        class_name: str | None = None,
        target_python_version: PythonVersionStr | None = None,
        model_type: str = "pydantic.BaseModel",
    ) -> str:
        """Convert this model to Python code asynchronously.

        Args:
            class_name: Optional custom class name for the generated code
            target_python_version: Target Python version for code generation
            model_type: Type of model to generate

        Returns:
            Generated Python code as string
        """
        return model_to_python_code(
            cls,
            class_name=class_name,
            target_python_version=target_python_version,
            model_type=model_type,
        )

    @classmethod
    def generate_test_data(
        cls,
        *,
        seed: int = 0,
        mode: Literal["minimal", "maximal", "default"] = "default",
        validate: bool = True,
    ) -> Self:
        """Generate test data that conforms to this schema.

        Args:
            seed: Seed for deterministic generation (default: 0)
            mode: Generation mode:
                - "minimal": Only required fields, minimum values
                - "maximal": All fields, maximum reasonable values
                - "default": Balanced generation (default)
            validate: Whether to validate the generated data (default: True)

        Returns:
            An instance of this schema populated with generated test data

        Example:
            ```python
            class PersonSchema(Schema):
                name: str
                age: int = 25
                email: str | None = None

            # Generate test data
            person = PersonSchema.generate_test_data(seed=42)
            # Result: PersonSchema(name="abc", age=42, email=None)

            # Generate minimal data (required fields only)
            minimal = PersonSchema.generate_test_data(mode="minimal")
            # Result: PersonSchema(name="a", age=0, email=None)

            # Generate maximal data (all fields populated)
            maximal = PersonSchema.generate_test_data(mode="maximal")
            # Result: PersonSchema(name="abcdefghij", age=1000, email="user0@example.com")
            ```
        """
        json_schema = cls.model_json_schema()
        generator = SchemaDataGenerator(json_schema, seed=seed)

        if mode == "minimal":
            data = generator.generate_minimal()
        elif mode == "maximal":
            data = generator.generate_maximal()
        else:  # default
            data = generator.generate()

        if validate:
            return cls.model_validate(data)
        return cls.model_construct(**data)

dump_markdown_schema classmethod

dump_markdown_schema(
    *,
    template: str | None = None,
    header_level: int = 1,
    include_defaults: bool = True,
    include_examples: bool = True,
    include_constraints: bool = True,
    display_mode: Literal["table", "python_code", "yaml"] = "table",
    mode: Literal["minimal", "maximal", "default"] = "default",
    exclude_none: bool = True,
    exclude_defaults: bool = False,
    exclude_unset: bool = False,
    indent: int = 2,
    header_style: Literal["default", "pymdownx"] = "default",
    serialization_mode: Literal["json", "python"] = "json"
) -> str

Dump model class schema to Markdown documentation.

Parameters:

Name Type Description Default
template str | None

Custom Jinja2 template string (uses default if None)

None
header_level int

Starting header level (1 = h1, 2 = h2, etc.)

1
include_defaults bool

Include default values in the table

True
include_examples bool

Include examples section

True
include_constraints bool

Include constraints section

True
display_mode Literal['table', 'python_code', 'yaml']

Output format - "table", "python_code", or "yaml"

'table'
mode Literal['minimal', 'maximal', 'default']

Generation mode for YAML examples

'default'
exclude_none bool

Exclude None values from YAML

True
exclude_defaults bool

Exclude default values from YAML

False
exclude_unset bool

Exclude unset values from YAML

False
indent int

YAML indentation

2
header_style Literal['default', 'pymdownx']

Code block header style - "default" or "pymdownx"

'default'
serialization_mode Literal['json', 'python']

Pydantic serialization mode - "json" (default) or "python"

'json'

Returns:

Type Description
str

Markdown string documenting the model schema

Source code in src/schemez/schema.py
@classmethod
def dump_markdown_schema(
    cls,
    *,
    template: str | None = None,
    header_level: int = 1,
    include_defaults: bool = True,
    include_examples: bool = True,
    include_constraints: bool = True,
    display_mode: Literal["table", "python_code", "yaml"] = "table",
    mode: Literal["minimal", "maximal", "default"] = "default",
    exclude_none: bool = True,
    exclude_defaults: bool = False,
    exclude_unset: bool = False,
    indent: int = 2,
    header_style: Literal["default", "pymdownx"] = "default",
    serialization_mode: Literal["json", "python"] = "json",
) -> str:
    """Dump model class schema to Markdown documentation.

    Args:
        template: Custom Jinja2 template string (uses default if None)
        header_level: Starting header level (1 = h1, 2 = h2, etc.)
        include_defaults: Include default values in the table
        include_examples: Include examples section
        include_constraints: Include constraints section
        display_mode: Output format - "table", "python_code", or "yaml"
        mode: Generation mode for YAML examples
        exclude_none: Exclude None values from YAML
        exclude_defaults: Exclude default values from YAML
        exclude_unset: Exclude unset values from YAML
        indent: YAML indentation
        header_style: Code block header style - "default" or "pymdownx"
        serialization_mode: Pydantic serialization mode - "json" (default) or "python"

    Returns:
        Markdown string documenting the model schema
    """
    from schemez.markdown import model_to_markdown

    return model_to_markdown(
        cls,
        template=template,
        header_level=header_level,
        include_defaults=include_defaults,
        include_examples=include_examples,
        include_constraints=include_constraints,
        display_mode=display_mode,
        mode=mode,
        exclude_none=exclude_none,
        exclude_defaults=exclude_defaults,
        exclude_unset=exclude_unset,
        indent=indent,
        header_style=header_style,
        serialization_mode=serialization_mode,
    )

for_class_ctor classmethod

for_class_ctor(target_cls: type) -> type[Schema]

Create a schema model from a class constructor.

Parameters:

Name Type Description Default
target_cls type

The class whose constructor to convert

required

Returns:

Type Description
type[Schema]

A new schema model class based on the constructor parameters

Source code in src/schemez/schema.py
@classmethod
def for_class_ctor(cls, target_cls: type) -> type[Schema]:
    """Create a schema model from a class constructor.

    Args:
        target_cls: The class whose constructor to convert

    Returns:
        A new schema model class based on the constructor parameters
    """
    from schemez.convert import get_ctor_basemodel

    return get_ctor_basemodel(target_cls)

for_function classmethod

for_function(func: Callable[..., Any], *, name: str | None = None) -> type[Schema]

Create a schema model from a function's signature.

Parameters:

Name Type Description Default
func Callable[..., Any]

The function to create a schema from

required
name str | None

Optional name for the model

None

Returns:

Type Description
type[Schema]

A new schema model class based on the function parameters

Source code in src/schemez/schema.py
@classmethod
def for_function(cls, func: Callable[..., Any], *, name: str | None = None) -> type[Schema]:
    """Create a schema model from a function's signature.

    Args:
        func: The function to create a schema from
        name: Optional name for the model

    Returns:
        A new schema model class based on the function parameters
    """
    from schemez.convert import get_function_model

    return get_function_model(func, name=name)

from_json_schema classmethod

from_json_schema(json_schema: dict[str, Any]) -> type[Schema]

Create a schema model from a JSON schema.

Parameters:

Name Type Description Default
json_schema dict[str, Any]

The JSON schema to create a schema from

required

Returns:

Type Description
type[Schema]

A new schema model class based on the JSON schema

Source code in src/schemez/schema.py
@classmethod
def from_json_schema(cls, json_schema: dict[str, Any]) -> type[Schema]:
    """Create a schema model from a JSON schema.

    Args:
        json_schema: The JSON schema to create a schema from

    Returns:
        A new schema model class based on the JSON schema
    """
    from schemez.schema_to_type import json_schema_to_pydantic_class

    return json_schema_to_pydantic_class(
        json_schema, class_name="GeneratedSchema", base_class=cls
    )

from_llm async classmethod

from_llm(
    *prompts: JoinablePathLike | str | UserContent,
    model: str = "google-gla:gemini-2.0-flash",
    system_prompt: str = DEFAULT_SYSTEM_PROMPT,
    user_prompt: str = DEFAULT_USER_PROMPT
) -> Self

Create a schema model from a text snippet using AI.

Parameters:

Name Type Description Default
prompts JoinablePathLike | str | UserContent

The text to create a schema from

()
model str

The AI model to use for schema extraction

'google-gla:gemini-2.0-flash'
system_prompt str

The system prompt to use for schema extraction

DEFAULT_SYSTEM_PROMPT
user_prompt str

The user prompt to use for schema extraction

DEFAULT_USER_PROMPT

Returns:

Type Description
Self

A new schema model class based on the document

Source code in src/schemez/schema.py
@classmethod
async def from_llm(
    cls,
    *prompts: JoinablePathLike | str | UserContent,
    model: str = "google-gla:gemini-2.0-flash",
    system_prompt: str = DEFAULT_SYSTEM_PROMPT,
    user_prompt: str = DEFAULT_USER_PROMPT,
) -> Self:
    """Create a schema model from a text snippet using AI.

    Args:
        prompts: The text to create a schema from
        model: The AI model to use for schema extraction
        system_prompt: The system prompt to use for schema extraction
        user_prompt: The user prompt to use for schema extraction

    Returns:
        A new schema model class based on the document
    """
    from agentpool import Agent

    prompt = system_prompt.format(name=cls.__name__)
    agent = Agent(model=model, system_prompt=prompt, output_type=cls)
    chat_message = await agent.run(user_prompt, prompts)
    return chat_message.content

from_yaml classmethod

from_yaml(content: str, inherit_path: JoinablePathLike | None = None) -> Self

Create from YAML string.

Source code in src/schemez/schema.py
@classmethod
def from_yaml(cls, content: str, inherit_path: JoinablePathLike | None = None) -> Self:
    """Create from YAML string."""
    import yamling

    data = yamling.load_yaml(content, resolve_inherit=inherit_path or False)
    return cls.model_validate(data)

generate_test_data classmethod

generate_test_data(
    *,
    seed: int = 0,
    mode: Literal["minimal", "maximal", "default"] = "default",
    validate: bool = True
) -> Self

Generate test data that conforms to this schema.

Parameters:

Name Type Description Default
seed int

Seed for deterministic generation (default: 0)

0
mode Literal['minimal', 'maximal', 'default']

Generation mode: - "minimal": Only required fields, minimum values - "maximal": All fields, maximum reasonable values - "default": Balanced generation (default)

'default'
validate bool

Whether to validate the generated data (default: True)

True

Returns:

Type Description
Self

An instance of this schema populated with generated test data

Example
class PersonSchema(Schema):
    name: str
    age: int = 25
    email: str | None = None

# Generate test data
person = PersonSchema.generate_test_data(seed=42)
# Result: PersonSchema(name="abc", age=42, email=None)

# Generate minimal data (required fields only)
minimal = PersonSchema.generate_test_data(mode="minimal")
# Result: PersonSchema(name="a", age=0, email=None)

# Generate maximal data (all fields populated)
maximal = PersonSchema.generate_test_data(mode="maximal")
# Result: PersonSchema(name="abcdefghij", age=1000, email="user0@example.com")
Source code in src/schemez/schema.py
@classmethod
def generate_test_data(
    cls,
    *,
    seed: int = 0,
    mode: Literal["minimal", "maximal", "default"] = "default",
    validate: bool = True,
) -> Self:
    """Generate test data that conforms to this schema.

    Args:
        seed: Seed for deterministic generation (default: 0)
        mode: Generation mode:
            - "minimal": Only required fields, minimum values
            - "maximal": All fields, maximum reasonable values
            - "default": Balanced generation (default)
        validate: Whether to validate the generated data (default: True)

    Returns:
        An instance of this schema populated with generated test data

    Example:
        ```python
        class PersonSchema(Schema):
            name: str
            age: int = 25
            email: str | None = None

        # Generate test data
        person = PersonSchema.generate_test_data(seed=42)
        # Result: PersonSchema(name="abc", age=42, email=None)

        # Generate minimal data (required fields only)
        minimal = PersonSchema.generate_test_data(mode="minimal")
        # Result: PersonSchema(name="a", age=0, email=None)

        # Generate maximal data (all fields populated)
        maximal = PersonSchema.generate_test_data(mode="maximal")
        # Result: PersonSchema(name="abcdefghij", age=1000, email="user0@example.com")
        ```
    """
    json_schema = cls.model_json_schema()
    generator = SchemaDataGenerator(json_schema, seed=seed)

    if mode == "minimal":
        data = generator.generate_minimal()
    elif mode == "maximal":
        data = generator.generate_maximal()
    else:  # default
        data = generator.generate()

    if validate:
        return cls.model_validate(data)
    return cls.model_construct(**data)

iter_submodel_types classmethod

iter_submodel_types(
    *, recursive: bool = True, include_union_members: bool = True
) -> Iterator[tuple[str, type[BaseModel]]]

Iterate through all nested BaseModel types in field annotations.

Supports field types: - BaseModel (direct type) - list[BaseModel] - dict[str, BaseModel] - BaseModel | OtherModel (unions, when include_union_members=True)

Parameters:

Name Type Description Default
recursive bool

If True, also iterate through submodel types of submodels

True
include_union_members bool

If True, yield each union member separately

True

Yields:

Type Description
tuple[str, type[BaseModel]]

Tuples of (path, model_type) where path is like "field", "field[]", "field{}"

Source code in src/schemez/schema.py
@classmethod
def iter_submodel_types(
    cls, *, recursive: bool = True, include_union_members: bool = True
) -> Iterator[tuple[str, type[BaseModel]]]:
    """Iterate through all nested BaseModel types in field annotations.

    Supports field types:
    - BaseModel (direct type)
    - list[BaseModel]
    - dict[str, BaseModel]
    - BaseModel | OtherModel (unions, when include_union_members=True)

    Args:
        recursive: If True, also iterate through submodel types of submodels
        include_union_members: If True, yield each union member separately

    Yields:
        Tuples of (path, model_type) where path is like "field", "field[]", "field{}"
    """
    return _iter_submodel_types(
        cls, recursive=recursive, include_union_members=include_union_members
    )

iter_submodels

iter_submodels(*, recursive: bool = True) -> Iterator[tuple[str, BaseModel]]

Iterate through all nested BaseModel instances in fields.

Supports fields of type: - BaseModel (direct instance) - list[BaseModel] - dict[str, BaseModel]

Parameters:

Name Type Description Default
recursive bool

If True, also iterate through submodels of submodels

True

Yields:

Type Description
tuple[str, BaseModel]

Tuples of (path, submodel) where path is like "field", "field[0]", "field['key']"

Source code in src/schemez/schema.py
def iter_submodels(self, *, recursive: bool = True) -> Iterator[tuple[str, BaseModel]]:
    """Iterate through all nested BaseModel instances in fields.

    Supports fields of type:
    - BaseModel (direct instance)
    - list[BaseModel]
    - dict[str, BaseModel]

    Args:
        recursive: If True, also iterate through submodels of submodels

    Yields:
        Tuples of (path, submodel) where path is like "field", "field[0]", "field['key']"
    """
    return _iter_submodels(self, recursive=recursive)

merge

merge(other: Self) -> Self

Merge with another instance by overlaying its non-None values.

Source code in src/schemez/schema.py
def merge(self, other: Self) -> Self:
    """Merge with another instance by overlaying its non-None values."""
    from schemez.helpers import merge_models

    return merge_models(self, other)

model_dump_markdown

model_dump_markdown(
    *,
    template: str | None = None,
    header_level: int = 1,
    include_defaults: bool = True,
    include_examples: bool = True,
    include_constraints: bool = True,
    include_values: bool = True,
    display_mode: Literal["table", "python_code", "yaml"] = "table",
    exclude_none: bool = True,
    exclude_defaults_yaml: bool = False,
    exclude_unset: bool = False,
    indent: int = 2,
    header_style: Literal["default", "pymdownx"] = "default",
    serialization_mode: Literal["json", "python"] = "json"
) -> str

Dump model instance to Markdown documentation.

Parameters:

Name Type Description Default
template str | None

Custom Jinja2 template string (uses default if None)

None
header_level int

Starting header level (1 = h1, 2 = h2, etc.)

1
include_defaults bool

Include default values in the table

True
include_examples bool

Include examples section

True
include_constraints bool

Include constraints section

True
include_values bool

Include current instance values

True
display_mode Literal['table', 'python_code', 'yaml']

Output format - "table", "python_code", or "yaml"

'table'
exclude_none bool

Exclude None values from YAML

True
exclude_defaults_yaml bool

Exclude default values from YAML

False
exclude_unset bool

Exclude unset values from YAML

False
indent int

YAML indentation

2
header_style Literal['default', 'pymdownx']

Code block header style - "default" or "pymdownx"

'default'
serialization_mode Literal['json', 'python']

Pydantic serialization mode - "json" (default) or "python"

'json'

Returns:

Type Description
str

Markdown string documenting the model

Source code in src/schemez/schema.py
def model_dump_markdown(
    self,
    *,
    template: str | None = None,
    header_level: int = 1,
    include_defaults: bool = True,
    include_examples: bool = True,
    include_constraints: bool = True,
    include_values: bool = True,
    display_mode: Literal["table", "python_code", "yaml"] = "table",
    exclude_none: bool = True,
    exclude_defaults_yaml: bool = False,
    exclude_unset: bool = False,
    indent: int = 2,
    header_style: Literal["default", "pymdownx"] = "default",
    serialization_mode: Literal["json", "python"] = "json",
) -> str:
    """Dump model instance to Markdown documentation.

    Args:
        template: Custom Jinja2 template string (uses default if None)
        header_level: Starting header level (1 = h1, 2 = h2, etc.)
        include_defaults: Include default values in the table
        include_examples: Include examples section
        include_constraints: Include constraints section
        include_values: Include current instance values
        display_mode: Output format - "table", "python_code", or "yaml"
        exclude_none: Exclude None values from YAML
        exclude_defaults_yaml: Exclude default values from YAML
        exclude_unset: Exclude unset values from YAML
        indent: YAML indentation
        header_style: Code block header style - "default" or "pymdownx"
        serialization_mode: Pydantic serialization mode - "json" (default) or "python"

    Returns:
        Markdown string documenting the model
    """
    from schemez.markdown import instance_to_markdown

    return instance_to_markdown(
        self,
        template=template,
        header_level=header_level,
        include_defaults=include_defaults,
        include_examples=include_examples,
        include_constraints=include_constraints,
        include_values=include_values,
        display_mode=display_mode,
        exclude_none=exclude_none,
        exclude_defaults_yaml=exclude_defaults_yaml,
        exclude_unset=exclude_unset,
        indent=indent,
        header_style=header_style,
        serialization_mode=serialization_mode,
    )

model_dump_yaml

model_dump_yaml(
    exclude_none: bool = True,
    exclude_defaults: bool = False,
    exclude_unset: bool = False,
    indent: int = 2,
    default_flow_style: bool | None = None,
    allow_unicode: bool = True,
    comments: bool = False,
    sort_keys: bool = True,
    mode: Literal["json", "python"] = "python",
) -> str

Dump configuration to YAML string.

Parameters:

Name Type Description Default
exclude_none bool

Exclude fields with None values

True
exclude_defaults bool

Exclude fields with default values

False
exclude_unset bool

Exclude fields that are not set

False
indent int

Indentation level for YAML output

2
default_flow_style bool | None

Default flow style for YAML output

None
allow_unicode bool

Allow unicode characters in YAML output

True
comments bool

Include descriptions as comments in the YAML output

False
sort_keys bool

Sort keys in the YAML output

True
mode Literal['json', 'python']

Output mode, either "json" or "python"

'python'

Returns:

Type Description
str

YAML string representation of the model

Source code in src/schemez/schema.py
def model_dump_yaml(
    self,
    exclude_none: bool = True,
    exclude_defaults: bool = False,
    exclude_unset: bool = False,
    indent: int = 2,
    default_flow_style: bool | None = None,
    allow_unicode: bool = True,
    comments: bool = False,
    sort_keys: bool = True,
    mode: Literal["json", "python"] = "python",
) -> str:
    """Dump configuration to YAML string.

    Args:
        exclude_none: Exclude fields with None values
        exclude_defaults: Exclude fields with default values
        exclude_unset: Exclude fields that are not set
        indent: Indentation level for YAML output
        default_flow_style: Default flow style for YAML output
        allow_unicode: Allow unicode characters in YAML output
        comments: Include descriptions as comments in the YAML output
        sort_keys: Sort keys in the YAML output
        mode: Output mode, either "json" or "python"

    Returns:
        YAML string representation of the model
    """
    import yamling

    from schemez.commented_yaml import process_yaml_lines

    data = self.model_dump(
        exclude_none=exclude_none,
        exclude_defaults=exclude_defaults,
        exclude_unset=exclude_unset,
        mode=mode,
    )
    base_yaml = yamling.dump_yaml(
        data,
        sort_keys=sort_keys,
        indent=indent,
        default_flow_style=default_flow_style,
        allow_unicode=allow_unicode,
    )
    if not comments:
        return base_yaml

    schema = self.model_json_schema()
    yaml_lines = base_yaml.strip().split("\n")
    commented_lines = process_yaml_lines(yaml_lines, schema, as_listitem=False, wrapped_in=None)

    return "\n".join(commented_lines)

save

save(path: JoinablePathLike, overwrite: bool = False) -> None

Save configuration to a YAML file.

Parameters:

Name Type Description Default
path JoinablePathLike

Path to save the configuration to

required
overwrite bool

Whether to overwrite an existing file

False

Raises:

Type Description
OSError

If file cannot be written

ValueError

If path is invalid

Source code in src/schemez/schema.py
def save(self, path: JoinablePathLike, overwrite: bool = False) -> None:
    """Save configuration to a YAML file.

    Args:
        path: Path to save the configuration to
        overwrite: Whether to overwrite an existing file

    Raises:
        OSError: If file cannot be written
        ValueError: If path is invalid
    """
    yaml_str = self.model_dump_yaml()
    try:
        file_path = upath.UPath(path)
        if file_path.exists() and not overwrite:
            msg = f"File already exists: {path}"
            raise FileExistsError(msg)  # noqa: TRY301
        file_path.parent.mkdir(parents=True, exist_ok=True)
        file_path.write_text(yaml_str)
    except Exception as exc:
        msg = f"Failed to save configuration to {path}"
        raise ValueError(msg) from exc

to_python_code classmethod

to_python_code(
    *,
    class_name: str | None = None,
    target_python_version: PythonVersionStr | None = None,
    model_type: str = "pydantic.BaseModel"
) -> str

Convert this model to Python code asynchronously.

Parameters:

Name Type Description Default
class_name str | None

Optional custom class name for the generated code

None
target_python_version PythonVersionStr | None

Target Python version for code generation

None
model_type str

Type of model to generate

'pydantic.BaseModel'

Returns:

Type Description
str

Generated Python code as string

Source code in src/schemez/schema.py
@classmethod
def to_python_code(
    cls,
    *,
    class_name: str | None = None,
    target_python_version: PythonVersionStr | None = None,
    model_type: str = "pydantic.BaseModel",
) -> str:
    """Convert this model to Python code asynchronously.

    Args:
        class_name: Optional custom class name for the generated code
        target_python_version: Target Python version for code generation
        model_type: Type of model to generate

    Returns:
        Generated Python code as string
    """
    return model_to_python_code(
        cls,
        class_name=class_name,
        target_python_version=target_python_version,
        model_type=model_type,
    )

SchemaField

Bases: Schema

Field definition for inline response types.

Defines a single field in an inline response definition, including: - Data type specification - Optional description - Validation constraints - Enum values (when type is 'enum') - Field dependencies and relationships

Used by InlineSchemaDef to structure response fields.

Source code in src/schemez/schemadef/schemadef.py
class SchemaField(Schema):
    """Field definition for inline response types.

    Defines a single field in an inline response definition, including:
    - Data type specification
    - Optional description
    - Validation constraints
    - Enum values (when type is 'enum')
    - Field dependencies and relationships

    Used by InlineSchemaDef to structure response fields.
    """

    type: FieldType | str = Field(
        title="Field type", examples=["str", "int", "list[str]", "dict[str, Any]", "enum"]
    )
    """Data type of the response field"""

    description: str | None = Field(
        default=None,
        title="Field description",
        examples=["User name", "Port number", "Enable debug mode"],
    )
    """Optional description of what this field represents"""

    values: list[Any] | None = Field(
        default=None,
        title="Enum values",
        examples=[["active", "inactive", "pending"], ["small", "medium", "large"]],
    )
    """Values for enum type fields"""

    default: Any | None = Field(
        default=None,
        title="Default value",
        examples=["localhost", 8080, True, []],
    )
    """Default value for the field"""

    title: str | None = Field(
        default=None,
        title="Field title",
        examples=["Server Name", "Port Number", "Debug Mode"],
    )
    """Title for the field in generated JSON Schema"""

    pattern: str | None = Field(
        default=None,
        title="Regex pattern",
        examples=["^[A-Za-z]+$", "\\d{3}-\\d{3}-\\d{4}", "^[a-z0-9_]+$"],
    )
    """Regex pattern for string validation"""

    min_length: Annotated[int | None, Field(ge=0)] = Field(
        default=None,
        title="Minimum length",
        examples=[1, 3, 8],
    )
    """Minimum length for collections"""

    max_length: Annotated[int | None, Field(ge=0)] = Field(
        default=None, title="Maximum length", examples=[50, 255, 1000]
    )
    """Maximum length for collections"""

    gt: float | None = Field(default=None, title="Greater than", examples=[0, 1.0, 100])
    """Greater than (exclusive) validation for numbers"""

    ge: float | None = Field(
        default=None,
        title="Greater than or equal",
        examples=[0, 1, 18],
    )
    """Greater than or equal (inclusive) validation for numbers"""

    lt: float | None = Field(default=None, title="Less than", examples=[100, 65536, 1.0])
    """Less than (exclusive) validation for numbers"""

    le: float | None = Field(
        default=None,
        title="Less than or equal",
        examples=[100, 255, 99.9],
    )
    """Less than or equal (inclusive) validation for numbers"""

    multiple_of: Annotated[float | None, Field(gt=0)] = Field(
        default=None,
        title="Multiple of",
        examples=[2, 5, 10, 0.5],
    )
    """Number must be a multiple of this value"""

    literal_value: Any | None = Field(
        default=None,
        title="Literal value",
        examples=["production", 42, True],
    )
    """Value for Literal type constraint, makes field accept only this specific value"""

    examples: list[Any] | None = Field(
        default=None,
        title="Field examples",
        examples=[["localhost", "example.com"], [8080, 3000, 443], [True, False]],
    )
    """Examples for this field in JSON Schema"""

    optional: bool = Field(default=False, title="Optional field")
    """Whether this field is optional (None value allowed)"""

    json_schema_extra: dict[str, Any] | None = Field(
        default=None,
        title="JSON Schema extras",
        examples=[{"format": "email"}, {"contentMediaType": "application/json"}],
    )
    """Additional JSON Schema information"""

    field_config: dict[str, Any] | None = Field(
        default=None,
        title="Pydantic field config",
        examples=[{"alias": "userName"}, {"exclude": True}],
    )
    """Configuration for Pydantic model fields"""

    # Dependencies between fields
    dependent_required: dict[str, list[str]] = Field(
        default_factory=dict,
        title="Required field dependencies",
        examples=[
            {"payment_method": ["card_number", "expiry_date"]},
            {"auth_enabled": ["username", "password"]},
        ],
    )
    """Field dependencies - when this field exists, dependent fields are required"""

    dependent_schema: dict[str, dict[str, Any]] = Field(
        default_factory=dict,
        title="Schema dependencies",
        examples=[
            {"ssl_enabled": {"properties": {"ssl_cert": {"type": "string"}}}},
            {"debug": {"properties": {"log_level": {"enum": ["debug", "trace"]}}}},
        ],
    )
    """Schema dependencies - when this field exists, dependent fields must match schema"""

    # Extensibility for future or custom constraints
    constraints: dict[ConstraintType | str, Any] = Field(
        default_factory=dict,
        title="Constraints",
        examples=[
            {"min_length": 3, "max_length": 50},
            {"ge": 0, "le": 100},
            {"strict": True, "frozen": False},
        ],
    )
    """Additional Pydantic Field constraints not covered by explicit fields"""

    def add_required_dependency(self, field_name: str, required_fields: list[str]) -> None:
        """Add a dependency requiring other fields when this field exists.

        Args:
            field_name: The field that triggers the dependency
            required_fields: Fields that become required when field_name exists
        """
        if field_name not in self.dependent_required:
            self.dependent_required[field_name] = []
        self.dependent_required[field_name].extend([
            field for field in required_fields if field not in self.dependent_required[field_name]
        ])

    def add_schema_dependency(self, field_name: str, schema: dict[str, Any]) -> None:
        """Add a schema dependency when this field exists.

        Args:
            field_name: The field that triggers the dependency
            schema: JSON Schema to apply when field_name exists
        """
        self.dependent_schema[field_name] = schema

    @field_validator("max_length")
    @classmethod
    def validate_max_min_length(cls, v: int | None, info: ValidationInfo) -> int | None:
        min_length = info.data.get("min_length")
        if v is not None and min_length is not None and v < min_length:
            msg = "max_length must be ≥ min_length"
            raise ValueError(msg)
        return v

constraints class-attribute instance-attribute

constraints: dict[ConstraintType | str, Any] = Field(
    default_factory=dict,
    title="Constraints",
    examples=[
        {"min_length": 3, "max_length": 50},
        {"ge": 0, "le": 100},
        {"strict": True, "frozen": False},
    ],
)

Additional Pydantic Field constraints not covered by explicit fields

default class-attribute instance-attribute

default: Any | None = Field(
    default=None, title="Default value", examples=["localhost", 8080, True, []]
)

Default value for the field

dependent_required class-attribute instance-attribute

dependent_required: dict[str, list[str]] = Field(
    default_factory=dict,
    title="Required field dependencies",
    examples=[
        {"payment_method": ["card_number", "expiry_date"]},
        {"auth_enabled": ["username", "password"]},
    ],
)

Field dependencies - when this field exists, dependent fields are required

dependent_schema class-attribute instance-attribute

dependent_schema: dict[str, dict[str, Any]] = Field(
    default_factory=dict,
    title="Schema dependencies",
    examples=[
        {"ssl_enabled": {"properties": {"ssl_cert": {"type": "string"}}}},
        {"debug": {"properties": {"log_level": {"enum": ["debug", "trace"]}}}},
    ],
)

Schema dependencies - when this field exists, dependent fields must match schema

description class-attribute instance-attribute

description: str | None = Field(
    default=None,
    title="Field description",
    examples=["User name", "Port number", "Enable debug mode"],
)

Optional description of what this field represents

examples class-attribute instance-attribute

examples: list[Any] | None = Field(
    default=None,
    title="Field examples",
    examples=[["localhost", "example.com"], [8080, 3000, 443], [True, False]],
)

Examples for this field in JSON Schema

field_config class-attribute instance-attribute

field_config: dict[str, Any] | None = Field(
    default=None, title="Pydantic field config", examples=[{"alias": "userName"}, {"exclude": True}]
)

Configuration for Pydantic model fields

ge class-attribute instance-attribute

ge: float | None = Field(default=None, title='Greater than or equal', examples=[0, 1, 18])

Greater than or equal (inclusive) validation for numbers

gt class-attribute instance-attribute

gt: float | None = Field(default=None, title='Greater than', examples=[0, 1.0, 100])

Greater than (exclusive) validation for numbers

json_schema_extra class-attribute instance-attribute

json_schema_extra: dict[str, Any] | None = Field(
    default=None,
    title="JSON Schema extras",
    examples=[{"format": "email"}, {"contentMediaType": "application/json"}],
)

Additional JSON Schema information

le class-attribute instance-attribute

le: float | None = Field(default=None, title='Less than or equal', examples=[100, 255, 99.9])

Less than or equal (inclusive) validation for numbers

literal_value class-attribute instance-attribute

literal_value: Any | None = Field(
    default=None, title="Literal value", examples=["production", 42, True]
)

Value for Literal type constraint, makes field accept only this specific value

lt class-attribute instance-attribute

lt: float | None = Field(default=None, title='Less than', examples=[100, 65536, 1.0])

Less than (exclusive) validation for numbers

max_length class-attribute instance-attribute

max_length: Annotated[int | None, Field(ge=0)] = Field(
    default=None, title="Maximum length", examples=[50, 255, 1000]
)

Maximum length for collections

min_length class-attribute instance-attribute

min_length: Annotated[int | None, Field(ge=0)] = Field(
    default=None, title="Minimum length", examples=[1, 3, 8]
)

Minimum length for collections

multiple_of class-attribute instance-attribute

multiple_of: Annotated[float | None, Field(gt=0)] = Field(
    default=None, title="Multiple of", examples=[2, 5, 10, 0.5]
)

Number must be a multiple of this value

optional class-attribute instance-attribute

optional: bool = Field(default=False, title='Optional field')

Whether this field is optional (None value allowed)

pattern class-attribute instance-attribute

pattern: str | None = Field(
    default=None,
    title="Regex pattern",
    examples=["^[A-Za-z]+$", "\\d{3}-\\d{3}-\\d{4}", "^[a-z0-9_]+$"],
)

Regex pattern for string validation

title class-attribute instance-attribute

title: str | None = Field(
    default=None, title="Field title", examples=["Server Name", "Port Number", "Debug Mode"]
)

Title for the field in generated JSON Schema

type class-attribute instance-attribute

type: FieldType | str = Field(
    title="Field type", examples=["str", "int", "list[str]", "dict[str, Any]", "enum"]
)

Data type of the response field

values class-attribute instance-attribute

values: list[Any] | None = Field(
    default=None,
    title="Enum values",
    examples=[["active", "inactive", "pending"], ["small", "medium", "large"]],
)

Values for enum type fields

add_required_dependency

add_required_dependency(field_name: str, required_fields: list[str]) -> None

Add a dependency requiring other fields when this field exists.

Parameters:

Name Type Description Default
field_name str

The field that triggers the dependency

required
required_fields list[str]

Fields that become required when field_name exists

required
Source code in src/schemez/schemadef/schemadef.py
def add_required_dependency(self, field_name: str, required_fields: list[str]) -> None:
    """Add a dependency requiring other fields when this field exists.

    Args:
        field_name: The field that triggers the dependency
        required_fields: Fields that become required when field_name exists
    """
    if field_name not in self.dependent_required:
        self.dependent_required[field_name] = []
    self.dependent_required[field_name].extend([
        field for field in required_fields if field not in self.dependent_required[field_name]
    ])

add_schema_dependency

add_schema_dependency(field_name: str, schema: dict[str, Any]) -> None

Add a schema dependency when this field exists.

Parameters:

Name Type Description Default
field_name str

The field that triggers the dependency

required
schema dict[str, Any]

JSON Schema to apply when field_name exists

required
Source code in src/schemez/schemadef/schemadef.py
def add_schema_dependency(self, field_name: str, schema: dict[str, Any]) -> None:
    """Add a schema dependency when this field exists.

    Args:
        field_name: The field that triggers the dependency
        schema: JSON Schema to apply when field_name exists
    """
    self.dependent_schema[field_name] = schema

TOMLCode

Bases: BaseCode

TOML with syntax validation.

Source code in src/schemez/code.py
class TOMLCode(BaseCode):
    """TOML with syntax validation."""

    @field_validator("code")
    @classmethod
    def validate_syntax(cls, code: str) -> str:
        import yamling

        try:
            yamling.load(code, mode="toml")
        except yamling.ParsingError as e:
            msg = f"Invalid TOML syntax: {e}"
            raise ValueError(msg) from e
        else:
            return code

ToolCodeGenerator dataclass

Generates code artifacts for a single tool.

Source code in src/schemez/code_generation/tool_code_generator.py
@dataclass
class ToolCodeGenerator:
    """Generates code artifacts for a single tool."""

    schema: FunctionSchema
    """Schema of the tool (primary source of truth)."""

    callable: Callable[..., Any] | None = None
    """Optional callable for actual execution. Required only for FastAPI route generation
    and Python namespace execution. All other operations (client code generation,
    signatures, models) work purely from the schema."""

    name_override: str | None = None
    """Name override for the function to generate code for."""

    @classmethod
    def from_callable(
        cls,
        fn: Callable[..., Any],
        exclude_types: list[type] | None = None,
        schema_type: SchemaType = "simple",
    ) -> ToolCodeGenerator:
        """Create a ToolCodeGenerator from a callable."""
        schema = create_schema(fn, exclude_types=exclude_types, mode=schema_type)
        return cls(schema=schema, callable=fn)

    @classmethod
    def from_schema(
        cls,
        schema: FunctionSchema,
        name_override: str | None = None,
    ) -> ToolCodeGenerator:
        """Create a ToolCodeGenerator from a schema only (no execution capability)."""
        return cls(schema=schema, callable=None, name_override=name_override)

    @property
    def name(self) -> str:
        """Name of the tool."""
        if self.name_override:
            return self.name_override
        if self.callable:
            return get_object_name(self.callable, "unknown")
        return self.schema.name

    def get_function_signature(self) -> str:
        """Assembles a signature for given generator, excluding (async) def."""
        return f"{self.name}{self.schema.to_python_signature()}"

    def get_function_definition(self, include_docstrings: bool = True) -> str:
        """Extract function definition using FunctionSchema."""
        parts = []
        parts.append(f"async def {self.get_function_signature()}")
        if include_docstrings and self.schema.description:
            lines = self.schema.description.split("\n")
            parts.extend(f"    {i.strip()}" for i in lines if i.strip())
        return "\n".join(parts)

    def generate_return_model(self) -> str | None:
        """Generate Pydantic model code for the tool's return type."""
        try:
            if self.schema.returns.get("type") not in {"object", "array"}:
                return None

            class_name = f"{self.name.title()}Response"
            model_code = self.schema.to_return_model_code(class_name=class_name)
            return model_code.strip() or None

        except Exception:  # noqa: BLE001
            return None

    def generate_parameter_model(self) -> str | None:
        """Generate Pydantic model code for the tool's parameters."""
        try:
            if not self.schema.parameters.get("properties"):
                return None

            class_name = f"{self.name.title()}Params"
            model_code = self.schema.to_parameter_model_code(class_name=class_name)
            return model_code.strip() or None

        except Exception:  # noqa: BLE001
            return None

    def generate_route_handler(self) -> Callable[..., Awaitable[dict[str, Any]]]:
        """Generate FastAPI route handler for this tool.

        Returns:
            Async route handler function

        Raises:
            ValueError: If callable is not provided
        """
        if self.callable is None:
            msg = f"Callable required for route generation for tool '{self.name}'"
            raise ValueError(msg)
        param_cls = create_param_model(dict(self.schema.parameters))
        return create_route_handler(self.callable, param_cls)

    def add_route_to_app(self, app: FastAPI, path_prefix: str = "/tools") -> None:
        """Add this tool's route to FastAPI app.

        Args:
            app: FastAPI application instance
            path_prefix: Path prefix for the route

        Raises:
            ValueError: If callable is not provided
        """
        if self.callable is None:
            msg = f"Callable required for route generation for tool '{self.name}'"
            raise ValueError(msg)
        param_cls = create_param_model(dict(self.schema.parameters))
        route_handler = self.generate_route_handler()
        # Set up the route with proper parameter annotations for FastAPI
        if param_cls:
            func_code = generate_func_code(param_cls.model_fields)
            namespace: dict[str, Any] = {"route_handler": route_handler, "Any": Any}
            exec(func_code, namespace)  # Execute the dynamic function creation
            dynamic_handler: Callable[..., Any] = namespace["dynamic_handler"]
        else:

            async def dynamic_handler() -> dict[str, Any]:
                return await route_handler()

        app.get(f"{path_prefix}/{self.name}")(dynamic_handler)  # Add route to FastAPI app

callable class-attribute instance-attribute

callable: Callable[..., Any] | None = None

Optional callable for actual execution. Required only for FastAPI route generation and Python namespace execution. All other operations (client code generation, signatures, models) work purely from the schema.

name property

name: str

Name of the tool.

name_override class-attribute instance-attribute

name_override: str | None = None

Name override for the function to generate code for.

schema instance-attribute

Schema of the tool (primary source of truth).

add_route_to_app

add_route_to_app(app: FastAPI, path_prefix: str = '/tools') -> None

Add this tool's route to FastAPI app.

Parameters:

Name Type Description Default
app FastAPI

FastAPI application instance

required
path_prefix str

Path prefix for the route

'/tools'

Raises:

Type Description
ValueError

If callable is not provided

Source code in src/schemez/code_generation/tool_code_generator.py
def add_route_to_app(self, app: FastAPI, path_prefix: str = "/tools") -> None:
    """Add this tool's route to FastAPI app.

    Args:
        app: FastAPI application instance
        path_prefix: Path prefix for the route

    Raises:
        ValueError: If callable is not provided
    """
    if self.callable is None:
        msg = f"Callable required for route generation for tool '{self.name}'"
        raise ValueError(msg)
    param_cls = create_param_model(dict(self.schema.parameters))
    route_handler = self.generate_route_handler()
    # Set up the route with proper parameter annotations for FastAPI
    if param_cls:
        func_code = generate_func_code(param_cls.model_fields)
        namespace: dict[str, Any] = {"route_handler": route_handler, "Any": Any}
        exec(func_code, namespace)  # Execute the dynamic function creation
        dynamic_handler: Callable[..., Any] = namespace["dynamic_handler"]
    else:

        async def dynamic_handler() -> dict[str, Any]:
            return await route_handler()

    app.get(f"{path_prefix}/{self.name}")(dynamic_handler)  # Add route to FastAPI app

from_callable classmethod

from_callable(
    fn: Callable[..., Any],
    exclude_types: list[type] | None = None,
    schema_type: SchemaType = "simple",
) -> ToolCodeGenerator

Create a ToolCodeGenerator from a callable.

Source code in src/schemez/code_generation/tool_code_generator.py
@classmethod
def from_callable(
    cls,
    fn: Callable[..., Any],
    exclude_types: list[type] | None = None,
    schema_type: SchemaType = "simple",
) -> ToolCodeGenerator:
    """Create a ToolCodeGenerator from a callable."""
    schema = create_schema(fn, exclude_types=exclude_types, mode=schema_type)
    return cls(schema=schema, callable=fn)

from_schema classmethod

from_schema(schema: FunctionSchema, name_override: str | None = None) -> ToolCodeGenerator

Create a ToolCodeGenerator from a schema only (no execution capability).

Source code in src/schemez/code_generation/tool_code_generator.py
@classmethod
def from_schema(
    cls,
    schema: FunctionSchema,
    name_override: str | None = None,
) -> ToolCodeGenerator:
    """Create a ToolCodeGenerator from a schema only (no execution capability)."""
    return cls(schema=schema, callable=None, name_override=name_override)

generate_parameter_model

generate_parameter_model() -> str | None

Generate Pydantic model code for the tool's parameters.

Source code in src/schemez/code_generation/tool_code_generator.py
def generate_parameter_model(self) -> str | None:
    """Generate Pydantic model code for the tool's parameters."""
    try:
        if not self.schema.parameters.get("properties"):
            return None

        class_name = f"{self.name.title()}Params"
        model_code = self.schema.to_parameter_model_code(class_name=class_name)
        return model_code.strip() or None

    except Exception:  # noqa: BLE001
        return None

generate_return_model

generate_return_model() -> str | None

Generate Pydantic model code for the tool's return type.

Source code in src/schemez/code_generation/tool_code_generator.py
def generate_return_model(self) -> str | None:
    """Generate Pydantic model code for the tool's return type."""
    try:
        if self.schema.returns.get("type") not in {"object", "array"}:
            return None

        class_name = f"{self.name.title()}Response"
        model_code = self.schema.to_return_model_code(class_name=class_name)
        return model_code.strip() or None

    except Exception:  # noqa: BLE001
        return None

generate_route_handler

generate_route_handler() -> Callable[..., Awaitable[dict[str, Any]]]

Generate FastAPI route handler for this tool.

Returns:

Type Description
Callable[..., Awaitable[dict[str, Any]]]

Async route handler function

Raises:

Type Description
ValueError

If callable is not provided

Source code in src/schemez/code_generation/tool_code_generator.py
def generate_route_handler(self) -> Callable[..., Awaitable[dict[str, Any]]]:
    """Generate FastAPI route handler for this tool.

    Returns:
        Async route handler function

    Raises:
        ValueError: If callable is not provided
    """
    if self.callable is None:
        msg = f"Callable required for route generation for tool '{self.name}'"
        raise ValueError(msg)
    param_cls = create_param_model(dict(self.schema.parameters))
    return create_route_handler(self.callable, param_cls)

get_function_definition

get_function_definition(include_docstrings: bool = True) -> str

Extract function definition using FunctionSchema.

Source code in src/schemez/code_generation/tool_code_generator.py
def get_function_definition(self, include_docstrings: bool = True) -> str:
    """Extract function definition using FunctionSchema."""
    parts = []
    parts.append(f"async def {self.get_function_signature()}")
    if include_docstrings and self.schema.description:
        lines = self.schema.description.split("\n")
        parts.extend(f"    {i.strip()}" for i in lines if i.strip())
    return "\n".join(parts)

get_function_signature

get_function_signature() -> str

Assembles a signature for given generator, excluding (async) def.

Source code in src/schemez/code_generation/tool_code_generator.py
def get_function_signature(self) -> str:
    """Assembles a signature for given generator, excluding (async) def."""
    return f"{self.name}{self.schema.to_python_signature()}"

ToolsetCodeGenerator dataclass

Generates code artifacts for multiple tools.

Source code in src/schemez/code_generation/toolset_code_generator.py
@dataclass
class ToolsetCodeGenerator:
    """Generates code artifacts for multiple tools."""

    generators: Sequence[ToolCodeGenerator]
    """ToolCodeGenerator instances for each tool."""

    include_docstrings: bool = True
    """Include function docstrings in documentation."""

    @classmethod
    def from_callables(
        cls,
        callables: Sequence[Callable[..., Any]],
        include_docstrings: bool = True,
        exclude_types: list[type] | None = None,
    ) -> ToolsetCodeGenerator:
        """Create a ToolsetCodeGenerator from a sequence of callables."""
        gens = [ToolCodeGenerator.from_callable(i, exclude_types=exclude_types) for i in callables]
        return cls(gens, include_docstrings)

    @classmethod
    def from_schemas(
        cls,
        schemas: Sequence[FunctionSchema],
        include_docstrings: bool = True,
    ) -> ToolsetCodeGenerator:
        """Create a ToolsetCodeGenerator from schemas only (no execution capability)."""
        generators = [ToolCodeGenerator.from_schema(schema) for schema in schemas]
        return cls(generators, include_docstrings)

    def generate_tool_description(self) -> str:
        """Generate comprehensive tool description with available functions."""
        if not self.generators:
            return "Execute Python code (no tools available)"

        parts = ["Available functions:"]
        for generator in self.generators:
            desc = generator.get_function_definition(self.include_docstrings)
            parts.append(desc)
        return "\n".join(parts)

    def generate_execution_namespace(self) -> dict[str, Any]:
        """Build Python namespace with tool functions and generated models.

        Raises:
            ValueError: If any generator lacks a callable
        """
        namespace: dict[str, Any] = {"__builtins__": __builtins__, "_result": None}
        # Add tool functions - all generators must have callables for execution
        for generator in self.generators:
            namespace[generator.name] = NamespaceCallable.from_generator(generator)
        # Add generated model classes to namespace
        if models_code := self.generate_return_models():
            with contextlib.suppress(Exception):
                exec(models_code, namespace)
        return namespace

    def generate_return_models(self) -> str:
        """Generate Pydantic models for tool return types."""
        model_parts = [c for g in self.generators if (c := g.generate_return_model())]
        return "\n\n".join(model_parts) if model_parts else ""

    def get_fastmcp_client_code(self, server_configs: dict[str, str]) -> str:
        """Generate FastMCP client code with connection management.

        Args:
            server_configs: Dict mapping server names to their transport URLs
                          e.g., {"github": "sse://localhost:8080/github"}

        Returns:
            FastMCP client code as string
        """
        server_config_code = "SERVERS = " + repr(server_configs)
        return f'''{server_config_code}

# Connection management
_clients: dict[str, Client] = {{}}

async def get_mcp_client(server_name: str) -> Client:
    """Get or create FastMCP client for server."""
    if server_name not in _clients:
        if server_name not in SERVERS:
            raise ValueError(f"Unknown MCP server: {{server_name}}")

        transport_url = SERVERS[server_name]
        client = Client(transport_url)
        _clients[server_name] = client

    return _clients[server_name]

async def call_mcp_tool(
    server_name: str, tool_name: str, arguments: dict[str, Any]
) -> Any:
    """Call a FastMCP tool and return the result."""
    client = await get_mcp_client(server_name)

    async with client:
        result = await client.call_tool(tool_name, arguments)

        # FastMCP returns CallToolResult with structured content handling
        if result.data is not None:
            return result.data  # Parsed structured content
        elif result.content:
            # Extract text from content blocks
            text_parts = []
            for content_block in result.content:
                if hasattr(content_block, 'text'):
                    text_parts.append(content_block.text)
            return "\\n".join(text_parts) if text_parts else ""

        return ""

async def close_all_mcp_connections():
    """Close all MCP client connections."""
    for server_name, client in _clients.items():
        try:
            await client.close()
        except Exception as e:
            print(f"Error closing connection to {{server_name}}: {{e}}")
    _clients.clear()
'''

    def generate_structured_code(
        self,
        base_url: str = "http://localhost:8000",
        path_prefix: str = "/tools",
        client_type: ClientType = "http",
    ) -> GeneratedCode:
        """Generate structured code with all components.

        Args:
            base_url: Base URL of the tool server (HTTP) or server name (FastMCP)
            path_prefix: Path prefix for routes (HTTP only)
            client_type: Type of client to generate ("http" or "fastmcp")

        Returns:
            GeneratedCode with all components separated
        """
        start_time = time.time()
        logger.info("Starting structured code generation")

        models_parts: list[str] = []
        http_methods_parts: list[str] = []
        clean_methods_parts: list[str] = []
        model_stubs_parts: list[str] = []
        explicit_stubs_parts: list[str] = []

        for generator in self.generators:
            # Generate input model from schema parameters
            input_class_name = None
            try:
                params = generator.schema.parameters
                if params.get("properties"):
                    words = [word.title() for word in generator.name.split("_")]
                    input_class_name = f"{''.join(words)}Input"
                    if model_code := model_to_python_code(params, class_name=input_class_name):
                        cleaned_model = clean_generated_code(model_code)
                        models_parts.append(cleaned_model)
            except ValueError, TypeError, AttributeError:
                input_class_name = None

            # Generate client method with model
            if input_class_name:
                if client_type == "fastmcp":
                    http_method = f'''
async def {generator.name}(input: {input_class_name}) -> Any:
    """{generator.schema.description or f"Call {generator.name} tool"}

    Args:
        input: Function parameters

    Returns:
        Result from the MCP server
    """
    result = await call_mcp_tool("{base_url}", "{generator.name}", input.model_dump())
    return result
'''
                else:
                    http_method = f'''
async def {generator.name}(input: {input_class_name}) -> str:
    """{generator.schema.description or f"Call {generator.name} tool"}

    Args:
        input: Function parameters

    Returns:
        String response from the tool server
    """
    async with httpx2.AsyncClient() as client:
        response = await client.get(
            "{base_url}{path_prefix}/{generator.name}",
            params=input.model_dump() if hasattr(input, 'model_dump') else {{}},
            timeout=30.0
        )
        response.raise_for_status()
        return response.text
'''
            elif client_type == "fastmcp":
                http_method = f'''
async def {generator.name}() -> Any:
    """{generator.schema.description or f"Call {generator.name} tool"}

    Returns:
        Result from the MCP server
    """
    result = await call_mcp_tool("{base_url}", "{generator.name}", {{}})
    return result
'''
            else:
                http_method = f'''
async def {generator.name}() -> str:
    """{generator.schema.description or f"Call {generator.name} tool"}

    Returns:
        String response from the tool server
    """
    async with httpx2.AsyncClient() as client:
        response = await client.get(
            "{base_url}{path_prefix}/{generator.name}",
            timeout=30.0
        )
        response.raise_for_status()
        return response.text
'''
            http_methods_parts.append(http_method)
            # Generate clean method with natural signature
            signature_str = generator.get_function_signature()
            params = generator.schema.parameters
            param_names = list(params.get("properties", {}).keys())
            if client_type == "fastmcp":
                clean_method = f'''
async def {signature_str}:
    """{generator.schema.description or f"Call {generator.name} tool"}"""
    # Build parameters dict
    params = {{{", ".join(f'"{name}": {name}' for name in param_names)}}}
    # Remove None values
    clean_params = {{k: v for k, v in params.items() if v is not None}}

    result = await call_mcp_tool("{base_url}", "{generator.name}", clean_params)
    return result
'''
            else:
                clean_method = f'''
async def {signature_str}:
    """{generator.schema.description or f"Call {generator.name} tool"}"""
    # Build parameters dict
    params = {{{", ".join(f'"{name}": {name}' for name in param_names)}}}
    # Remove None values
    clean_params = {{k: v for k, v in params.items() if v is not None}}

    async with httpx2.AsyncClient() as client:
        response = await client.get(
            "{base_url}{path_prefix}/{generator.name}",
            params=clean_params,
            timeout=30.0
        )
        response.raise_for_status()
        # Parse JSON response and return the result
        result = response.json()
        return result.get("result", response.text)
'''
            clean_methods_parts.append(clean_method)
            # Generate model-based stub
            if input_class_name:
                model_stub = f'''
async def {generator.name}(input: {input_class_name}) -> Any:
    """{generator.schema.description or f"Call {generator.name} tool"}

    Args:
        input: Function parameters

    Returns:
        Function result
    """
    ...
'''
                model_stubs_parts.append(model_stub)

            # Generate explicit signature stub
            explicit_stub = f'''
async def {signature_str}:
    """{generator.schema.description or f"Call {generator.name} tool"}"""
    ...
'''
            explicit_stubs_parts.append(explicit_stub)

        # Choose appropriate imports based on client type
        imports = FASTMCP_IMPORTS if client_type == "fastmcp" else HTTP_IMPORTS
        elapsed = time.time() - start_time
        logger.info("Structured code generation completed in %.2fs", elapsed)
        return GeneratedCode(
            models="\n".join(models_parts),
            http_methods="\n".join(http_methods_parts),
            clean_methods="\n".join(clean_methods_parts),
            model_stubs="\n".join(model_stubs_parts),
            explicit_stubs="\n".join(explicit_stubs_parts),
            imports=imports,
        )

    def generate_code(
        self,
        base_url: str = "http://localhost:8000",
        path_prefix: str = "/tools",
        args_format: ArgsFormat = "explicit",
        output_type: OutputType = "implementation",
    ) -> str:
        """Generate HTTP client code with specified format and type.

        Args:
            base_url: Base URL of the tool server
            path_prefix: Path prefix for routes
            args_format: Format for function arguments
            output_type: Type of output to generate

        Returns:
            Generated client code
        """
        structured_code = self.generate_structured_code(base_url, path_prefix)
        return structured_code.get_client_code(args_format, output_type)

    def generate_mcp_code(
        self,
        server_configs: dict[str, str],
        args_format: ArgsFormat = "explicit",
        output_type: OutputType = "implementation",
    ) -> str:
        """Generate complete FastMCP client code with tools.

        Args:
            server_configs: FastMCP server configurations mapping server names to
                           transport URLs
                           e.g., {"github": "sse://localhost:8080/github"}
            args_format: Format for function arguments
            output_type: Type of output to generate

        Returns:
            Complete FastMCP client code
        """
        # Generate structured code with FastMCP client type
        structured = self.generate_structured_code(client_type="fastmcp")
        # Get FastMCP client code
        mcp_client_code = self.get_fastmcp_client_code(server_configs)
        # Get the appropriate client code based on format/type
        tools_code = structured.get_client_code(args_format, output_type, client_type="fastmcp")
        # Combine client and tools code
        return f"""{FASTMCP_IMPORTS}
{mcp_client_code}

{tools_code}"""

    def add_all_routes(self, app: FastAPI, path_prefix: str = "/tools") -> None:
        """Add FastAPI routes for all tools."""
        for generator in self.generators:
            generator.add_route_to_app(app, path_prefix)

generators instance-attribute

generators: Sequence[ToolCodeGenerator]

ToolCodeGenerator instances for each tool.

include_docstrings class-attribute instance-attribute

include_docstrings: bool = True

Include function docstrings in documentation.

add_all_routes

add_all_routes(app: FastAPI, path_prefix: str = '/tools') -> None

Add FastAPI routes for all tools.

Source code in src/schemez/code_generation/toolset_code_generator.py
def add_all_routes(self, app: FastAPI, path_prefix: str = "/tools") -> None:
    """Add FastAPI routes for all tools."""
    for generator in self.generators:
        generator.add_route_to_app(app, path_prefix)

from_callables classmethod

from_callables(
    callables: Sequence[Callable[..., Any]],
    include_docstrings: bool = True,
    exclude_types: list[type] | None = None,
) -> ToolsetCodeGenerator

Create a ToolsetCodeGenerator from a sequence of callables.

Source code in src/schemez/code_generation/toolset_code_generator.py
@classmethod
def from_callables(
    cls,
    callables: Sequence[Callable[..., Any]],
    include_docstrings: bool = True,
    exclude_types: list[type] | None = None,
) -> ToolsetCodeGenerator:
    """Create a ToolsetCodeGenerator from a sequence of callables."""
    gens = [ToolCodeGenerator.from_callable(i, exclude_types=exclude_types) for i in callables]
    return cls(gens, include_docstrings)

from_schemas classmethod

from_schemas(
    schemas: Sequence[FunctionSchema], include_docstrings: bool = True
) -> ToolsetCodeGenerator

Create a ToolsetCodeGenerator from schemas only (no execution capability).

Source code in src/schemez/code_generation/toolset_code_generator.py
@classmethod
def from_schemas(
    cls,
    schemas: Sequence[FunctionSchema],
    include_docstrings: bool = True,
) -> ToolsetCodeGenerator:
    """Create a ToolsetCodeGenerator from schemas only (no execution capability)."""
    generators = [ToolCodeGenerator.from_schema(schema) for schema in schemas]
    return cls(generators, include_docstrings)

generate_code

generate_code(
    base_url: str = "http://localhost:8000",
    path_prefix: str = "/tools",
    args_format: ArgsFormat = "explicit",
    output_type: OutputType = "implementation",
) -> str

Generate HTTP client code with specified format and type.

Parameters:

Name Type Description Default
base_url str

Base URL of the tool server

'http://localhost:8000'
path_prefix str

Path prefix for routes

'/tools'
args_format ArgsFormat

Format for function arguments

'explicit'
output_type OutputType

Type of output to generate

'implementation'

Returns:

Type Description
str

Generated client code

Source code in src/schemez/code_generation/toolset_code_generator.py
def generate_code(
    self,
    base_url: str = "http://localhost:8000",
    path_prefix: str = "/tools",
    args_format: ArgsFormat = "explicit",
    output_type: OutputType = "implementation",
) -> str:
    """Generate HTTP client code with specified format and type.

    Args:
        base_url: Base URL of the tool server
        path_prefix: Path prefix for routes
        args_format: Format for function arguments
        output_type: Type of output to generate

    Returns:
        Generated client code
    """
    structured_code = self.generate_structured_code(base_url, path_prefix)
    return structured_code.get_client_code(args_format, output_type)

generate_execution_namespace

generate_execution_namespace() -> dict[str, Any]

Build Python namespace with tool functions and generated models.

Raises:

Type Description
ValueError

If any generator lacks a callable

Source code in src/schemez/code_generation/toolset_code_generator.py
def generate_execution_namespace(self) -> dict[str, Any]:
    """Build Python namespace with tool functions and generated models.

    Raises:
        ValueError: If any generator lacks a callable
    """
    namespace: dict[str, Any] = {"__builtins__": __builtins__, "_result": None}
    # Add tool functions - all generators must have callables for execution
    for generator in self.generators:
        namespace[generator.name] = NamespaceCallable.from_generator(generator)
    # Add generated model classes to namespace
    if models_code := self.generate_return_models():
        with contextlib.suppress(Exception):
            exec(models_code, namespace)
    return namespace

generate_mcp_code

generate_mcp_code(
    server_configs: dict[str, str],
    args_format: ArgsFormat = "explicit",
    output_type: OutputType = "implementation",
) -> str

Generate complete FastMCP client code with tools.

Parameters:

Name Type Description Default
server_configs dict[str, str]

FastMCP server configurations mapping server names to transport URLs e.g., {"github": "sse://localhost:8080/github"}

required
args_format ArgsFormat

Format for function arguments

'explicit'
output_type OutputType

Type of output to generate

'implementation'

Returns:

Type Description
str

Complete FastMCP client code

Source code in src/schemez/code_generation/toolset_code_generator.py
    def generate_mcp_code(
        self,
        server_configs: dict[str, str],
        args_format: ArgsFormat = "explicit",
        output_type: OutputType = "implementation",
    ) -> str:
        """Generate complete FastMCP client code with tools.

        Args:
            server_configs: FastMCP server configurations mapping server names to
                           transport URLs
                           e.g., {"github": "sse://localhost:8080/github"}
            args_format: Format for function arguments
            output_type: Type of output to generate

        Returns:
            Complete FastMCP client code
        """
        # Generate structured code with FastMCP client type
        structured = self.generate_structured_code(client_type="fastmcp")
        # Get FastMCP client code
        mcp_client_code = self.get_fastmcp_client_code(server_configs)
        # Get the appropriate client code based on format/type
        tools_code = structured.get_client_code(args_format, output_type, client_type="fastmcp")
        # Combine client and tools code
        return f"""{FASTMCP_IMPORTS}
{mcp_client_code}

{tools_code}"""

generate_return_models

generate_return_models() -> str

Generate Pydantic models for tool return types.

Source code in src/schemez/code_generation/toolset_code_generator.py
def generate_return_models(self) -> str:
    """Generate Pydantic models for tool return types."""
    model_parts = [c for g in self.generators if (c := g.generate_return_model())]
    return "\n\n".join(model_parts) if model_parts else ""

generate_structured_code

generate_structured_code(
    base_url: str = "http://localhost:8000",
    path_prefix: str = "/tools",
    client_type: ClientType = "http",
) -> GeneratedCode

Generate structured code with all components.

Parameters:

Name Type Description Default
base_url str

Base URL of the tool server (HTTP) or server name (FastMCP)

'http://localhost:8000'
path_prefix str

Path prefix for routes (HTTP only)

'/tools'
client_type ClientType

Type of client to generate ("http" or "fastmcp")

'http'

Returns:

Type Description
GeneratedCode

GeneratedCode with all components separated

Source code in src/schemez/code_generation/toolset_code_generator.py
    def generate_structured_code(
        self,
        base_url: str = "http://localhost:8000",
        path_prefix: str = "/tools",
        client_type: ClientType = "http",
    ) -> GeneratedCode:
        """Generate structured code with all components.

        Args:
            base_url: Base URL of the tool server (HTTP) or server name (FastMCP)
            path_prefix: Path prefix for routes (HTTP only)
            client_type: Type of client to generate ("http" or "fastmcp")

        Returns:
            GeneratedCode with all components separated
        """
        start_time = time.time()
        logger.info("Starting structured code generation")

        models_parts: list[str] = []
        http_methods_parts: list[str] = []
        clean_methods_parts: list[str] = []
        model_stubs_parts: list[str] = []
        explicit_stubs_parts: list[str] = []

        for generator in self.generators:
            # Generate input model from schema parameters
            input_class_name = None
            try:
                params = generator.schema.parameters
                if params.get("properties"):
                    words = [word.title() for word in generator.name.split("_")]
                    input_class_name = f"{''.join(words)}Input"
                    if model_code := model_to_python_code(params, class_name=input_class_name):
                        cleaned_model = clean_generated_code(model_code)
                        models_parts.append(cleaned_model)
            except ValueError, TypeError, AttributeError:
                input_class_name = None

            # Generate client method with model
            if input_class_name:
                if client_type == "fastmcp":
                    http_method = f'''
async def {generator.name}(input: {input_class_name}) -> Any:
    """{generator.schema.description or f"Call {generator.name} tool"}

    Args:
        input: Function parameters

    Returns:
        Result from the MCP server
    """
    result = await call_mcp_tool("{base_url}", "{generator.name}", input.model_dump())
    return result
'''
                else:
                    http_method = f'''
async def {generator.name}(input: {input_class_name}) -> str:
    """{generator.schema.description or f"Call {generator.name} tool"}

    Args:
        input: Function parameters

    Returns:
        String response from the tool server
    """
    async with httpx2.AsyncClient() as client:
        response = await client.get(
            "{base_url}{path_prefix}/{generator.name}",
            params=input.model_dump() if hasattr(input, 'model_dump') else {{}},
            timeout=30.0
        )
        response.raise_for_status()
        return response.text
'''
            elif client_type == "fastmcp":
                http_method = f'''
async def {generator.name}() -> Any:
    """{generator.schema.description or f"Call {generator.name} tool"}

    Returns:
        Result from the MCP server
    """
    result = await call_mcp_tool("{base_url}", "{generator.name}", {{}})
    return result
'''
            else:
                http_method = f'''
async def {generator.name}() -> str:
    """{generator.schema.description or f"Call {generator.name} tool"}

    Returns:
        String response from the tool server
    """
    async with httpx2.AsyncClient() as client:
        response = await client.get(
            "{base_url}{path_prefix}/{generator.name}",
            timeout=30.0
        )
        response.raise_for_status()
        return response.text
'''
            http_methods_parts.append(http_method)
            # Generate clean method with natural signature
            signature_str = generator.get_function_signature()
            params = generator.schema.parameters
            param_names = list(params.get("properties", {}).keys())
            if client_type == "fastmcp":
                clean_method = f'''
async def {signature_str}:
    """{generator.schema.description or f"Call {generator.name} tool"}"""
    # Build parameters dict
    params = {{{", ".join(f'"{name}": {name}' for name in param_names)}}}
    # Remove None values
    clean_params = {{k: v for k, v in params.items() if v is not None}}

    result = await call_mcp_tool("{base_url}", "{generator.name}", clean_params)
    return result
'''
            else:
                clean_method = f'''
async def {signature_str}:
    """{generator.schema.description or f"Call {generator.name} tool"}"""
    # Build parameters dict
    params = {{{", ".join(f'"{name}": {name}' for name in param_names)}}}
    # Remove None values
    clean_params = {{k: v for k, v in params.items() if v is not None}}

    async with httpx2.AsyncClient() as client:
        response = await client.get(
            "{base_url}{path_prefix}/{generator.name}",
            params=clean_params,
            timeout=30.0
        )
        response.raise_for_status()
        # Parse JSON response and return the result
        result = response.json()
        return result.get("result", response.text)
'''
            clean_methods_parts.append(clean_method)
            # Generate model-based stub
            if input_class_name:
                model_stub = f'''
async def {generator.name}(input: {input_class_name}) -> Any:
    """{generator.schema.description or f"Call {generator.name} tool"}

    Args:
        input: Function parameters

    Returns:
        Function result
    """
    ...
'''
                model_stubs_parts.append(model_stub)

            # Generate explicit signature stub
            explicit_stub = f'''
async def {signature_str}:
    """{generator.schema.description or f"Call {generator.name} tool"}"""
    ...
'''
            explicit_stubs_parts.append(explicit_stub)

        # Choose appropriate imports based on client type
        imports = FASTMCP_IMPORTS if client_type == "fastmcp" else HTTP_IMPORTS
        elapsed = time.time() - start_time
        logger.info("Structured code generation completed in %.2fs", elapsed)
        return GeneratedCode(
            models="\n".join(models_parts),
            http_methods="\n".join(http_methods_parts),
            clean_methods="\n".join(clean_methods_parts),
            model_stubs="\n".join(model_stubs_parts),
            explicit_stubs="\n".join(explicit_stubs_parts),
            imports=imports,
        )

generate_tool_description

generate_tool_description() -> str

Generate comprehensive tool description with available functions.

Source code in src/schemez/code_generation/toolset_code_generator.py
def generate_tool_description(self) -> str:
    """Generate comprehensive tool description with available functions."""
    if not self.generators:
        return "Execute Python code (no tools available)"

    parts = ["Available functions:"]
    for generator in self.generators:
        desc = generator.get_function_definition(self.include_docstrings)
        parts.append(desc)
    return "\n".join(parts)

get_fastmcp_client_code

get_fastmcp_client_code(server_configs: dict[str, str]) -> str

Generate FastMCP client code with connection management.

Parameters:

Name Type Description Default
server_configs dict[str, str]

Dict mapping server names to their transport URLs e.g., {"github": "sse://localhost:8080/github"}

required

Returns:

Type Description
str

FastMCP client code as string

Source code in src/schemez/code_generation/toolset_code_generator.py
    def get_fastmcp_client_code(self, server_configs: dict[str, str]) -> str:
        """Generate FastMCP client code with connection management.

        Args:
            server_configs: Dict mapping server names to their transport URLs
                          e.g., {"github": "sse://localhost:8080/github"}

        Returns:
            FastMCP client code as string
        """
        server_config_code = "SERVERS = " + repr(server_configs)
        return f'''{server_config_code}

# Connection management
_clients: dict[str, Client] = {{}}

async def get_mcp_client(server_name: str) -> Client:
    """Get or create FastMCP client for server."""
    if server_name not in _clients:
        if server_name not in SERVERS:
            raise ValueError(f"Unknown MCP server: {{server_name}}")

        transport_url = SERVERS[server_name]
        client = Client(transport_url)
        _clients[server_name] = client

    return _clients[server_name]

async def call_mcp_tool(
    server_name: str, tool_name: str, arguments: dict[str, Any]
) -> Any:
    """Call a FastMCP tool and return the result."""
    client = await get_mcp_client(server_name)

    async with client:
        result = await client.call_tool(tool_name, arguments)

        # FastMCP returns CallToolResult with structured content handling
        if result.data is not None:
            return result.data  # Parsed structured content
        elif result.content:
            # Extract text from content blocks
            text_parts = []
            for content_block in result.content:
                if hasattr(content_block, 'text'):
                    text_parts.append(content_block.text)
            return "\\n".join(text_parts) if text_parts else ""

        return ""

async def close_all_mcp_connections():
    """Close all MCP client connections."""
    for server_name, client in _clients.items():
        try:
            await client.close()
        except Exception as e:
            print(f"Error closing connection to {{server_name}}: {{e}}")
    _clients.clear()
'''

YAMLCode

Bases: BaseCode

YAML with syntax validation.

Source code in src/schemez/code.py
class YAMLCode(BaseCode):
    """YAML with syntax validation."""

    @field_validator("code")
    @classmethod
    def validate_syntax(cls, code: str) -> str:
        import yamling

        try:
            yamling.load(code, mode="yaml")
        except yamling.ParsingError as e:
            msg = f"Invalid YAML syntax: {e}"
            raise ValueError(msg) from e
        else:
            return code

create_constructor_schema

create_constructor_schema(cls: type) -> FunctionSchema

Create OpenAI function schema from class constructor.

Parameters:

Name Type Description Default
cls type

Class to create schema for

required

Returns:

Type Description
FunctionSchema

OpenAI function schema for class constructor

Source code in src/schemez/functionschema/schema_generators.py
def create_constructor_schema(cls: type) -> FunctionSchema:
    """Create OpenAI function schema from class constructor.

    Args:
        cls: Class to create schema for

    Returns:
        OpenAI function schema for class constructor
    """
    if isinstance(cls, type) and issubclass(cls, pydantic.BaseModel):
        properties = {}
        required = []
        for name, field in cls.model_fields.items():
            param_type = field.annotation
            properties[name] = resolve_type_annotation(
                param_type,
                description=field.description,
                default=field.default,
            )
            if field.is_required():
                required.append(name)

    # Handle dataclasses
    elif dataclasses.is_dataclass(cls):
        properties = {}
        required = []
        dc_fields = dataclasses.fields(cls)
        hints = get_resolved_hints(cls, include_extras=False)

        for dc_field in dc_fields:
            param_type = hints[dc_field.name]
            properties[dc_field.name] = resolve_type_annotation(
                param_type, default=dc_field.default
            )
            if (
                dc_field.default is dataclasses.MISSING
                and dc_field.default_factory is dataclasses.MISSING
            ):
                required.append(dc_field.name)

    # Handle regular classes
    else:
        sig = get_signature(cls.__init__)
        hints = get_resolved_hints(cls.__init__, include_extras=False)
        properties = {}
        required = []

        for name, param in sig.parameters.items():
            if name == "self":
                continue

            param_type = hints.get(name, Any)
            properties[name] = resolve_type_annotation(
                param_type,
                default=param.default,
            )

            if param.default is param.empty:
                required.append(name)

    name = f"create_{cls.__name__}"
    description = inspect.getdoc(cls) or f"Create {cls.__name__} instance"

    # Create parameters with required list included
    params = ToolParameters({
        "type": "object",
        "properties": properties,
        "required": required,
    })

    return FunctionSchema(name=name, description=description, parameters=params, required=required)

create_executable

create_executable(func: Callable[..., Generator[T_co]]) -> ExecutableFunction[T_co]
create_executable(func: Callable[..., AsyncGenerator[T_co]]) -> ExecutableFunction[T_co]
create_executable(func: Callable[..., T_co]) -> ExecutableFunction[T_co]
create_executable(
    func: (
        Callable[..., T_co] | Callable[..., Generator[T_co]] | Callable[..., AsyncGenerator[T_co]]
    ),
) -> ExecutableFunction[T_co]

Create an executable function wrapper with schema.

Parameters:

Name Type Description Default
func Callable[..., T_co] | Callable[..., Generator[T_co]] | Callable[..., AsyncGenerator[T_co]]

Function to wrap

required

Returns:

Type Description
ExecutableFunction[T_co]

Executable wrapper with schema

Source code in src/schemez/functionschema/executable.py
def create_executable[T_co](
    func: (
        Callable[..., T_co] | Callable[..., Generator[T_co]] | Callable[..., AsyncGenerator[T_co]]
    ),
) -> ExecutableFunction[T_co]:
    """Create an executable function wrapper with schema.

    Args:
        func: Function to wrap

    Returns:
        Executable wrapper with schema
    """
    schema = create_schema(func)
    return ExecutableFunction[T_co](schema, func)

create_schema

create_schema(
    func: Callable[..., Any],
    name_override: str | None = None,
    description_override: str | None = None,
    exclude_types: list[type] | None = None,
    mode: SchemaType = "simple",
) -> FunctionSchema

Create an OpenAI function schema from a Python function.

If an iterator is passed, the schema return type is a list of the iterator's element type. Variable arguments (*args) and keyword arguments (**kwargs) are not supported in OpenAI function schemas and will be ignored with a warning.

Parameters:

Name Type Description Default
func Callable[..., Any]

Function to create schema for

required
name_override str | None

Optional name override (otherwise the function name)

None
description_override str | None

Optional description override (otherwise the function docstring)

None
exclude_types list[type] | None

Types to exclude from parameters (e.g., context types)

None
mode SchemaType

Schema generation mode - simple" (default) uses custom simple implementation, - "openai" for OpenAI function calling via Pydantic, - "jsonschema" for standard JSON schema via Pydantic

'simple'
Source code in src/schemez/functionschema/functionschema.py
def create_schema(
    func: Callable[..., Any],
    name_override: str | None = None,
    description_override: str | None = None,
    exclude_types: list[type] | None = None,
    mode: SchemaType = "simple",
) -> FunctionSchema:
    """Create an OpenAI function schema from a Python function.

    If an iterator is passed, the schema return type is a list of the iterator's
    element type.
    Variable arguments (*args) and keyword arguments (**kwargs) are not
    supported in OpenAI function schemas and will be ignored with a warning.

    Args:
        func: Function to create schema for
        name_override: Optional name override (otherwise the function name)
        description_override: Optional description override
                              (otherwise the function docstring)
        exclude_types: Types to exclude from parameters (e.g., context types)
        mode: Schema generation mode
              - simple" (default) uses custom simple implementation,
              - "openai" for OpenAI function calling via Pydantic,
              - "jsonschema" for standard JSON schema via Pydantic
    """
    exclude_types = exclude_types or []
    if mode == "simple":
        return _create_schema_simple(func, name_override, description_override, exclude_types)
    return _create_schema_pydantic(
        func,
        name_override,
        description_override,
        exclude_types,
        use_openai_format=mode == "openai",
    )

create_schemas_from_callables

create_schemas_from_callables(
    callables: dict[str, Callable[..., Any]],
    prefix: str | Literal[False] | None = None,
    exclude_private: bool = True,
) -> dict[str, FunctionSchema]

Generate OpenAI function schemas from a dictionary of callables.

Parameters:

Name Type Description Default
callables dict[str, Callable[..., Any]]

Dictionary mapping names to callable objects

required
prefix str | Literal[False] | None

Schema name prefix to prepend to function names. If None, no prefix. If False, use raw name. If string, uses that prefix.

None
exclude_private bool

Whether to exclude callables starting with underscore

True

Returns:

Type Description
dict[str, FunctionSchema]

Dictionary mapping qualified names to FunctionSchema objects

Example

def foo(x: int) -> str: ... def bar(y: float) -> int: ... callables = {'foo': foo, 'bar': bar} schemas = create_schemas_from_callables(callables, prefix='math') print(schemas['math.foo'])

Source code in src/schemez/functionschema/schema_generators.py
def create_schemas_from_callables(
    callables: dict[str, Callable[..., Any]],
    prefix: str | Literal[False] | None = None,
    exclude_private: bool = True,
) -> dict[str, FunctionSchema]:
    """Generate OpenAI function schemas from a dictionary of callables.

    Args:
        callables: Dictionary mapping names to callable objects
        prefix: Schema name prefix to prepend to function names.
               If None, no prefix. If False, use raw name.
               If string, uses that prefix.
        exclude_private: Whether to exclude callables starting with underscore

    Returns:
        Dictionary mapping qualified names to FunctionSchema objects

    Example:
        >>> def foo(x: int) -> str: ...
        >>> def bar(y: float) -> int: ...
        >>> callables = {'foo': foo, 'bar': bar}
        >>> schemas = create_schemas_from_callables(callables, prefix='math')
        >>> print(schemas['math.foo'])
    """
    schemas = {}
    for name, callable_obj in callables.items():
        if exclude_private and name.startswith("_"):  # Skip private members if requested
            continue
        # Generate schema key based on prefix setting
        key = name if prefix is False else f"{prefix}.{name}" if prefix else name
        schemas[key] = create_schema(callable_obj)
    return schemas

create_schemas_from_class

create_schemas_from_class(
    cls: type, prefix: str | Literal[False] | None = None
) -> dict[str, FunctionSchema]

Generate OpenAI function schemas for all public methods in a class.

Parameters:

Name Type Description Default
cls type

The class to generate schemas from

required
prefix str | Literal[False] | None

Schema name prefix. If None, uses class name. If False, no prefix. If string, uses that prefix.

None

Returns:

Type Description
dict[str, FunctionSchema]

Dictionary mapping qualified method names to FunctionSchema objects

Example

class MyClass: ... def my_method(self, x: int) -> str: ... return str(x) schemas = create_schemas_from_class(MyClass) print(schemas['MyClass.my_method'])

Source code in src/schemez/functionschema/schema_generators.py
def create_schemas_from_class(
    cls: type,
    prefix: str | Literal[False] | None = None,
) -> dict[str, FunctionSchema]:
    """Generate OpenAI function schemas for all public methods in a class.

    Args:
        cls: The class to generate schemas from
        prefix: Schema name prefix. If None, uses class name.
               If False, no prefix. If string, uses that prefix.

    Returns:
        Dictionary mapping qualified method names to FunctionSchema objects

    Example:
        >>> class MyClass:
        ...     def my_method(self, x: int) -> str:
        ...         return str(x)
        >>> schemas = create_schemas_from_class(MyClass)
        >>> print(schemas['MyClass.my_method'])
    """
    callables: dict[str, Callable[..., Any]] = {}

    for name, attr in inspect.getmembers(cls):  # Get all attributes of the class
        if inspect.isfunction(attr) or inspect.ismethod(attr):
            callables[name] = attr
        elif isinstance(attr, classmethod | staticmethod):
            callables[name] = attr.__get__(None, cls)

    # Use default prefix of class name if not specified
    effective_prefix = cls.__name__ if prefix is None else prefix
    return create_schemas_from_callables(callables, prefix=effective_prefix)

create_schemas_from_module

create_schemas_from_module(
    module: ModuleType | str,
    include_functions: list[str] | None = None,
    prefix: str | Literal[False] | None = None,
) -> dict[str, FunctionSchema]

Generate OpenAI function schemas from a Python module's functions.

Parameters:

Name Type Description Default
module ModuleType | str

Either a ModuleType object or string name of module to analyze

required
include_functions list[str] | None

Optional list of function names to specifically include

None
prefix str | Literal[False] | None

Schema name prefix. If None, uses module name. If False, no prefix. If string, uses that prefix.

None

Returns:

Type Description
dict[str, FunctionSchema]

Dictionary mapping function names to FunctionSchema objects

Raises:

Type Description
ImportError

If module string name cannot be imported

Example

import math schemas = create_schemas_from_module(math, ['sin', 'cos']) print(schemas['math.sin'])

Source code in src/schemez/functionschema/schema_generators.py
def create_schemas_from_module(
    module: types.ModuleType | str,
    include_functions: list[str] | None = None,
    prefix: str | Literal[False] | None = None,
) -> dict[str, FunctionSchema]:
    """Generate OpenAI function schemas from a Python module's functions.

    Args:
        module: Either a ModuleType object or string name of module to analyze
        include_functions: Optional list of function names to specifically include
        prefix: Schema name prefix. If None, uses module name.
                If False, no prefix. If string, uses that prefix.

    Returns:
        Dictionary mapping function names to FunctionSchema objects

    Raises:
        ImportError: If module string name cannot be imported

    Example:
        >>> import math
        >>> schemas = create_schemas_from_module(math, ['sin', 'cos'])
        >>> print(schemas['math.sin'])
    """
    # Resolve module if string name provided
    mod = module if isinstance(module, types.ModuleType) else importlib.import_module(module)

    # Get all functions from module
    callables: dict[str, Callable[..., Any]] = {
        name: func
        for name, func in inspect.getmembers(mod, predicate=inspect.isfunction)
        if include_functions is None
        or (name in include_functions and func.__module__.startswith(mod.__name__))
    }

    # Use default prefix of module name if not specified
    effective_prefix = mod.__name__ if prefix is None else prefix
    return create_schemas_from_callables(callables, prefix=effective_prefix)

jsonschema_to_code

jsonschema_to_code(
    schema_json: str, class_name: str | None = None, input_path: str | None = None
) -> str

Generate Pydantic model code from a JSON schema.

Source code in src/schemez/helpers.py
def jsonschema_to_code(
    schema_json: str,
    class_name: str | None = None,
    input_path: str | None = None,
) -> str:
    """Generate Pydantic model code from a JSON schema."""
    from datamodel_code_generator import LiteralType, PythonVersion
    from datamodel_code_generator.enums import DataModelType
    from datamodel_code_generator.model import get_data_model_types
    from datamodel_code_generator.parser.jsonschema import JsonSchemaParser

    data_model_types = get_data_model_types(
        DataModelType.PydanticV2BaseModel,
        target_python_version=PythonVersion.PY_312,
    )
    parser = JsonSchemaParser(
        source=schema_json,
        data_model_type=data_model_types.data_model,
        data_model_root_type=data_model_types.root_model,
        data_model_field_type=data_model_types.field_model,
        data_type_manager_type=data_model_types.data_type_manager,
        dump_resolve_reference_action=data_model_types.dump_resolve_reference_action,
        class_name=class_name or (input_path or "DefaultClass").split(".")[-1],
        use_union_operator=True,
        use_schema_description=True,
        enum_field_as_literal=LiteralType.All,
    )
    return str(parser.parse())

models_to_markdown_docs

models_to_markdown_docs(
    *models: type[BaseModel],
    header_level: int = 2,
    expand_mode: Literal["minimal", "maximal", "default"] = "default",
    seed: int = 0,
    validate: bool = False,
    exclude_none: bool = True,
    exclude_defaults: bool = False,
    exclude_unset: bool = False,
    indent: int = 2,
    sort_keys: bool = True
) -> str

Generate markdown documentation with commented YAML examples for BaseModel classes.

Creates markdown chapters for each model with: - Model name as header - Model docstring - Commented YAML example with test data

Parameters:

Name Type Description Default
models type[BaseModel]

One or more BaseModel classes to document

()
header_level int

Starting header level (2 = h2, 3 = h3, etc.)

2
expand_mode Literal['minimal', 'maximal', 'default']

YAML generation mode - "minimal", "maximal", or "default"

'default'
seed int

Seed for deterministic YAML generation

0
validate bool

Whether to validate the generated test data

False
exclude_none bool

Exclude fields with None values in YAML

True
exclude_defaults bool

Exclude fields with default values in YAML

False
exclude_unset bool

Exclude fields that are not set in YAML

False
indent int

Indentation level for YAML output

2
sort_keys bool

Sort keys in the YAML output

True

Returns:

Type Description
str

Markdown string with chapters for each model

Example
from pydantic import BaseModel, Field

class Person(BaseModel):
    '''A person with basic information.'''

    name: str = Field(description='Full name')
    age: int = Field(description='Age in years')
    email: str | None = Field(default=None, description='Email address')

class Company(BaseModel):
    '''A company entity.'''

    name: str = Field(description='Company name')
    founded: int = Field(description='Year founded')

# Generate documentation
docs = models_to_markdown_docs(Person, Company)
print(docs)

Output:

## Person

A person with basic information.

```yaml
age: 0  # Age in years
name: a  # Full name

Company

A company entity.

founded: 0  # Year founded
name: a  # Company name
```

Source code in src/schemez/helpers.py
def models_to_markdown_docs(
    *models: type[BaseModel],
    header_level: int = 2,
    expand_mode: Literal["minimal", "maximal", "default"] = "default",
    seed: int = 0,
    validate: bool = False,
    exclude_none: bool = True,
    exclude_defaults: bool = False,
    exclude_unset: bool = False,
    indent: int = 2,
    sort_keys: bool = True,
) -> str:
    """Generate markdown documentation with commented YAML examples for BaseModel classes.

    Creates markdown chapters for each model with:
    - Model name as header
    - Model docstring
    - Commented YAML example with test data

    Args:
        models: One or more BaseModel classes to document
        header_level: Starting header level (2 = h2, 3 = h3, etc.)
        expand_mode: YAML generation mode - "minimal", "maximal", or "default"
        seed: Seed for deterministic YAML generation
        validate: Whether to validate the generated test data
        exclude_none: Exclude fields with None values in YAML
        exclude_defaults: Exclude fields with default values in YAML
        exclude_unset: Exclude fields that are not set in YAML
        indent: Indentation level for YAML output
        sort_keys: Sort keys in the YAML output

    Returns:
        Markdown string with chapters for each model

    Example:
        ```python
        from pydantic import BaseModel, Field

        class Person(BaseModel):
            '''A person with basic information.'''

            name: str = Field(description='Full name')
            age: int = Field(description='Age in years')
            email: str | None = Field(default=None, description='Email address')

        class Company(BaseModel):
            '''A company entity.'''

            name: str = Field(description='Company name')
            founded: int = Field(description='Year founded')

        # Generate documentation
        docs = models_to_markdown_docs(Person, Company)
        print(docs)
        ```

        Output:
        ```markdown
        ## Person

        A person with basic information.

        ```yaml
        age: 0  # Age in years
        name: a  # Full name
        ```

        ## Company

        A company entity.

        ```yaml
        founded: 0  # Year founded
        name: a  # Company name
        ```
        ```
    """
    from schemez.commented_yaml import create_yaml_description

    sections = []
    header_prefix = "#" * header_level

    for model in models:
        model_name = model.__name__
        model_doc = model.__doc__ or ""
        model_doc = model_doc.strip()

        yaml_example = create_yaml_description(
            model,
            exclude_none=exclude_none,
            exclude_defaults=exclude_defaults,
            exclude_unset=exclude_unset,
            indent=indent,
            comments=True,
            sort_keys=sort_keys,
            validate=validate,
            expand_mode=expand_mode,
        )

        section = f"{header_prefix} {model_name}\n\n"
        if model_doc:
            section += f"{model_doc}\n\n"
        section += f"```yaml\n{yaml_example}\n```"

        sections.append(section)

    return "\n\n".join(sections)

openapi_to_code

openapi_to_code(input_path: str, class_name: str | None = None) -> str

Generate Pydantic model code from an OpenAPI specification URL.

Source code in src/schemez/helpers.py
def openapi_to_code(input_path: str, class_name: str | None = None) -> str:
    """Generate Pydantic model code from an OpenAPI specification URL."""
    from datamodel_code_generator import LiteralType, PythonVersion
    from datamodel_code_generator.enums import DataModelType
    from datamodel_code_generator.model import get_data_model_types
    from datamodel_code_generator.parser.openapi import OpenAPIParser

    data_model_types = get_data_model_types(
        DataModelType.PydanticV2BaseModel,
        target_python_version=PythonVersion.PY_312,
    )
    parser = OpenAPIParser(
        source=input_path,
        data_model_type=data_model_types.data_model,
        data_model_root_type=data_model_types.root_model,
        data_model_field_type=data_model_types.field_model,
        data_type_manager_type=data_model_types.data_type_manager,
        dump_resolve_reference_action=data_model_types.dump_resolve_reference_action,
        class_name=class_name,
        use_union_operator=True,
        use_schema_description=True,
        enum_field_as_literal=LiteralType.All,
    )
    return str(parser.parse())