Skip to content

loaders

Class info

Re-exported classes

Class Module Description
CLIResourceLoader llmling.resources.loaders.cli Loads context from CLI command execution.
CallableResourceLoader llmling.resources.loaders.callable Loads context from Python callable execution with URI parameter support.
PathResourceLoader llmling.resources.loaders.path Loads context from files or URLs.
RepositoryResourceLoader llmling.resources.loaders.repository Loads content from Git repositories.
ResourceLoaderRegistry llmling.resources.loaders.registry Registry for context loaders.
SourceResourceLoader llmling.resources.loaders.source Loads context from Python source code.
TextResourceLoader llmling.resources.loaders.text Loads context from raw text.

🛈 DocStrings

Resource loader implementations.

CLIResourceLoader

Bases: ResourceLoader[CLIResource]

Loads context from CLI command execution.

Source code in src/llmling/resources/loaders/cli.py
class CLIResourceLoader(ResourceLoader[CLIResource]):
    """Loads context from CLI command execution."""

    context_class = CLIResource
    uri_scheme = "cli"
    supported_mime_types: ClassVar[list[str]] = ["text/plain"]

    async def _load_impl(
        self,
        resource: CLIResource,
        name: str,
        processor_registry: ProcessorRegistry | None,
    ) -> AsyncIterator[LoadedResource]:
        """Execute command and load output."""
        command = cmd if isinstance((cmd := resource.command), str) else " ".join(cmd)
        try:
            kwargs: dict[str, Any] = dict(
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
                cwd=resource.cwd,
            )
            if resource.shell:
                proc = await asyncio.create_subprocess_shell(command, **kwargs)
            else:
                proc = await asyncio.create_subprocess_exec(*command.split(), **kwargs)
            coro = proc.communicate()
            stdout, stderr = await asyncio.wait_for(coro, timeout=resource.timeout)

            if proc.returncode != 0:
                error = stderr.decode().strip()
                msg = f"Command failed with code {proc.returncode}: {error}"
                raise exceptions.LoaderError(msg)  # noqa: TRY301

            content = stdout.decode()

            if processor_registry and (procs := resource.processors):
                processed = await processor_registry.process(content, procs)
                content = processed.content
            meta = {"command": command, "exit_code": proc.returncode}
            yield create_loaded_resource(
                content=content,
                source_type="cli",
                uri=self.create_uri(name=name),
                mime_type=self.supported_mime_types[0],
                name=resource.description or f"CLI Output: {command}",
                description=resource.description,
                additional_metadata=meta,
            )
        except Exception as exc:
            msg = f"CLI command execution failed: {command}"
            raise exceptions.LoaderError(msg) from exc

CallableResourceLoader

Bases: ResourceLoader[CallableResource]

Loads context from Python callable execution with URI parameter support.

Source code in src/llmling/resources/loaders/callable.py
class CallableResourceLoader(ResourceLoader[CallableResource]):
    """Loads context from Python callable execution with URI parameter support."""

    context_class = CallableResource
    uri_scheme = "callable"
    supported_mime_types: ClassVar[list[str]] = ["text/plain"]

    async def _load_impl(
        self,
        resource: CallableResource,
        name: str,
        processor_registry: ProcessorRegistry | None,
    ) -> AsyncIterator[LoadedResource]:
        """Execute callable with parameters from URI if present."""
        try:
            # Get base kwargs from resource config
            kwargs = resource.keyword_args.copy()

            # If we have a URI context, extract and merge parameters
            if self.context:
                uri = self.create_uri(name=self.context.name)
                uri_params = self.get_params_from_uri(uri)
                kwargs.update(uri_params)

            # Execute the callable with combined parameters
            content = await calling.execute_callable(resource.import_path, **kwargs)

            if processor_registry and (procs := resource.processors):
                processed = await processor_registry.process(content, procs)
                content = processed.content

            meta = {"import_path": resource.import_path, "args": kwargs}

            yield create_loaded_resource(
                content=content,
                source_type="callable",
                uri=self.create_uri(name=name),
                name=resource.description or resource.import_path,
                description=resource.description,
                additional_metadata=meta,
            )
        except Exception as exc:
            msg = f"Failed to execute callable {resource.import_path}"
            raise exceptions.LoaderError(msg) from exc

PathResourceLoader

Bases: ResourceLoader[PathResource]

Loads context from files or URLs.

Source code in src/llmling/resources/loaders/path.py
class PathResourceLoader(ResourceLoader[PathResource]):
    """Loads context from files or URLs."""

    context_class = PathResource
    uri_scheme = "file"
    supported_mime_types: ClassVar[list[str]] = [
        "text/plain",
        "application/json",
        "text/markdown",
        "text/yaml",
    ]

    @classmethod
    def get_name_from_uri(cls, uri: str) -> str:
        """Extract the normalized path from a URI."""
        try:
            return paths.uri_to_path(uri)
        except ValueError as exc:
            msg = f"Invalid URI: {uri}"
            raise exceptions.LoaderError(msg) from exc

    def create_uri(self, *, name: str, params: dict[str, str] | None = None) -> str:
        """Create a URI based on resource path basename or explicit URI."""
        from upathtools import to_upath

        try:
            if self.context and self.context.resource:
                if self.context.resource.uri:
                    return paths.path_to_uri(self.context.resource.uri)
                # Use basename of the configured path
                path = to_upath(self.context.resource.path)
                return paths.path_to_uri(path.name)
            # Fallback to name if no context
            return paths.path_to_uri(name)
        except ValueError as exc:
            msg = f"Failed to create URI from {name}"
            raise exceptions.LoaderError(msg) from exc

    async def get_completions(
        self,
        current_value: str,
        argument_name: str | None = None,
        **options: Any,
    ) -> list[str]:
        """Get path completions."""
        from upath import UPath

        try:
            # Handle both absolute and relative paths
            path = UPath(current_value) if current_value else UPath()
            if not current_value:
                # Show current directory contents for empty input
                matches = list(path.glob("*"))
            else:
                pattern = f"{path}*" if path.is_dir() else f"{path.parent}/*"
                matches = list(UPath().glob(pattern))

            return [str(p) for p in matches if str(p).startswith(current_value or ".")]
        except Exception:
            logger.exception("Path completion failed")
            return []

    async def _load_impl(
        self,
        resource: PathResource,
        name: str,
        processor_registry: ProcessorRegistry | None,
    ) -> AsyncIterator[LoadedResource]:
        """Load content from file(s)."""
        from upathtools import to_upath

        try:
            path = to_upath(resource.path)

            if path.is_dir():
                # Handle directory recursively
                files = [p for p in path.rglob("*") if p.is_file()]
                for file_path in files:
                    content = file_path.read_text("utf-8")
                    if processor_registry and (procs := resource.processors):
                        processed = await processor_registry.process(content, procs)
                        content = processed.content
                    # Preserve original format - if input was file URL, use file URL
                    path_for_meta = (
                        str(resource.path)
                        if str(resource.path).startswith("file://")
                        else str(file_path)
                    )
                    meta = {
                        "type": "path",
                        "path": path_for_meta,
                        "scheme": file_path.protocol,
                        "relative_to": str(path),
                    }
                    yield create_loaded_resource(
                        content=content,
                        source_type="path",
                        uri=self.create_uri(name=file_path.name),  # Use filename for URI
                        mime_type=self.supported_mime_types[0],
                        name=resource.description or file_path.name,
                        description=resource.description,
                        additional_metadata=meta,
                    )
            else:
                # Handle single file
                content = path.read_text("utf-8")
                if processor_registry and (procs := resource.processors):
                    processed = await processor_registry.process(content, procs)
                    content = processed.content
                # Preserve original format - if input was file URL, use file URL
                path_for_meta = (
                    str(resource.path) if str(resource.path).startswith("file://") else str(path)
                )
                meta = {"type": "path", "path": path_for_meta, "scheme": path.protocol}
                yield create_loaded_resource(
                    content=content,
                    source_type="path",
                    uri=self.create_uri(name=name),
                    mime_type=self.supported_mime_types[0],
                    name=resource.description or path.name,
                    description=resource.description,
                    additional_metadata=meta,
                )
        except Exception as exc:
            msg = f"Failed to load content from {resource.path}"
            raise exceptions.LoaderError(msg) from exc

create_uri

create_uri(*, name: str, params: dict[str, str] | None = None) -> str

Create a URI based on resource path basename or explicit URI.

Source code in src/llmling/resources/loaders/path.py
def create_uri(self, *, name: str, params: dict[str, str] | None = None) -> str:
    """Create a URI based on resource path basename or explicit URI."""
    from upathtools import to_upath

    try:
        if self.context and self.context.resource:
            if self.context.resource.uri:
                return paths.path_to_uri(self.context.resource.uri)
            # Use basename of the configured path
            path = to_upath(self.context.resource.path)
            return paths.path_to_uri(path.name)
        # Fallback to name if no context
        return paths.path_to_uri(name)
    except ValueError as exc:
        msg = f"Failed to create URI from {name}"
        raise exceptions.LoaderError(msg) from exc

get_completions async

get_completions(current_value: str, argument_name: str | None = None, **options: Any) -> list[str]

Get path completions.

Source code in src/llmling/resources/loaders/path.py
async def get_completions(
    self,
    current_value: str,
    argument_name: str | None = None,
    **options: Any,
) -> list[str]:
    """Get path completions."""
    from upath import UPath

    try:
        # Handle both absolute and relative paths
        path = UPath(current_value) if current_value else UPath()
        if not current_value:
            # Show current directory contents for empty input
            matches = list(path.glob("*"))
        else:
            pattern = f"{path}*" if path.is_dir() else f"{path.parent}/*"
            matches = list(UPath().glob(pattern))

        return [str(p) for p in matches if str(p).startswith(current_value or ".")]
    except Exception:
        logger.exception("Path completion failed")
        return []

get_name_from_uri classmethod

get_name_from_uri(uri: str) -> str

Extract the normalized path from a URI.

Source code in src/llmling/resources/loaders/path.py
@classmethod
def get_name_from_uri(cls, uri: str) -> str:
    """Extract the normalized path from a URI."""
    try:
        return paths.uri_to_path(uri)
    except ValueError as exc:
        msg = f"Invalid URI: {uri}"
        raise exceptions.LoaderError(msg) from exc

RepositoryResourceLoader

Bases: ResourceLoader[RepositoryResource]

Loads content from Git repositories.

Source code in src/llmling/resources/loaders/repository.py
class RepositoryResourceLoader(ResourceLoader[RepositoryResource]):
    """Loads content from Git repositories."""

    context_class = RepositoryResource
    uri_scheme = "repository"
    supported_mime_types: ClassVar[list[str]] = ["text/plain", "text/x-python"]

    def __init__(self, context: LoaderContext[RepositoryResource] | None = None) -> None:
        super().__init__(context)
        self._cache: dict[str, tuple[Repo, float]] = {}
        self._cache_timeout = 300  # 5 minutes

    def _get_cached_repo(self, repo_url: str) -> Repo | None:
        """Get cached repository if not expired."""
        if cached := self._cache.get(repo_url):
            repo, last_access = cached
            if time() - last_access <= self._cache_timeout:
                self._cache[repo_url] = (repo, time())  # Update access time
                return repo
            # Remove expired cache entry
            self._cache.pop(repo_url)
        return None

    def _cache_repo(self, repo_url: str, repo: Repo) -> None:
        """Cache repository for reuse."""
        self._cache[repo_url] = (repo, time())

    def _create_resource(
        self,
        path: JoinablePathLike,
        name: str,
        resource: RepositoryResource,
    ) -> LoadedResource:
        """Create LoadedResource from file."""
        from upathtools import to_upath

        path_obj = to_upath(path)
        try:
            content = path_obj.read_text("utf-8")
            description = f"Repository content from {resource.repo_url} ({resource.ref})"
            return create_loaded_resource(
                content=content,
                source_type="repository",
                uri=self.create_uri(name=name),
                mime_type=guess_mime_type(path),
                name=resource.description or path_obj.name,
                description=description,
                additional_metadata={
                    "repo": resource.repo_url,
                    "ref": resource.ref,
                    "path": str(path),
                },
            )
        except Exception as exc:
            msg = f"Failed to create resource from {path}: {exc}"
            raise exceptions.LoaderError(msg) from exc

    async def _load_impl(
        self,
        resource: RepositoryResource,
        name: str,
        processor_registry: ProcessorRegistry | None,
    ) -> AsyncIterator[LoadedResource]:
        """Load git content."""
        import git
        from upathtools import to_upath

        try:
            repo = self._get_cached_repo(resource.repo_url)
            if not repo:
                # The clone must outlive this call since the repo object gets cached.
                tmp_dir = tempfile.mkdtemp(prefix="llmling_repo_")
                logger.debug("Cloning %s to %s", resource.repo_url, tmp_dir)
                repo = git.Repo.clone_from(resource.repo_url, tmp_dir, branch=resource.ref)
                if resource.sparse_checkout:
                    path_str = " ".join(resource.sparse_checkout)
                    repo.git.sparse_checkout("set", path_str)
                self._cache_repo(resource.repo_url, repo)

            # Switch to requested ref
            repo.git.checkout(resource.ref)

            base_path = to_upath(repo.working_dir) / resource.path.lstrip("/")
            if base_path.is_file():
                loaded = self._create_resource(base_path, name, resource)
                if processor_registry and resource.processors:
                    result = await processor_registry.process(loaded.content, resource.processors)
                    loaded.content = result.content
                yield loaded
            else:
                # Directory - yield all matching files
                files = [p for p in base_path.rglob("*") if p.is_file()]
                for file_path in files:
                    rel_path = file_path.relative_to(base_path)
                    loaded = self._create_resource(file_path, str(rel_path), resource)
                    if processor_registry and resource.processors:
                        result = await processor_registry.process(
                            loaded.content, resource.processors
                        )
                        loaded.content = result.content
                    yield loaded

        except git.exc.GitCommandError as exc:
            msg = f"Git operation failed: {exc}"
            raise exceptions.LoaderError(msg) from exc
        except Exception as exc:
            msg = f"Failed to load repository content: {exc}"
            raise exceptions.LoaderError(msg) from exc

ResourceLoaderRegistry

Bases: BaseRegistry[str, ResourceLoader[Any]]

Registry for context loaders.

Source code in src/llmling/resources/loaders/registry.py
class ResourceLoaderRegistry(BaseRegistry[str, ResourceLoader[Any]]):
    """Registry for context loaders."""

    def __init__(self, register_default_loaders: bool = False, **kwargs) -> None:
        """Initialize registry.

        Args:
            register_default_loaders: Register default loaders on initialization.
            kwargs: Additional keyword arguments passed to the parent class.
        """
        super().__init__(**kwargs)
        if register_default_loaders:
            self.register_default_loaders()

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

    def get_supported_schemes(self) -> list[str]:
        """Get all supported URI schemes."""
        return [loader.uri_scheme for loader in self._items.values()]

    def register_default_loaders(self) -> None:
        from llmling.resources import (
            CallableResourceLoader,
            CLIResourceLoader,
            PathResourceLoader,
            RepositoryResourceLoader,
            SourceResourceLoader,
            TextResourceLoader,
        )

        self["path"] = PathResourceLoader
        self["text"] = TextResourceLoader
        self["cli"] = CLIResourceLoader
        self["source"] = SourceResourceLoader
        self["callable"] = CallableResourceLoader
        self["repository"] = RepositoryResourceLoader

    def get_uri_templates(self) -> list[dict[str, Any]]:
        """Get URI templates for all registered loaders."""
        return [
            {
                "scheme": loader.uri_scheme,
                "template": loader.get_uri_template(),
                "mimeTypes": loader.supported_mime_types,
            }
            for loader in self._items.values()
        ]

    def find_loader_for_uri(self, uri: str) -> ResourceLoader[Any]:
        """Find appropriate loader for a URI."""
        # Parse scheme from URI string
        try:
            scheme = uri.split("://", maxsplit=1)[0]
        except IndexError:
            msg = f"Invalid URI format: {uri}"
            raise exceptions.LoaderError(msg) from None

        for loader in self._items.values():
            if loader.uri_scheme == scheme:
                return loader

        msg = f"No loader found for URI scheme: {scheme}"
        raise exceptions.LoaderError(msg)

    def _validate_item(self, item: Any) -> ResourceLoader[Any]:
        """Validate and possibly transform item before registration."""
        from upathtools import to_upath

        match item:
            case str() if "\n" in item:
                resource = TextResource(content=item)
                return TextResourceLoader.create(resource=resource, name="inline-text")
            case str() | os.PathLike() if to_upath(item).exists():
                path_resource = PathResource(path=str(item))
                name = to_upath(item).name
                return PathResourceLoader.create(resource=path_resource, name=name)
            case type() if issubclass(item, ResourceLoader):
                return item()
            case ResourceLoader():
                return item
            case _:
                msg = f"Invalid context loader type: {type(item)}"
                raise exceptions.LoaderError(msg)

    def get_loader(self, context: BaseResource) -> ResourceLoader[Any]:
        """Get a loader instance for a context type."""
        return self.get(context.type)

__init__

__init__(register_default_loaders: bool = False, **kwargs) -> None

Initialize registry.

Parameters:

Name Type Description Default
register_default_loaders bool

Register default loaders on initialization.

False
kwargs

Additional keyword arguments passed to the parent class.

{}
Source code in src/llmling/resources/loaders/registry.py
def __init__(self, register_default_loaders: bool = False, **kwargs) -> None:
    """Initialize registry.

    Args:
        register_default_loaders: Register default loaders on initialization.
        kwargs: Additional keyword arguments passed to the parent class.
    """
    super().__init__(**kwargs)
    if register_default_loaders:
        self.register_default_loaders()

find_loader_for_uri

find_loader_for_uri(uri: str) -> ResourceLoader[Any]

Find appropriate loader for a URI.

Source code in src/llmling/resources/loaders/registry.py
def find_loader_for_uri(self, uri: str) -> ResourceLoader[Any]:
    """Find appropriate loader for a URI."""
    # Parse scheme from URI string
    try:
        scheme = uri.split("://", maxsplit=1)[0]
    except IndexError:
        msg = f"Invalid URI format: {uri}"
        raise exceptions.LoaderError(msg) from None

    for loader in self._items.values():
        if loader.uri_scheme == scheme:
            return loader

    msg = f"No loader found for URI scheme: {scheme}"
    raise exceptions.LoaderError(msg)

get_loader

get_loader(context: BaseResource) -> ResourceLoader[Any]

Get a loader instance for a context type.

Source code in src/llmling/resources/loaders/registry.py
def get_loader(self, context: BaseResource) -> ResourceLoader[Any]:
    """Get a loader instance for a context type."""
    return self.get(context.type)

get_supported_schemes

get_supported_schemes() -> list[str]

Get all supported URI schemes.

Source code in src/llmling/resources/loaders/registry.py
def get_supported_schemes(self) -> list[str]:
    """Get all supported URI schemes."""
    return [loader.uri_scheme for loader in self._items.values()]

get_uri_templates

get_uri_templates() -> list[dict[str, Any]]

Get URI templates for all registered loaders.

Source code in src/llmling/resources/loaders/registry.py
def get_uri_templates(self) -> list[dict[str, Any]]:
    """Get URI templates for all registered loaders."""
    return [
        {
            "scheme": loader.uri_scheme,
            "template": loader.get_uri_template(),
            "mimeTypes": loader.supported_mime_types,
        }
        for loader in self._items.values()
    ]

SourceResourceLoader

Bases: ResourceLoader[SourceResource]

Loads context from Python source code.

Source code in src/llmling/resources/loaders/source.py
class SourceResourceLoader(ResourceLoader[SourceResource]):
    """Loads context from Python source code."""

    context_class = SourceResource
    uri_scheme = "python"
    supported_mime_types: ClassVar[list[str]] = ["text/x-python"]

    async def _load_impl(
        self,
        resource: SourceResource,
        name: str,
        processor_registry: ProcessorRegistry | None,
    ) -> AsyncIterator[LoadedResource]:
        """Load Python source content."""
        try:
            content = importing.get_module_source(
                resource.import_path,
                recursive=resource.recursive,
                include_tests=resource.include_tests,
            )

            if processor_registry and (procs := resource.processors):
                processed = await processor_registry.process(content, procs)
                content = processed.content
            meta = {"import_path": resource.import_path, "recursive": resource.recursive}
            yield create_loaded_resource(
                content=content,
                source_type="source",
                uri=self.create_uri(name=name),
                mime_type="text/x-python",
                name=resource.description or resource.import_path,
                description=resource.description,
                additional_metadata=meta,
            )
        except Exception as exc:
            msg = f"Failed to load source from {resource.import_path}"
            raise exceptions.LoaderError(msg) from exc

    async def get_completions(
        self,
        current_value: str,
        argument_name: str | None = None,
        **options: Any,
    ) -> list[str]:
        """Get Python import path completions."""
        try:
            return [name for name in sys.modules if name.startswith(current_value or "")]
        except Exception:
            logger.exception("Import completion failed")
            return []

get_completions async

get_completions(current_value: str, argument_name: str | None = None, **options: Any) -> list[str]

Get Python import path completions.

Source code in src/llmling/resources/loaders/source.py
async def get_completions(
    self,
    current_value: str,
    argument_name: str | None = None,
    **options: Any,
) -> list[str]:
    """Get Python import path completions."""
    try:
        return [name for name in sys.modules if name.startswith(current_value or "")]
    except Exception:
        logger.exception("Import completion failed")
        return []

TextResourceLoader

Bases: ResourceLoader[TextResource]

Loads context from raw text.

Source code in src/llmling/resources/loaders/text.py
class TextResourceLoader(ResourceLoader[TextResource]):
    """Loads context from raw text."""

    context_class = TextResource
    uri_scheme = "text"
    supported_mime_types: ClassVar[list[str]] = ["text/plain"]

    async def _load_impl(
        self,
        resource: TextResource,
        name: str,
        processor_registry: ProcessorRegistry | None,
    ) -> AsyncIterator[LoadedResource]:
        """Load text content."""
        try:
            content = resource.content
            if processor_registry and (procs := resource.processors):
                processed = await processor_registry.process(content, procs)
                content = processed.content

            yield create_loaded_resource(
                content=content,
                source_type="text",
                uri=self.create_uri(name=name),
                mime_type=self.supported_mime_types[0],
                name=resource.description or name,
                description=resource.description,
                additional_metadata={"type": "text"},
            )
        except Exception as exc:
            msg = f"Failed to load text content: {exc}"
            raise exceptions.LoaderError(msg) from exc