Skip to content

resources

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.
LoadedResource llmling.resources.models Result of loading and processing a context.
PathResourceLoader llmling.resources.loaders.path Loads context from files or URLs.
RepositoryResourceLoader llmling.resources.loaders.repository Loads content from Git repositories.
ResourceLoader llmling.resources.base Base class for resource loaders.
ResourceLoaderRegistry llmling.resources.loaders.registry Registry for context loaders.
ResourceRegistry llmling.resources.registry Registry for managing configured resources.
SourceResourceLoader llmling.resources.loaders.source Loads context from Python source code.
TextResourceLoader llmling.resources.loaders.text Loads context from raw text.

🛈 DocStrings

Resource loading functionality.

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

LoadedResource

Bases: Schema

Result of loading and processing a context.

Source code in src/llmling/resources/models.py
class LoadedResource(Schema):
    """Result of loading and processing a context."""

    content: str = ""  # Keep for backward compatibility
    content_items: list[MessageContent] = Field(default_factory=list)
    source_type: str | None = None
    metadata: ResourceMetadata
    etag: str | None = None  # For MCP caching support

    @model_validator(mode="before")
    @classmethod
    def ensure_content_sync(cls, data: dict[str, Any]) -> dict[str, Any]:
        """Ensure content and content_items are in sync."""
        if isinstance(data, dict):
            content = data.get("content", "")
            content_items = data.get("content_items", [])

            # If we have content but no items, create a text item
            if content and not content_items:
                msg_content = MessageContent(type="text", content=content)
                data["content_items"] = [msg_content.model_dump()]
            # If we have items but no content, use first text item's content
            elif content_items and not content:
                text_items = [
                    i for i in content_items if isinstance(i, dict) and i.get("type") == "text"
                ]
                if text_items:
                    data["content"] = text_items[0]["content"]
        return data

ensure_content_sync classmethod

ensure_content_sync(data: dict[str, Any]) -> dict[str, Any]

Ensure content and content_items are in sync.

Source code in src/llmling/resources/models.py
@model_validator(mode="before")
@classmethod
def ensure_content_sync(cls, data: dict[str, Any]) -> dict[str, Any]:
    """Ensure content and content_items are in sync."""
    if isinstance(data, dict):
        content = data.get("content", "")
        content_items = data.get("content_items", [])

        # If we have content but no items, create a text item
        if content and not content_items:
            msg_content = MessageContent(type="text", content=content)
            data["content_items"] = [msg_content.model_dump()]
        # If we have items but no content, use first text item's content
        elif content_items and not content:
            text_items = [
                i for i in content_items if isinstance(i, dict) and i.get("type") == "text"
            ]
            if text_items:
                data["content"] = text_items[0]["content"]
    return data

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

ResourceLoader

Bases: ABC, CompletionProvider

Base class for resource loaders.

Source code in src/llmling/resources/base.py
class ResourceLoader[TResource: BaseResource](ABC, CompletionProvider):
    """Base class for resource loaders."""

    context_class: type[TResource]
    uri_scheme: ClassVar[str]
    supported_mime_types: ClassVar[list[str]] = ["text/plain"]
    # Invalid path characters (Windows + Unix)
    invalid_chars_pattern = re.compile(r'[\x00-\x1F<>:"|?*\\]')

    def __init__(self, context: LoaderContext[TResource] | None = None) -> None:
        """Initialize loader with optional context."""
        self.context = context

    async def get_completions(
        self,
        current_value: str,
        argument_name: str | None = None,
        **options: Any,
    ) -> list[str]:
        """Get completions for this resource type. Override to implement."""
        return []

    @classmethod
    def create(cls, resource: TResource, name: str) -> ResourceLoader[TResource]:
        """Create a loader instance with named context."""
        return cls(LoaderContext(resource=resource, name=name))

    @classmethod
    def supports_uri(cls, uri: str) -> bool:
        """Check if this loader supports a given URI."""
        return uri.startswith(f"{cls.uri_scheme}://")

    @classmethod  # could be classproperty
    def get_uri_template(cls) -> str:
        """Get the URI template for this resource type."""
        return f"{cls.uri_scheme}://{{name}}"

    @classmethod
    def get_name_from_uri(cls, uri: str) -> str:
        """Extract resource name from URI, ignoring parameters.

        Args:
            uri: URI in format "{scheme}://{name}[?param1=value1]"

        Returns:
            Resource name

        Raises:
            LoaderError: If URI format is invalid
        """
        import urllib.parse

        try:
            if not cls.supports_uri(uri):
                msg = f"Unsupported URI: {uri}"
                raise exceptions.LoaderError(msg)  # noqa: TRY301

            parsed = urllib.parse.urlparse(uri)
            path = parsed.netloc or parsed.path.lstrip("/")

            # Get parts excluding protocol info
            parts = [
                urllib.parse.unquote(str(part))  # URL decode each part
                for part in path.split("/")
                if not paths.is_ignorable_part(str(part))
            ]

            if not parts:
                msg = "Empty path after normalization"
                raise exceptions.LoaderError(msg)  # noqa: TRY301

            # Validate path components
            if any(cls.invalid_chars_pattern.search(part) for part in parts):
                msg = "Invalid characters in path component"
                raise exceptions.LoaderError(msg)  # noqa: TRY301

            # Join with forward slashes and normalize path
            joined = "/".join(parts)
            # Normalize path (resolve .. and .)
            normalized = os.path.normpath(joined).replace("\\", "/")
        except Exception as exc:
            if isinstance(exc, exceptions.LoaderError):
                raise
            msg = f"Invalid URI format: {uri}"
            raise exceptions.LoaderError(msg) from exc
        else:
            return normalized

    @classmethod
    def get_params_from_uri(cls, uri: str) -> dict[str, str]:
        """Extract parameters from URI.

        Args:
            uri: URI containing query parameters

        Returns:
            Dictionary of parameters
        """
        import urllib.parse

        parsed = urllib.parse.urlparse(uri)
        return dict(urllib.parse.parse_qsl(parsed.query))

    def create_uri(self, *, name: str, params: dict[str, str] | None = None) -> str:
        """Create a valid URI for this resource type.

        Args:
            name: Resource name or identifier
            params: Optional URI parameters

        Returns:
            URI in format "{scheme}://{name}[?param1=value1&...]"
        """
        import urllib.parse

        # Remove any existing scheme
        if "://" in name:
            name = name.split("://", 1)[1]

        base_uri = self.get_uri_template().format(name=name)
        if not params:
            return base_uri

        query = urllib.parse.urlencode(params)
        return f"{base_uri}?{query}"

    def __repr__(self) -> str:
        """Show loader type and context."""
        return f"{self.__class__.__name__}(resource_type={self.resource_type!r})"

    @classproperty  # type: ignore
    def resource_type(self) -> str:
        """Infer context type from context class."""
        fields = self.context_class.model_fields
        return fields["type"].default

    @overload
    def load(
        self,
        context: LoaderContext[TResource],
        processor_registry: ProcessorRegistry | None = None,
    ) -> AsyncIterator[LoadedResource]: ...

    @overload
    def load(
        self,
        context: TResource,
        processor_registry: ProcessorRegistry | None = None,
    ) -> AsyncIterator[LoadedResource]: ...

    @overload
    def load(
        self,
        context: None = None,
        processor_registry: ProcessorRegistry | None = None,
    ) -> AsyncIterator[LoadedResource]: ...

    async def load(
        self,
        context: LoaderContext[TResource] | TResource | None = None,
        processor_registry: ProcessorRegistry | None = None,
    ) -> AsyncIterator[LoadedResource]:
        """Load and process content.

        Args:
            context: Either a LoaderContext, direct Resource, or None (uses self.context)
            processor_registry: Optional processor registry for content processing

        Returns:
            Loaded resource content

        Raises:
            LoaderError: If loading fails
        """
        # Resolve the actual resource and name
        match context:
            case LoaderContext():
                resource = context.resource
                name = context.name
            case None if self.context:
                resource = self.context.resource
                name = self.context.name
            case None:
                msg = "No context provided"
                raise exceptions.LoaderError(msg)
            case _ if isinstance(context, self.context_class):
                resource = context
                name = "unnamed"  # fallback
            case _:
                msg = f"Invalid context type: {type(context)}"
                raise exceptions.LoaderError(msg)

        # Type assertion to ensure resource is of correct type
        assert isinstance(resource, self.context_class), (
            f"Expected {self.context_class}, got {type(resource)}"
        )
        generator = self._load_impl(resource, name, processor_registry)
        # Then yield from the generator
        async for result in generator:
            yield result

    @abstractmethod
    async def _load_impl(
        self,
        resource: TResource,
        name: str,
        processor_registry: ProcessorRegistry | None,
    ) -> AsyncIterator[LoadedResource]:
        """Implementation of actual loading logic."""
        yield NotImplemented  # type: ignore

__init__

__init__(context: LoaderContext[TResource] | None = None) -> None

Initialize loader with optional context.

Source code in src/llmling/resources/base.py
def __init__(self, context: LoaderContext[TResource] | None = None) -> None:
    """Initialize loader with optional context."""
    self.context = context

__repr__

__repr__() -> str

Show loader type and context.

Source code in src/llmling/resources/base.py
def __repr__(self) -> str:
    """Show loader type and context."""
    return f"{self.__class__.__name__}(resource_type={self.resource_type!r})"

create classmethod

create(resource: TResource, name: str) -> ResourceLoader[TResource]

Create a loader instance with named context.

Source code in src/llmling/resources/base.py
@classmethod
def create(cls, resource: TResource, name: str) -> ResourceLoader[TResource]:
    """Create a loader instance with named context."""
    return cls(LoaderContext(resource=resource, name=name))

create_uri

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

Create a valid URI for this resource type.

Parameters:

Name Type Description Default
name str

Resource name or identifier

required
params dict[str, str] | None

Optional URI parameters

None

Returns:

Type Description
str

URI in format "{scheme}://{name}[?param1=value1&...]"

Source code in src/llmling/resources/base.py
def create_uri(self, *, name: str, params: dict[str, str] | None = None) -> str:
    """Create a valid URI for this resource type.

    Args:
        name: Resource name or identifier
        params: Optional URI parameters

    Returns:
        URI in format "{scheme}://{name}[?param1=value1&...]"
    """
    import urllib.parse

    # Remove any existing scheme
    if "://" in name:
        name = name.split("://", 1)[1]

    base_uri = self.get_uri_template().format(name=name)
    if not params:
        return base_uri

    query = urllib.parse.urlencode(params)
    return f"{base_uri}?{query}"

get_completions async

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

Get completions for this resource type. Override to implement.

Source code in src/llmling/resources/base.py
async def get_completions(
    self,
    current_value: str,
    argument_name: str | None = None,
    **options: Any,
) -> list[str]:
    """Get completions for this resource type. Override to implement."""
    return []

get_name_from_uri classmethod

get_name_from_uri(uri: str) -> str

Extract resource name from URI, ignoring parameters.

Parameters:

Name Type Description Default
uri str

URI in format "{scheme}://{name}[?param1=value1]"

required

Returns:

Type Description
str

Resource name

Raises:

Type Description
LoaderError

If URI format is invalid

Source code in src/llmling/resources/base.py
@classmethod
def get_name_from_uri(cls, uri: str) -> str:
    """Extract resource name from URI, ignoring parameters.

    Args:
        uri: URI in format "{scheme}://{name}[?param1=value1]"

    Returns:
        Resource name

    Raises:
        LoaderError: If URI format is invalid
    """
    import urllib.parse

    try:
        if not cls.supports_uri(uri):
            msg = f"Unsupported URI: {uri}"
            raise exceptions.LoaderError(msg)  # noqa: TRY301

        parsed = urllib.parse.urlparse(uri)
        path = parsed.netloc or parsed.path.lstrip("/")

        # Get parts excluding protocol info
        parts = [
            urllib.parse.unquote(str(part))  # URL decode each part
            for part in path.split("/")
            if not paths.is_ignorable_part(str(part))
        ]

        if not parts:
            msg = "Empty path after normalization"
            raise exceptions.LoaderError(msg)  # noqa: TRY301

        # Validate path components
        if any(cls.invalid_chars_pattern.search(part) for part in parts):
            msg = "Invalid characters in path component"
            raise exceptions.LoaderError(msg)  # noqa: TRY301

        # Join with forward slashes and normalize path
        joined = "/".join(parts)
        # Normalize path (resolve .. and .)
        normalized = os.path.normpath(joined).replace("\\", "/")
    except Exception as exc:
        if isinstance(exc, exceptions.LoaderError):
            raise
        msg = f"Invalid URI format: {uri}"
        raise exceptions.LoaderError(msg) from exc
    else:
        return normalized

get_params_from_uri classmethod

get_params_from_uri(uri: str) -> dict[str, str]

Extract parameters from URI.

Parameters:

Name Type Description Default
uri str

URI containing query parameters

required

Returns:

Type Description
dict[str, str]

Dictionary of parameters

Source code in src/llmling/resources/base.py
@classmethod
def get_params_from_uri(cls, uri: str) -> dict[str, str]:
    """Extract parameters from URI.

    Args:
        uri: URI containing query parameters

    Returns:
        Dictionary of parameters
    """
    import urllib.parse

    parsed = urllib.parse.urlparse(uri)
    return dict(urllib.parse.parse_qsl(parsed.query))

get_uri_template classmethod

get_uri_template() -> str

Get the URI template for this resource type.

Source code in src/llmling/resources/base.py
@classmethod  # could be classproperty
def get_uri_template(cls) -> str:
    """Get the URI template for this resource type."""
    return f"{cls.uri_scheme}://{{name}}"

load async

load(
    context: LoaderContext[TResource], processor_registry: ProcessorRegistry | None = None
) -> AsyncIterator[LoadedResource]
load(
    context: TResource, processor_registry: ProcessorRegistry | None = None
) -> AsyncIterator[LoadedResource]
load(
    context: None = None, processor_registry: ProcessorRegistry | None = None
) -> AsyncIterator[LoadedResource]
load(
    context: LoaderContext[TResource] | TResource | None = None,
    processor_registry: ProcessorRegistry | None = None,
) -> AsyncIterator[LoadedResource]

Load and process content.

Parameters:

Name Type Description Default
context LoaderContext[TResource] | TResource | None

Either a LoaderContext, direct Resource, or None (uses self.context)

None
processor_registry ProcessorRegistry | None

Optional processor registry for content processing

None

Returns:

Type Description
AsyncIterator[LoadedResource]

Loaded resource content

Raises:

Type Description
LoaderError

If loading fails

Source code in src/llmling/resources/base.py
async def load(
    self,
    context: LoaderContext[TResource] | TResource | None = None,
    processor_registry: ProcessorRegistry | None = None,
) -> AsyncIterator[LoadedResource]:
    """Load and process content.

    Args:
        context: Either a LoaderContext, direct Resource, or None (uses self.context)
        processor_registry: Optional processor registry for content processing

    Returns:
        Loaded resource content

    Raises:
        LoaderError: If loading fails
    """
    # Resolve the actual resource and name
    match context:
        case LoaderContext():
            resource = context.resource
            name = context.name
        case None if self.context:
            resource = self.context.resource
            name = self.context.name
        case None:
            msg = "No context provided"
            raise exceptions.LoaderError(msg)
        case _ if isinstance(context, self.context_class):
            resource = context
            name = "unnamed"  # fallback
        case _:
            msg = f"Invalid context type: {type(context)}"
            raise exceptions.LoaderError(msg)

    # Type assertion to ensure resource is of correct type
    assert isinstance(resource, self.context_class), (
        f"Expected {self.context_class}, got {type(resource)}"
    )
    generator = self._load_impl(resource, name, processor_registry)
    # Then yield from the generator
    async for result in generator:
        yield result

resource_type

resource_type() -> str

Infer context type from context class.

Source code in src/llmling/resources/base.py
@classproperty  # type: ignore
def resource_type(self) -> str:
    """Infer context type from context class."""
    fields = self.context_class.model_fields
    return fields["type"].default

supports_uri classmethod

supports_uri(uri: str) -> bool

Check if this loader supports a given URI.

Source code in src/llmling/resources/base.py
@classmethod
def supports_uri(cls, uri: str) -> bool:
    """Check if this loader supports a given URI."""
    return uri.startswith(f"{cls.uri_scheme}://")

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()
    ]

ResourceRegistry

Bases: BaseRegistry[str, BaseResource]

Registry for managing configured resources.

Source code in src/llmling/resources/registry.py
class ResourceRegistry(BaseRegistry[str, BaseResource]):
    """Registry for managing configured resources."""

    def __init__(
        self,
        loader_registry: ResourceLoaderRegistry,
        processor_registry: ProcessorRegistry,
    ) -> None:
        """Initialize registry with required dependencies."""
        super().__init__()
        self.loader_registry = loader_registry
        self.processor_registry = processor_registry
        # Cache by URI instead of name for consistency
        self._cache: dict[str, LoadedResource] = {}
        self._last_loaded: dict[str, datetime] = {}
        self.watcher = ResourceWatcher(self)

    def register(self, key: str, item: BaseResource | Any, replace: bool = False) -> None:
        """Register an item."""
        try:
            # Create copy with name and URI if needed
            updates = {"name": key}  # Always set name from key
            if not item.uri:  # Set URI if missing
                loader = self.loader_registry.get_loader(item)
                uri = loader.create_uri(name=key)
                updates["uri"] = uri
            item = item.model_copy(update=updates)

        except exceptions.LoaderError as exc:
            msg = f"No loader registered for resource type '{item.type}'"
            raise exceptions.ResourceError(msg) from exc

        # Call parent registration
        super().register(key, item, replace)

        # Set up watching if needed
        if self._items[key].is_watched():
            self.watcher.add_watch(key, self._items[key])

    def __delitem__(self, key: str) -> None:
        """Remove item and its watch if present."""
        if key in self._items:
            # Remove watch first
            self.watcher.remove_watch(key)
        super().__delitem__(key)

    async def startup(self) -> None:
        """Initialize registry and start watcher."""
        await super().startup()
        # Start watcher
        await self.watcher.start()
        # Set up watches for existing resources
        for name, resource in self._items.items():
            if resource.is_watched():
                self.watcher.add_watch(name, resource)

    async def shutdown(self) -> None:
        """Cleanup registry and stop watcher."""
        # Stop watcher first
        await self.watcher.stop()
        # Then regular shutdown
        await super().shutdown()

    @property
    def _error_class(self) -> type[exceptions.ResourceError]:
        """Error class to use for this registry."""
        return exceptions.ResourceError

    def _validate_item(self, item: Any) -> BaseResource:
        """Validate and possibly transform items.

        Args:
            item: Item to validate

        Returns:
            Validated Resource

        Raises:
            ResourceError: If item is invalid
        """
        try:
            match item:
                # Match against concrete resource types
                case BaseResource():
                    return item

                case dict() if "resource_type" in item:
                    # Map resource_type to appropriate class
                    resource_classes: dict[str, type[BaseResource]] = {
                        "path": PathResource,
                        "text": TextResource,
                        "cli": CLIResource,
                        "source": SourceResource,
                        "callable": CallableResource,
                    }

                    resource_type = item["resource_type"]
                    if resource_type not in resource_classes:
                        msg = f"Unknown resource type: {resource_type}"
                        raise exceptions.ResourceError(msg)  # noqa: TRY301

                    # Validate using appropriate class
                    return resource_classes[resource_type].model_validate(item)

                case _:
                    msg = f"Invalid resource type: {type(item)}"
                    raise exceptions.ResourceError(msg)  # noqa: TRY301

        except Exception as exc:
            if isinstance(exc, exceptions.ResourceError):
                raise
            msg = f"Failed to validate resource: {exc}"
            raise exceptions.ResourceError(msg) from exc

    def get_uri(self, name: str) -> str:
        """Get URI for a resource by name."""
        resource = self[name]
        loader = self.loader_registry.get_loader(resource)
        loader = loader.create(resource, name)  # Create instance
        return loader.create_uri(name=name)

    async def load_all(
        self, name: str, *, force_reload: bool = False
    ) -> AsyncIterator[LoadedResource]:
        """Load all resources for a given name."""
        try:
            resource = self[name]
            uri = self.get_uri(name)

            # Check cache unless force reload
            if not force_reload and uri in self._cache:
                yield self._cache[uri]
                return

            # Get loader and initialize with context
            loader = self.loader_registry.get_loader(resource)
            loader = loader.create(resource, name)

            async for loaded in loader.load(
                context=loader.context,
                processor_registry=self.processor_registry,
            ):
                # Ensure the URI is set correctly
                if loaded.metadata.uri != uri:
                    msg = "Loader returned different URI than expected: %s != %s"
                    logger.warning(msg, loaded.metadata.uri, uri)
                    loaded.metadata = loaded.metadata.model_copy(update={"uri": uri})

                # Update cache using URI
                self._cache[uri] = loaded
                self._last_loaded[uri] = datetime.now()

                yield loaded

        except KeyError as exc:
            msg = f"Resource not found: {name}"
            raise exceptions.ResourceError(msg) from exc
        except Exception as exc:
            msg = f"Failed to load resource {name}: {exc}"
            raise exceptions.ResourceError(msg) from exc

    async def load(self, name: str, *, force_reload: bool = False) -> LoadedResource:
        """Load first/single resource (backward compatibility)."""
        async for resource in self.load_all(name, force_reload=force_reload):
            return resource
        msg = f"No resources loaded for {name}"
        raise exceptions.ResourceError(msg)

    async def load_by_uri(self, uri: str) -> LoadedResource:
        """Load a resource by URI."""
        try:
            # For simple resource names in file:/// format
            if uri.startswith("file:///"):
                # Extract resource name
                name = uri.rsplit("/", maxsplit=1)[-1]
                # Load using the name which will use the configured path/URL
                return await self.load(name)

            # For direct URLs or other schemes
            loader = self.loader_registry.find_loader_for_uri(uri)
            name = loader.get_name_from_uri(uri)
            return await self.load(name)

        except Exception as exc:
            msg = f"Failed to load resource from URI {uri}"
            raise exceptions.ResourceError(msg) from exc

    def invalidate(self, name: str) -> None:
        """Invalidate cache for a resource."""
        try:
            uri = self.get_uri(name)
            self._cache.pop(uri, None)
            self._last_loaded.pop(uri, None)
        except Exception:
            logger.exception("Failed to invalidate resource: %s", name)

    def clear_cache(self) -> None:
        """Clear all cached resources."""
        self._cache.clear()
        self._last_loaded.clear()

__delitem__

__delitem__(key: str) -> None

Remove item and its watch if present.

Source code in src/llmling/resources/registry.py
def __delitem__(self, key: str) -> None:
    """Remove item and its watch if present."""
    if key in self._items:
        # Remove watch first
        self.watcher.remove_watch(key)
    super().__delitem__(key)

__init__

__init__(loader_registry: ResourceLoaderRegistry, processor_registry: ProcessorRegistry) -> None

Initialize registry with required dependencies.

Source code in src/llmling/resources/registry.py
def __init__(
    self,
    loader_registry: ResourceLoaderRegistry,
    processor_registry: ProcessorRegistry,
) -> None:
    """Initialize registry with required dependencies."""
    super().__init__()
    self.loader_registry = loader_registry
    self.processor_registry = processor_registry
    # Cache by URI instead of name for consistency
    self._cache: dict[str, LoadedResource] = {}
    self._last_loaded: dict[str, datetime] = {}
    self.watcher = ResourceWatcher(self)

clear_cache

clear_cache() -> None

Clear all cached resources.

Source code in src/llmling/resources/registry.py
def clear_cache(self) -> None:
    """Clear all cached resources."""
    self._cache.clear()
    self._last_loaded.clear()

get_uri

get_uri(name: str) -> str

Get URI for a resource by name.

Source code in src/llmling/resources/registry.py
def get_uri(self, name: str) -> str:
    """Get URI for a resource by name."""
    resource = self[name]
    loader = self.loader_registry.get_loader(resource)
    loader = loader.create(resource, name)  # Create instance
    return loader.create_uri(name=name)

invalidate

invalidate(name: str) -> None

Invalidate cache for a resource.

Source code in src/llmling/resources/registry.py
def invalidate(self, name: str) -> None:
    """Invalidate cache for a resource."""
    try:
        uri = self.get_uri(name)
        self._cache.pop(uri, None)
        self._last_loaded.pop(uri, None)
    except Exception:
        logger.exception("Failed to invalidate resource: %s", name)

load async

load(name: str, *, force_reload: bool = False) -> LoadedResource

Load first/single resource (backward compatibility).

Source code in src/llmling/resources/registry.py
async def load(self, name: str, *, force_reload: bool = False) -> LoadedResource:
    """Load first/single resource (backward compatibility)."""
    async for resource in self.load_all(name, force_reload=force_reload):
        return resource
    msg = f"No resources loaded for {name}"
    raise exceptions.ResourceError(msg)

load_all async

load_all(name: str, *, force_reload: bool = False) -> AsyncIterator[LoadedResource]

Load all resources for a given name.

Source code in src/llmling/resources/registry.py
async def load_all(
    self, name: str, *, force_reload: bool = False
) -> AsyncIterator[LoadedResource]:
    """Load all resources for a given name."""
    try:
        resource = self[name]
        uri = self.get_uri(name)

        # Check cache unless force reload
        if not force_reload and uri in self._cache:
            yield self._cache[uri]
            return

        # Get loader and initialize with context
        loader = self.loader_registry.get_loader(resource)
        loader = loader.create(resource, name)

        async for loaded in loader.load(
            context=loader.context,
            processor_registry=self.processor_registry,
        ):
            # Ensure the URI is set correctly
            if loaded.metadata.uri != uri:
                msg = "Loader returned different URI than expected: %s != %s"
                logger.warning(msg, loaded.metadata.uri, uri)
                loaded.metadata = loaded.metadata.model_copy(update={"uri": uri})

            # Update cache using URI
            self._cache[uri] = loaded
            self._last_loaded[uri] = datetime.now()

            yield loaded

    except KeyError as exc:
        msg = f"Resource not found: {name}"
        raise exceptions.ResourceError(msg) from exc
    except Exception as exc:
        msg = f"Failed to load resource {name}: {exc}"
        raise exceptions.ResourceError(msg) from exc

load_by_uri async

load_by_uri(uri: str) -> LoadedResource

Load a resource by URI.

Source code in src/llmling/resources/registry.py
async def load_by_uri(self, uri: str) -> LoadedResource:
    """Load a resource by URI."""
    try:
        # For simple resource names in file:/// format
        if uri.startswith("file:///"):
            # Extract resource name
            name = uri.rsplit("/", maxsplit=1)[-1]
            # Load using the name which will use the configured path/URL
            return await self.load(name)

        # For direct URLs or other schemes
        loader = self.loader_registry.find_loader_for_uri(uri)
        name = loader.get_name_from_uri(uri)
        return await self.load(name)

    except Exception as exc:
        msg = f"Failed to load resource from URI {uri}"
        raise exceptions.ResourceError(msg) from exc

register

register(key: str, item: BaseResource | Any, replace: bool = False) -> None

Register an item.

Source code in src/llmling/resources/registry.py
def register(self, key: str, item: BaseResource | Any, replace: bool = False) -> None:
    """Register an item."""
    try:
        # Create copy with name and URI if needed
        updates = {"name": key}  # Always set name from key
        if not item.uri:  # Set URI if missing
            loader = self.loader_registry.get_loader(item)
            uri = loader.create_uri(name=key)
            updates["uri"] = uri
        item = item.model_copy(update=updates)

    except exceptions.LoaderError as exc:
        msg = f"No loader registered for resource type '{item.type}'"
        raise exceptions.ResourceError(msg) from exc

    # Call parent registration
    super().register(key, item, replace)

    # Set up watching if needed
    if self._items[key].is_watched():
        self.watcher.add_watch(key, self._items[key])

shutdown async

shutdown() -> None

Cleanup registry and stop watcher.

Source code in src/llmling/resources/registry.py
async def shutdown(self) -> None:
    """Cleanup registry and stop watcher."""
    # Stop watcher first
    await self.watcher.stop()
    # Then regular shutdown
    await super().shutdown()

startup async

startup() -> None

Initialize registry and start watcher.

Source code in src/llmling/resources/registry.py
async def startup(self) -> None:
    """Initialize registry and start watcher."""
    await super().startup()
    # Start watcher
    await self.watcher.start()
    # Set up watches for existing resources
    for name, resource in self._items.items():
        if resource.is_watched():
            self.watcher.add_watch(name, resource)

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