Skip to content

functionschema

Class info

Re-exported classes

Class Module Description
FunctionSchema schemez.functionschema.functionschema Schema representing an OpenAI function definition and metadata.
OpenAIFunctionDefinition schemez.functionschema.typedefs Schema for the function definition part of an OpenAI tool.
OpenAIFunctionTool schemez.functionschema.typedefs Complete OpenAI tool definition for function calling.
SimpleProperty schemez.functionschema.typedefs Schema property for primitive types.
ToolParameters schemez.functionschema.typedefs

🛈 DocStrings

FunctionSchema.

ToolParameters module-attribute

ToolParameters = TypedDict(
    "ToolParameters",
    {
        "type": Literal["object"],
        "properties": dict[str, Any],
        "required": NotRequired[list[str]],
        "$defs": NotRequired[dict[str, Any]],
    },
)

Schema for tool parameters (JSON Schema object type).

FunctionSchema

Bases: BaseModel

Schema representing an OpenAI function definition and metadata.

This class encapsulates all the necessary information to describe a function to the OpenAI API, including its name, description, parameters, return type, and execution characteristics. It follows the OpenAI function calling format while adding additional metadata useful for Python function handling.

Source code in src/schemez/functionschema/functionschema.py
class FunctionSchema(pydantic.BaseModel):
    """Schema representing an OpenAI function definition and metadata.

    This class encapsulates all the necessary information to describe a function to the
    OpenAI API, including its name, description, parameters, return type, and execution
    characteristics. It follows the OpenAI function calling format while adding
    additional metadata useful for Python function handling.
    """

    name: str
    """The name of the function as it will be presented to the OpenAI API."""

    description: str | None = None
    """Optional description of what the function does."""

    parameters: ToolParameters = pydantic.Field(
        default_factory=lambda: ToolParameters(type="object", properties={}, required=[]),
    )
    """JSON Schema object describing the function's parameters."""

    required: list[str] = pydantic.Field(default_factory=list)
    """List of parameter names that are required (do not have default values)."""

    returns: dict[str, Any] = pydantic.Field(
        default_factory=lambda: {"type": "object"},
    )
    """JSON Schema object describing the function's return type."""

    model_config = pydantic.ConfigDict(frozen=True)

    def create_parameter_model(self) -> type[pydantic.BaseModel]:
        """Create a Pydantic model from the schema parameters."""
        fields: dict[str, Any] = {}
        properties = self.parameters.get("properties", {})
        required = self.parameters.get("required", self.required)

        for name, details in properties.items():
            if name.startswith("_"):  # TODO: kwarg for renaming instead perhaps?
                logger.debug("Skipping parameter %s due to leading underscore", name)
                continue
            param_type = _schema_to_python_type(details)

            # Handle optional types (if there's a default of None)
            default_value = details.get("default")
            if default_value is None and name not in required:
                param_type = param_type | None

            # Create a proper pydantic Field
            field = (
                param_type,
                pydantic.Field(default=... if name in required else default_value),
            )
            fields[name] = field

        return pydantic.create_model(f"{self.name}_params", **fields)

    def model_dump_openai(self) -> OpenAIFunctionTool:
        """Convert the schema to OpenAI's function calling format.

        Returns:
            A dictionary matching OpenAI's complete function tool definition format.
            {"type": "function", "function": {"name": ..., "description": ..., "parameters": ...}}
        """
        parameters: ToolParameters = {
            "type": "object",
            "properties": self.parameters["properties"],
            "required": self.required,
        }
        if "$defs" in self.parameters:
            parameters["$defs"] = self.parameters["$defs"]

        # First create the function definition
        function_def = OpenAIFunctionDefinition(
            name=self.name,
            description=self.description or "",
            parameters=parameters,
        )

        return OpenAIFunctionTool(type="function", function=function_def)

    def to_python_signature(self) -> inspect.Signature:
        """Convert the schema back to a Python function signature.

        This method creates a Python function signature from the OpenAI schema,
        mapping JSON schema types back to their Python equivalents.
        """
        model = self.create_parameter_model()
        param_type = TYPE_MAP.get(self.returns.get("type", "string"), Any)
        return pydantic_model_to_signature(model, param_type)

    def to_return_model_code(self, class_name: str | None = None) -> str:
        """Generate Pydantic model code for return type using datamodel-codegen.

        Args:
            class_name: Name for the generated class (default: {name}Response)

        Returns:
            Generated Python code string
        """
        name = class_name or f"{self.name.title()}Response"
        return json_schema_to_pydantic_code(
            self.returns,
            class_name=name,
            target_python_version="3.13",
        )

    def to_parameter_model_code(self, class_name: str | None = None) -> str:
        """Generate Pydantic model code for parameters using datamodel-codegen.

        Args:
            class_name: Name for the generated class (default: {name}Params)

        Returns:
            Generated Python code string
        """
        name = class_name or f"{self.name.title()}Params"
        return json_schema_to_pydantic_code(
            dict(self.parameters),
            class_name=name,
            target_python_version="3.13",
        )

    def get_annotations(self, return_type: Any = str) -> dict[str, type[Any]]:
        """Get a dictionary of parameter names to their Python types.

        This can be used directly for __annotations__ assignment.

        Returns:
            Dictionary mapping parameter names to their Python types.
        """
        model = self.create_parameter_model()
        annotations: dict[str, Any] = {}
        for name, field in model.model_fields.items():
            annotations[name] = field.annotation
        annotations["return"] = return_type
        return annotations

    @classmethod
    def from_dict(
        cls,
        schema: Mapping[str, Any],
        output_schema: dict[str, Any] | None = None,
    ) -> FunctionSchema:
        """Create a FunctionSchema from a raw schema dictionary.

        Args:
            schema: OpenAI function schema dictionary (also an ``OpenAIFunctionTool``
                or ``OpenAIFunctionDefinition``).
                Can be either a direct function definition or a tool wrapper.
            output_schema: Optional dictionary specifying the return type.
                If not provided, an object type will be set.

        Raises:
            ValueError: If schema format is invalid or missing required fields
        """
        # Handle tool wrapper format
        if "type" in schema and schema["type"] == "function":
            if "function" not in schema:
                msg = 'Tool with type "function" must have a "function" field'
                raise ValueError(msg)
            schema = schema["function"]
        elif "type" in schema and schema.get("type") != "function":
            msg = f"Unknown tool type: {schema.get('type')}"
            raise ValueError(msg)

        # Get function name
        name = schema.get("name", schema.get("function", {}).get("name"))
        if not name:
            msg = 'Schema must have a "name" field'
            raise ValueError(msg)

        # Extract parameters
        param_dict = schema.get("parameters", {"type": "object", "properties": {}})
        if not isinstance(param_dict, dict):
            msg = "Schema parameters must be a dictionary"
            raise ValueError(msg)  # noqa: TRY004

        # Clean up properties that have advanced JSON Schema features
        properties = param_dict.get("properties", {})
        cleaned_props: dict[str, Property] = {}
        for prop_name, prop in properties.items():
            cleaned_props[prop_name] = clean_property(prop)
        required = param_dict.get("required", [])
        if not isinstance(required, list):
            msg = "Schema required field must be a list"
            raise ValueError(msg)  # noqa: TRY004
        parameters: ToolParameters = {"type": "object", "properties": cleaned_props}
        if required:
            parameters["required"] = required
        return cls(
            name=name,
            description=schema.get("description"),
            parameters=parameters,
            required=required,
            returns=output_schema or {"type": "object"},
        )

description class-attribute instance-attribute

description: str | None = None

Optional description of what the function does.

name instance-attribute

name: str

The name of the function as it will be presented to the OpenAI API.

parameters class-attribute instance-attribute

parameters: ToolParameters = pydantic.Field(
    default_factory=lambda: ToolParameters(type="object", properties={}, required=[])
)

JSON Schema object describing the function's parameters.

required class-attribute instance-attribute

required: list[str] = pydantic.Field(default_factory=list)

List of parameter names that are required (do not have default values).

returns class-attribute instance-attribute

returns: dict[str, Any] = pydantic.Field(default_factory=lambda: {'type': 'object'})

JSON Schema object describing the function's return type.

create_parameter_model

create_parameter_model() -> type[BaseModel]

Create a Pydantic model from the schema parameters.

Source code in src/schemez/functionschema/functionschema.py
def create_parameter_model(self) -> type[pydantic.BaseModel]:
    """Create a Pydantic model from the schema parameters."""
    fields: dict[str, Any] = {}
    properties = self.parameters.get("properties", {})
    required = self.parameters.get("required", self.required)

    for name, details in properties.items():
        if name.startswith("_"):  # TODO: kwarg for renaming instead perhaps?
            logger.debug("Skipping parameter %s due to leading underscore", name)
            continue
        param_type = _schema_to_python_type(details)

        # Handle optional types (if there's a default of None)
        default_value = details.get("default")
        if default_value is None and name not in required:
            param_type = param_type | None

        # Create a proper pydantic Field
        field = (
            param_type,
            pydantic.Field(default=... if name in required else default_value),
        )
        fields[name] = field

    return pydantic.create_model(f"{self.name}_params", **fields)

from_dict classmethod

from_dict(schema: Mapping[str, Any], output_schema: dict[str, Any] | None = None) -> FunctionSchema

Create a FunctionSchema from a raw schema dictionary.

Parameters:

Name Type Description Default
schema Mapping[str, Any]

OpenAI function schema dictionary (also an OpenAIFunctionTool or OpenAIFunctionDefinition). Can be either a direct function definition or a tool wrapper.

required
output_schema dict[str, Any] | None

Optional dictionary specifying the return type. If not provided, an object type will be set.

None

Raises:

Type Description
ValueError

If schema format is invalid or missing required fields

Source code in src/schemez/functionschema/functionschema.py
@classmethod
def from_dict(
    cls,
    schema: Mapping[str, Any],
    output_schema: dict[str, Any] | None = None,
) -> FunctionSchema:
    """Create a FunctionSchema from a raw schema dictionary.

    Args:
        schema: OpenAI function schema dictionary (also an ``OpenAIFunctionTool``
            or ``OpenAIFunctionDefinition``).
            Can be either a direct function definition or a tool wrapper.
        output_schema: Optional dictionary specifying the return type.
            If not provided, an object type will be set.

    Raises:
        ValueError: If schema format is invalid or missing required fields
    """
    # Handle tool wrapper format
    if "type" in schema and schema["type"] == "function":
        if "function" not in schema:
            msg = 'Tool with type "function" must have a "function" field'
            raise ValueError(msg)
        schema = schema["function"]
    elif "type" in schema and schema.get("type") != "function":
        msg = f"Unknown tool type: {schema.get('type')}"
        raise ValueError(msg)

    # Get function name
    name = schema.get("name", schema.get("function", {}).get("name"))
    if not name:
        msg = 'Schema must have a "name" field'
        raise ValueError(msg)

    # Extract parameters
    param_dict = schema.get("parameters", {"type": "object", "properties": {}})
    if not isinstance(param_dict, dict):
        msg = "Schema parameters must be a dictionary"
        raise ValueError(msg)  # noqa: TRY004

    # Clean up properties that have advanced JSON Schema features
    properties = param_dict.get("properties", {})
    cleaned_props: dict[str, Property] = {}
    for prop_name, prop in properties.items():
        cleaned_props[prop_name] = clean_property(prop)
    required = param_dict.get("required", [])
    if not isinstance(required, list):
        msg = "Schema required field must be a list"
        raise ValueError(msg)  # noqa: TRY004
    parameters: ToolParameters = {"type": "object", "properties": cleaned_props}
    if required:
        parameters["required"] = required
    return cls(
        name=name,
        description=schema.get("description"),
        parameters=parameters,
        required=required,
        returns=output_schema or {"type": "object"},
    )

get_annotations

get_annotations(return_type: Any = str) -> dict[str, type[Any]]

Get a dictionary of parameter names to their Python types.

This can be used directly for annotations assignment.

Returns:

Type Description
dict[str, type[Any]]

Dictionary mapping parameter names to their Python types.

Source code in src/schemez/functionschema/functionschema.py
def get_annotations(self, return_type: Any = str) -> dict[str, type[Any]]:
    """Get a dictionary of parameter names to their Python types.

    This can be used directly for __annotations__ assignment.

    Returns:
        Dictionary mapping parameter names to their Python types.
    """
    model = self.create_parameter_model()
    annotations: dict[str, Any] = {}
    for name, field in model.model_fields.items():
        annotations[name] = field.annotation
    annotations["return"] = return_type
    return annotations

model_dump_openai

model_dump_openai() -> OpenAIFunctionTool

Convert the schema to OpenAI's function calling format.

Returns:

Type Description
OpenAIFunctionTool

A dictionary matching OpenAI's complete function tool definition format.

OpenAIFunctionTool

{"type": "function", "function": {"name": ..., "description": ..., "parameters": ...}}

Source code in src/schemez/functionschema/functionschema.py
def model_dump_openai(self) -> OpenAIFunctionTool:
    """Convert the schema to OpenAI's function calling format.

    Returns:
        A dictionary matching OpenAI's complete function tool definition format.
        {"type": "function", "function": {"name": ..., "description": ..., "parameters": ...}}
    """
    parameters: ToolParameters = {
        "type": "object",
        "properties": self.parameters["properties"],
        "required": self.required,
    }
    if "$defs" in self.parameters:
        parameters["$defs"] = self.parameters["$defs"]

    # First create the function definition
    function_def = OpenAIFunctionDefinition(
        name=self.name,
        description=self.description or "",
        parameters=parameters,
    )

    return OpenAIFunctionTool(type="function", function=function_def)

to_parameter_model_code

to_parameter_model_code(class_name: str | None = None) -> str

Generate Pydantic model code for parameters using datamodel-codegen.

Parameters:

Name Type Description Default
class_name str | None

Name for the generated class (default: {name}Params)

None

Returns:

Type Description
str

Generated Python code string

Source code in src/schemez/functionschema/functionschema.py
def to_parameter_model_code(self, class_name: str | None = None) -> str:
    """Generate Pydantic model code for parameters using datamodel-codegen.

    Args:
        class_name: Name for the generated class (default: {name}Params)

    Returns:
        Generated Python code string
    """
    name = class_name or f"{self.name.title()}Params"
    return json_schema_to_pydantic_code(
        dict(self.parameters),
        class_name=name,
        target_python_version="3.13",
    )

to_python_signature

to_python_signature() -> Signature

Convert the schema back to a Python function signature.

This method creates a Python function signature from the OpenAI schema, mapping JSON schema types back to their Python equivalents.

Source code in src/schemez/functionschema/functionschema.py
def to_python_signature(self) -> inspect.Signature:
    """Convert the schema back to a Python function signature.

    This method creates a Python function signature from the OpenAI schema,
    mapping JSON schema types back to their Python equivalents.
    """
    model = self.create_parameter_model()
    param_type = TYPE_MAP.get(self.returns.get("type", "string"), Any)
    return pydantic_model_to_signature(model, param_type)

to_return_model_code

to_return_model_code(class_name: str | None = None) -> str

Generate Pydantic model code for return type using datamodel-codegen.

Parameters:

Name Type Description Default
class_name str | None

Name for the generated class (default: {name}Response)

None

Returns:

Type Description
str

Generated Python code string

Source code in src/schemez/functionschema/functionschema.py
def to_return_model_code(self, class_name: str | None = None) -> str:
    """Generate Pydantic model code for return type using datamodel-codegen.

    Args:
        class_name: Name for the generated class (default: {name}Response)

    Returns:
        Generated Python code string
    """
    name = class_name or f"{self.name.title()}Response"
    return json_schema_to_pydantic_code(
        self.returns,
        class_name=name,
        target_python_version="3.13",
    )

OpenAIFunctionDefinition

Bases: TypedDict

Schema for the function definition part of an OpenAI tool.

This represents the inner "function" object that contains the actual function metadata and parameters.

Source code in src/schemez/functionschema/typedefs.py
class OpenAIFunctionDefinition(TypedDict):
    """Schema for the function definition part of an OpenAI tool.

    This represents the inner "function" object that contains the actual
    function metadata and parameters.
    """

    name: str
    description: str
    parameters: ToolParameters

OpenAIFunctionTool

Bases: TypedDict

Complete OpenAI tool definition for function calling.

This represents the top-level tool object that wraps a function definition and identifies it as a function tool type.

Source code in src/schemez/functionschema/typedefs.py
class OpenAIFunctionTool(TypedDict):
    """Complete OpenAI tool definition for function calling.

    This represents the top-level tool object that wraps a function definition
    and identifies it as a function tool type.
    """

    type: Literal["function"]
    function: OpenAIFunctionDefinition

SimpleProperty

Bases: PropertyBase

Schema property for primitive types.

Source code in src/schemez/functionschema/typedefs.py
class SimpleProperty(PropertyBase):
    """Schema property for primitive types."""

    type: Literal["string", "number", "integer", "boolean"]
    enum: NotRequired[list[Any]]

create_constructor_schema

create_constructor_schema(cls: type) -> FunctionSchema

Create OpenAI function schema from class constructor.

Parameters:

Name Type Description Default
cls type

Class to create schema for

required

Returns:

Type Description
FunctionSchema

OpenAI function schema for class constructor

Source code in src/schemez/functionschema/schema_generators.py
def create_constructor_schema(cls: type) -> FunctionSchema:
    """Create OpenAI function schema from class constructor.

    Args:
        cls: Class to create schema for

    Returns:
        OpenAI function schema for class constructor
    """
    if isinstance(cls, type) and issubclass(cls, pydantic.BaseModel):
        properties = {}
        required = []
        for name, field in cls.model_fields.items():
            param_type = field.annotation
            properties[name] = resolve_type_annotation(
                param_type,
                description=field.description,
                default=field.default,
            )
            if field.is_required():
                required.append(name)

    # Handle dataclasses
    elif dataclasses.is_dataclass(cls):
        properties = {}
        required = []
        dc_fields = dataclasses.fields(cls)
        hints = get_resolved_hints(cls, include_extras=False)

        for dc_field in dc_fields:
            param_type = hints[dc_field.name]
            properties[dc_field.name] = resolve_type_annotation(
                param_type, default=dc_field.default
            )
            if (
                dc_field.default is dataclasses.MISSING
                and dc_field.default_factory is dataclasses.MISSING
            ):
                required.append(dc_field.name)

    # Handle regular classes
    else:
        sig = get_signature(cls.__init__)
        hints = get_resolved_hints(cls.__init__, include_extras=False)
        properties = {}
        required = []

        for name, param in sig.parameters.items():
            if name == "self":
                continue

            param_type = hints.get(name, Any)
            properties[name] = resolve_type_annotation(
                param_type,
                default=param.default,
            )

            if param.default is param.empty:
                required.append(name)

    name = f"create_{cls.__name__}"
    description = inspect.getdoc(cls) or f"Create {cls.__name__} instance"

    # Create parameters with required list included
    params = ToolParameters({
        "type": "object",
        "properties": properties,
        "required": required,
    })

    return FunctionSchema(name=name, description=description, parameters=params, required=required)

create_schema

create_schema(
    func: Callable[..., Any],
    name_override: str | None = None,
    description_override: str | None = None,
    exclude_types: list[type] | None = None,
    mode: SchemaType = "simple",
) -> FunctionSchema

Create an OpenAI function schema from a Python function.

If an iterator is passed, the schema return type is a list of the iterator's element type. Variable arguments (*args) and keyword arguments (**kwargs) are not supported in OpenAI function schemas and will be ignored with a warning.

Parameters:

Name Type Description Default
func Callable[..., Any]

Function to create schema for

required
name_override str | None

Optional name override (otherwise the function name)

None
description_override str | None

Optional description override (otherwise the function docstring)

None
exclude_types list[type] | None

Types to exclude from parameters (e.g., context types)

None
mode SchemaType

Schema generation mode - simple" (default) uses custom simple implementation, - "openai" for OpenAI function calling via Pydantic, - "jsonschema" for standard JSON schema via Pydantic

'simple'
Source code in src/schemez/functionschema/functionschema.py
def create_schema(
    func: Callable[..., Any],
    name_override: str | None = None,
    description_override: str | None = None,
    exclude_types: list[type] | None = None,
    mode: SchemaType = "simple",
) -> FunctionSchema:
    """Create an OpenAI function schema from a Python function.

    If an iterator is passed, the schema return type is a list of the iterator's
    element type.
    Variable arguments (*args) and keyword arguments (**kwargs) are not
    supported in OpenAI function schemas and will be ignored with a warning.

    Args:
        func: Function to create schema for
        name_override: Optional name override (otherwise the function name)
        description_override: Optional description override
                              (otherwise the function docstring)
        exclude_types: Types to exclude from parameters (e.g., context types)
        mode: Schema generation mode
              - simple" (default) uses custom simple implementation,
              - "openai" for OpenAI function calling via Pydantic,
              - "jsonschema" for standard JSON schema via Pydantic
    """
    exclude_types = exclude_types or []
    if mode == "simple":
        return _create_schema_simple(func, name_override, description_override, exclude_types)
    return _create_schema_pydantic(
        func,
        name_override,
        description_override,
        exclude_types,
        use_openai_format=mode == "openai",
    )

create_schemas_from_callables

create_schemas_from_callables(
    callables: dict[str, Callable[..., Any]],
    prefix: str | Literal[False] | None = None,
    exclude_private: bool = True,
) -> dict[str, FunctionSchema]

Generate OpenAI function schemas from a dictionary of callables.

Parameters:

Name Type Description Default
callables dict[str, Callable[..., Any]]

Dictionary mapping names to callable objects

required
prefix str | Literal[False] | None

Schema name prefix to prepend to function names. If None, no prefix. If False, use raw name. If string, uses that prefix.

None
exclude_private bool

Whether to exclude callables starting with underscore

True

Returns:

Type Description
dict[str, FunctionSchema]

Dictionary mapping qualified names to FunctionSchema objects

Example

def foo(x: int) -> str: ... def bar(y: float) -> int: ... callables = {'foo': foo, 'bar': bar} schemas = create_schemas_from_callables(callables, prefix='math') print(schemas['math.foo'])

Source code in src/schemez/functionschema/schema_generators.py
def create_schemas_from_callables(
    callables: dict[str, Callable[..., Any]],
    prefix: str | Literal[False] | None = None,
    exclude_private: bool = True,
) -> dict[str, FunctionSchema]:
    """Generate OpenAI function schemas from a dictionary of callables.

    Args:
        callables: Dictionary mapping names to callable objects
        prefix: Schema name prefix to prepend to function names.
               If None, no prefix. If False, use raw name.
               If string, uses that prefix.
        exclude_private: Whether to exclude callables starting with underscore

    Returns:
        Dictionary mapping qualified names to FunctionSchema objects

    Example:
        >>> def foo(x: int) -> str: ...
        >>> def bar(y: float) -> int: ...
        >>> callables = {'foo': foo, 'bar': bar}
        >>> schemas = create_schemas_from_callables(callables, prefix='math')
        >>> print(schemas['math.foo'])
    """
    schemas = {}
    for name, callable_obj in callables.items():
        if exclude_private and name.startswith("_"):  # Skip private members if requested
            continue
        # Generate schema key based on prefix setting
        key = name if prefix is False else f"{prefix}.{name}" if prefix else name
        schemas[key] = create_schema(callable_obj)
    return schemas

create_schemas_from_class

create_schemas_from_class(
    cls: type, prefix: str | Literal[False] | None = None
) -> dict[str, FunctionSchema]

Generate OpenAI function schemas for all public methods in a class.

Parameters:

Name Type Description Default
cls type

The class to generate schemas from

required
prefix str | Literal[False] | None

Schema name prefix. If None, uses class name. If False, no prefix. If string, uses that prefix.

None

Returns:

Type Description
dict[str, FunctionSchema]

Dictionary mapping qualified method names to FunctionSchema objects

Example

class MyClass: ... def my_method(self, x: int) -> str: ... return str(x) schemas = create_schemas_from_class(MyClass) print(schemas['MyClass.my_method'])

Source code in src/schemez/functionschema/schema_generators.py
def create_schemas_from_class(
    cls: type,
    prefix: str | Literal[False] | None = None,
) -> dict[str, FunctionSchema]:
    """Generate OpenAI function schemas for all public methods in a class.

    Args:
        cls: The class to generate schemas from
        prefix: Schema name prefix. If None, uses class name.
               If False, no prefix. If string, uses that prefix.

    Returns:
        Dictionary mapping qualified method names to FunctionSchema objects

    Example:
        >>> class MyClass:
        ...     def my_method(self, x: int) -> str:
        ...         return str(x)
        >>> schemas = create_schemas_from_class(MyClass)
        >>> print(schemas['MyClass.my_method'])
    """
    callables: dict[str, Callable[..., Any]] = {}

    for name, attr in inspect.getmembers(cls):  # Get all attributes of the class
        if inspect.isfunction(attr) or inspect.ismethod(attr):
            callables[name] = attr
        elif isinstance(attr, classmethod | staticmethod):
            callables[name] = attr.__get__(None, cls)

    # Use default prefix of class name if not specified
    effective_prefix = cls.__name__ if prefix is None else prefix
    return create_schemas_from_callables(callables, prefix=effective_prefix)

create_schemas_from_module

create_schemas_from_module(
    module: ModuleType | str,
    include_functions: list[str] | None = None,
    prefix: str | Literal[False] | None = None,
) -> dict[str, FunctionSchema]

Generate OpenAI function schemas from a Python module's functions.

Parameters:

Name Type Description Default
module ModuleType | str

Either a ModuleType object or string name of module to analyze

required
include_functions list[str] | None

Optional list of function names to specifically include

None
prefix str | Literal[False] | None

Schema name prefix. If None, uses module name. If False, no prefix. If string, uses that prefix.

None

Returns:

Type Description
dict[str, FunctionSchema]

Dictionary mapping function names to FunctionSchema objects

Raises:

Type Description
ImportError

If module string name cannot be imported

Example

import math schemas = create_schemas_from_module(math, ['sin', 'cos']) print(schemas['math.sin'])

Source code in src/schemez/functionschema/schema_generators.py
def create_schemas_from_module(
    module: types.ModuleType | str,
    include_functions: list[str] | None = None,
    prefix: str | Literal[False] | None = None,
) -> dict[str, FunctionSchema]:
    """Generate OpenAI function schemas from a Python module's functions.

    Args:
        module: Either a ModuleType object or string name of module to analyze
        include_functions: Optional list of function names to specifically include
        prefix: Schema name prefix. If None, uses module name.
                If False, no prefix. If string, uses that prefix.

    Returns:
        Dictionary mapping function names to FunctionSchema objects

    Raises:
        ImportError: If module string name cannot be imported

    Example:
        >>> import math
        >>> schemas = create_schemas_from_module(math, ['sin', 'cos'])
        >>> print(schemas['math.sin'])
    """
    # Resolve module if string name provided
    mod = module if isinstance(module, types.ModuleType) else importlib.import_module(module)

    # Get all functions from module
    callables: dict[str, Callable[..., Any]] = {
        name: func
        for name, func in inspect.getmembers(mod, predicate=inspect.isfunction)
        if include_functions is None
        or (name in include_functions and func.__module__.startswith(mod.__name__))
    }

    # Use default prefix of module name if not specified
    effective_prefix = mod.__name__ if prefix is None else prefix
    return create_schemas_from_callables(callables, prefix=effective_prefix)

determine_function_type

determine_function_type(func: Callable[..., Any]) -> FunctionType

Determine the type of the function.

Source code in src/schemez/functionschema/helpers.py
def determine_function_type(func: Callable[..., Any]) -> FunctionType:
    """Determine the type of the function."""
    if inspect.isasyncgenfunction(func):
        return "async_generator"
    if inspect.isgeneratorfunction(func):
        return "sync_generator"
    if inspect.iscoroutinefunction(func):
        return "async"
    return "sync"

resolve_type_annotation

resolve_type_annotation(
    typ: Any,
    description: str | None = None,
    default: Any = empty,
    is_parameter: bool = True,
    defs: dict[str, Any] | None = None,
) -> Property

Resolve a type annotation into an OpenAI schema type.

Parameters:

Name Type Description Default
typ Any

Type to resolve

required
description str | None

Optional description

None
default Any

Default value if any

empty
is_parameter bool

Whether this is for a parameter (affects dict schema)

True
defs dict[str, Any] | None

Collects the definitions of recursive types, referenced as #/$defs/<name>; the caller puts them at the root of its schema. Without it, they are added to the returned schema as $defs.

None
Source code in src/schemez/functionschema/helpers.py
def resolve_type_annotation(
    typ: Any,
    description: str | None = None,
    default: Any = inspect.Parameter.empty,
    is_parameter: bool = True,
    defs: dict[str, Any] | None = None,
) -> Property:
    """Resolve a type annotation into an OpenAI schema type.

    Args:
        typ: Type to resolve
        description: Optional description
        default: Default value if any
        is_parameter: Whether this is for a parameter (affects dict schema)
        defs: Collects the definitions of recursive types, referenced as
            `#/$defs/<name>`; the caller puts them at the root of its schema.
            Without it, they are added to the returned schema as `$defs`.
    """
    ctx = _Context(defs={} if defs is None else defs)
    schema = _resolve(typ, ctx, is_parameter=is_parameter, optional=default is None)
    if description and (hint := _description_hint(typ)):
        description = f"{description} ({hint})"
    schema = _with_meta(schema, description, default)
    if defs is None and ctx.defs:
        schema["$defs"] = ctx.defs
    return typing.cast("Property", schema)