Skip to content

ExecutableFunction

Base classes

Name Children Inherits
Generic
typing
Abstract base class for generic types.

⋔ Inheritance diagram

graph TD
  1708917541["executable.ExecutableFunction"]
  3481597255["typing.Generic"]
  2751680898["builtins.object"]
  3481597255 --> 1708917541
  2751680898 --> 3481597255

🛈 DocStrings

Wrapper for executing functions with different calling patterns.

Source code in src/schemez/functionschema/executable.py
class ExecutableFunction[T_co]:
    """Wrapper for executing functions with different calling patterns."""

    def __init__(
        self,
        schema: FunctionSchema,
        func: (
            Callable[..., T_co]
            | Callable[..., Generator[T_co]]
            | Callable[..., AsyncGenerator[T_co]]
            | Callable[..., AsyncIterator[T_co]]
        ),
    ) -> None:
        """Initialize with schema and function.

        Args:
            schema: OpenAI function schema
            func: The actual function to execute
        """
        from schemez.functionschema import determine_function_type

        self.schema = schema
        self.func = func
        self.function_type: FunctionType = determine_function_type(self.func)

    def run(self, *args: Any, **kwargs: Any) -> T_co | list[T_co]:
        """Run the function synchronously.

        Args:
            *args: Positional arguments to pass to the function
            **kwargs: Keyword arguments to pass to the function

        Returns:
            Either a single result or list of results for generators

        Inside a running event loop, coroutines run on a worker thread's own loop
        (blocking the caller); use `arun` from async code.
        """
        func: Callable[..., Any] = self.func
        match self.function_type:
            case "sync":
                return func(*args, **kwargs)
            case "async":
                return _run_coroutine(lambda: func(*args, **kwargs))
            case "sync_generator":
                return list(func(*args, **kwargs))
            case "async_generator":
                return _run_coroutine(lambda: self._collect_async_gen(*args, **kwargs))
            case _ as unreachable:
                assert_never(unreachable)

    async def _collect_async_gen(self, *args: Any, **kwargs: Any) -> list[T_co]:
        """Collect async generator results into a list.

        Args:
            *args: Positional arguments to pass to the function
            **kwargs: Keyword arguments to pass to the function

        Returns:
            List of collected results
        """
        func: Callable[..., Any] = self.func
        return [x async for x in func(*args, **kwargs)]

    async def arun(self, *args: Any, **kwargs: Any) -> T_co | list[T_co]:
        """Run the function asynchronously.

        Args:
            *args: Positional arguments to pass to the function
            **kwargs: Keyword arguments to pass to the function

        Returns:
            Function result or list of results for generators

        Raises:
            ValueError: If the function type is unknown
        """
        func: Callable[..., Any] = self.func
        match self.function_type:
            case "sync":
                return func(*args, **kwargs)
            case "async":
                return await func(*args, **kwargs)
            case "sync_generator":
                return list(func(*args, **kwargs))
            case "async_generator":
                return [x async for x in func(*args, **kwargs)]
            case _:
                msg = f"Unknown function type: {self.function_type}"
                raise ValueError(msg)

    async def astream(self, *args: Any, **kwargs: Any) -> AsyncIterator[T_co]:
        """Stream results from the function.

        Args:
            *args: Positional arguments to pass to the function
            **kwargs: Keyword arguments to pass to the function

        Yields:
            Individual results as they become available

        Raises:
            ValueError: If the function type is unknown
        """
        func: Callable[..., Any] = self.func
        match self.function_type:
            case "sync_generator":
                for x in func(*args, **kwargs):
                    yield x
            case "async_generator":
                async for x in func(*args, **kwargs):
                    yield x
            case "sync":
                yield func(*args, **kwargs)
            case "async":
                yield await func(*args, **kwargs)
            case _ as unreachable:
                assert_never(unreachable)

__init__

__init__(
    schema: FunctionSchema,
    func: (
        Callable[..., T_co]
        | Callable[..., Generator[T_co]]
        | Callable[..., AsyncGenerator[T_co]]
        | Callable[..., AsyncIterator[T_co]]
    ),
) -> None

Initialize with schema and function.

Parameters:

Name Type Description Default
schema FunctionSchema

OpenAI function schema

required
func Callable[..., T_co] | Callable[..., Generator[T_co]] | Callable[..., AsyncGenerator[T_co]] | Callable[..., AsyncIterator[T_co]]

The actual function to execute

required
Source code in src/schemez/functionschema/executable.py
def __init__(
    self,
    schema: FunctionSchema,
    func: (
        Callable[..., T_co]
        | Callable[..., Generator[T_co]]
        | Callable[..., AsyncGenerator[T_co]]
        | Callable[..., AsyncIterator[T_co]]
    ),
) -> None:
    """Initialize with schema and function.

    Args:
        schema: OpenAI function schema
        func: The actual function to execute
    """
    from schemez.functionschema import determine_function_type

    self.schema = schema
    self.func = func
    self.function_type: FunctionType = determine_function_type(self.func)

arun async

arun(*args: Any, **kwargs: Any) -> T_co | list[T_co]

Run the function asynchronously.

Parameters:

Name Type Description Default
*args Any

Positional arguments to pass to the function

()
**kwargs Any

Keyword arguments to pass to the function

{}

Returns:

Type Description
T_co | list[T_co]

Function result or list of results for generators

Raises:

Type Description
ValueError

If the function type is unknown

Source code in src/schemez/functionschema/executable.py
async def arun(self, *args: Any, **kwargs: Any) -> T_co | list[T_co]:
    """Run the function asynchronously.

    Args:
        *args: Positional arguments to pass to the function
        **kwargs: Keyword arguments to pass to the function

    Returns:
        Function result or list of results for generators

    Raises:
        ValueError: If the function type is unknown
    """
    func: Callable[..., Any] = self.func
    match self.function_type:
        case "sync":
            return func(*args, **kwargs)
        case "async":
            return await func(*args, **kwargs)
        case "sync_generator":
            return list(func(*args, **kwargs))
        case "async_generator":
            return [x async for x in func(*args, **kwargs)]
        case _:
            msg = f"Unknown function type: {self.function_type}"
            raise ValueError(msg)

astream async

astream(*args: Any, **kwargs: Any) -> AsyncIterator[T_co]

Stream results from the function.

Parameters:

Name Type Description Default
*args Any

Positional arguments to pass to the function

()
**kwargs Any

Keyword arguments to pass to the function

{}

Yields:

Type Description
AsyncIterator[T_co]

Individual results as they become available

Raises:

Type Description
ValueError

If the function type is unknown

Source code in src/schemez/functionschema/executable.py
async def astream(self, *args: Any, **kwargs: Any) -> AsyncIterator[T_co]:
    """Stream results from the function.

    Args:
        *args: Positional arguments to pass to the function
        **kwargs: Keyword arguments to pass to the function

    Yields:
        Individual results as they become available

    Raises:
        ValueError: If the function type is unknown
    """
    func: Callable[..., Any] = self.func
    match self.function_type:
        case "sync_generator":
            for x in func(*args, **kwargs):
                yield x
        case "async_generator":
            async for x in func(*args, **kwargs):
                yield x
        case "sync":
            yield func(*args, **kwargs)
        case "async":
            yield await func(*args, **kwargs)
        case _ as unreachable:
            assert_never(unreachable)

run

run(*args: Any, **kwargs: Any) -> T_co | list[T_co]

Run the function synchronously.

Parameters:

Name Type Description Default
*args Any

Positional arguments to pass to the function

()
**kwargs Any

Keyword arguments to pass to the function

{}

Returns:

Type Description
T_co | list[T_co]

Either a single result or list of results for generators

Inside a running event loop, coroutines run on a worker thread's own loop (blocking the caller); use arun from async code.

Source code in src/schemez/functionschema/executable.py
def run(self, *args: Any, **kwargs: Any) -> T_co | list[T_co]:
    """Run the function synchronously.

    Args:
        *args: Positional arguments to pass to the function
        **kwargs: Keyword arguments to pass to the function

    Returns:
        Either a single result or list of results for generators

    Inside a running event loop, coroutines run on a worker thread's own loop
    (blocking the caller); use `arun` from async code.
    """
    func: Callable[..., Any] = self.func
    match self.function_type:
        case "sync":
            return func(*args, **kwargs)
        case "async":
            return _run_coroutine(lambda: func(*args, **kwargs))
        case "sync_generator":
            return list(func(*args, **kwargs))
        case "async_generator":
            return _run_coroutine(lambda: self._collect_async_gen(*args, **kwargs))
        case _ as unreachable:
            assert_never(unreachable)

:fa-brands-github: Show source on GitHub