Schemez
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 definitionto_python_signature(),get_annotations(): reconstruct the signaturecreate_parameter_model(): Pydantic model for the parametersto_parameter_model_code()/to_return_model_code(): Python source for those models (codegenextra)create_schema(func, exclude_types=[Context])drops parameters of the given types (e.g. injected context objects);name_override/description_overridereplace 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.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| schemez-2.3.0.tar.gz | 81.0 kB | With provenance | Details for schemez-2.3.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| schemez-2.3.0-py3-none-any.whl | Python 3 | none | any | Details for schemez-2.3.0-py3-none-any.whl |
Total release size: 173.6 kB
Release files / schemez-2.3.0.tar.gz
| Download URL | schemez-2.3.0.tar.gz |
|---|---|
| Size | 81.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d94a21071b77630d532addd35a0a49551449ca0528490d2bec9f0d855ac6184b
|
|
BLAKE2b-256 checksum How to use checksums |
25354f09f31ea9c0e4e6f16e345439e0171cebfd0360b87ddffbdf522e211a51
|
| 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 logRelease files / schemez-2.3.0-py3-none-any.whl
| Download URL | schemez-2.3.0-py3-none-any.whl |
|---|---|
| Size | 92.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
765459846722353cf63452ea0806999e4bf1723415e52eef3312feaf5b200a5c
|
|
BLAKE2b-256 checksum How to use checksums |
0600b3e58b9c521672da7539a548facd30a72abcd9e3a6f349e40e628c84ac2b
|
| 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 logSecurity for schemez 2.3.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.
Attestation for schemez-2.3.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 logA 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.