Skip to content

processors

Class info

Re-exported classes

Class Module Description
Processor llmling.processors.base Content processor that executes a callable.
ProcessorConfig llmling.processors.base Configuration for content processors.
ProcessorRegistry llmling.processors.registry Registry for content processors.
ProcessorResult llmling.processors.base Result of processing content.

🛈 DocStrings

Collection of content processors for text transformation pipelines.

Processor

Bases: BaseProcessor

Content processor that executes a callable.

Source code in src/llmling/processors/base.py
class Processor(BaseProcessor):
    """Content processor that executes a callable."""

    def __init__(self, config: ProcessorConfig) -> None:
        super().__init__()
        self.config = config
        self._callable: Any = None

    async def startup(self) -> None:
        """Load the callable during startup."""
        if not self.config.import_path:
            msg = "Import path not configured"
            raise exceptions.ProcessorError(msg)

        try:
            self._callable = calling.import_callable(self.config.import_path)
        except ValueError as exc:
            msg = f"Failed to load callable: {exc}"
            raise exceptions.ProcessorError(msg) from exc

        self._initialized = True

    async def process(self, context: ProcessingContext) -> ProcessorResult:
        """Process content using the configured callable."""
        if not self._initialized or not self._callable:
            msg = "Processor not initialized"
            raise exceptions.ProcessorError(msg)

        try:
            # Execute callable
            result = self._callable(context.current_content, **context.kwargs)

            # Handle async functions
            if calling.is_async_callable(self._callable):
                result = await result

            # Convert result to string
            content = str(result)
            is_async = calling.is_async_callable(self._callable)
            meta = {"function": self.config.import_path, "is_async": is_async}
            orig = context.original_content
            return ProcessorResult(content=content, original_content=orig, metadata=meta)
        except Exception as exc:
            msg = f"Processing failed: {exc}"
            raise exceptions.ProcessorError(msg) from exc

    async def shutdown(self) -> None:
        """Clean up resources."""
        self._initialized = False
        self._callable = None

process async

process(context: ProcessingContext) -> ProcessorResult

Process content using the configured callable.

Source code in src/llmling/processors/base.py
async def process(self, context: ProcessingContext) -> ProcessorResult:
    """Process content using the configured callable."""
    if not self._initialized or not self._callable:
        msg = "Processor not initialized"
        raise exceptions.ProcessorError(msg)

    try:
        # Execute callable
        result = self._callable(context.current_content, **context.kwargs)

        # Handle async functions
        if calling.is_async_callable(self._callable):
            result = await result

        # Convert result to string
        content = str(result)
        is_async = calling.is_async_callable(self._callable)
        meta = {"function": self.config.import_path, "is_async": is_async}
        orig = context.original_content
        return ProcessorResult(content=content, original_content=orig, metadata=meta)
    except Exception as exc:
        msg = f"Processing failed: {exc}"
        raise exceptions.ProcessorError(msg) from exc

shutdown async

shutdown() -> None

Clean up resources.

Source code in src/llmling/processors/base.py
async def shutdown(self) -> None:
    """Clean up resources."""
    self._initialized = False
    self._callable = None

startup async

startup() -> None

Load the callable during startup.

Source code in src/llmling/processors/base.py
async def startup(self) -> None:
    """Load the callable during startup."""
    if not self.config.import_path:
        msg = "Import path not configured"
        raise exceptions.ProcessorError(msg)

    try:
        self._callable = calling.import_callable(self.config.import_path)
    except ValueError as exc:
        msg = f"Failed to load callable: {exc}"
        raise exceptions.ProcessorError(msg) from exc

    self._initialized = True

ProcessorConfig

Bases: Schema

Configuration for content processors.

Source code in src/llmling/processors/base.py
class ProcessorConfig(Schema):
    """Configuration for content processors."""

    name: str | None = None
    description: str | None = None
    import_path: str
    async_execution: bool = False
    timeout: float | None = None
    cache_results: bool = False
    metadata: dict[str, Any] = Field(default_factory=dict)

ProcessorRegistry

Bases: BaseRegistry[str, BaseProcessor]

Registry for content processors.

Source code in src/llmling/processors/registry.py
class ProcessorRegistry(BaseRegistry[str, BaseProcessor]):
    """Registry for content processors."""

    def __init__(self, *args, **kwargs) -> None:
        """Initialize registry with builtin processors."""
        super().__init__(*args, **kwargs)

    @property
    def _error_class(self) -> type[exceptions.ProcessorError]:
        return exceptions.ProcessorError

    def _validate_item(self, item: Any) -> BaseProcessor:
        """Validate and transform items."""
        match item:
            case BaseProcessor():
                return item
            case ProcessorConfig():
                return Processor(item)  # Creates function-based processor
            case _ if callable(item):
                path = f"{item.__module__}.{item.__qualname__}"
                is_coro = inspect.iscoroutinefunction(item)
                config = ProcessorConfig(import_path=path, async_execution=is_coro)
                return Processor(config)
            case _:
                msg = f"Invalid processor type: {type(item)}"
                raise exceptions.ProcessorError(msg)

    async def process(
        self,
        content: str,
        steps: list[ProcessingStep],
        metadata: dict[str, Any] | None = None,
    ) -> ProcessorResult:
        """Process content through steps."""
        if not self._initialized:
            await self.startup()

        current_context = ProcessingContext(
            original_content=content,
            current_content=content,
            metadata=metadata or {},
            kwargs={},
        )

        result = None
        for step in steps:
            step_context = ProcessingContext(
                original_content=current_context.original_content,
                current_content=current_context.current_content,
                metadata=current_context.metadata,
                kwargs=step.kwargs or {},
            )

            processor = await self.get_processor(step.name)
            try:
                result = await processor.process(step_context)
            except Exception as exc:
                if step.required:
                    msg = f"Required step {step.name} failed: {exc}"
                    raise exceptions.ProcessorError(msg) from exc

                # Optional step failed, continue with current context
                logger.warning("Optional step %s failed: %s", step.name, exc)
                result = ProcessorResult(
                    content=current_context.current_content,
                    original_content=current_context.original_content,
                    metadata=current_context.metadata,
                )

            # Update context for next step
            if result:
                current_context = ProcessingContext(
                    original_content=content,
                    current_content=result.content,
                    metadata={**current_context.metadata, **result.metadata},
                    kwargs={},
                )

        return (
            result
            if result
            else ProcessorResult(
                content=content,
                original_content=content,
                metadata=current_context.metadata,
            )
        )

    async def get_processor(self, name: str) -> BaseProcessor:
        """Get a processor by name."""
        processor = self.get(name)
        if not getattr(processor, "_initialized", False):
            await processor.startup()
            processor._initialized = True
        return processor

__init__

__init__(*args, **kwargs) -> None

Initialize registry with builtin processors.

Source code in src/llmling/processors/registry.py
def __init__(self, *args, **kwargs) -> None:
    """Initialize registry with builtin processors."""
    super().__init__(*args, **kwargs)

get_processor async

get_processor(name: str) -> BaseProcessor

Get a processor by name.

Source code in src/llmling/processors/registry.py
async def get_processor(self, name: str) -> BaseProcessor:
    """Get a processor by name."""
    processor = self.get(name)
    if not getattr(processor, "_initialized", False):
        await processor.startup()
        processor._initialized = True
    return processor

process async

process(
    content: str, steps: list[ProcessingStep], metadata: dict[str, Any] | None = None
) -> ProcessorResult

Process content through steps.

Source code in src/llmling/processors/registry.py
async def process(
    self,
    content: str,
    steps: list[ProcessingStep],
    metadata: dict[str, Any] | None = None,
) -> ProcessorResult:
    """Process content through steps."""
    if not self._initialized:
        await self.startup()

    current_context = ProcessingContext(
        original_content=content,
        current_content=content,
        metadata=metadata or {},
        kwargs={},
    )

    result = None
    for step in steps:
        step_context = ProcessingContext(
            original_content=current_context.original_content,
            current_content=current_context.current_content,
            metadata=current_context.metadata,
            kwargs=step.kwargs or {},
        )

        processor = await self.get_processor(step.name)
        try:
            result = await processor.process(step_context)
        except Exception as exc:
            if step.required:
                msg = f"Required step {step.name} failed: {exc}"
                raise exceptions.ProcessorError(msg) from exc

            # Optional step failed, continue with current context
            logger.warning("Optional step %s failed: %s", step.name, exc)
            result = ProcessorResult(
                content=current_context.current_content,
                original_content=current_context.original_content,
                metadata=current_context.metadata,
            )

        # Update context for next step
        if result:
            current_context = ProcessingContext(
                original_content=content,
                current_content=result.content,
                metadata={**current_context.metadata, **result.metadata},
                kwargs={},
            )

    return (
        result
        if result
        else ProcessorResult(
            content=content,
            original_content=content,
            metadata=current_context.metadata,
        )
    )

ProcessorResult

Bases: Schema

Result of processing content.

Source code in src/llmling/processors/base.py
class ProcessorResult(Schema):
    """Result of processing content."""

    content: str
    original_content: str
    metadata: dict[str, Any] = Field(default_factory=dict)

    model_config = ConfigDict(frozen=True)