Skip to content

helpers

Class info

🛈 DocStrings

Module for creating OpenAI function schemas from Python functions.

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"

get_param_type

get_param_type(param_details: Property) -> type[Any]

Get the Python type for a parameter based on its schema details.

Source code in src/schemez/functionschema/helpers.py
def get_param_type(param_details: Property) -> type[Any]:
    """Get the Python type for a parameter based on its schema details."""
    if "enum" in param_details:
        # For enum parameters, we just use str since we can't reconstruct
        # the exact enum class
        return str

    type_map = {
        "string": str,
        "integer": int,
        "number": float,
        "boolean": bool,
        "array": list,
        "object": dict,
    }
    return type_map.get(param_details.get("type", "string"), Any)

is_optional_type

is_optional_type(typ: type) -> TypeGuard[type]

Check if a type is Optional[T] or T | None.

Parameters:

Name Type Description Default
typ type

Type to check

required

Returns:

Type Description
TypeGuard[type]

True if the type is Optional, False otherwise

Source code in src/schemez/functionschema/helpers.py
def is_optional_type(typ: type) -> TypeGuard[type]:
    """Check if a type is Optional[T] or T | None.

    Args:
        typ: Type to check

    Returns:
        True if the type is Optional, False otherwise
    """
    origin = get_origin(typ)
    if origin not in {typing.Union, types.UnionType}:  # pyright: ignore
        return False
    args = get_args(typ)
    # Check if any of the union members is None or NoneType
    return any(arg is type(None) for arg in args)

pydantic_model_to_signature

pydantic_model_to_signature(model: type[BaseModel], return_type: type) -> Signature

Convert a Pydantic model to an inspect.Signature.

Model fields are represented as keyword-only parameters.

Parameters:

Name Type Description Default
model type[BaseModel]

The Pydantic model to convert.

required
return_type type

The return type of the function.

required
Source code in src/schemez/functionschema/helpers.py
def pydantic_model_to_signature(
    model: type[BaseModel],
    return_type: type,
) -> inspect.Signature:
    """Convert a Pydantic model to an inspect.Signature.

    Model fields are represented as keyword-only parameters.

    Args:
        model: The Pydantic model to convert.
        return_type: The return type of the function.
    """
    parameters: list[inspect.Parameter] = []
    for name, field in model.model_fields.items():
        default = inspect.Parameter.empty if field.is_required() else field.default
        param = inspect.Parameter(
            name=name,
            kind=inspect.Parameter.KEYWORD_ONLY,
            annotation=field.annotation,
            default=default,
        )
        parameters.append(param)
    return inspect.Signature(parameters=parameters, return_annotation=return_type)

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)

types_match

types_match(annotation: Any, exclude_type: type) -> bool

Check if annotation matches exclude_type using various strategies.

Source code in src/schemez/functionschema/helpers.py
def types_match(annotation: Any, exclude_type: type) -> bool:
    """Check if annotation matches exclude_type using various strategies."""
    try:
        # Direct type match
        if annotation is exclude_type:
            return True

        # Handle generic types - get origin for comparison
        origin_annotation = get_origin(annotation)
        if origin_annotation is exclude_type:
            return True

        # String-based comparison for forward references and __future__.annotations
        annotation_str = str(annotation)
        exclude_type_name = exclude_type.__name__
        exclude_type_full_name = f"{exclude_type.__module__}.{exclude_type.__name__}"

        # Check various string representations
        if exclude_type_name in annotation_str or exclude_type_full_name in annotation_str:
            # Be more specific to avoid false positives
            # Check if it's the exact type name, not just a substring
            patterns = [
                rf"\b{re.escape(exclude_type_name)}\b",
                rf"\b{re.escape(exclude_type_full_name)}\b",
            ]
            if any(re.search(pattern, annotation_str) for pattern in patterns):
                return True

    except Exception:  # noqa: BLE001
        pass

    return False