Skip to content

schellma

scheLLMa - Schemas for LLMs

scheLLMa is a professional Python package that converts Pydantic models to clean, simplified type definitions perfect for LLM prompts. Unlike verbose JSON Schema formats, scheLLMa produces readable, concise schemas that are ideal for language model interactions.

Why scheLLMa?

When working with LLMs, you need clean, readable schemas that: - Reduce token usage - Concise format saves on API costs - Improve LLM understanding - Simple syntax is easier for models to parse - Minimize errors - Less verbose than JSON Schema, reducing confusion - Stay readable - Human-friendly format for prompt engineering

Key Features

  • Optimized for LLM prompts with clean, readable type definitions
  • Support for all common Python types (str, int, bool, etc.)
  • Handle complex nested structures and collections
  • Support for enums, optional types, and unions
  • Comprehensive error handling with descriptive messages
  • Circular reference detection and prevention
  • Customizable output formatting
  • Token-efficient output reduces LLM API costs

Basic Usage

from pydantic import BaseModel
from schellma import pydantic_to_schellma

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

# Generate clean schema for LLM prompts
schema = pydantic_to_schellma(User)
print(schema)

Output:

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

LLM Integration

from schellma import pydantic_to_schellma

class TaskRequest(BaseModel):
    title: str
    priority: int
    tags: list[str]

schema = pydantic_to_schellma(TaskRequest)

prompt = f'''
Please create a task with this structure:
{schema}
'''
# Use with OpenAI, Anthropic, or any LLM API

Error Handling

from schellma.exceptions import InvalidSchemaError, ConversionError
try:
    result = pydantic_to_schellma(SomeModel)
except InvalidSchemaError as e:
    print(f"Schema validation failed: {e}")
except ConversionError as e:
    print(f"Conversion failed: {e}")

Modules:

Name Description
constants

Constants for scheLLMa package.

converters

JSON Schema to ScheLLMa conversion utilities.

demo_features

Features Demonstration

exceptions

Custom exceptions for scheLLMa package.

logger

Logging configuration for scheLLMa package.

utils

Functions:

Name Description
json_schema_to_schellma

Convert a JSON Schema to ScheLLMa type definition string.

pydantic_to_schellma

Convert a Pydantic model to a ScheLLMa type definition string.

schellma

Convert a JSON Schema dictionary or Pydantic model to a ScheLLMa type definition string.

json_schema_to_schellma

json_schema_to_schellma(
    schema: dict,
    define_types: bool = True,
    indent: int | bool | None = DEFAULT_INDENT,
) -> str

Convert a JSON Schema to ScheLLMa type definition string.

Parameters:

Name Type Description Default

schema

dict

JSON Schema dictionary from model.model_json_schema()

required

define_types

bool

If True, define reused types separately to avoid repetition

True

indent

int | bool | None

Indentation configuration: - False/None/0: No indentation (compact format) - int: Number of spaces per indentation level (default: 2)

DEFAULT_INDENT

Returns:

Type Description
str

A string representation of the ScheLLMa type definition

Raises:

Type Description
InvalidSchemaError

If the schema is invalid or malformed

ConversionError

If conversion fails for any reason

CircularReferenceError

If circular references are detected

Source code in src/schellma/converters.py
def json_schema_to_schellma(
    schema: dict, define_types: bool = True, indent: int | bool | None = DEFAULT_INDENT
) -> str:
    """Convert a JSON Schema to ScheLLMa type definition string.

    Args:
        schema: JSON Schema dictionary from model.model_json_schema()
        define_types: If True, define reused types separately to avoid repetition
        indent: Indentation configuration:
            - False/None/0: No indentation (compact format)
            - int: Number of spaces per indentation level (default: 2)

    Returns:
        A string representation of the ScheLLMa type definition

    Raises:
        InvalidSchemaError: If the schema is invalid or malformed
        ConversionError: If conversion fails for any reason
        CircularReferenceError: If circular references are detected
    """
    converter = SchemaConverter(schema, define_types, indent)
    return converter.convert()

pydantic_to_schellma

pydantic_to_schellma(
    model_class: type[BaseModel],
    define_types: bool = False,
    indent: int | bool | None = DEFAULT_INDENT,
) -> str

Convert a Pydantic model to a ScheLLMa type definition string.

Parameters:

Name Type Description Default

model_class

type[BaseModel]

A Pydantic BaseModel class

required

define_types

bool

If True, define reused types separately to avoid repetition

False

indent

int | bool | None

Indentation configuration: - False/None/0: No indentation (compact format) - int: Number of spaces per indentation level (default: 2)

DEFAULT_INDENT

Returns:

Type Description
str

A string representation of the ScheLLMa type definition

Raises:

Type Description
InvalidSchemaError

If the model is invalid

ConversionError

If conversion fails for any reason

CircularReferenceError

If circular references are detected

Source code in src/schellma/converters.py
def pydantic_to_schellma(
    model_class: type[BaseModel],
    define_types: bool = False,
    indent: int | bool | None = DEFAULT_INDENT,
) -> str:
    """Convert a Pydantic model to a ScheLLMa type definition string.

    Args:
        model_class: A Pydantic BaseModel class
        define_types: If True, define reused types separately to avoid repetition
        indent: Indentation configuration:
            - False/None/0: No indentation (compact format)
            - int: Number of spaces per indentation level (default: 2)

    Returns:
        A string representation of the ScheLLMa type definition

    Raises:
        InvalidSchemaError: If the model is invalid
        ConversionError: If conversion fails for any reason
        CircularReferenceError: If circular references are detected
    """
    logger.debug(
        f"Converting Pydantic model {getattr(model_class, '__name__', str(model_class))} to ScheLLMa"
    )

    if not isinstance(model_class, type):
        logger.error(f"Invalid model class type: {type(model_class).__name__}")
        raise InvalidSchemaError(
            f"model_class must be a class, got {type(model_class).__name__}"
        )

    # Check if it's a BaseModel subclass
    try:
        if not issubclass(model_class, BaseModel):
            raise InvalidSchemaError(
                f"model_class must be a BaseModel subclass, got {model_class.__name__}"
            )
    except TypeError as e:
        raise InvalidSchemaError(
            f"model_class must be a class, got {type(model_class).__name__}"
        ) from e

    try:
        schema = model_class.model_json_schema()
    except Exception as e:
        raise InvalidSchemaError(
            f"Failed to generate JSON schema from model: {e}"
        ) from e

    return json_schema_to_schellma(schema, define_types, indent)

schellma

schellma(
    obj: dict | type[BaseModel],
    define_types: bool = False,
    indent: int | bool | None = DEFAULT_INDENT,
) -> str

Convert a JSON Schema dictionary or Pydantic model to a ScheLLMa type definition string.

Parameters:

Name Type Description Default

obj

dict | type[BaseModel]

A JSON Schema dictionary or Pydantic model

required

define_types

bool

If True, define reused types separately to avoid repetition

False

indent

int | bool | None

Indentation configuration: - False/None/0: No indentation (compact format) - int: Number of spaces per indentation level (default: 2)

DEFAULT_INDENT

Returns:

Type Description
str

A string representation of the ScheLLMa type definition

Raises:

Type Description
InvalidSchemaError

If the model is invalid

ConversionError

If conversion fails for any reason

CircularReferenceError

If circular references are detected

Source code in src/schellma/converters.py
def schellma(
    obj: dict | type[BaseModel],
    define_types: bool = False,
    indent: int | bool | None = DEFAULT_INDENT,
) -> str:
    """Convert a JSON Schema dictionary or Pydantic model to a ScheLLMa type definition string.

    Args:
        obj: A JSON Schema dictionary or Pydantic model
        define_types: If True, define reused types separately to avoid repetition
        indent: Indentation configuration:
            - False/None/0: No indentation (compact format)
            - int: Number of spaces per indentation level (default: 2)

    Returns:
        A string representation of the ScheLLMa type definition

    Raises:
        InvalidSchemaError: If the model is invalid
        ConversionError: If conversion fails for any reason
        CircularReferenceError: If circular references are detected
    """
    if isinstance(obj, type) and issubclass(obj, BaseModel):
        return pydantic_to_schellma(obj, define_types, indent)
    elif isinstance(obj, dict):
        return json_schema_to_schellma(obj, define_types, indent)
    else:
        raise InvalidSchemaError(f"Invalid object type: {type(obj).__name__}")