Skip to main content

Schemez

PyPI License Package status Monthly downloads Distribution format Wheel availability Python version Implementation Releases Github Contributors Github Forks Github Issues Github Issues Github Watchers Github Stars Github Repository size Github last commit Github release date Github language count Github commits this month Package status PyUp

Read the documentation!

Schemez is a Pydantic toolkit for turning Python code into schemas and schemas into code. It builds OpenAI-compatible tool schemas from function signatures, creates Pydantic models from JSON Schema, generates HTTP/MCP client code and FastAPI routes for tools, and gives your config models YAML, markdown and test-data helpers.

Installation

pip install schemez

Optional extras enable individual features:

Extra Enables
yaml Schema.from_yaml(), Schema.model_dump_yaml()
codegen Schema.from_json_schema(), FunctionSchema.to_parameter_model_code(), jsonschema_to_code(), openapi_to_code()
tool_execution FastAPI routes and the HTTP tool server
storage ModelStore (async SQLite storage)
markdown Jinja templates for markdown docs
ai Schema.from_llm(), create_schema(..., mode="openai"), schemez.openapi
pip install "schemez[yaml,codegen]"

Quick start

from typing import Literal

from schemez import create_schema


def search_users(
    query: str,
    limit: int = 10,
    status: Literal["active", "inactive"] = "active",
) -> list[dict]:
    """Search for users.

    Args:
        query: Search query string
        limit: Maximum number of results
        status: User status filter
    """
    return []


schema = create_schema(search_users)
schema.name  # "search_users"
schema.description  # "Search for users."
schema.parameters["properties"]["status"]
# {'type': 'string', 'description': 'User status filter',
#  'enum': ['active', 'inactive'], 'default': 'active'}

schema.model_dump_openai()  # {"type": "function", "function": {...}}
schema.to_python_signature()
# (*, query: str, limit: int = 10, status: Literal['active', 'inactive'] = 'active') -> list[typing.Any]

Features

Function schemas

create_schema() returns a FunctionSchema (name, description, parameters, required, returns) built from type hints and docstrings (Google, NumPy and Sphinx styles).

  • model_dump_openai(): OpenAI function-calling tool definition
  • to_python_signature(), get_annotations(): reconstruct the signature
  • create_parameter_model(): Pydantic model for the parameters
  • to_parameter_model_code() / to_return_model_code(): Python source for those models (codegen extra)
  • create_schema(func, exclude_types=[Context]) drops parameters of the given types (e.g. injected context objects); name_override / description_override replace name and docstring.
  • mode="simple" (default) produces compact, LLM-friendly schemas: unions collapse to their first type, enums become plain value lists. mode="jsonschema" keeps Pydantic's full JSON Schema (anyOf, $defs), mode="openai" uses pydantic-ai's tool schema generator.

Bulk helpers: create_schemas_from_callables({"name": func, ...}), create_schemas_from_class(cls), create_schemas_from_module(module, include_functions=[...]) and create_constructor_schema(cls).

create_executable(func) wraps a function together with its schema and runs sync, async and (async) generator functions uniformly via run(), arun() and astream().

Schema base model

Schema is a pydantic.BaseModel with extra="forbid" and attribute docstrings as field descriptions, plus helpers:

from schemez import Schema


class DatabaseConfig(Schema):
    host: str = "localhost"
    """Database host."""

    port: int = 5432
    """Database port."""


class AppConfig(Schema):
    name: str
    database: DatabaseConfig = DatabaseConfig()


config = AppConfig.from_yaml("name: my-app\ndatabase:\n  port: 6543\n")
print(config.model_dump_yaml(comments=True))
# database:
#   host: localhost  # Database host.
#   port: 6543  # Database port.
# name: my-app

config.model_dump_markdown()  # markdown table documenting the model and its values
AppConfig.generate_test_data(mode="minimal")  # valid instance generated from the schema

More class methods: Schema.for_function(func) and Schema.for_class_ctor(cls) build models from signatures, Schema.from_json_schema(json_schema) builds one from JSON Schema (codegen extra), to_python_code() emits model source code, and merge() / iter_submodels() work on instances.

JSON Schema and OpenAPI to code

jsonschema_to_code() and openapi_to_code() generate Pydantic model source code (via datamodel-code-generator). SchemaDef (InlineSchemaDef, ImportedSchemaDef) lets you declare models in YAML/JSON config and build them with get_schema().

Tool code generation

ToolsetCodeGenerator turns a set of callables (or FunctionSchemas) into client code, LLM stubs or FastAPI routes:

from fastapi import FastAPI

from schemez import ToolsetCodeGenerator


def get_weather(location: str, unit: str = "C") -> dict:
    """Get weather for a location."""
    return {"temp": 22, "location": location}


generator = ToolsetCodeGenerator.from_callables([get_weather, search_users])

# Async httpx2 client functions calling a tool server
client_code = generator.generate_code(base_url="https://api.example.com", path_prefix="/tools")
# Signatures + docstrings only, for LLM prompts
stubs = generator.generate_code(output_type="stubs")
# Functions taking a generated Pydantic input model instead of keyword arguments
model_based = generator.generate_code(args_format="model")
# Human-readable overview of the available functions
print(generator.generate_tool_description())

# Expose the callables as FastAPI routes: GET /tools/get_weather, GET /tools/search_users
app = FastAPI()
generator.add_all_routes(app, path_prefix="/tools")

ToolsetCodeGenerator.from_schemas([...]) works without implementations (code generation only), generate_mcp_code(server_configs) emits FastMCP client code, and ToolCodeGenerator handles a single tool. schemez.tool_executor.HttpToolExecutor serves tools over HTTP.

Model storage

from pydantic import BaseModel

from schemez import ModelStore


class Note(BaseModel):
    title: str
    tags: list[str] = []


async def main() -> None:
    async with ModelStore(Note, "notes.db") as store:
        note_id = await store.insert(Note(title="hello", tags=["a"]))
        await store.get(note_id)  # Note(title='hello', tags=['a'])
        await store.query(title="hello")

    # Reopen later: the model type is rebuilt from the stored JSON schema
    async with await ModelStore.open("notes.db") as store:
        await store.all()

Markdown documentation

models_to_markdown_docs() renders documentation for several models; the jinjarope entry point registers the markdown helpers as Jinja filters.

Documentation

Full API reference: https://phil65.github.io/schemez/

License

MIT

Metadata

Release files for schemez 2.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for schemez 2.4.0
File Size Uploaded Provenance Actions
schemez-2.4.0.tar.gz 82.9 kB With provenance Details for schemez-2.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for schemez 2.4.0
File Interpreter ABI Platform Actions
schemez-2.4.0-py3-none-any.whl Python 3 none any Details for schemez-2.4.0-py3-none-any.whl

Total release size: 177.8 kB

Release files / schemez-2.4.0.tar.gz

Download URL schemez-2.4.0.tar.gz
Size 82.9 kB
Tags Source
SHA-256 checksum
How to use checksums
f523a17f4a267ebc87aee0fbaa2b775a1ece7857eca524109d498cdcba88d5bf
BLAKE2b-256 checksum
How to use checksums
bf4b70daa093459327708a97acded2253a3899e35787b383e5a02e1aebf931d0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.

Transparency log

Release files / schemez-2.4.0-py3-none-any.whl

Download URL schemez-2.4.0-py3-none-any.whl
Size 94.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
13c6ed5aa9665d4e112959fbe092f00809e9479cb9d2219f2cae9a4a5f5cf07f
BLAKE2b-256 checksum
How to use checksums
9317c2e2ff0438fc9ac5dabea49e63e826be33bd973b7caa924a8e0bd3c69e94
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.

Transparency log

Security for schemez 2.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for schemez-2.4.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

2.4.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page