Skip to content

Component

Defines an abstract base class for all components used throughout the Gen AI applications.

Component

An abstract base class for all components used throughout the Gen AI applications.

Every instance of Component has access to class-level _default_log_level and _logger, as detailed below. For components that require high observability, it is recommended to set _default_log_level to logging.INFO or higher.

Defining Custom Components

There are two ways to define the main execution logic for a component:

  1. Using the @main decorator (Recommended): Decorate an async method with @main to mark it as the primary entrypoint. This is the preferred approach as it provides explicit control over the main method.

```python class MyComponent(Component): _default_log_level = logging.INFO

   @main
   async def execute(self, **kwargs: Any) -> Any:
       return "Hello from @main!"

```

  1. Implementing _run method (Deprecated): Override the abstract _run method. This is the traditional approach and still supported.

```python class MyComponent(Component): _default_log_level = logging.INFO

   async def _run(self, **kwargs: Any) -> Any:
       return "Hello, World!"

```

The run() method resolves the main entrypoint using the following precedence: 1. Method decorated with @main in the current class. 2. Method decorated with @main in the nearest ancestor class. 3. Method named in main_method property. 4. The _run method (with deprecation warning).

Attributes:

Name Type Description
run_profile RunProfile

The profile of the _run method. This property is used by Pipeline to analyze the input requirements of the component. In most cases, unless you are working with Pipeline and PipelineSteps, you will not need to use this property.

Do not override this property in your subclass.

You also do not need to write this attribute in your component's docstring.

input_params property

Return the Pydantic model describing this component's main method input parameters.

Returns:

Type Description
type[BaseModel] | None

type[BaseModel] | None: The cached model that mirrors the signature of the resolved main method, or None if no main method can be determined.

Examples:

from pydantic import ValidationError

component = SomeComponent()
ParamsModel = component.input_params
assert ParamsModel.__name__ == "SomeComponentParams"
fields = list(ParamsModel.model_fields)

# Validation with valid params
params = ParamsModel(text="hello")

# Validation catches missing required fields
try:
    invalid_params = ParamsModel()  # Missing required 'text' field
except ValidationError as e:
    print(f"Validation failed: {e.error_count()} errors")

# Argument construction
payload = params.model_dump()
result = await component.run(**payload)

run_profile property

Analyzes the _run method and retrieves its profile.

This property method analyzes the _run method of the class to generate a RunProfile object. It also updates the method signatures for methods that fully utilize the arguments.

Returns:

Name Type Description
RunProfile RunProfile

The profile of the _run method, including method signatures for full-pass argument usages.

__init_subclass__(**kwargs)

Hook called when a subclass is created.

This validates the main_method property and checks for multiple @main decorators within the current class definition. Uses MainMethodResolver for consistent validation logic.

Note: Multiple inheritance conflicts are intentionally deferred to runtime (get_main()) to allow class definition to succeed.

Raises:

Type Description
AttributeError

If main_method refers to a non-existent method.

TypeError

If multiple methods are decorated with @main in the same class.

as_tool(name=None, description=None, title=None)

Convert the component's main method into a Tool instance.

Example
from gllm_core.schema import Component, main

class MyComponent(Component):
    @main
    async def my_method(self, param: str) -> str:
        return param

component = MyComponent()
tool = component.as_tool()

Parameters:

Name Type Description Default
name str | None

Identifier for the resulting tool. Defaults to the component class name.

None
description str | None

Summary of the tool's behavior. Defaults to None, in which case the main method's docstring is used.

None
title str | None

Optional display title for the tool. Defaults to None, in which case the component's class name is used.

None

Returns:

Name Type Description
Tool Tool

The tool wrapping the component's main method.

Raises:

Type Description
RuntimeError

If the component does not declare a main method using @main or main_method.

get_main() cached classmethod

Return the resolved main coroutine for this Component class.

This method resolves the main method for the Component class following the precedence rules: 1. Most derived coroutine decorated with @main. 2. Method named by __main_method__. 3. _run coroutine as a deprecated fallback.

Results are cached for performance.

Returns:

Type Description
Callable | None

Callable | None: The coroutine that will be executed by run() or None when no entrypoint can be determined.

Raises:

Type Description
TypeError

If conflicting main methods are inherited from multiple ancestors.

run(**kwargs) async

Runs the operations defined for the component.

This method emits the provided input arguments using an EventEmitter instance if available, executes the resolved main method, and emits the resulting output if the EventEmitter is provided.

The main method is resolved using the following precedence: 1. Method decorated with @main in the current class. 2. Method decorated with @main in the nearest ancestor class. 3. Method named in main_method property. 4. The _run method (with deprecation warning).

Parameters:

Name Type Description Default
**kwargs Any

A dictionary of arguments to be processed. May include an event_emitter key with an EventEmitter instance.

{}

Returns:

Name Type Description
Any Any

The result of the resolved main method.

Raises:

Type Description
TypeError

If conflicting main methods are inherited from multiple ancestors.

AttributeError

If main_method refers to a non-existent method.

to_dynamic(init_kwargs=None, cache_instances=False, cache_size=256) classmethod

Create a DynamicComponent wrapper for this component class.

Examples:

Runtime constructor binding:

from gllm_core.schema import Lazy

retriever = SomeRetriever.to_dynamic(
    init_kwargs={
        "tenant_id": Lazy.from_runtime("tenant_id"),
        "timeout": 30,
    },
    cache_instances=True,
    cache_size=256,
)

result = await retriever.run(tenant_id="acme", query="hello")

Resolver-based constructor binding:

from gllm_core.schema import Lazy

connector = SomeConnector.to_dynamic(
    init_kwargs={
        "base_url": Lazy.resolver(resolve_base_url, arg_name="tenant_id"),
        "api_key": Lazy.async_resolver(load_api_key, arg_name="tenant_id"),
    },
)

result = await connector.run(tenant_id="org-123", query="status")

Parameters:

Name Type Description Default
init_kwargs dict[str, object | Lazy[object]] | None

Constructor kwargs for the wrapped component. Values may be literals or runtime-resolved Lazy bindings. Defaults to None.

None
cache_instances bool

Whether to reuse wrapped component instances for identical resolved constructor kwargs. Defaults to False.

False
cache_size int | None

Maximum number of cached instances when cache_instances is enabled. Use None for unbounded cache. Defaults to 256.

256

Returns:

Type Description
DynamicComponent[Self]

DynamicComponent[Self]: Dynamic wrapper bound to this component class.

Raises:

Type Description
TypeError

If cls is not a concrete Component subtype when wrapper validation runs.

main(method)

Decorate a Component method as the async main entrypoint.

Usage

Declare the coroutine that should act as the primary execution path for a Component subclass. The decorated coroutine will be resolved by Component.run() unless another subclass overrides the decoration.

Parameters:

Name Type Description Default
method Callable

Coroutine to mark as the main entrypoint.

required

Returns:

Name Type Description
Callable Callable

The same coroutine that is passed to the decorator. The decorator only marks the method as the main entrypoint. It does not wrap or change its behavior or signature.

Raises:

Type Description
TypeError

If the decorated callable is not asynchronous.