Skip to main content

Clean, simplified schemas from Pydantic models for LLM prompts - less verbose than JSON Schema

Project description

scheLLMa

Schemas for LLMs and Structured Output

Documentation Demo and Examples Python 3.11+ PyPI version PyPI - Downloads

Converts Pydantic models/JSON Schemas to clean, simplified type definitions perfect for generating structured output with LLM prompts.

Unlike verbose JSON Schema formats, scheLLMa produces readable, concise type definitions that are ideal for language model interactions and structured output generation:

  • Reduce token usage - Concise format saves on API costs
  • Minimize parsing errors - Simple syntax is easier for models to parse, less verbose than JSON Schema, reducing confusion
  • Stay readable - Human-friendly format for prompt engineering

View the documentation for more details.

Checkout the demo for more examples!

Combine it with parsing libs, like openai sdk or Instructor for AWESOME results!

Features

  • 🤖 Optimized for LLM prompts - Clean, readable type definitions
  • 💰 Token-efficient - Reduces LLM API costs
  • 🎯 Support for all common Python types (str, int, bool, datetime, etc.)
  • 🏗️ Handle complex nested structures and collections - Strong support for Pydantic model types
  • 🔗 Support for enums, optional types, and unions - Properly extract and display union types
  • ⚙️ Customizable output formatting - Indentation, compact mode, and more
  • 🎨 Rich Default Values - Automatically shows default values in human-readable comments
  • 📏 Smart Constraints - Displays field constraints (length, range, patterns) in clear language
  • Clear Field Status - Explicit required/optional marking
  • 📚 Rich Examples - Inline examples and documentation for better LLM understanding
  • 🔀 Advanced Union Types - Full support for allOf, not constraints, and discriminated unions
  • 🔢 Advanced Arrays - Contains constraints, minContains/maxContains, and enhanced tuple support

Quick Start

View the demo for more examples and features!

from pydantic import BaseModel
from schellma import schellma
import openai

class TaskRequest(BaseModel):
    title: str
    priority: int
    tags: list[str]
    due_date: str | None = None

# Generate schema for LLM prompt
schema = schellma(TaskRequest)

# Add the scheLLMa schema to the prompt
prompt = f"""
Please create a task with the following structure:

{schema}
"""
print(prompt)

# Use with your favorite LLM API
completion = openai.chat.completions.create(
    model="gpt-4.1-mini",
    messages=[{
        "role": "user",
        "content": prompt
    }]
)

content = completion.choices[0].message.content
print(content)

task = TaskRequest.model_validate_json(clean_content(content))
print(task)
# TaskRequest(title='Task 1', priority=1, tags=['tag1', 'tag2'], due_date=None)

Using the new openai chat.completions.parse API

# or directly parse with openai sdk
completion = openai.chat.completions.parse(
    model="gpt-4.1-mini",
    messages=[{
        "role": "user",
        "content": prompt
    }]
)
task = completion.choices[0].message.parsed
print(task)
# TaskRequest(title='Task 1', priority=1, tags=['tag1', 'tag2'], due_date=None)

Using the new openai Responses API

class CalendarEvent(BaseModel):
    name: str
    date: str
    participants: list[str]

schema = schellma(CalendarEvent)

response = openai.responses.parse(
    model="gpt-4o-2024-08-06",
    input=[
        # Make sure to include the schema in your prompt
        {"role": "system", "content": f"Extract the event information. {schema}"},
        {
            "role": "user",
            "content": "Alice and Bob are going to a science fair on Friday.",
        },
    ],
    text_format=CalendarEvent,
)

event = response.output_parsed
print(event)
# CalendarEvent(name='Alice and Bob are going to a science fair on Friday.', date='Friday', participants=['Alice', 'Bob'])

Installation

pip install schellma

Or using uv:

uv add schellma

Install from github

uv add git+https://github.com/andrader/schellma.git

Comparison with JSON Schema

JSON Schema (verbose, token-heavy):

{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "age": { "type": "integer" },
    "email": { "type": ["string", "null"], "default": null }
  },
  "required": ["name", "age"],
  "additionalProperties": false
}

scheLLMa (clean, token-efficient):

{
    "name": string,
    "age": int,
    "email": string | null,
}

Advanced Usage with Type Definitions

from pydantic import BaseModel
from typing import List, Optional
from schellma import schellma

class Address(BaseModel):
    street: str
    city: str
    country: str

class User(BaseModel):
    name: str
    age: int
    addresses: List[Address]
    primary_address: Optional[Address] = None

# Generate with separate type definitions
schema = schellma(User, define_types=True)
print(schema)

Output:

Address {
    "street": string,
    "city": string,
    "country": string,
}

{
    "name": string,
    "age": int,
    "addresses": Address[],
    "primary_address": Address | null,
}

Examples

View more exemples at Demo

Enum Support

from enum import Enum
from pydantic import BaseModel

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

class Task(BaseModel):
    title: str
    status: Status

schema = schellma(Task)
# Output: { "title": string, "status": "active" | "inactive" }

Complex Nested Structures

from pydantic import BaseModel
from typing import Dict, List

class Tag(BaseModel):
    name: str
    color: str

class Post(BaseModel):
    title: str
    content: str
    tags: List[Tag]
    metadata: Dict[str, str]

schema = schellma(Post, define_types=True)

Development

Setup

git clone https://github.com/andrader/schellma.git
cd schellma
uv sync --dev

Running Tests

uv run python -m pytest

Type Checking

uv run mypy src/schellma/

Linting

uv run ruff check src/schellma/
uv run ruff format src/schellma/

Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

Development Guidelines

  1. Follow the existing code style (enforced by ruff)
  2. Add tests for any new functionality
  3. Update documentation as needed
  4. Ensure all tests pass and type checking succeeds

License

This project is licensed under the MIT License - see the LICENSE file for details.

Changelog

See Changelog for the changelog.

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

schellma-0.4.0.tar.gz (118.1 kB view details)

Uploaded Source

Built Distribution

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

schellma-0.4.0-py3-none-any.whl (23.4 kB view details)

Uploaded Python 3

File details

Details for the file schellma-0.4.0.tar.gz.

File metadata

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

File hashes

Hashes for schellma-0.4.0.tar.gz
Algorithm Hash digest
SHA256 b16c1cfd33ae78366db39850c0bb5ac91dffd0bc2028291779ad09b4ba95c930
MD5 21606ef2f9da3a4afda19fcb2975f307
BLAKE2b-256 47d443712bb2c2aa0cc23a1ac87dba0c644aec2b7c61690d1e2e283ff131c42c

See more details on using hashes here.

Provenance

The following attestation bundles were made for schellma-0.4.0.tar.gz:

Publisher: publish.yaml on andrader/schellma

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

File details

Details for the file schellma-0.4.0-py3-none-any.whl.

File metadata

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

File hashes

Hashes for schellma-0.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f7759c5882d858c92ae731629b35b0378eff2e0da4e8a815fc6c44cdc671e2b3
MD5 b44d6daaf8cc99c267f8f824e01ef317
BLAKE2b-256 b0d5eccaa3593c1bbd51f81632d4796794a09790348f9dc66a56d44078aa9965

See more details on using hashes here.

Provenance

The following attestation bundles were made for schellma-0.4.0-py3-none-any.whl:

Publisher: publish.yaml on andrader/schellma

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