Skip to main content

Pydantic shim for config stuff

Project description

Schemez

PyPI License Package status Monthly downloads Distribution format Wheel availability Python version Implementation Releases Github Contributors Github Discussions 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!

A powerful toolkit for Python function schema generation and code generation. Extract schemas from functions, generate OpenAI-compatible tools, create HTTP clients, and set up FastAPI routes - all from your function signatures.

Installation

pip install schemez

Quick Start

from schemez import create_schema

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

# Create schema from function
schema = create_schema(get_weather)
print(schema.name)          # "get_weather"
print(schema.description)   # "Get weather for a location."
print(schema.parameters)    # Full parameter schema

FunctionSchema - The Core

The FunctionSchema class is the heart of schemez, providing a rich representation of Python functions with powerful methods for introspection and code generation.

Schema Creation

from schemez import create_schema
from typing import Literal

def search_users(
    query: str,
    limit: int = 10,
    status: Literal["active", "inactive"] = "active",
    include_details: bool = False
) -> list[dict]:
    """Search for users with filters.
    
    Args:
        query: Search query string
        limit: Maximum number of results
        status: User status filter
        include_details: Include detailed user information
    """
    return []

# Create schema
schema = create_schema(search_users)

Key Methods

schema output

# Get OpenAI-compatible tool definition
openai_tool = schema.model_dump_openai()
# Returns: {"type": "function", "function": {...}}

Code Generation

# Generate Python function signature
signature = schema.to_python_signature()
# Returns: "(*, query: str, limit: int = 10, status: Literal['active', 'inactive'] = 'active', include_details: bool = False) -> list[dict]"

# Generate Pydantic model for return type
model_code = schema.to_pydantic_model_code("SearchResponse")
# Returns Python code string for a Pydantic model

Schema Inspection

# Access schema components
print(schema.name)                    # Function name
print(schema.description)             # Function docstring
print(schema.parameters)              # Parameter schema dict
print(schema.returns)                 # Return type schema
print(schema.get_annotations())       # Python type annotations

Bulk Schema Generation

from schemez.schema_generators import (
    create_schemas_from_module,
    create_schemas_from_class,
    create_schemas_from_callables
)

# From module
import math
schemas = create_schemas_from_module(math, include_functions=['sin', 'cos'])

# From class
class Calculator:
    def add(self, x: int, y: int) -> int:
        """Add two numbers."""
        return x + y
    
    def multiply(self, x: int, y: int) -> int:
        """Multiply two numbers."""
        return x * y

schemas = create_schemas_from_class(Calculator)

# From callable list
functions = [get_weather, search_users]
schemas = create_schemas_from_callables({"weather": get_weather, "search": search_users})

Code Generation - Powerful Automation

Transform your schemas into executable code for different contexts: HTTP clients, FastAPI routes, and Python execution environments.

HTTP Client Generation

Generate complete HTTP client code from schemas:

from schemez.code_generation import ToolsetCodeGenerator

# Create from functions
functions = [get_weather, search_users]
generator = ToolsetCodeGenerator.from_callables(functions)

# Generate HTTP client code
client_code = generator.generate_client_code(
    base_url="https://api.example.com",
    path_prefix="/v1/tools"
)

# Generated code includes:
# - Pydantic input models for each function
# - Async HTTP wrapper functions
# - Type-safe parameter validation
# - Complete module with imports and exports

Example generated client:

"""Generated HTTP client tools."""

from __future__ import annotations
from pydantic import BaseModel
import httpx

class GetWeatherInput(BaseModel):
    location: str
    unit: str | None = 'C'

async def get_weather(input: GetWeatherInput) -> str:
    """Get weather for a location."""
    async with httpx.AsyncClient() as client:
        response = await client.get(
            "https://api.example.com/v1/tools/get_weather",
            params=input.model_dump(),
            timeout=30.0
        )
        response.raise_for_status()
        return response.text

__all__ = ['GetWeatherInput', 'get_weather', ...]

FastAPI Route Setup

Automatically create FastAPI routes from your functions:

from fastapi import FastAPI
from schemez.code_generation import ToolsetCodeGenerator

app = FastAPI()

# Create generator with actual callables for execution
generator = ToolsetCodeGenerator.from_callables([get_weather, search_users])

# Add all routes automatically
generator.add_all_routes(app, path_prefix="/api/tools")

# Creates routes:
# GET /api/tools/get_weather
# GET /api/tools/search_users

Python Execution Environment

Create sandboxed execution environments with tool functions:

# Generate execution namespace
namespace = generator.generate_execution_namespace()

# Execute Python code with tools available
code = """
async def main():
    # Tools are available as async functions
    weather = await get_weather(GetWeatherInput(location="London"))
    users = await search_users(SearchUsersInput(query="john", limit=5))
    return {"weather": weather, "users": users}
"""

exec(code, namespace)
result = await namespace['main']()

Schema-Only Code Generation

Generate code without needing actual function implementations:

from schemez import create_schema
from schemez.code_generation import ToolsetCodeGenerator

# Create schemas from function signatures only
schema1 = create_schema(get_weather)
schema2 = create_schema(search_users)

# Generate client code from schemas
generator = ToolsetCodeGenerator.from_schemas([schema1, schema2])
client_code = generator.generate_client_code()

# Works for client generation, signatures, models
# Routes require actual callables for execution

Tool Documentation

Generate comprehensive documentation for your tools:

# Generate tool descriptions with signatures and docstrings
documentation = generator.generate_tool_description()

# Includes:
# - Function signatures with type hints  
# - Docstrings and parameter descriptions
# - Usage examples and constraints
# - Available return type models

Advanced Features

Type Support

Schemez handles complex Python types:

from typing import Literal, Optional, Union
from enum import Enum
from dataclasses import dataclass

class Status(Enum):
    ACTIVE = "active"
    INACTIVE = "inactive"

@dataclass
class User:
    name: str
    email: str

def complex_function(
    users: list[User],                    # -> Nested object arrays
    status: Status,                       # -> Enum values
    mode: Literal["fast", "detailed"],    # -> String literals
    metadata: dict[str, Any],             # -> Objects with any properties
    optional: Optional[str] = None,       # -> Optional parameters
) -> Union[dict, list]:                   # -> Union return types
    """Handle complex types."""
    pass

schema = create_schema(complex_function)

Configuration

Fine-tune schema generation:

# Exclude specific parameter types (e.g., context objects)
schema = create_schema(my_function, exclude_types=[Context, Session])

# Override names and descriptions
schema = create_schema(
    my_function,
    name_override="custom_name",
    description_override="Custom description"
)

Error Handling

Robust error handling throughout:

from schemez.code_generation import ToolCodeGenerator

# Schema-only generator (no execution capability)
generator = ToolCodeGenerator.from_schema(schema)

try:
    # This will fail with clear error message
    generator.add_route_to_app(app)
except ValueError as e:
    print(e)  # "Callable required for route generation for tool 'my_function'"

Use Cases

  • AI Tool Integration: Convert functions to OpenAI-compatible tools
  • API Client Generation: Create type-safe HTTP clients from schemas
  • FastAPI Automation: Auto-generate routes with validation
  • Documentation: Generate comprehensive API docs
  • Testing: Create mock implementations and test data
  • Code Analysis: Extract and analyze function signatures
  • Dynamic Execution: Build sandboxed Python environments

Differences from Pydantic

While Pydantic focuses on detailed type preservation, schemez optimizes for practical AI interaction:

  • Simplified unions: Takes first type instead of complex anyOf schemas
  • Enum flattening: Extracts enum values as simple string arrays
  • AI-optimized: Generates schemas that work well with LLM function calling
  • Code generation focus: Built for generating executable code, not just validation

Contributing

Contributions welcome! This library consolidates schema and type utilities from multiple projects into a unified toolkit.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

schemez-2.0.1.tar.gz (46.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

schemez-2.0.1-py3-none-any.whl (56.3 kB view details)

Uploaded Python 3

File details

Details for the file schemez-2.0.1.tar.gz.

File metadata

  • Download URL: schemez-2.0.1.tar.gz
  • Upload date:
  • Size: 46.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for schemez-2.0.1.tar.gz
Algorithm Hash digest
SHA256 701aa372b4fbcbb291a83f9a4f717f02b19dc87060942a77b2a57b970891c66a
MD5 014cbb2cefc826201d177a2010dab59e
BLAKE2b-256 7bfe0859fd2055d430b803da1344d0f39bcd5884be3b65cecd847067c8e8f4b7

See more details on using hashes here.

Provenance

The following attestation bundles were made for schemez-2.0.1.tar.gz:

Publisher: build.yml on phil65/schemez

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file schemez-2.0.1-py3-none-any.whl.

File metadata

  • Download URL: schemez-2.0.1-py3-none-any.whl
  • Upload date:
  • Size: 56.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for schemez-2.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 d6fe3fff9274a4742c991752abccdb1f16001c2f0fc1b403cc2378f7513debd5
MD5 63b6cd9ca3fdcbeeab4a4ff9e4707d05
BLAKE2b-256 19ea1496613a29906ae5397526a83d99ce4430c901d1a164dc13fe97c780e0ab

See more details on using hashes here.

Provenance

The following attestation bundles were made for schemez-2.0.1-py3-none-any.whl:

Publisher: build.yml on phil65/schemez

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page