Skip to content

llmling

Class info

Re-exported classes

Class Module Description
BasePrompt llmling.prompts.models Base class for all prompts.
BaseRegistry llmling.core.baseregistry Base class for registries providing item storage and change notifications.
Config llmling.config.models Root configuration model.
ConfigError llmling.core.exceptions Configuration related errors.
ConfigModel llmling.config.base Base class for all LLMling configuration models.
ConfigStore llmling.config.store Manages stored config mappings.
DynamicPrompt llmling.prompts.models Dynamic prompt loaded from callable.
GlobalSettings llmling.config.models Global settings that apply to all components.
LLMCallableTool llmling.tools.base LLMCallableTool(callable: collections.abc.Callable[P, TReturnType], name: str, description: str = '', import_path: str
LLMCapabilitiesConfig llmling.config.models Configuration for LLM system capabilities.
LLMError llmling.core.exceptions LLM related errors.
LLMLingError llmling.core.exceptions Base exception for all llmling errors.
LoadedResource llmling.resources.models Result of loading and processing a context.
LoaderError llmling.core.exceptions Error during context loading.
ProcessorError llmling.core.exceptions Base class for processor-related errors.
ProcessorRegistry llmling.processors.registry Registry for content processors.
PromptMessage llmling.prompts.models A message in a prompt template.
PromptParameter llmling.prompts.models Prompt argument with validation information.
ResourceError llmling.core.exceptions Base class for context-related errors.
ResourceLoader llmling.resources.base Base class for resource loaders.
RuntimeConfig llmling.config.runtime Fully initialized runtime configuration.
StaticPrompt llmling.prompts.models Static prompt defined by message list.
ToolError llmling.tools.exceptions Base exception for tool-related errors.

🛈 DocStrings

LLMling: main package.

LLM simplified.

BasePrompt

Bases: BaseModel

Base class for all prompts.

Source code in src/llmling/prompts/models.py
class BasePrompt(BaseModel):
    """Base class for all prompts."""

    name: str | None = Field(None, exclude=True)
    """Technical identifier (automatically set from config key during registration)."""

    description: str
    """Human-readable description of what this prompt does."""

    title: str | None = None
    """Title of the prompt."""

    arguments: list[PromptParameter] = Field(default_factory=list)
    """List of arguments that this prompt accepts."""

    metadata: dict[str, Any] = Field(default_factory=dict)
    """Additional metadata for storing custom prompt information."""
    # messages: list[PromptMessage]

    model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)

    def get_messages(self) -> list[PromptMessage]:
        """Get the messages for this prompt."""
        if not hasattr(self, "messages"):
            msg = f"{self.__class__.__name__} must implement 'messages' attribute"
            raise NotImplementedError(msg)
        return self.messages  # pyright: ignore  # ty: ignore[invalid-explicit-return]

    def validate_arguments(self, provided: dict[str, Any]) -> None:
        """Validate that required arguments are provided."""
        required = {arg.name for arg in self.arguments if arg.required}
        missing = required - set(provided)
        if missing:
            msg = f"Missing required arguments: {', '.join(missing)}"
            raise ValueError(msg)

    async def format(self, arguments: dict[str, Any] | None = None) -> list[PromptMessage]:
        """Format this prompt with given arguments.

        Args:
            arguments: Optional argument values

        Returns:
            List of formatted messages

        Raises:
            ValueError: If required arguments are missing
        """
        raise NotImplementedError

    def to_mcp_prompt(self) -> MCPPrompt:
        """Convert to MCP Prompt."""
        from mcp.types import Prompt as MCPPrompt

        if self.name is None:
            msg = "Prompt name not set. This should be set during registration."
            raise ValueError(msg)
        args = [arg.to_mcp_argument() for arg in self.arguments]
        return MCPPrompt(name=self.name, description=self.description, arguments=args)

arguments class-attribute instance-attribute

arguments: list[PromptParameter] = Field(default_factory=list)

List of arguments that this prompt accepts.

description instance-attribute

description: str

Human-readable description of what this prompt does.

metadata class-attribute instance-attribute

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

Additional metadata for storing custom prompt information.

name class-attribute instance-attribute

name: str | None = Field(None, exclude=True)

Technical identifier (automatically set from config key during registration).

title class-attribute instance-attribute

title: str | None = None

Title of the prompt.

format async

format(arguments: dict[str, Any] | None = None) -> list[PromptMessage]

Format this prompt with given arguments.

Parameters:

Name Type Description Default
arguments dict[str, Any] | None

Optional argument values

None

Returns:

Type Description
list[PromptMessage]

List of formatted messages

Raises:

Type Description
ValueError

If required arguments are missing

Source code in src/llmling/prompts/models.py
async def format(self, arguments: dict[str, Any] | None = None) -> list[PromptMessage]:
    """Format this prompt with given arguments.

    Args:
        arguments: Optional argument values

    Returns:
        List of formatted messages

    Raises:
        ValueError: If required arguments are missing
    """
    raise NotImplementedError

get_messages

get_messages() -> list[PromptMessage]

Get the messages for this prompt.

Source code in src/llmling/prompts/models.py
def get_messages(self) -> list[PromptMessage]:
    """Get the messages for this prompt."""
    if not hasattr(self, "messages"):
        msg = f"{self.__class__.__name__} must implement 'messages' attribute"
        raise NotImplementedError(msg)
    return self.messages  # pyright: ignore  # ty: ignore[invalid-explicit-return]

to_mcp_prompt

to_mcp_prompt() -> Prompt

Convert to MCP Prompt.

Source code in src/llmling/prompts/models.py
def to_mcp_prompt(self) -> MCPPrompt:
    """Convert to MCP Prompt."""
    from mcp.types import Prompt as MCPPrompt

    if self.name is None:
        msg = "Prompt name not set. This should be set during registration."
        raise ValueError(msg)
    args = [arg.to_mcp_argument() for arg in self.arguments]
    return MCPPrompt(name=self.name, description=self.description, arguments=args)

validate_arguments

validate_arguments(provided: dict[str, Any]) -> None

Validate that required arguments are provided.

Source code in src/llmling/prompts/models.py
def validate_arguments(self, provided: dict[str, Any]) -> None:
    """Validate that required arguments are provided."""
    required = {arg.name for arg in self.arguments if arg.required}
    missing = required - set(provided)
    if missing:
        msg = f"Missing required arguments: {', '.join(missing)}"
        raise ValueError(msg)

BaseRegistry

Bases: MutableMapping[TKey, TItem], ABC

Base class for registries providing item storage and change notifications.

This registry implements a dictionary-like interface backed by an EventedDict, providing automatic event emission for all mutations (additions, removals, modifications).

Features: - Dictionary-like access (registry[key] = item) - Event emission for all changes - Item validation - Type safety - Customizable error handling

Available events (accessed via .events): - adding(key, value): Before an item is added - added(key, value): After an item is added - removing(key, value): Before an item is removed - removed(key, value): After an item is removed - changing(key, value): Before an item is modified - changed(key, value): After an item is modified

To implement, override: - _validate_item: Custom validation/transformation of items - _error_class: Custom error type for exceptions

Source code in src/llmling/core/baseregistry.py
class BaseRegistry[TKey, TItem](MutableMapping[TKey, TItem], ABC):
    """Base class for registries providing item storage and change notifications.

    This registry implements a dictionary-like interface backed by an EventedDict,
    providing automatic event emission for all mutations (additions, removals,
    modifications).

    Features:
    - Dictionary-like access (registry[key] = item)
    - Event emission for all changes
    - Item validation
    - Type safety
    - Customizable error handling

    Available events (accessed via .events):
        - adding(key, value): Before an item is added
        - added(key, value): After an item is added
        - removing(key, value): Before an item is removed
        - removed(key, value): After an item is removed
        - changing(key, value): Before an item is modified
        - changed(key, value): After an item is modified

    To implement, override:
    - _validate_item: Custom validation/transformation of items
    - _error_class: Custom error type for exceptions
    """

    def __init__(self) -> None:
        """Initialize an empty registry."""
        self._items = EventedDict[TKey, TItem]()
        self._initialized = False
        self._configs: dict[TKey, Any] = {}

    def __repr__(self) -> str:
        return f"{self.__class__.__name__}({self._items})"

    @property
    def is_empty(self) -> bool:
        """Check if registry has any items."""
        return not bool(self._items)

    def has_item(self, key: TKey) -> bool:
        """Check if an item is registered."""
        return key in self._items

    @property
    def events(self):
        """Access to all dictionary events."""
        return self._items.events

    def register(self, key: TKey, item: TItem | Any, replace: bool = False) -> None:
        """Register an item."""
        if key in self._items and not replace:
            msg = f"Item already registered: {key}"
            raise self._error_class(msg)

        validated_item = self._validate_item(item)
        self._items[key] = validated_item

    def get(self, key: TKey) -> TItem:  # type: ignore
        """Get an item by key."""
        return self[key]

    def list_items(self) -> Sequence[TKey]:
        """List all registered item keys."""
        return list(self._items.keys())

    def reset(self) -> None:
        """Reset registry to initial state."""
        self._items.clear()
        self._configs.clear()
        self._initialized = False

    async def startup(self) -> None:
        """Initialize all registered items."""
        if self._initialized:
            return

        try:
            for item in self._items.values():
                await self._initialize_item(item)
            self._initialized = True
        except Exception as exc:
            await self.shutdown()
            msg = f"Registry startup failed: {exc}"
            raise self._error_class(msg) from exc

    async def shutdown(self) -> None:
        """Cleanup all registered items."""
        if not self._initialized:
            return

        errors: list[tuple[TKey, Exception]] = []

        for key, item in self._items.items():
            try:
                await self._cleanup_item(item)
            except Exception as exc:  # noqa: BLE001
                errors.append((key, exc))

        self._initialized = False

        if errors:
            error_msgs = [f"{key}: {exc}" for key, exc in errors]
            msg = f"Errors during shutdown: {', '.join(error_msgs)}"
            raise self._error_class(msg)

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

    @abstractmethod
    def _validate_item(self, item: Any) -> TItem:
        """Validate and possibly transform item before registration."""

    async def _initialize_item(self, item: TItem) -> None:
        """Initialize an item during startup."""
        if hasattr(item, "startup") and callable(item.startup):  # pyright: ignore
            await item.startup()  # pyright: ignore  # ty: ignore[invalid-await]

    async def _cleanup_item(self, item: TItem) -> None:
        """Clean up an item during shutdown."""
        if hasattr(item, "shutdown") and callable(item.shutdown):  # pyright: ignore
            await item.shutdown()  # pyright: ignore  # ty: ignore[invalid-await]

    # Implementing MutableMapping methods
    def __getitem__(self, key: TKey) -> TItem:
        try:
            return self._items[key]
        except KeyError as exc:
            msg = f"Item not found: {key}"
            raise self._error_class(msg) from exc

    def __setitem__(self, key: TKey, value: Any) -> None:
        """Support dict-style assignment."""
        self.register(key, value)

    def __contains__(self, key: object) -> bool:
        """Support 'in' operator without raising exceptions."""
        return key in self._items

    def __delitem__(self, key: TKey) -> None:
        if key in self._items:
            del self._items[key]
        else:
            msg = f"Item not found: {key}"
            raise self._error_class(msg)

    def __iter__(self) -> Iterator[TKey]:
        return iter(self._items)

    async def __aiter__(self):
        """Async iterate over items, ensuring they're initialized."""
        if not self._initialized:
            await self.startup()
        for key, item in self._items.items():
            yield key, item

    def __len__(self) -> int:
        return len(self._items)

events property

events

Access to all dictionary events.

is_empty property

is_empty: bool

Check if registry has any items.

__aiter__ async

__aiter__()

Async iterate over items, ensuring they're initialized.

Source code in src/llmling/core/baseregistry.py
async def __aiter__(self):
    """Async iterate over items, ensuring they're initialized."""
    if not self._initialized:
        await self.startup()
    for key, item in self._items.items():
        yield key, item

__contains__

__contains__(key: object) -> bool

Support 'in' operator without raising exceptions.

Source code in src/llmling/core/baseregistry.py
def __contains__(self, key: object) -> bool:
    """Support 'in' operator without raising exceptions."""
    return key in self._items

__init__

__init__() -> None

Initialize an empty registry.

Source code in src/llmling/core/baseregistry.py
def __init__(self) -> None:
    """Initialize an empty registry."""
    self._items = EventedDict[TKey, TItem]()
    self._initialized = False
    self._configs: dict[TKey, Any] = {}

__setitem__

__setitem__(key: TKey, value: Any) -> None

Support dict-style assignment.

Source code in src/llmling/core/baseregistry.py
def __setitem__(self, key: TKey, value: Any) -> None:
    """Support dict-style assignment."""
    self.register(key, value)

get

get(key: TKey) -> TItem

Get an item by key.

Source code in src/llmling/core/baseregistry.py
def get(self, key: TKey) -> TItem:  # type: ignore
    """Get an item by key."""
    return self[key]

has_item

has_item(key: TKey) -> bool

Check if an item is registered.

Source code in src/llmling/core/baseregistry.py
def has_item(self, key: TKey) -> bool:
    """Check if an item is registered."""
    return key in self._items

list_items

list_items() -> Sequence[TKey]

List all registered item keys.

Source code in src/llmling/core/baseregistry.py
def list_items(self) -> Sequence[TKey]:
    """List all registered item keys."""
    return list(self._items.keys())

register

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

Register an item.

Source code in src/llmling/core/baseregistry.py
def register(self, key: TKey, item: TItem | Any, replace: bool = False) -> None:
    """Register an item."""
    if key in self._items and not replace:
        msg = f"Item already registered: {key}"
        raise self._error_class(msg)

    validated_item = self._validate_item(item)
    self._items[key] = validated_item

reset

reset() -> None

Reset registry to initial state.

Source code in src/llmling/core/baseregistry.py
def reset(self) -> None:
    """Reset registry to initial state."""
    self._items.clear()
    self._configs.clear()
    self._initialized = False

shutdown async

shutdown() -> None

Cleanup all registered items.

Source code in src/llmling/core/baseregistry.py
async def shutdown(self) -> None:
    """Cleanup all registered items."""
    if not self._initialized:
        return

    errors: list[tuple[TKey, Exception]] = []

    for key, item in self._items.items():
        try:
            await self._cleanup_item(item)
        except Exception as exc:  # noqa: BLE001
            errors.append((key, exc))

    self._initialized = False

    if errors:
        error_msgs = [f"{key}: {exc}" for key, exc in errors]
        msg = f"Errors during shutdown: {', '.join(error_msgs)}"
        raise self._error_class(msg)

startup async

startup() -> None

Initialize all registered items.

Source code in src/llmling/core/baseregistry.py
async def startup(self) -> None:
    """Initialize all registered items."""
    if self._initialized:
        return

    try:
        for item in self._items.values():
            await self._initialize_item(item)
        self._initialized = True
    except Exception as exc:
        await self.shutdown()
        msg = f"Registry startup failed: {exc}"
        raise self._error_class(msg) from exc

Config

Bases: ConfigModel

Root configuration model.

Source code in src/llmling/config/models.py
class Config(ConfigModel):
    """Root configuration model."""

    version: str = "1.0"
    """Version string for this configuration format."""

    global_settings: GlobalSettings = Field(default_factory=GlobalSettings)
    """Global settings that apply to all components."""

    context_processors: dict[str, ProcessorConfig] = Field(default_factory=dict)
    """Content processors available for resource transformation."""

    resources: dict[str, Resource] = Field(default_factory=dict)
    """Resource definitions keyed by name."""

    resource_groups: dict[str, list[str]] = Field(default_factory=dict)
    """Groups of resources for logical organization."""

    tools: dict[str, ToolConfig] = Field(default_factory=dict)
    """Tool definitions keyed by name."""

    toolsets: dict[str, ToolsetConfig] = Field(default_factory=dict)
    """Toolset configurations for extensible tool collections."""

    prompts: dict[str, PromptType] = Field(default_factory=dict)
    """Prompt definitions keyed by name."""

    model_config = ConfigDict(
        frozen=True,
        arbitrary_types_allowed=True,
        extra="allow",  # extra fields used by the server for example.
    )

    # @model_validator(mode="before")
    # @classmethod
    # def populate_prompt_names(cls, data: dict[str, Any]) -> dict[str, Any]:
    #     """Populate prompt names from dictionary keys before validation."""
    #     if isinstance(data, dict) and "prompts" in data:
    #         prompts = data["prompts"]
    #         if isinstance(prompts, dict):
    #             # Add name to each prompt's data
    #             data["prompts"] = {
    #                 key: {
    #                     "name": key,
    #                     **(val if isinstance(val, dict) else val.model_dump()),
    #                 }
    #                 for key, val in prompts.items()
    #             }
    #     return data

    @model_validator(mode="after")
    def validate_references(self) -> Config:
        """Validate all references between components."""
        # Only validate if the optional components are present
        if self.resource_groups:
            self._validate_resource_groups()
        if self.context_processors:
            self._validate_processor_references()
        return self

    def _validate_resource_groups(self) -> None:
        """Validate resource references in groups."""
        for group, resources in self.resource_groups.items():
            for resource in resources:
                if resource not in self.resources:
                    msg = f"Resource {resource} referenced in group {group} not found"
                    raise ValueError(msg)

    def _validate_processor_references(self) -> None:
        """Validate processor references in resources."""
        for resource in self.resources.values():
            for processor in resource.processors:
                if processor.name not in self.context_processors:
                    msg = f"Processor {processor.name!r} not found"
                    raise ValueError(msg)

    @classmethod
    def from_file(cls, path: JoinablePathLike) -> Self:
        """Load configuration from YAML file.

        This function only handles the basic loading and model validation.
        For full validation and management, use ConfigManager.load() instead.

        Args:
            path: Path to configuration file

        Returns:
            Loaded configuration

        Raises:
            ConfigError: If loading fails
        """
        import yamling

        logger.debug("Loading configuration from %s", path)

        try:
            content = yamling.load_yaml_file(path)
        except Exception as exc:
            msg = f"Failed to load YAML from {path!r}"
            raise exceptions.ConfigError(msg) from exc

        # Validate basic structure
        if not isinstance(content, dict):
            msg = "Configuration must be a dictionary"
            raise exceptions.ConfigError(msg)

        try:
            config = cls.model_validate(content)
        except Exception as exc:
            msg = f"Failed to validate configuration from {path}"
            raise exceptions.ConfigError(msg) from exc
        else:
            logger.debug("Loaded raw configuration:")
            msg = "version=%s, resources=%d, tools=%d, toolsets=%d, prompts=%d"
            logger.debug(
                msg,
                config.version,
                len(config.resources),
                len(config.tools),
                len(config.toolsets),
                len(config.prompts),
            )
            return config

context_processors class-attribute instance-attribute

context_processors: dict[str, ProcessorConfig] = Field(default_factory=dict)

Content processors available for resource transformation.

global_settings class-attribute instance-attribute

global_settings: GlobalSettings = Field(default_factory=GlobalSettings)

Global settings that apply to all components.

prompts class-attribute instance-attribute

prompts: dict[str, PromptType] = Field(default_factory=dict)

Prompt definitions keyed by name.

resource_groups class-attribute instance-attribute

resource_groups: dict[str, list[str]] = Field(default_factory=dict)

Groups of resources for logical organization.

resources class-attribute instance-attribute

resources: dict[str, Resource] = Field(default_factory=dict)

Resource definitions keyed by name.

tools class-attribute instance-attribute

tools: dict[str, ToolConfig] = Field(default_factory=dict)

Tool definitions keyed by name.

toolsets class-attribute instance-attribute

toolsets: dict[str, ToolsetConfig] = Field(default_factory=dict)

Toolset configurations for extensible tool collections.

version class-attribute instance-attribute

version: str = '1.0'

Version string for this configuration format.

from_file classmethod

from_file(path: JoinablePathLike) -> Self

Load configuration from YAML file.

This function only handles the basic loading and model validation. For full validation and management, use ConfigManager.load() instead.

Parameters:

Name Type Description Default
path JoinablePathLike

Path to configuration file

required

Returns:

Type Description
Self

Loaded configuration

Raises:

Type Description
ConfigError

If loading fails

Source code in src/llmling/config/models.py
@classmethod
def from_file(cls, path: JoinablePathLike) -> Self:
    """Load configuration from YAML file.

    This function only handles the basic loading and model validation.
    For full validation and management, use ConfigManager.load() instead.

    Args:
        path: Path to configuration file

    Returns:
        Loaded configuration

    Raises:
        ConfigError: If loading fails
    """
    import yamling

    logger.debug("Loading configuration from %s", path)

    try:
        content = yamling.load_yaml_file(path)
    except Exception as exc:
        msg = f"Failed to load YAML from {path!r}"
        raise exceptions.ConfigError(msg) from exc

    # Validate basic structure
    if not isinstance(content, dict):
        msg = "Configuration must be a dictionary"
        raise exceptions.ConfigError(msg)

    try:
        config = cls.model_validate(content)
    except Exception as exc:
        msg = f"Failed to validate configuration from {path}"
        raise exceptions.ConfigError(msg) from exc
    else:
        logger.debug("Loaded raw configuration:")
        msg = "version=%s, resources=%d, tools=%d, toolsets=%d, prompts=%d"
        logger.debug(
            msg,
            config.version,
            len(config.resources),
            len(config.tools),
            len(config.toolsets),
            len(config.prompts),
        )
        return config

validate_references

validate_references() -> Config

Validate all references between components.

Source code in src/llmling/config/models.py
@model_validator(mode="after")
def validate_references(self) -> Config:
    """Validate all references between components."""
    # Only validate if the optional components are present
    if self.resource_groups:
        self._validate_resource_groups()
    if self.context_processors:
        self._validate_processor_references()
    return self

ConfigError

Bases: LLMLingError

Configuration related errors.

Source code in src/llmling/core/exceptions.py
class ConfigError(LLMLingError):
    """Configuration related errors."""

ConfigModel

Bases: Schema

Base class for all LLMling configuration models.

Provides: - Common Pydantic settings - YAML serialization - Basic merge functionality

Source code in src/llmling/config/base.py
class ConfigModel(Schema):
    """Base class for all LLMling configuration models.

    Provides:
    - Common Pydantic settings
    - YAML serialization
    - Basic merge functionality
    """

    model_config = ConfigDict(frozen=True)

ConfigStore

Manages stored config mappings.

Source code in src/llmling/config/store.py
class ConfigStore:
    """Manages stored config mappings."""

    def __init__(self, filename: str | None = None) -> None:
        """Initialize store with default paths."""
        import platformdirs
        from upath import UPath

        llmling_dir = platformdirs.user_config_dir("llmling")
        self.config_dir = UPath(llmling_dir)
        name = filename or "configs.json"
        self.config_file = self.config_dir / name
        self._ensure_config_dir()

    def _ensure_config_dir(self) -> None:
        """Create config directory if needed."""
        self.config_dir.mkdir(parents=True, exist_ok=True)
        if not self.config_file.exists():
            mapping = ConfigMapping(configs={}, active=None)
            self.save_mapping(mapping)

    def load_mapping(self) -> ConfigMapping:
        """Load config mapping from disk."""
        import anyenv

        if not self.config_file.exists():
            return ConfigMapping(configs={}, active=None)
        try:
            text = self.config_file.read_text("utf-8")
            data = anyenv.load_json(text, return_type=dict)
            active = data.get("active")
            configs = data.get("configs", {})
            return ConfigMapping(configs=configs, active=active)
        except Exception:
            logger.exception("Failed to load config mapping")
            return ConfigMapping(configs={}, active=None)

    def save_mapping(self, mapping: ConfigMapping) -> None:
        """Save config mapping to disk."""
        import anyenv

        try:
            self.config_file.write_text(anyenv.dump_json(mapping, indent=True))
        except Exception:
            logger.exception("Failed to save config mapping")

    def add_config(self, name: str, path: JoinablePathLike) -> None:
        """Add a new named config.

        Args:
            name: Name to register the config under
            path: Path to the config file

        Raises:
            ValueError: If name is invalid
            FileNotFoundError: If config file doesn't exist
            PermissionError: If config file can't be read
            IsADirectoryError: If path points to a directory
        """
        # Basic validation
        from upathtools import to_upath

        if not name.isidentifier():
            msg = f"Invalid config name: {name} (must be a valid Python identifier)"
            raise ValueError(msg)

        path_obj = to_upath(path).resolve()
        if not path_obj.exists():
            msg = f"Config file not found: {path}"
            raise FileNotFoundError(msg)

        if not path_obj.is_file():
            msg = f"Path is not a file: {path}"
            raise IsADirectoryError(msg)

        try:
            # Try to read file to verify access
            path_obj.read_bytes()
        except PermissionError as exc:
            msg = f"Cannot read config file: {path}"
            raise PermissionError(msg) from exc
        # All good, save the config
        mapping = self.load_mapping()
        mapping["configs"][name] = str(path_obj)
        logger.debug("Adding config %r -> %s", name, path_obj)
        self.save_mapping(mapping)

    def remove_config(self, name: str) -> None:
        """Remove a named config."""
        mapping = self.load_mapping()
        if name == mapping["active"]:
            mapping["active"] = None
        mapping["configs"].pop(name, None)
        self.save_mapping(mapping)

    def set_active(self, name: str) -> None:
        """Set the active config."""
        mapping = self.load_mapping()
        if name not in mapping["configs"]:
            msg = f"Config {name} not found"
            raise KeyError(msg)
        mapping["active"] = name
        self.save_mapping(mapping)

    def get_active(self) -> ConfigFile | None:
        """Get active config if one is set.

        Returns:
            ConfigFile if an active config is set, None otherwise
        """
        mapping = self.load_mapping()
        if not mapping["active"]:
            return None
        name = mapping["active"]
        return ConfigFile(name=name, path=mapping["configs"][name])

    def list_configs(self) -> list[tuple[str, str]]:
        """List all configs with their paths."""
        mapping = self.load_mapping()
        return list(mapping["configs"].items())

    def get_config(self, name: str) -> str:
        """Get path for a named config."""
        mapping = self.load_mapping()
        if name not in mapping["configs"]:
            msg = f"Config {name} not found"
            raise KeyError(msg)
        return mapping["configs"][name]

__init__

__init__(filename: str | None = None) -> None

Initialize store with default paths.

Source code in src/llmling/config/store.py
def __init__(self, filename: str | None = None) -> None:
    """Initialize store with default paths."""
    import platformdirs
    from upath import UPath

    llmling_dir = platformdirs.user_config_dir("llmling")
    self.config_dir = UPath(llmling_dir)
    name = filename or "configs.json"
    self.config_file = self.config_dir / name
    self._ensure_config_dir()

add_config

add_config(name: str, path: JoinablePathLike) -> None

Add a new named config.

Parameters:

Name Type Description Default
name str

Name to register the config under

required
path JoinablePathLike

Path to the config file

required

Raises:

Type Description
ValueError

If name is invalid

FileNotFoundError

If config file doesn't exist

PermissionError

If config file can't be read

IsADirectoryError

If path points to a directory

Source code in src/llmling/config/store.py
def add_config(self, name: str, path: JoinablePathLike) -> None:
    """Add a new named config.

    Args:
        name: Name to register the config under
        path: Path to the config file

    Raises:
        ValueError: If name is invalid
        FileNotFoundError: If config file doesn't exist
        PermissionError: If config file can't be read
        IsADirectoryError: If path points to a directory
    """
    # Basic validation
    from upathtools import to_upath

    if not name.isidentifier():
        msg = f"Invalid config name: {name} (must be a valid Python identifier)"
        raise ValueError(msg)

    path_obj = to_upath(path).resolve()
    if not path_obj.exists():
        msg = f"Config file not found: {path}"
        raise FileNotFoundError(msg)

    if not path_obj.is_file():
        msg = f"Path is not a file: {path}"
        raise IsADirectoryError(msg)

    try:
        # Try to read file to verify access
        path_obj.read_bytes()
    except PermissionError as exc:
        msg = f"Cannot read config file: {path}"
        raise PermissionError(msg) from exc
    # All good, save the config
    mapping = self.load_mapping()
    mapping["configs"][name] = str(path_obj)
    logger.debug("Adding config %r -> %s", name, path_obj)
    self.save_mapping(mapping)

get_active

get_active() -> ConfigFile | None

Get active config if one is set.

Returns:

Type Description
ConfigFile | None

ConfigFile if an active config is set, None otherwise

Source code in src/llmling/config/store.py
def get_active(self) -> ConfigFile | None:
    """Get active config if one is set.

    Returns:
        ConfigFile if an active config is set, None otherwise
    """
    mapping = self.load_mapping()
    if not mapping["active"]:
        return None
    name = mapping["active"]
    return ConfigFile(name=name, path=mapping["configs"][name])

get_config

get_config(name: str) -> str

Get path for a named config.

Source code in src/llmling/config/store.py
def get_config(self, name: str) -> str:
    """Get path for a named config."""
    mapping = self.load_mapping()
    if name not in mapping["configs"]:
        msg = f"Config {name} not found"
        raise KeyError(msg)
    return mapping["configs"][name]

list_configs

list_configs() -> list[tuple[str, str]]

List all configs with their paths.

Source code in src/llmling/config/store.py
def list_configs(self) -> list[tuple[str, str]]:
    """List all configs with their paths."""
    mapping = self.load_mapping()
    return list(mapping["configs"].items())

load_mapping

load_mapping() -> ConfigMapping

Load config mapping from disk.

Source code in src/llmling/config/store.py
def load_mapping(self) -> ConfigMapping:
    """Load config mapping from disk."""
    import anyenv

    if not self.config_file.exists():
        return ConfigMapping(configs={}, active=None)
    try:
        text = self.config_file.read_text("utf-8")
        data = anyenv.load_json(text, return_type=dict)
        active = data.get("active")
        configs = data.get("configs", {})
        return ConfigMapping(configs=configs, active=active)
    except Exception:
        logger.exception("Failed to load config mapping")
        return ConfigMapping(configs={}, active=None)

remove_config

remove_config(name: str) -> None

Remove a named config.

Source code in src/llmling/config/store.py
def remove_config(self, name: str) -> None:
    """Remove a named config."""
    mapping = self.load_mapping()
    if name == mapping["active"]:
        mapping["active"] = None
    mapping["configs"].pop(name, None)
    self.save_mapping(mapping)

save_mapping

save_mapping(mapping: ConfigMapping) -> None

Save config mapping to disk.

Source code in src/llmling/config/store.py
def save_mapping(self, mapping: ConfigMapping) -> None:
    """Save config mapping to disk."""
    import anyenv

    try:
        self.config_file.write_text(anyenv.dump_json(mapping, indent=True))
    except Exception:
        logger.exception("Failed to save config mapping")

set_active

set_active(name: str) -> None

Set the active config.

Source code in src/llmling/config/store.py
def set_active(self, name: str) -> None:
    """Set the active config."""
    mapping = self.load_mapping()
    if name not in mapping["configs"]:
        msg = f"Config {name} not found"
        raise KeyError(msg)
    mapping["active"] = name
    self.save_mapping(mapping)

DynamicPrompt

Bases: BasePrompt

Dynamic prompt loaded from callable.

Source code in src/llmling/prompts/models.py
class DynamicPrompt(BasePrompt):
    """Dynamic prompt loaded from callable."""

    import_path: str | Callable
    """Dotted import path to the callable that generates the prompt."""

    template: str | None = None
    """Optional template string for formatting the callable's output."""

    completions: dict[str, str] | None = None
    """Optional mapping of argument names to completion functions."""

    type: Literal["function"] = Field("function", init=False)
    """Discriminator field identifying this as a function-based prompt."""

    model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)

    @property
    def messages(self) -> list[PromptMessage]:
        """Get the template messages for this prompt.

        Note: These are template messages - actual content will be populated
        during format() when the callable is executed.
        """
        template = self.template or "{result}"
        sys_content = MessageContent(type="text", content=f"Content from {self.name}:")
        user_content = MessageContent(type="text", content=template)
        return [
            PromptMessage(role="system", content=sys_content),
            PromptMessage(role="user", content=user_content),
        ]

    def to_fastmcp_prompt(self) -> FunctionPrompt:
        from fastmcp.prompts import FunctionPrompt

        return FunctionPrompt.from_function(
            self.fn,
            title=self.title,
            description=self.description,
            tags=None,
            icons=None,
        )

    @property
    def fn(self) -> Callable[..., Any]:
        if isinstance(self.import_path, str):
            return importing.import_callable(self.import_path)
        return self.import_path

    def get_completion_functions(self) -> dict[str, CompletionFunction]:
        """Resolve completion function import paths and return a completion fn dict."""
        completion_funcs: dict[str, CompletionFunction] = {}
        if not self.completions:
            return {}
        for arg_name, import_path in self.completions.items():
            try:
                func = importing.import_callable(import_path)
                completion_funcs[arg_name] = func
            except ValueError:
                msg = "Failed to import completion function for %s: %s"
                logger.warning(msg, arg_name, import_path)
        return completion_funcs

    async def format(self, arguments: dict[str, Any] | None = None) -> list[PromptMessage]:
        """Format this prompt with given arguments."""
        args = arguments or {}
        self.validate_arguments(args)

        try:
            if isinstance(self.import_path, str):
                result = await calling.execute_callable(self.import_path, **args)
            elif inspect.iscoroutinefunction(self.import_path):
                result = await self.import_path(**args)
            elif inspect.isfunction(self.import_path):
                result = self.import_path(**args)
            else:
                msg = "Invalid result type"
                raise ValueError(msg)  # noqa: TRY301
            # Use result directly in template
            template = self.template or "{result}"
            msg = template.format(result=result)
            content = MessageContent(type="text", content=msg)
            msg = f"Content from {self.name}:"
            sys_content = MessageContent(type="text", content=msg)
            return [
                PromptMessage(role="system", content=sys_content),
                PromptMessage(role="user", content=content),
            ]
        except Exception as exc:
            msg = f"Failed to execute prompt callable: {exc}"
            raise ValueError(msg) from exc

    @classmethod
    def from_callable(
        cls,
        fn: Callable[..., Any] | str,
        *,
        name_override: str | None = None,
        description_override: str | None = None,
        template_override: str | None = None,
        completions: Mapping[str, CompletionFunction] | None = None,
    ) -> DynamicPrompt:
        """Create a prompt from a callable.

        Args:
            fn: Function or import path to create prompt from
            name_override: Optional override for prompt name
            description_override: Optional override for prompt description
            template_override: Optional override for message template
            completions: Optional dict mapping argument names to completion functions

        Returns:
            DynamicPrompt instance

        Raises:
            ValueError: If callable cannot be imported or is invalid
        """
        from docstring_parser import parse as parse_docstring

        completions = completions or {}
        # Import if string path provided
        if isinstance(fn, str):
            fn = importing.import_callable(fn)

        # Get function metadata
        name = name_override or getattr(fn, "__name__", "unknown")
        # FORWARDREF: names imported only under TYPE_CHECKING stay ForwardRefs (-> Any)
        sig = inspect.signature(fn, annotation_format=annotationlib.Format.FORWARDREF)
        hints = get_type_hints(
            fn, include_extras=True, localns=locals(), format=annotationlib.Format.FORWARDREF
        )

        # Parse docstring
        docstring = inspect.getdoc(fn)
        if docstring:
            parsed = parse_docstring(docstring)
            description = description_override or parsed.short_description
            # Create mapping of param names to descriptions
            arg_docs = {
                param.arg_name: param.description
                for param in parsed.params
                if param.arg_name and param.description
            }
        else:
            description = description_override or f"Prompt from {name}"
            arg_docs = {}

        # Create arguments
        arguments = []
        for param_name, param in sig.parameters.items():
            if param.kind in (param.VAR_POSITIONAL, param.VAR_KEYWORD):
                continue

            type_hint = hints.get(param_name, Any)
            if isinstance(type_hint, ForwardRef):
                type_hint = Any
            required = param.default == param.empty
            arg = PromptParameter(
                name=param_name,
                description=arg_docs.get(param_name),
                required=required,
                type_hint=type_hint,
                default=None if param.default is param.empty else param.default,
                completion_function=completions.get(param_name),
            )
            arguments.append(arg)

        qualname = getattr(fn, "__qualname__", fn.__class__.__qualname__)
        path = f"{fn.__module__}.{qualname}"
        return cls(
            name=name,
            description=description or "",
            arguments=arguments,
            import_path=path,
            template=template_override,
            metadata={"source": "function", "import_path": path},
        )

completions class-attribute instance-attribute

completions: dict[str, str] | None = None

Optional mapping of argument names to completion functions.

import_path instance-attribute

import_path: str | Callable

Dotted import path to the callable that generates the prompt.

messages property

messages: list[PromptMessage]

Get the template messages for this prompt.

Note: These are template messages - actual content will be populated during format() when the callable is executed.

template class-attribute instance-attribute

template: str | None = None

Optional template string for formatting the callable's output.

type class-attribute instance-attribute

type: Literal['function'] = Field('function', init=False)

Discriminator field identifying this as a function-based prompt.

format async

format(arguments: dict[str, Any] | None = None) -> list[PromptMessage]

Format this prompt with given arguments.

Source code in src/llmling/prompts/models.py
async def format(self, arguments: dict[str, Any] | None = None) -> list[PromptMessage]:
    """Format this prompt with given arguments."""
    args = arguments or {}
    self.validate_arguments(args)

    try:
        if isinstance(self.import_path, str):
            result = await calling.execute_callable(self.import_path, **args)
        elif inspect.iscoroutinefunction(self.import_path):
            result = await self.import_path(**args)
        elif inspect.isfunction(self.import_path):
            result = self.import_path(**args)
        else:
            msg = "Invalid result type"
            raise ValueError(msg)  # noqa: TRY301
        # Use result directly in template
        template = self.template or "{result}"
        msg = template.format(result=result)
        content = MessageContent(type="text", content=msg)
        msg = f"Content from {self.name}:"
        sys_content = MessageContent(type="text", content=msg)
        return [
            PromptMessage(role="system", content=sys_content),
            PromptMessage(role="user", content=content),
        ]
    except Exception as exc:
        msg = f"Failed to execute prompt callable: {exc}"
        raise ValueError(msg) from exc

from_callable classmethod

from_callable(
    fn: Callable[..., Any] | str,
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    template_override: str | None = None,
    completions: Mapping[str, CompletionFunction] | None = None
) -> DynamicPrompt

Create a prompt from a callable.

Parameters:

Name Type Description Default
fn Callable[..., Any] | str

Function or import path to create prompt from

required
name_override str | None

Optional override for prompt name

None
description_override str | None

Optional override for prompt description

None
template_override str | None

Optional override for message template

None
completions Mapping[str, CompletionFunction] | None

Optional dict mapping argument names to completion functions

None

Returns:

Type Description
DynamicPrompt

DynamicPrompt instance

Raises:

Type Description
ValueError

If callable cannot be imported or is invalid

Source code in src/llmling/prompts/models.py
@classmethod
def from_callable(
    cls,
    fn: Callable[..., Any] | str,
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    template_override: str | None = None,
    completions: Mapping[str, CompletionFunction] | None = None,
) -> DynamicPrompt:
    """Create a prompt from a callable.

    Args:
        fn: Function or import path to create prompt from
        name_override: Optional override for prompt name
        description_override: Optional override for prompt description
        template_override: Optional override for message template
        completions: Optional dict mapping argument names to completion functions

    Returns:
        DynamicPrompt instance

    Raises:
        ValueError: If callable cannot be imported or is invalid
    """
    from docstring_parser import parse as parse_docstring

    completions = completions or {}
    # Import if string path provided
    if isinstance(fn, str):
        fn = importing.import_callable(fn)

    # Get function metadata
    name = name_override or getattr(fn, "__name__", "unknown")
    # FORWARDREF: names imported only under TYPE_CHECKING stay ForwardRefs (-> Any)
    sig = inspect.signature(fn, annotation_format=annotationlib.Format.FORWARDREF)
    hints = get_type_hints(
        fn, include_extras=True, localns=locals(), format=annotationlib.Format.FORWARDREF
    )

    # Parse docstring
    docstring = inspect.getdoc(fn)
    if docstring:
        parsed = parse_docstring(docstring)
        description = description_override or parsed.short_description
        # Create mapping of param names to descriptions
        arg_docs = {
            param.arg_name: param.description
            for param in parsed.params
            if param.arg_name and param.description
        }
    else:
        description = description_override or f"Prompt from {name}"
        arg_docs = {}

    # Create arguments
    arguments = []
    for param_name, param in sig.parameters.items():
        if param.kind in (param.VAR_POSITIONAL, param.VAR_KEYWORD):
            continue

        type_hint = hints.get(param_name, Any)
        if isinstance(type_hint, ForwardRef):
            type_hint = Any
        required = param.default == param.empty
        arg = PromptParameter(
            name=param_name,
            description=arg_docs.get(param_name),
            required=required,
            type_hint=type_hint,
            default=None if param.default is param.empty else param.default,
            completion_function=completions.get(param_name),
        )
        arguments.append(arg)

    qualname = getattr(fn, "__qualname__", fn.__class__.__qualname__)
    path = f"{fn.__module__}.{qualname}"
    return cls(
        name=name,
        description=description or "",
        arguments=arguments,
        import_path=path,
        template=template_override,
        metadata={"source": "function", "import_path": path},
    )

get_completion_functions

get_completion_functions() -> dict[str, CompletionFunction]

Resolve completion function import paths and return a completion fn dict.

Source code in src/llmling/prompts/models.py
def get_completion_functions(self) -> dict[str, CompletionFunction]:
    """Resolve completion function import paths and return a completion fn dict."""
    completion_funcs: dict[str, CompletionFunction] = {}
    if not self.completions:
        return {}
    for arg_name, import_path in self.completions.items():
        try:
            func = importing.import_callable(import_path)
            completion_funcs[arg_name] = func
        except ValueError:
            msg = "Failed to import completion function for %s: %s"
            logger.warning(msg, arg_name, import_path)
    return completion_funcs

GlobalSettings

Bases: ConfigModel

Global settings that apply to all components.

Source code in src/llmling/config/models.py
class GlobalSettings(ConfigModel):
    """Global settings that apply to all components."""

    timeout: int = Field(default=30, ge=0)
    """Maximum time in seconds to wait for operations"""

    max_retries: int = Field(default=3, ge=0)
    """Maximum number of retries for failed operations"""

    requirements: list[str] = Field(default_factory=list)
    """List of package requirments for the functions used in this file."""

    pip_index_url: HttpUrl | None = None
    """Alternative PyPI index URL for package installation"""

    extra_paths: list[str] = Field(default_factory=list)
    """Additional import paths"""

    scripts: list[str] = Field(default_factory=list)
    """PEP723 scripts (can be imported and will be scanned for dependencies)"""

    prefer_uv: bool = False
    """Explicitely use uv for package installation / management """

    log_level: LogLevel = "INFO"
    """Log level for LLMling core."""

    jinja_environment: Jinja2Config = Field(default_factory=Jinja2Config)
    """Jinja2 environment configuration"""

    llm_capabilities: LLMCapabilitiesConfig = Field(default_factory=LLMCapabilitiesConfig)
    """Control which system capabilities are exposed to LLMs."""

extra_paths class-attribute instance-attribute

extra_paths: list[str] = Field(default_factory=list)

Additional import paths

jinja_environment class-attribute instance-attribute

jinja_environment: Jinja2Config = Field(default_factory=Jinja2Config)

Jinja2 environment configuration

llm_capabilities class-attribute instance-attribute

llm_capabilities: LLMCapabilitiesConfig = Field(default_factory=LLMCapabilitiesConfig)

Control which system capabilities are exposed to LLMs.

log_level class-attribute instance-attribute

log_level: LogLevel = 'INFO'

Log level for LLMling core.

max_retries class-attribute instance-attribute

max_retries: int = Field(default=3, ge=0)

Maximum number of retries for failed operations

pip_index_url class-attribute instance-attribute

pip_index_url: HttpUrl | None = None

Alternative PyPI index URL for package installation

prefer_uv class-attribute instance-attribute

prefer_uv: bool = False

Explicitely use uv for package installation / management

requirements class-attribute instance-attribute

requirements: list[str] = Field(default_factory=list)

List of package requirments for the functions used in this file.

scripts class-attribute instance-attribute

scripts: list[str] = Field(default_factory=list)

PEP723 scripts (can be imported and will be scanned for dependencies)

timeout class-attribute instance-attribute

timeout: int = Field(default=30, ge=0)

Maximum time in seconds to wait for operations

LLMCallableTool dataclass

Source code in src/llmling/tools/base.py
@dataclass
class LLMCallableTool[**P, TReturnType]:
    supported_mime_types: ClassVar[list[str]] = ["text/plain"]
    callable: Callable[P, TReturnType]
    name: str
    description: str = ""
    import_path: str | None = None
    schema_override: schemez.OpenAIFunctionDefinition | None = None
    hints: ToolHints | None = None

    @classmethod
    def from_callable(
        cls,
        fn: Callable[P, TReturnType] | str,
        *,
        name_override: str | None = None,
        description_override: str | None = None,
        schema_override: schemez.OpenAIFunctionDefinition | None = None,
        hints: ToolHints | None = None,
    ) -> Self:
        """Create a tool from a callable or import path."""
        if isinstance(fn, str):
            import_path = fn
            from llmling.utils import importing

            callable_obj = importing.import_callable(fn)
            name = getattr(callable_obj, "__name__", "unknown")
            import_path = fn
        else:
            callable_obj = fn
            module = fn.__module__
            if hasattr(fn, "__qualname__"):  # Regular function
                name = getattr(fn, "__name__", fn.__class__.__name__)
                import_path = f"{module}.{fn.__qualname__}"
            else:  # Instance with __call__ method
                name = fn.__class__.__name__
                import_path = f"{module}.{fn.__class__.__qualname__}"

        return cls(
            callable=callable_obj,
            name=name_override or name,
            description=description_override or inspect.getdoc(callable_obj) or "",
            import_path=import_path,
            schema_override=schema_override,
            hints=hints,
        )

    @classmethod
    def from_crewai_tool(
        cls,
        tool: Any,
        *,
        name_override: str | None = None,
        description_override: str | None = None,
        schema_override: schemez.OpenAIFunctionDefinition | None = None,
    ) -> Self:
        """Allows importing crewai / langchain tools."""
        try:
            from crewai.tools import BaseTool as CrewAiBaseTool
        except ImportError as e:
            msg = "crewai package not found. Please install it with 'pip install crewai'"
            raise ImportError(msg) from e

        if not isinstance(tool, CrewAiBaseTool):
            msg = f"Expected CrewAI BaseTool, got {type(tool)}"
            raise TypeError(msg)

        return cls.from_callable(
            tool._run,
            name_override=name_override or tool.__class__.__name__.removesuffix("Tool"),
            description_override=description_override or tool.description,
            schema_override=schema_override,
        )

    @classmethod
    def from_langchain_tool(
        cls,
        tool: Any,
        *,
        name_override: str | None = None,
        description_override: str | None = None,
        schema_override: schemez.OpenAIFunctionDefinition | None = None,
    ) -> Self:
        """Create a tool from a LangChain tool."""
        try:
            from langchain_core.tools import BaseTool as LangChainBaseTool
        except ImportError as e:
            msg = "langchain-core package not found."
            raise ImportError(msg) from e

        if not isinstance(tool, LangChainBaseTool):
            msg = f"Expected LangChain BaseTool, got {type(tool)}"
            raise TypeError(msg)

        return cls.from_callable(
            tool.invoke,
            name_override=name_override or tool.name,
            description_override=description_override or tool.description,
            schema_override=schema_override,
        )

    @classmethod
    def from_autogen_tool(
        cls,
        tool: Any,
        *,
        name_override: str | None = None,
        description_override: str | None = None,
        schema_override: schemez.OpenAIFunctionDefinition | None = None,
    ) -> Self:
        """Create a tool from a AutoGen tool."""
        try:
            from autogen_core import CancellationToken
            from autogen_core.tools import BaseTool
        except ImportError as e:
            msg = "autogent_core package not found."
            raise ImportError(msg) from e

        if not isinstance(tool, BaseTool):
            msg = f"Expected AutoGent BaseTool, got {type(tool)}"
            raise TypeError(msg)
        token = CancellationToken()

        input_model = tool.__class__.__orig_bases__[0].__args__[0]

        name = name_override or tool.name or tool.__class__.__name__.removesuffix("Tool")
        description = (
            description_override or tool.description or inspect.getdoc(tool.__class__) or ""
        )

        async def wrapper(**kwargs: Any) -> Any:
            # Convert kwargs to the expected input model
            model = input_model(**kwargs)
            return await tool.run(model, cancellation_token=token)

        return cls.from_callable(
            wrapper,  # type: ignore
            name_override=name,
            description_override=description,
            schema_override=schema_override,
        )

    async def execute(self, *args: P.args, **kwargs: P.kwargs) -> TReturnType:
        """Execute the wrapped callable."""
        if inspect.iscoroutinefunction(self.callable):
            return await self.callable(*args, **kwargs)
        return self.callable(*args, **kwargs)

    def get_schema(self) -> schemez.OpenAIFunctionTool:
        """Get OpenAI function schema."""
        schema = schemez.create_schema(self.callable).model_dump_openai()
        schema["function"]["name"] = self.name
        schema["function"]["description"] = self.description
        if self.schema_override:
            schema["function"] = self.schema_override
        return schema

execute async

execute(*args: P.args, **kwargs: P.kwargs) -> TReturnType

Execute the wrapped callable.

Source code in src/llmling/tools/base.py
async def execute(self, *args: P.args, **kwargs: P.kwargs) -> TReturnType:
    """Execute the wrapped callable."""
    if inspect.iscoroutinefunction(self.callable):
        return await self.callable(*args, **kwargs)
    return self.callable(*args, **kwargs)

from_autogen_tool classmethod

from_autogen_tool(
    tool: Any,
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    schema_override: OpenAIFunctionDefinition | None = None
) -> Self

Create a tool from a AutoGen tool.

Source code in src/llmling/tools/base.py
@classmethod
def from_autogen_tool(
    cls,
    tool: Any,
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    schema_override: schemez.OpenAIFunctionDefinition | None = None,
) -> Self:
    """Create a tool from a AutoGen tool."""
    try:
        from autogen_core import CancellationToken
        from autogen_core.tools import BaseTool
    except ImportError as e:
        msg = "autogent_core package not found."
        raise ImportError(msg) from e

    if not isinstance(tool, BaseTool):
        msg = f"Expected AutoGent BaseTool, got {type(tool)}"
        raise TypeError(msg)
    token = CancellationToken()

    input_model = tool.__class__.__orig_bases__[0].__args__[0]

    name = name_override or tool.name or tool.__class__.__name__.removesuffix("Tool")
    description = (
        description_override or tool.description or inspect.getdoc(tool.__class__) or ""
    )

    async def wrapper(**kwargs: Any) -> Any:
        # Convert kwargs to the expected input model
        model = input_model(**kwargs)
        return await tool.run(model, cancellation_token=token)

    return cls.from_callable(
        wrapper,  # type: ignore
        name_override=name,
        description_override=description,
        schema_override=schema_override,
    )

from_callable classmethod

from_callable(
    fn: Callable[P, TReturnType] | str,
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    schema_override: OpenAIFunctionDefinition | None = None,
    hints: ToolHints | None = None
) -> Self

Create a tool from a callable or import path.

Source code in src/llmling/tools/base.py
@classmethod
def from_callable(
    cls,
    fn: Callable[P, TReturnType] | str,
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    schema_override: schemez.OpenAIFunctionDefinition | None = None,
    hints: ToolHints | None = None,
) -> Self:
    """Create a tool from a callable or import path."""
    if isinstance(fn, str):
        import_path = fn
        from llmling.utils import importing

        callable_obj = importing.import_callable(fn)
        name = getattr(callable_obj, "__name__", "unknown")
        import_path = fn
    else:
        callable_obj = fn
        module = fn.__module__
        if hasattr(fn, "__qualname__"):  # Regular function
            name = getattr(fn, "__name__", fn.__class__.__name__)
            import_path = f"{module}.{fn.__qualname__}"
        else:  # Instance with __call__ method
            name = fn.__class__.__name__
            import_path = f"{module}.{fn.__class__.__qualname__}"

    return cls(
        callable=callable_obj,
        name=name_override or name,
        description=description_override or inspect.getdoc(callable_obj) or "",
        import_path=import_path,
        schema_override=schema_override,
        hints=hints,
    )

from_crewai_tool classmethod

from_crewai_tool(
    tool: Any,
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    schema_override: OpenAIFunctionDefinition | None = None
) -> Self

Allows importing crewai / langchain tools.

Source code in src/llmling/tools/base.py
@classmethod
def from_crewai_tool(
    cls,
    tool: Any,
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    schema_override: schemez.OpenAIFunctionDefinition | None = None,
) -> Self:
    """Allows importing crewai / langchain tools."""
    try:
        from crewai.tools import BaseTool as CrewAiBaseTool
    except ImportError as e:
        msg = "crewai package not found. Please install it with 'pip install crewai'"
        raise ImportError(msg) from e

    if not isinstance(tool, CrewAiBaseTool):
        msg = f"Expected CrewAI BaseTool, got {type(tool)}"
        raise TypeError(msg)

    return cls.from_callable(
        tool._run,
        name_override=name_override or tool.__class__.__name__.removesuffix("Tool"),
        description_override=description_override or tool.description,
        schema_override=schema_override,
    )

from_langchain_tool classmethod

from_langchain_tool(
    tool: Any,
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    schema_override: OpenAIFunctionDefinition | None = None
) -> Self

Create a tool from a LangChain tool.

Source code in src/llmling/tools/base.py
@classmethod
def from_langchain_tool(
    cls,
    tool: Any,
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    schema_override: schemez.OpenAIFunctionDefinition | None = None,
) -> Self:
    """Create a tool from a LangChain tool."""
    try:
        from langchain_core.tools import BaseTool as LangChainBaseTool
    except ImportError as e:
        msg = "langchain-core package not found."
        raise ImportError(msg) from e

    if not isinstance(tool, LangChainBaseTool):
        msg = f"Expected LangChain BaseTool, got {type(tool)}"
        raise TypeError(msg)

    return cls.from_callable(
        tool.invoke,
        name_override=name_override or tool.name,
        description_override=description_override or tool.description,
        schema_override=schema_override,
    )

get_schema

get_schema() -> OpenAIFunctionTool

Get OpenAI function schema.

Source code in src/llmling/tools/base.py
def get_schema(self) -> schemez.OpenAIFunctionTool:
    """Get OpenAI function schema."""
    schema = schemez.create_schema(self.callable).model_dump_openai()
    schema["function"]["name"] = self.name
    schema["function"]["description"] = self.description
    if self.schema_override:
        schema["function"] = self.schema_override
    return schema

LLMCapabilitiesConfig

Bases: ConfigModel

Configuration for LLM system capabilities.

Source code in src/llmling/config/models.py
class LLMCapabilitiesConfig(ConfigModel):
    """Configuration for LLM system capabilities."""

    load_resource: bool = False
    """Whether the LLM can load and access resource content."""

    get_resources: bool = False
    """Whether the LLM can discover available resources."""

    install_package: bool = False
    """Whether the LLM can install new Python packages for future tools."""

    register_tool: bool = False
    """Whether the LLM can register importable functions as new tools."""

    register_code_tool: bool = False
    """Whether the LLM can create new tools from provided Python code."""

    chain_tools: bool = False
    """Whether the LLM gains capability to chain multiple tool calls into one."""

chain_tools class-attribute instance-attribute

chain_tools: bool = False

Whether the LLM gains capability to chain multiple tool calls into one.

get_resources class-attribute instance-attribute

get_resources: bool = False

Whether the LLM can discover available resources.

install_package class-attribute instance-attribute

install_package: bool = False

Whether the LLM can install new Python packages for future tools.

load_resource class-attribute instance-attribute

load_resource: bool = False

Whether the LLM can load and access resource content.

register_code_tool class-attribute instance-attribute

register_code_tool: bool = False

Whether the LLM can create new tools from provided Python code.

register_tool class-attribute instance-attribute

register_tool: bool = False

Whether the LLM can register importable functions as new tools.

LLMError

Bases: LLMLingError

LLM related errors.

Source code in src/llmling/core/exceptions.py
class LLMError(LLMLingError):
    """LLM related errors."""

LLMLingError

Bases: Exception

Base exception for all llmling errors.

Source code in src/llmling/core/exceptions.py
class LLMLingError(Exception):
    """Base exception for all llmling errors."""

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

LoaderError

Bases: ResourceError

Error during context loading.

Source code in src/llmling/core/exceptions.py
class LoaderError(ResourceError):
    """Error during context loading."""

ProcessorError

Bases: LLMLingError

Base class for processor-related errors.

Source code in src/llmling/core/exceptions.py
class ProcessorError(LLMLingError):
    """Base class for processor-related errors."""

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,
        )
    )

PromptMessage

Bases: BaseModel

A message in a prompt template.

Source code in src/llmling/prompts/models.py
class PromptMessage(BaseModel):
    """A message in a prompt template."""

    role: MessageRole
    content: str | MessageContent | list[MessageContent] = ""

    model_config = ConfigDict(frozen=True)

    def get_text_content(self) -> str:
        """Get text content of message."""
        match self.content:
            case str():
                return self.content
            case MessageContent() if self.content.type == "text":
                return self.content.content
            case list() if self.content:
                # Join text content items with space
                text_items = [
                    item.content
                    for item in self.content
                    if isinstance(item, MessageContent) and item.type == "text"
                ]
                return " ".join(text_items) if text_items else ""
            case _:
                return ""

get_text_content

get_text_content() -> str

Get text content of message.

Source code in src/llmling/prompts/models.py
def get_text_content(self) -> str:
    """Get text content of message."""
    match self.content:
        case str():
            return self.content
        case MessageContent() if self.content.type == "text":
            return self.content.content
        case list() if self.content:
            # Join text content items with space
            text_items = [
                item.content
                for item in self.content
                if isinstance(item, MessageContent) and item.type == "text"
            ]
            return " ".join(text_items) if text_items else ""
        case _:
            return ""

PromptParameter

Bases: BaseModel

Prompt argument with validation information.

Source code in src/llmling/prompts/models.py
class PromptParameter(BaseModel):
    """Prompt argument with validation information."""

    name: str
    """Name of the argument as used in the prompt."""

    description: str | None = None
    """Human-readable description of the argument."""

    required: bool = False
    """Whether this argument must be provided when formatting the prompt."""

    type_hint: ImportString = Field(default="str")
    """Type annotation for the argument, defaults to str."""

    default: Any | None = None
    """Default value if argument is optional."""

    completion_function: ImportString | None = Field(default=None)
    """Optional function to provide argument completions."""

    model_config = ConfigDict(use_attribute_docstrings=True)

    def to_mcp_argument(self) -> PromptArgument:
        """Convert to MCP PromptArgument."""
        from mcp.types import PromptArgument

        return PromptArgument(name=self.name, description=self.description, required=self.required)

completion_function class-attribute instance-attribute

completion_function: ImportString | None = Field(default=None)

Optional function to provide argument completions.

default class-attribute instance-attribute

default: Any | None = None

Default value if argument is optional.

description class-attribute instance-attribute

description: str | None = None

Human-readable description of the argument.

name instance-attribute

name: str

Name of the argument as used in the prompt.

required class-attribute instance-attribute

required: bool = False

Whether this argument must be provided when formatting the prompt.

type_hint class-attribute instance-attribute

type_hint: ImportString = Field(default='str')

Type annotation for the argument, defaults to str.

to_mcp_argument

to_mcp_argument() -> PromptArgument

Convert to MCP PromptArgument.

Source code in src/llmling/prompts/models.py
def to_mcp_argument(self) -> PromptArgument:
    """Convert to MCP PromptArgument."""
    from mcp.types import PromptArgument

    return PromptArgument(name=self.name, description=self.description, required=self.required)

ResourceError

Bases: LLMLingError

Base class for context-related errors.

Source code in src/llmling/core/exceptions.py
class ResourceError(LLMLingError):
    """Base class for context-related errors."""

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}://")

RuntimeConfig

Fully initialized runtime configuration.

This represents the "live" state of a Config, with all components initialized and ready to use. It provides a clean interface to access and manage runtime resources without exposing internal registries.

Source code in src/llmling/config/runtime.py
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
class RuntimeConfig:
    """Fully initialized runtime configuration.

    This represents the "live" state of a Config, with all components
    initialized and ready to use. It provides a clean interface to
    access and manage runtime resources without exposing internal registries.
    """

    def __init__(
        self,
        config: Config,
        *,
        loader_registry: ResourceLoaderRegistry,
        processor_registry: ProcessorRegistry,
        resource_registry: ResourceRegistry,
        prompt_registry: PromptRegistry,
        tool_registry: ToolRegistry,
    ) -> None:
        """Initialize with config and registries.

        Args:
            config: Original static configuration
            loader_registry: Registry for resource loaders
            processor_registry: Registry for content processors
            resource_registry: Registry for resources
            prompt_registry: Registry for prompts
            tool_registry: Registry for tools
        """
        from llmling.depmanager import DependencyManager

        super().__init__()
        self._config = config
        self._loader_registry = loader_registry
        self._processor_registry = processor_registry
        self._resource_registry = resource_registry
        self._prompt_registry = prompt_registry
        self._tool_registry = tool_registry
        self._initialized = False
        # Register builtin processors
        proc = Jinja2Processor(config.global_settings.jinja_environment)
        self._processor_registry["jinja_template"] = proc
        settings = self._config.global_settings
        self._dep_manager = DependencyManager(
            prefer_uv=settings.prefer_uv,
            requirements=settings.requirements,
            extra_paths=settings.extra_paths,
            pip_index_url=str(settings.pip_index_url) if settings.pip_index_url else None,
            scripts=settings.scripts,
        )

    def __enter__(self) -> Self:
        """Synchronous context manager entry."""
        self._dep_manager.__enter__()
        # Initialize registries if not already done
        import asyncio

        if not self._initialized:
            loop = asyncio.new_event_loop()
            try:
                loop.run_until_complete(self._initialize_registries())
                self._initialized = True
            finally:
                loop.close()
        return self

    def __exit__(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: types.TracebackType | None,
    ) -> None:
        """Synchronous context manager exit."""
        self._dep_manager.__exit__(exc_type, exc_val, exc_tb)

    async def __aenter__(self) -> Self:
        """Initialize dependencies and registries."""
        # Check and set initialized flag atomically before ANY async op
        # This should allow caeses where same runtime gets initialized multiple times
        needs_init = not self._initialized
        self._initialized = True

        if needs_init:
            await self._dep_manager.__aenter__()
            await self._initialize_registries()
        return self

    async def __aexit__(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: types.TracebackType | None,
    ) -> None:
        """Clean up dependencies and registries."""
        try:
            await self.shutdown()
        finally:
            await self._dep_manager.__aexit__(exc_type, exc_val, exc_tb)

    def _register_default_components(self) -> None:
        """Register all default components and config items."""
        self._loader_registry.register_default_loaders()
        for name, proc_config in self._config.context_processors.items():
            self._processor_registry[name] = proc_config

        for name, resource in self._config.resources.items():
            self._resource_registry[name] = resource

        for name, tool_config in self._config.tools.items():
            self._tool_registry[name] = LLMCallableTool.from_callable(
                tool_config.import_path,
                name_override=tool_config.name,
                description_override=tool_config.description,
                hints=tool_config.hints,
            )

        self._initialize_toolsets()

        for name, prompt in self._config.prompts.items():
            if isinstance(prompt, DynamicPrompt):
                # Convert completion function import paths to actual functions
                # TODO: we are setting .completions to a non-allowed type here
                prompt.completions = prompt.get_completion_functions()  # type: ignore
                args, desc = extract_function_info(prompt.import_path, prompt.completions)
                prompt.arguments = args
                if not prompt.description:
                    prompt.description = desc

            self._prompt_registry[name] = prompt

    def _initialize_toolsets(self) -> None:
        """Initialize toolsets from config."""
        for name, config in self._config.toolsets.items():
            try:
                toolset = toolset_config_to_toolset(config)
                for tool in toolset.get_llm_callable_tools():
                    # tool_name = f"{name}.{tool.name}"
                    tool_name = tool.name
                    if tool_name in self._tool_registry:
                        msg = "Tool %s from toolset %s overlaps with existing tool"
                        logger.warning(msg, tool.name, name)
                        continue
                    self._tool_registry[tool_name] = tool

            except Exception:
                logger.exception("Failed to load toolset: %s", name)

    async def _initialize_registries(self) -> None:
        """Initialize all registries."""
        self._register_default_components()
        await self.startup()

    @classmethod
    async def create(cls, config: Config) -> Self:
        """Create and initialize a runtime configuration.

        This is a convenience method that ensures proper initialization
        when not using the async context manager.

        Args:
            config: Static configuration to initialize from

        Returns:
            Initialized runtime configuration
        """
        runtime = cls.from_config(config)
        async with runtime as initialized:
            return initialized

    @classmethod
    @asynccontextmanager
    async def open(
        cls,
        source: JoinablePathLike | Config,
        *,
        validate: bool = True,
        strict: bool = False,
    ) -> AsyncGenerator[RuntimeConfig]:
        """Create and manage a runtime configuration asynchronously.

        This is the primary way to create and use a RuntimeConfig. It ensures proper
        initialization and cleanup of all resources and provides an async context
        manager interface.

        Args:
            source: Either a path to a configuration file or a Config object.
                   File paths can be strings or PathLike objects.
            validate: Whether to validate the configuration. When True, performs
                     additional checks beyond basic schema validation.
            strict: Whether to raise exceptions on validation warnings. Only
                   applicable when validate=True.

        Yields:
            Fully initialized RuntimeConfig instance

        Raises:
            ConfigError: If configuration is invalid or validation fails in strict mode
            TypeError: If source is neither a path nor a Config object
            OSError: If configuration file cannot be accessed

        Example:
            ```python
            async with RuntimeConfig.open("config.yml") as runtime:
                resource = await runtime.load_resource("example")
            ```

        Note:
            The context manager ensures that all resources are properly initialized
            before use and cleaned up afterwards, even if an error occurs.
        """
        runtime = prepare_runtime(cls, source, validate=validate, strict=strict)
        async with runtime as r:
            yield r

    @classmethod
    @contextmanager
    def open_sync(
        cls,
        source: JoinablePathLike | Config,
        *,
        validate: bool = True,
        strict: bool = False,
    ) -> Generator[RuntimeConfig]:
        """Create and manage a runtime configuration synchronously.

        This is the synchronous version of open(). It provides the same functionality
        but uses a standard synchronous context manager interface. Use this if you
        don't need async functionality.

        Args:
            source: Either a path to a configuration file or a Config object.
                   File paths can be strings or PathLike objects.
            validate: Whether to validate the configuration. When True, performs
                     additional checks beyond basic schema validation.
            strict: Whether to raise exceptions on validation warnings. Only
                   applicable when validate=True.

        Yields:
            Fully initialized RuntimeConfig instance

        Raises:
            ConfigError: If configuration is invalid or validation fails in strict mode
            TypeError: If source is neither a path nor a Config object
            OSError: If configuration file cannot be accessed

        Example:
            ```python
            with RuntimeConfig.open_sync("config.yml") as runtime:
                resource = runtime.load_resource_sync("example")
            ```

        Note:
            The context manager ensures that all resources are properly initialized
            before use and cleaned up afterwards, even if an error occurs.
        """
        runtime = prepare_runtime(cls, source, validate=validate, strict=strict)
        with runtime:
            yield runtime

    @classmethod
    def from_file(cls, path: JoinablePathLike) -> Self:
        """Convenience function to directly create runtime config from a file.

        Args:
            path: Path to the config file

        Returns:
            Initialized runtime configuration
        """
        manager = ConfigManager.load(path)
        return cls.from_config(manager.config)

    @classmethod
    def from_config(cls, config: Config | JoinablePathLike) -> Self:
        """Create a fully initialized runtime config from static config.

        Args:
            config: Static configuration to initialize from

        Returns:
            Initialized runtime configuration
        """
        if isinstance(config, str | os.PathLike | UPath):
            config = ConfigManager.load(config).config
        loader_registry = ResourceLoaderRegistry()
        processor_registry = ProcessorRegistry()
        resource_registry = ResourceRegistry(
            loader_registry=loader_registry,
            processor_registry=processor_registry,
        )
        prompt_registry = PromptRegistry()
        tool_registry = ToolRegistry()
        assert isinstance(config, Config)
        runtime = cls(
            config=config,
            loader_registry=loader_registry,
            processor_registry=processor_registry,
            resource_registry=resource_registry,
            prompt_registry=prompt_registry,
            tool_registry=tool_registry,
        )
        from llmling.config.llm_tools import LLMTools

        llm_tools = LLMTools(runtime)
        capabilities = config.global_settings.llm_capabilities

        # Register enabled capabilities
        if capabilities.load_resource:
            tool_registry["load_resource"] = llm_tools.load_resource
        if capabilities.get_resources:
            tool_registry["get_resources"] = llm_tools.get_resources
        if capabilities.install_package:
            tool_registry["install_package"] = llm_tools.install_package
        if capabilities.register_tool:
            tool_registry["register_tool"] = llm_tools.register_tool
        if capabilities.register_code_tool:
            tool_registry["register_code_tool"] = llm_tools.register_code_tool
        if capabilities.chain_tools:
            tool_registry["chain"] = ChainTool(runtime)
        return runtime

    async def startup(self) -> None:
        """Start all runtime components."""
        await self._processor_registry.startup()
        await self._tool_registry.startup()
        await self._resource_registry.startup()
        await self._prompt_registry.startup()

    async def shutdown(self) -> None:
        """Shut down all runtime components."""
        await self._prompt_registry.shutdown()
        await self._resource_registry.shutdown()
        await self._tool_registry.shutdown()
        await self._processor_registry.shutdown()

    # Resource Management
    async def load_resource(self, name: str) -> LoadedResource:
        """Load a resource by its registered name.

        Args:
            name: Name of the resource as registered in configuration

        Returns:
            LoadedResource containing content and metadata

        Raises:
            ResourceError: If resource doesn't exist or cannot be loaded
        """
        return await self._resource_registry.load(name)

    async def resolve_resource_uri(self, uri_or_name: str) -> tuple[str, BaseResource]:
        """Resolve a resource identifier to a proper URI and resource.

        Args:
            uri_or_name: Can be:
                - Resource name: "test.txt"
                - Full URI: "file:///test.txt"
                - Local path: "/path/to/file.txt"

        Returns:
            Tuple of (resolved URI, resource object)

        Raises:
            ResourceError: If resolution fails
        """
        logger.debug("Resolving resource identifier: %s", uri_or_name)

        # 1. If it's already a URI, use directly
        if "://" in uri_or_name:
            logger.debug("Using direct URI")
            loader = self._loader_registry.find_loader_for_uri(uri_or_name)
            name = loader.get_name_from_uri(uri_or_name)
            if name in self._resource_registry:
                return uri_or_name, self._resource_registry[name]
            # Create temporary resource for the URI
            resource: BaseResource = PathResource(path=uri_or_name)  # pyright: ignore
            return uri_or_name, resource

        # 2. Try as resource name
        try:
            logger.debug("Trying as resource name")
            resource = self._resource_registry[uri_or_name]
            loader = self._loader_registry.get_loader(resource)
            loader = loader.create(resource, uri_or_name)  # Create instance
            uri = loader.create_uri(name=uri_or_name)
        except KeyError:
            pass
        else:
            return uri, resource

        # 3. If it looks like a path, try as file
        if "/" in uri_or_name or "\\" in uri_or_name or "." in uri_or_name:
            try:
                logger.debug("Trying as file path")
                resource = PathResource(path=uri_or_name)  # pyright: ignore
                loader = PathResourceLoader.create(resource, uri_or_name)
                uri = loader.create_uri(name=uri_or_name)
            except Exception as exc:  # noqa: BLE001
                logger.debug("Failed to create file URI: %s", exc)
            else:
                return uri, resource
        msg = f"Could not resolve resource {uri_or_name!r}. Expected resource name or path."
        raise exceptions.ResourceError(msg)

    async def load_resource_by_uri(self, uri: str) -> LoadedResource:
        """Load a resource by URI."""
        try:
            resolved_uri, resource = await self.resolve_resource_uri(uri)
            loader = self._loader_registry.get_loader(resource)
            name = loader.get_name_from_uri(resolved_uri)
            loader = loader.create(resource, name)
            async for res in loader.load(processor_registry=self._processor_registry):
                return res  # Return first resource
            msg = "No resources loaded"
            raise exceptions.ResourceError(msg)  # noqa: TRY301
        except Exception as exc:
            msg = f"Failed to load resource from URI {uri}"
            raise exceptions.ResourceError(msg) from exc

    def list_resource_names(self) -> Sequence[str]:
        """List all available resource names.

        Returns:
            List of registered resource names
        """
        return self._resource_registry.list_items()

    def list_resource_uris(self) -> Sequence[str]:
        """List all available resource URIs.

        Returns:
            List of registered resource names
        """
        return [res.uri for res in self._resource_registry.values() if res.uri]

    def get_resource_uri(self, name: str) -> str:
        """Get URI for a resource.

        Args:
            name: Name of the resource

        Returns:
            URI for the resource

        Raises:
            ResourceError: If resource not found
        """
        return self._resource_registry.get_uri(name)

    def get_resource(self, name_or_uri: str) -> BaseResource:
        """Get a resource configuration by name or URI.

        Args:
            name_or_uri: Name of the resource or its URI. URIs must start with a scheme
                (e.g., "file://", "text://", etc.)

        Returns:
            The resource configuration

        Raises:
            ResourceError: If resource not found
        """
        if "://" in name_or_uri:  # It's a URI
            for resource in self._resource_registry.values():
                if resource.uri == name_or_uri:
                    return resource
            msg = f"No resource found with URI: {name_or_uri}"
            raise exceptions.ResourceError(msg)
        return self._resource_registry[name_or_uri]

    def get_resources(self) -> Sequence[BaseResource]:
        """Get all registered resource configurations.

        Returns:
            List of all resource configurations
        """
        return list(self._resource_registry.values())

    async def register_resource_by_loader(
        self,
        loader_type: str,
        name: str,
        *,
        description: str = "",
        **params: Any,
    ) -> BaseResource:
        """Register a resource using a loader type.

        Provides a parameter-based interface for registering resources
        without requiring resource objects.

        Args:
            loader_type: Type of loader to use ("path", "text", "cli", etc.)
            name: Name for the resource
            description: Optional description
            **params: Loader-specific parameters

        Example:
            await runtime.register_resource_by_loader(
                "path",
                "readme",
                description="Project readme",
                path="README.md"
            )

            await runtime.register_resource_by_loader(
                "text",
                "greeting",
                content="Hello, world!"
            )
        """
        try:
            # Get loader class from registry
            loader_cls = self._loader_registry[loader_type]

            # Get the resource class from the loader
            resource_class = loader_cls.context_class

            # Create resource instance with just the essential fields
            resource = resource_class(description=description, **params)
            self._resource_registry.register(name, resource)
        except KeyError as exc:
            msg = f"Unknown loader type: {loader_type}"
            raise exceptions.ResourceError(msg) from exc
        except Exception as exc:
            msg = f"Failed to create resource: {exc}"
            raise exceptions.ResourceError(msg) from exc
        else:
            return resource

    def register_resource(
        self,
        name: str,
        resource: BaseResource,
        *,
        replace: bool = False,
    ) -> None:
        """Register a new resource.

        Args:
            name: Name for the resource
            resource: Resource to register
            replace: Whether to replace existing resource

        Raises:
            ResourceError: If name exists and replace=False
        """
        self._resource_registry.register(name, resource, replace=replace)

    def get_resource_loader(self, resource: BaseResource) -> Any:  # type: ignore[return]
        """Get loader for a resource type.

        Args:
            resource: Resource to get loader for

        Returns:
            Resource loader instance

        Raises:
            LoaderError: If no loader found for resource type
        """
        return self._loader_registry.get_loader(resource)

    # Tool Management
    def list_tool_names(self) -> Sequence[str]:
        """List all available tool names.

        Returns:
            List of registered tool names
        """
        return self._tool_registry.list_items()

    @property
    def tools(self) -> dict[str, LLMCallableTool]:
        """Get all registered tools.

        Returns:
            Dictionary mapping tool names to tools
        """
        return dict(self._tool_registry)

    async def execute_tool(
        self,
        _name: str,  # prefixed with "_" to avoid name collisions
        **params: Any,
    ) -> Any:
        """Execute a tool by name.

        Args:
            _name: Name of the tool to execute
            **params: Parameters to pass to the tool

        Returns:
            Tool execution result

        Raises:
            ToolError: If tool execution fails
        """
        return await self._tool_registry.execute(_name, **params)

    def get_tool(self, name: str) -> LLMCallableTool:
        """Get a tool by name.

        Args:
            name: Name of the tool

        Returns:
            The tool

        Raises:
            ToolError: If tool not found
        """
        return self._tool_registry[name]

    def get_tools(self) -> Sequence[LLMCallableTool]:
        """Get all registered tools.

        Returns:
            List of all tools
        """
        return list(self._tool_registry.values())

    async def install_package(
        self,
        package: str,
    ) -> str:
        """Install a Python package using the dependency manager.

        Package specifications follow PIP format (e.g. "requests>=2.28.0").

        Args:
            package: Package specification to install

        Returns:
            Message confirming the installation

        Raises:
            ToolError: If installation fails or package spec is invalid

        Example:
            >>> await runtime.install_package("requests>=2.28.0")
        """
        try:
            self._dep_manager.install_dependency(package)
            return f"Successfully installed package: {package}"  # noqa: TRY300
        except Exception as exc:
            msg = f"Failed to install package: {exc}"
            raise ToolError(msg) from exc

    async def register_tool(
        self,
        function: str | Callable[..., Any],
        name: str | None = None,
        description: str | None = None,
        *,
        auto_install: bool = False,
    ) -> str:
        """Register a new tool from a function or import path.

        Args:
            function: Function to register (callable or import path)
            name: Optional name override (uses function name if None)
            description: Optional description override (uses docstring if None)
            auto_install: Whether to attempt installing missing package

        Returns:
            Message confirming the registration

        Raises:
            ToolError: If registration fails

        Example:
            >>> await runtime.register_tool("webbrowser.open", "open_url")
            >>> await runtime.register_tool(my_function)
        """
        try:
            if auto_install and isinstance(function, str):
                # Try to import root module, install if missing
                package = function.split(".")[0]
                try:
                    importlib.import_module(package)
                except ImportError:
                    logger.info("Attempting to install package: %s", package)
                    await self.install_package(package)

            tool = LLMCallableTool.from_callable(
                function, name_override=name, description_override=description
            )
            self._tool_registry.register(name or tool.name, tool)
            source = (
                function
                if isinstance(function, str)
                else getattr(function, "__name__", str(function))
            )
        except Exception as exc:
            msg = f"Failed to register tool: {exc}"
            raise ToolError(msg) from exc
        else:
            return f"Successfully registered tool: {tool.name} from {source}"

    async def register_code_tool(
        self,
        name: str,
        code: str,
        description: str | None = None,
    ) -> str:
        """Register a new tool from Python code.

        The provided code should define a function that will be converted into a tool.
        The function's docstring will be used as the tool's description if no description
        is provided.

        Args:
            name: Name for the new tool
            code: Python code defining the tool function
            description: Optional description override

        Returns:
            Message confirming the registration

        Raises:
            ToolError: If registration fails

        Example:
            >>> code = '''
            ... async def count_words(text: str) -> dict[str, int]:
            ...     words = text.split()
            ...     return {"total": len(words)}
            ... '''
            >>> await runtime.register_code_tool("word_count", code)
        """
        try:
            namespace: dict[str, Any] = {}
            exec(code, namespace)
            func = next((v for v in namespace.values() if callable(v)), None)
            if not func:
                msg = "No callable found in provided code"
                raise ValueError(msg)  # noqa: TRY301

            tool = LLMCallableTool.from_callable(
                func, name_override=name, description_override=description
            )
            self._tool_registry.register(name, tool)
            return f"Successfully registered tool: {name}"  # noqa: TRY300

        except Exception as exc:
            msg = f"Failed to register tool: {exc}"
            raise ToolError(msg) from exc

    # Prompt Management
    def list_prompt_names(self) -> Sequence[str]:
        """List all available prompt names.

        Returns:
            List of registered prompt names
        """
        return self._prompt_registry.list_items()

    def register_dynamic_prompt(
        self,
        name: str,
        fn: str | Callable[..., Any],
        *,
        description: str | None = None,
        template: str | None = None,
        replace: bool = False,
    ) -> None:
        """Register a function-based prompt.

        Args:
            name: Name to register under
            fn: Function or import path (e.g., "module.submodule.function")
            description: Optional description (extracted from docstring if not provided)
            template: Optional template for formatting output
            replace: Whether to replace existing prompt

        Example:
            >>> def get_info(url: str) -> str:
            ...     '''Fetch info from URL.'''
            ...     return "info"
            ...
            >>> runtime.register_dynamic_prompt("fetch", get_info)
            >>> # or
            >>> runtime.register_dynamic_prompt(
            ...     "github",
            ...     "my_module.get_github_info",
            ...     description="Fetch GitHub repository information"
            ... )
        """
        try:
            prompt = DynamicPrompt.from_callable(
                fn,
                name_override=name,
                description_override=description,
                template_override=template,
            )
            self._prompt_registry.register(name, prompt, replace=replace)

        except Exception as exc:
            msg = f"Failed to register dynamic prompt {name!r}: {exc}"
            raise exceptions.LLMLingError(msg) from exc

    def register_static_prompt(
        self,
        name: str,
        content: str,
        description: str | None = None,
        *,
        replace: bool = False,
    ) -> None:
        r"""Register a static prompt with text content.

        A static prompt is a simple text template that can be used as-is or with
        Python's string formatting (using {placeholder} syntax).

        Args:
            name: Name to register under
            content: Prompt text content
            description: Optional description of what the prompt does
            replace: Whether to replace existing prompt

        Example:
            >>> runtime.register_static_prompt(
            ...     "summarize",
            ...     "Please summarize the following text in 3 bullet points:\\n{text}",
            ...     description="Create a bullet-point summary",
            ... )
            >>> runtime.register_static_prompt(
            ...     "greet",
            ...     "Hello {name}! Welcome to {company}.",
            ...     description="Simple greeting template",
            ... )

        Raises:
            LLMLingError: If registration fails
        """
        try:
            # Create standard user message from content
            messages = [PromptMessage(role="user", content=content)]

            # Use content's first line as description if none provided
            if not description:
                first_line = content.split("\n", 1)[0]
                description = (
                    first_line[:100] + "..." if len(first_line) > 100 else first_line  # noqa: PLR2004
                )

            prompt = StaticPrompt(name=name, description=description, messages=messages)
            self._prompt_registry.register(name, prompt, replace=replace)

        except Exception as exc:
            msg = f"Failed to register static prompt {name!r}: {exc}"
            raise exceptions.LLMLingError(msg) from exc

    def register_file_prompt(
        self,
        name: str,
        path: JoinablePathLike,
        *,
        description: str,
        output_format: Literal["text", "markdown", "jinja2"] = "text",
        watch: bool = False,
        replace: bool = False,
    ) -> None:
        """Register a file-based prompt.

        Args:
            name: Name to register under
            path: Path to the prompt file
            description: Human-readable description
            output_format: Format of the file content
            watch: Whether to watch file for changes
            replace: Whether to replace existing prompt

        Example:
            >>> runtime.register_file_prompt(
            ...     "analyze",
            ...     "prompts/analysis.md",
            ...     description="Code analysis prompt",
            ...     format="markdown"
            ... )
        """
        from upathtools import to_upath

        try:
            if not to_upath(path).exists():
                msg = f"Prompt file not found: {path}"
                raise FileNotFoundError(msg)  # noqa: TRY301

            prompt = FilePrompt(
                name=name,
                path=upath.UPath(path),
                description=description,
                format=output_format,
                watch=watch,
            )
            self._prompt_registry.register(name, prompt, replace=replace)

        except Exception as exc:
            msg = f"Failed to register file prompt {name!r}: {exc}"
            raise exceptions.LLMLingError(msg) from exc

    def register_prompt(
        self,
        name: str,
        prompt: BasePrompt,
        *,
        replace: bool = False,
    ) -> None:
        """Register a pre-configured prompt.

        Note:
            The specialized registration methods should be preferred:
            - register_dynamic_prompt() for function-based prompts
            - register_static_prompt() for message-based prompts
            - register_file_prompt() for file-based prompts

        This method is provided for advanced use cases where you need
        to register an already configured prompt instance.

        Args:
            name: Name to register under
            prompt: Configured prompt instance
            replace: Whether to replace existing prompt
        """
        if isinstance(prompt, dict):
            if "type" not in prompt:
                msg = "Missing prompt type in configuration"
                raise exceptions.ConfigError(msg)
            from llmling.prompts.models import DynamicPrompt, FilePrompt, StaticPrompt

            match prompt["type"]:
                case "text":
                    prompt_obj: BasePrompt = StaticPrompt.model_validate(prompt)
                case "function":
                    prompt_obj = DynamicPrompt.model_validate(prompt)
                case "file":
                    prompt_obj = FilePrompt.model_validate(prompt)
                case _:
                    msg = f"Unknown prompt type: {prompt['type']}"
                    raise exceptions.ConfigError(msg)
        else:
            prompt_obj = prompt

        self._prompt_registry.register(name, prompt_obj, replace=replace)

    async def render_prompt(
        self,
        name: str,
        arguments: dict[str, Any] | None = None,
    ) -> Sequence[PromptMessage]:
        """Format a prompt with arguments.

        Args:
            name: Name of the prompt
            arguments: Optional arguments for formatting

        Returns:
            List of formatted messages

        Raises:
            LLMLingError: If prompt not found or formatting fails
        """
        try:
            prompt = self._prompt_registry[name]
            return await prompt.format(arguments)
        except KeyError as exc:
            msg = f"Prompt not found: {name}"
            raise exceptions.LLMLingError(msg) from exc
        except Exception as exc:
            msg = f"Failed to format prompt {name}: {exc}"
            raise exceptions.LLMLingError(msg) from exc

    def get_prompt(self, name: str) -> BasePrompt:
        """Get a prompt by name.

        Args:
            name: Name of the prompt

        Returns:
            The prompt

        Raises:
            LLMLingError: If prompt not found
        """
        try:
            return self._prompt_registry[name]
        except KeyError as exc:
            msg = f"Prompt not found: {name}"
            raise exceptions.LLMLingError(msg) from exc

    def get_prompts(self) -> Sequence[BasePrompt]:
        """Get all registered prompts.

        Returns:
            List of all prompts
        """
        return list(self._prompt_registry.values())

    async def process_content(
        self,
        content: str,
        processor_name: str,
        **kwargs: Any,
    ) -> ProcessorResult:
        """Process content with a named processor.

        Args:
            content: Content to process
            processor_name: Name of processor to use
            **kwargs: Additional processor arguments

        Returns:
            Processing result

        Raises:
            ProcessorError: If processing fails
        """
        return await self._processor_registry.process(
            content, [ProcessingStep(name=processor_name, kwargs=kwargs)]
        )

    @property
    def original_config(self) -> Config:
        """Get the original static configuration.

        Returns:
            Original configuration
        """
        return self._config

    async def get_prompt_completions(
        self,
        current_value: str,
        argument_name: str,
        prompt_name: str,
        **options: Any,
    ) -> list[str]:
        """Get completions for a prompt argument.

        Args:
            current_value: Current input value
            argument_name: Name of the argument
            prompt_name: Name of the prompt
            **options: Additional options

        Returns:
            List of completion suggestions
        """
        return await self._prompt_registry.get_completions(
            current_value=current_value,
            argument_name=argument_name,
            prompt_name=prompt_name,
            **options,
        )

    async def get_resource_completions(
        self,
        uri: str,
        current_value: str,
        argument_name: str | None = None,
        **options: Any,
    ) -> list[str]:
        """Get completions for a resource.

        Args:
            uri: Resource URI
            current_value: Current input value
            argument_name: Optional argument name
            **options: Additional options

        Returns:
            List of completion suggestions
        """
        loader = self._loader_registry.find_loader_for_uri(uri)
        return await loader.get_completions(
            current_value=current_value,
            argument_name=argument_name,
            **options,
        )

original_config property

original_config: Config

Get the original static configuration.

Returns:

Type Description
Config

Original configuration

tools property

tools: dict[str, LLMCallableTool]

Get all registered tools.

Returns:

Type Description
dict[str, LLMCallableTool]

Dictionary mapping tool names to tools

__aenter__ async

__aenter__() -> Self

Initialize dependencies and registries.

Source code in src/llmling/config/runtime.py
async def __aenter__(self) -> Self:
    """Initialize dependencies and registries."""
    # Check and set initialized flag atomically before ANY async op
    # This should allow caeses where same runtime gets initialized multiple times
    needs_init = not self._initialized
    self._initialized = True

    if needs_init:
        await self._dep_manager.__aenter__()
        await self._initialize_registries()
    return self

__aexit__ async

__aexit__(
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None

Clean up dependencies and registries.

Source code in src/llmling/config/runtime.py
async def __aexit__(
    self,
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: types.TracebackType | None,
) -> None:
    """Clean up dependencies and registries."""
    try:
        await self.shutdown()
    finally:
        await self._dep_manager.__aexit__(exc_type, exc_val, exc_tb)

__enter__

__enter__() -> Self

Synchronous context manager entry.

Source code in src/llmling/config/runtime.py
def __enter__(self) -> Self:
    """Synchronous context manager entry."""
    self._dep_manager.__enter__()
    # Initialize registries if not already done
    import asyncio

    if not self._initialized:
        loop = asyncio.new_event_loop()
        try:
            loop.run_until_complete(self._initialize_registries())
            self._initialized = True
        finally:
            loop.close()
    return self

__exit__

__exit__(
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None

Synchronous context manager exit.

Source code in src/llmling/config/runtime.py
def __exit__(
    self,
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: types.TracebackType | None,
) -> None:
    """Synchronous context manager exit."""
    self._dep_manager.__exit__(exc_type, exc_val, exc_tb)

__init__

__init__(
    config: Config,
    *,
    loader_registry: ResourceLoaderRegistry,
    processor_registry: ProcessorRegistry,
    resource_registry: ResourceRegistry,
    prompt_registry: PromptRegistry,
    tool_registry: ToolRegistry
) -> None

Initialize with config and registries.

Parameters:

Name Type Description Default
config Config

Original static configuration

required
loader_registry ResourceLoaderRegistry

Registry for resource loaders

required
processor_registry ProcessorRegistry

Registry for content processors

required
resource_registry ResourceRegistry

Registry for resources

required
prompt_registry PromptRegistry

Registry for prompts

required
tool_registry ToolRegistry

Registry for tools

required
Source code in src/llmling/config/runtime.py
def __init__(
    self,
    config: Config,
    *,
    loader_registry: ResourceLoaderRegistry,
    processor_registry: ProcessorRegistry,
    resource_registry: ResourceRegistry,
    prompt_registry: PromptRegistry,
    tool_registry: ToolRegistry,
) -> None:
    """Initialize with config and registries.

    Args:
        config: Original static configuration
        loader_registry: Registry for resource loaders
        processor_registry: Registry for content processors
        resource_registry: Registry for resources
        prompt_registry: Registry for prompts
        tool_registry: Registry for tools
    """
    from llmling.depmanager import DependencyManager

    super().__init__()
    self._config = config
    self._loader_registry = loader_registry
    self._processor_registry = processor_registry
    self._resource_registry = resource_registry
    self._prompt_registry = prompt_registry
    self._tool_registry = tool_registry
    self._initialized = False
    # Register builtin processors
    proc = Jinja2Processor(config.global_settings.jinja_environment)
    self._processor_registry["jinja_template"] = proc
    settings = self._config.global_settings
    self._dep_manager = DependencyManager(
        prefer_uv=settings.prefer_uv,
        requirements=settings.requirements,
        extra_paths=settings.extra_paths,
        pip_index_url=str(settings.pip_index_url) if settings.pip_index_url else None,
        scripts=settings.scripts,
    )

create async classmethod

create(config: Config) -> Self

Create and initialize a runtime configuration.

This is a convenience method that ensures proper initialization when not using the async context manager.

Parameters:

Name Type Description Default
config Config

Static configuration to initialize from

required

Returns:

Type Description
Self

Initialized runtime configuration

Source code in src/llmling/config/runtime.py
@classmethod
async def create(cls, config: Config) -> Self:
    """Create and initialize a runtime configuration.

    This is a convenience method that ensures proper initialization
    when not using the async context manager.

    Args:
        config: Static configuration to initialize from

    Returns:
        Initialized runtime configuration
    """
    runtime = cls.from_config(config)
    async with runtime as initialized:
        return initialized

execute_tool async

execute_tool(_name: str, **params: Any) -> Any

Execute a tool by name.

Parameters:

Name Type Description Default
_name str

Name of the tool to execute

required
**params Any

Parameters to pass to the tool

{}

Returns:

Type Description
Any

Tool execution result

Raises:

Type Description
ToolError

If tool execution fails

Source code in src/llmling/config/runtime.py
async def execute_tool(
    self,
    _name: str,  # prefixed with "_" to avoid name collisions
    **params: Any,
) -> Any:
    """Execute a tool by name.

    Args:
        _name: Name of the tool to execute
        **params: Parameters to pass to the tool

    Returns:
        Tool execution result

    Raises:
        ToolError: If tool execution fails
    """
    return await self._tool_registry.execute(_name, **params)

from_config classmethod

from_config(config: Config | JoinablePathLike) -> Self

Create a fully initialized runtime config from static config.

Parameters:

Name Type Description Default
config Config | JoinablePathLike

Static configuration to initialize from

required

Returns:

Type Description
Self

Initialized runtime configuration

Source code in src/llmling/config/runtime.py
@classmethod
def from_config(cls, config: Config | JoinablePathLike) -> Self:
    """Create a fully initialized runtime config from static config.

    Args:
        config: Static configuration to initialize from

    Returns:
        Initialized runtime configuration
    """
    if isinstance(config, str | os.PathLike | UPath):
        config = ConfigManager.load(config).config
    loader_registry = ResourceLoaderRegistry()
    processor_registry = ProcessorRegistry()
    resource_registry = ResourceRegistry(
        loader_registry=loader_registry,
        processor_registry=processor_registry,
    )
    prompt_registry = PromptRegistry()
    tool_registry = ToolRegistry()
    assert isinstance(config, Config)
    runtime = cls(
        config=config,
        loader_registry=loader_registry,
        processor_registry=processor_registry,
        resource_registry=resource_registry,
        prompt_registry=prompt_registry,
        tool_registry=tool_registry,
    )
    from llmling.config.llm_tools import LLMTools

    llm_tools = LLMTools(runtime)
    capabilities = config.global_settings.llm_capabilities

    # Register enabled capabilities
    if capabilities.load_resource:
        tool_registry["load_resource"] = llm_tools.load_resource
    if capabilities.get_resources:
        tool_registry["get_resources"] = llm_tools.get_resources
    if capabilities.install_package:
        tool_registry["install_package"] = llm_tools.install_package
    if capabilities.register_tool:
        tool_registry["register_tool"] = llm_tools.register_tool
    if capabilities.register_code_tool:
        tool_registry["register_code_tool"] = llm_tools.register_code_tool
    if capabilities.chain_tools:
        tool_registry["chain"] = ChainTool(runtime)
    return runtime

from_file classmethod

from_file(path: JoinablePathLike) -> Self

Convenience function to directly create runtime config from a file.

Parameters:

Name Type Description Default
path JoinablePathLike

Path to the config file

required

Returns:

Type Description
Self

Initialized runtime configuration

Source code in src/llmling/config/runtime.py
@classmethod
def from_file(cls, path: JoinablePathLike) -> Self:
    """Convenience function to directly create runtime config from a file.

    Args:
        path: Path to the config file

    Returns:
        Initialized runtime configuration
    """
    manager = ConfigManager.load(path)
    return cls.from_config(manager.config)

get_prompt

get_prompt(name: str) -> BasePrompt

Get a prompt by name.

Parameters:

Name Type Description Default
name str

Name of the prompt

required

Returns:

Type Description
BasePrompt

The prompt

Raises:

Type Description
LLMLingError

If prompt not found

Source code in src/llmling/config/runtime.py
def get_prompt(self, name: str) -> BasePrompt:
    """Get a prompt by name.

    Args:
        name: Name of the prompt

    Returns:
        The prompt

    Raises:
        LLMLingError: If prompt not found
    """
    try:
        return self._prompt_registry[name]
    except KeyError as exc:
        msg = f"Prompt not found: {name}"
        raise exceptions.LLMLingError(msg) from exc

get_prompt_completions async

get_prompt_completions(
    current_value: str, argument_name: str, prompt_name: str, **options: Any
) -> list[str]

Get completions for a prompt argument.

Parameters:

Name Type Description Default
current_value str

Current input value

required
argument_name str

Name of the argument

required
prompt_name str

Name of the prompt

required
**options Any

Additional options

{}

Returns:

Type Description
list[str]

List of completion suggestions

Source code in src/llmling/config/runtime.py
async def get_prompt_completions(
    self,
    current_value: str,
    argument_name: str,
    prompt_name: str,
    **options: Any,
) -> list[str]:
    """Get completions for a prompt argument.

    Args:
        current_value: Current input value
        argument_name: Name of the argument
        prompt_name: Name of the prompt
        **options: Additional options

    Returns:
        List of completion suggestions
    """
    return await self._prompt_registry.get_completions(
        current_value=current_value,
        argument_name=argument_name,
        prompt_name=prompt_name,
        **options,
    )

get_prompts

get_prompts() -> Sequence[BasePrompt]

Get all registered prompts.

Returns:

Type Description
Sequence[BasePrompt]

List of all prompts

Source code in src/llmling/config/runtime.py
def get_prompts(self) -> Sequence[BasePrompt]:
    """Get all registered prompts.

    Returns:
        List of all prompts
    """
    return list(self._prompt_registry.values())

get_resource

get_resource(name_or_uri: str) -> BaseResource

Get a resource configuration by name or URI.

Parameters:

Name Type Description Default
name_or_uri str

Name of the resource or its URI. URIs must start with a scheme (e.g., "file://", "text://", etc.)

required

Returns:

Type Description
BaseResource

The resource configuration

Raises:

Type Description
ResourceError

If resource not found

Source code in src/llmling/config/runtime.py
def get_resource(self, name_or_uri: str) -> BaseResource:
    """Get a resource configuration by name or URI.

    Args:
        name_or_uri: Name of the resource or its URI. URIs must start with a scheme
            (e.g., "file://", "text://", etc.)

    Returns:
        The resource configuration

    Raises:
        ResourceError: If resource not found
    """
    if "://" in name_or_uri:  # It's a URI
        for resource in self._resource_registry.values():
            if resource.uri == name_or_uri:
                return resource
        msg = f"No resource found with URI: {name_or_uri}"
        raise exceptions.ResourceError(msg)
    return self._resource_registry[name_or_uri]

get_resource_completions async

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

Get completions for a resource.

Parameters:

Name Type Description Default
uri str

Resource URI

required
current_value str

Current input value

required
argument_name str | None

Optional argument name

None
**options Any

Additional options

{}

Returns:

Type Description
list[str]

List of completion suggestions

Source code in src/llmling/config/runtime.py
async def get_resource_completions(
    self,
    uri: str,
    current_value: str,
    argument_name: str | None = None,
    **options: Any,
) -> list[str]:
    """Get completions for a resource.

    Args:
        uri: Resource URI
        current_value: Current input value
        argument_name: Optional argument name
        **options: Additional options

    Returns:
        List of completion suggestions
    """
    loader = self._loader_registry.find_loader_for_uri(uri)
    return await loader.get_completions(
        current_value=current_value,
        argument_name=argument_name,
        **options,
    )

get_resource_loader

get_resource_loader(resource: BaseResource) -> Any

Get loader for a resource type.

Parameters:

Name Type Description Default
resource BaseResource

Resource to get loader for

required

Returns:

Type Description
Any

Resource loader instance

Raises:

Type Description
LoaderError

If no loader found for resource type

Source code in src/llmling/config/runtime.py
def get_resource_loader(self, resource: BaseResource) -> Any:  # type: ignore[return]
    """Get loader for a resource type.

    Args:
        resource: Resource to get loader for

    Returns:
        Resource loader instance

    Raises:
        LoaderError: If no loader found for resource type
    """
    return self._loader_registry.get_loader(resource)

get_resource_uri

get_resource_uri(name: str) -> str

Get URI for a resource.

Parameters:

Name Type Description Default
name str

Name of the resource

required

Returns:

Type Description
str

URI for the resource

Raises:

Type Description
ResourceError

If resource not found

Source code in src/llmling/config/runtime.py
def get_resource_uri(self, name: str) -> str:
    """Get URI for a resource.

    Args:
        name: Name of the resource

    Returns:
        URI for the resource

    Raises:
        ResourceError: If resource not found
    """
    return self._resource_registry.get_uri(name)

get_resources

get_resources() -> Sequence[BaseResource]

Get all registered resource configurations.

Returns:

Type Description
Sequence[BaseResource]

List of all resource configurations

Source code in src/llmling/config/runtime.py
def get_resources(self) -> Sequence[BaseResource]:
    """Get all registered resource configurations.

    Returns:
        List of all resource configurations
    """
    return list(self._resource_registry.values())

get_tool

get_tool(name: str) -> LLMCallableTool

Get a tool by name.

Parameters:

Name Type Description Default
name str

Name of the tool

required

Returns:

Type Description
LLMCallableTool

The tool

Raises:

Type Description
ToolError

If tool not found

Source code in src/llmling/config/runtime.py
def get_tool(self, name: str) -> LLMCallableTool:
    """Get a tool by name.

    Args:
        name: Name of the tool

    Returns:
        The tool

    Raises:
        ToolError: If tool not found
    """
    return self._tool_registry[name]

get_tools

get_tools() -> Sequence[LLMCallableTool]

Get all registered tools.

Returns:

Type Description
Sequence[LLMCallableTool]

List of all tools

Source code in src/llmling/config/runtime.py
def get_tools(self) -> Sequence[LLMCallableTool]:
    """Get all registered tools.

    Returns:
        List of all tools
    """
    return list(self._tool_registry.values())

install_package async

install_package(package: str) -> str

Install a Python package using the dependency manager.

Package specifications follow PIP format (e.g. "requests>=2.28.0").

Parameters:

Name Type Description Default
package str

Package specification to install

required

Returns:

Type Description
str

Message confirming the installation

Raises:

Type Description
ToolError

If installation fails or package spec is invalid

Example

await runtime.install_package("requests>=2.28.0")

Source code in src/llmling/config/runtime.py
async def install_package(
    self,
    package: str,
) -> str:
    """Install a Python package using the dependency manager.

    Package specifications follow PIP format (e.g. "requests>=2.28.0").

    Args:
        package: Package specification to install

    Returns:
        Message confirming the installation

    Raises:
        ToolError: If installation fails or package spec is invalid

    Example:
        >>> await runtime.install_package("requests>=2.28.0")
    """
    try:
        self._dep_manager.install_dependency(package)
        return f"Successfully installed package: {package}"  # noqa: TRY300
    except Exception as exc:
        msg = f"Failed to install package: {exc}"
        raise ToolError(msg) from exc

list_prompt_names

list_prompt_names() -> Sequence[str]

List all available prompt names.

Returns:

Type Description
Sequence[str]

List of registered prompt names

Source code in src/llmling/config/runtime.py
def list_prompt_names(self) -> Sequence[str]:
    """List all available prompt names.

    Returns:
        List of registered prompt names
    """
    return self._prompt_registry.list_items()

list_resource_names

list_resource_names() -> Sequence[str]

List all available resource names.

Returns:

Type Description
Sequence[str]

List of registered resource names

Source code in src/llmling/config/runtime.py
def list_resource_names(self) -> Sequence[str]:
    """List all available resource names.

    Returns:
        List of registered resource names
    """
    return self._resource_registry.list_items()

list_resource_uris

list_resource_uris() -> Sequence[str]

List all available resource URIs.

Returns:

Type Description
Sequence[str]

List of registered resource names

Source code in src/llmling/config/runtime.py
def list_resource_uris(self) -> Sequence[str]:
    """List all available resource URIs.

    Returns:
        List of registered resource names
    """
    return [res.uri for res in self._resource_registry.values() if res.uri]

list_tool_names

list_tool_names() -> Sequence[str]

List all available tool names.

Returns:

Type Description
Sequence[str]

List of registered tool names

Source code in src/llmling/config/runtime.py
def list_tool_names(self) -> Sequence[str]:
    """List all available tool names.

    Returns:
        List of registered tool names
    """
    return self._tool_registry.list_items()

load_resource async

load_resource(name: str) -> LoadedResource

Load a resource by its registered name.

Parameters:

Name Type Description Default
name str

Name of the resource as registered in configuration

required

Returns:

Type Description
LoadedResource

LoadedResource containing content and metadata

Raises:

Type Description
ResourceError

If resource doesn't exist or cannot be loaded

Source code in src/llmling/config/runtime.py
async def load_resource(self, name: str) -> LoadedResource:
    """Load a resource by its registered name.

    Args:
        name: Name of the resource as registered in configuration

    Returns:
        LoadedResource containing content and metadata

    Raises:
        ResourceError: If resource doesn't exist or cannot be loaded
    """
    return await self._resource_registry.load(name)

load_resource_by_uri async

load_resource_by_uri(uri: str) -> LoadedResource

Load a resource by URI.

Source code in src/llmling/config/runtime.py
async def load_resource_by_uri(self, uri: str) -> LoadedResource:
    """Load a resource by URI."""
    try:
        resolved_uri, resource = await self.resolve_resource_uri(uri)
        loader = self._loader_registry.get_loader(resource)
        name = loader.get_name_from_uri(resolved_uri)
        loader = loader.create(resource, name)
        async for res in loader.load(processor_registry=self._processor_registry):
            return res  # Return first resource
        msg = "No resources loaded"
        raise exceptions.ResourceError(msg)  # noqa: TRY301
    except Exception as exc:
        msg = f"Failed to load resource from URI {uri}"
        raise exceptions.ResourceError(msg) from exc

open async classmethod

open(
    source: JoinablePathLike | Config, *, validate: bool = True, strict: bool = False
) -> AsyncGenerator[RuntimeConfig]

Create and manage a runtime configuration asynchronously.

This is the primary way to create and use a RuntimeConfig. It ensures proper initialization and cleanup of all resources and provides an async context manager interface.

Parameters:

Name Type Description Default
source JoinablePathLike | Config

Either a path to a configuration file or a Config object. File paths can be strings or PathLike objects.

required
validate bool

Whether to validate the configuration. When True, performs additional checks beyond basic schema validation.

True
strict bool

Whether to raise exceptions on validation warnings. Only applicable when validate=True.

False

Yields:

Type Description
AsyncGenerator[RuntimeConfig]

Fully initialized RuntimeConfig instance

Raises:

Type Description
ConfigError

If configuration is invalid or validation fails in strict mode

TypeError

If source is neither a path nor a Config object

OSError

If configuration file cannot be accessed

Example
async with RuntimeConfig.open("config.yml") as runtime:
    resource = await runtime.load_resource("example")
Note

The context manager ensures that all resources are properly initialized before use and cleaned up afterwards, even if an error occurs.

Source code in src/llmling/config/runtime.py
@classmethod
@asynccontextmanager
async def open(
    cls,
    source: JoinablePathLike | Config,
    *,
    validate: bool = True,
    strict: bool = False,
) -> AsyncGenerator[RuntimeConfig]:
    """Create and manage a runtime configuration asynchronously.

    This is the primary way to create and use a RuntimeConfig. It ensures proper
    initialization and cleanup of all resources and provides an async context
    manager interface.

    Args:
        source: Either a path to a configuration file or a Config object.
               File paths can be strings or PathLike objects.
        validate: Whether to validate the configuration. When True, performs
                 additional checks beyond basic schema validation.
        strict: Whether to raise exceptions on validation warnings. Only
               applicable when validate=True.

    Yields:
        Fully initialized RuntimeConfig instance

    Raises:
        ConfigError: If configuration is invalid or validation fails in strict mode
        TypeError: If source is neither a path nor a Config object
        OSError: If configuration file cannot be accessed

    Example:
        ```python
        async with RuntimeConfig.open("config.yml") as runtime:
            resource = await runtime.load_resource("example")
        ```

    Note:
        The context manager ensures that all resources are properly initialized
        before use and cleaned up afterwards, even if an error occurs.
    """
    runtime = prepare_runtime(cls, source, validate=validate, strict=strict)
    async with runtime as r:
        yield r

open_sync classmethod

open_sync(
    source: JoinablePathLike | Config, *, validate: bool = True, strict: bool = False
) -> Generator[RuntimeConfig]

Create and manage a runtime configuration synchronously.

This is the synchronous version of open(). It provides the same functionality but uses a standard synchronous context manager interface. Use this if you don't need async functionality.

Parameters:

Name Type Description Default
source JoinablePathLike | Config

Either a path to a configuration file or a Config object. File paths can be strings or PathLike objects.

required
validate bool

Whether to validate the configuration. When True, performs additional checks beyond basic schema validation.

True
strict bool

Whether to raise exceptions on validation warnings. Only applicable when validate=True.

False

Yields:

Type Description
Generator[RuntimeConfig]

Fully initialized RuntimeConfig instance

Raises:

Type Description
ConfigError

If configuration is invalid or validation fails in strict mode

TypeError

If source is neither a path nor a Config object

OSError

If configuration file cannot be accessed

Example
with RuntimeConfig.open_sync("config.yml") as runtime:
    resource = runtime.load_resource_sync("example")
Note

The context manager ensures that all resources are properly initialized before use and cleaned up afterwards, even if an error occurs.

Source code in src/llmling/config/runtime.py
@classmethod
@contextmanager
def open_sync(
    cls,
    source: JoinablePathLike | Config,
    *,
    validate: bool = True,
    strict: bool = False,
) -> Generator[RuntimeConfig]:
    """Create and manage a runtime configuration synchronously.

    This is the synchronous version of open(). It provides the same functionality
    but uses a standard synchronous context manager interface. Use this if you
    don't need async functionality.

    Args:
        source: Either a path to a configuration file or a Config object.
               File paths can be strings or PathLike objects.
        validate: Whether to validate the configuration. When True, performs
                 additional checks beyond basic schema validation.
        strict: Whether to raise exceptions on validation warnings. Only
               applicable when validate=True.

    Yields:
        Fully initialized RuntimeConfig instance

    Raises:
        ConfigError: If configuration is invalid or validation fails in strict mode
        TypeError: If source is neither a path nor a Config object
        OSError: If configuration file cannot be accessed

    Example:
        ```python
        with RuntimeConfig.open_sync("config.yml") as runtime:
            resource = runtime.load_resource_sync("example")
        ```

    Note:
        The context manager ensures that all resources are properly initialized
        before use and cleaned up afterwards, even if an error occurs.
    """
    runtime = prepare_runtime(cls, source, validate=validate, strict=strict)
    with runtime:
        yield runtime

process_content async

process_content(content: str, processor_name: str, **kwargs: Any) -> ProcessorResult

Process content with a named processor.

Parameters:

Name Type Description Default
content str

Content to process

required
processor_name str

Name of processor to use

required
**kwargs Any

Additional processor arguments

{}

Returns:

Type Description
ProcessorResult

Processing result

Raises:

Type Description
ProcessorError

If processing fails

Source code in src/llmling/config/runtime.py
async def process_content(
    self,
    content: str,
    processor_name: str,
    **kwargs: Any,
) -> ProcessorResult:
    """Process content with a named processor.

    Args:
        content: Content to process
        processor_name: Name of processor to use
        **kwargs: Additional processor arguments

    Returns:
        Processing result

    Raises:
        ProcessorError: If processing fails
    """
    return await self._processor_registry.process(
        content, [ProcessingStep(name=processor_name, kwargs=kwargs)]
    )

register_code_tool async

register_code_tool(name: str, code: str, description: str | None = None) -> str

Register a new tool from Python code.

The provided code should define a function that will be converted into a tool. The function's docstring will be used as the tool's description if no description is provided.

Parameters:

Name Type Description Default
name str

Name for the new tool

required
code str

Python code defining the tool function

required
description str | None

Optional description override

None

Returns:

Type Description
str

Message confirming the registration

Raises:

Type Description
ToolError

If registration fails

Example

code = ''' ... async def count_words(text: str) -> dict[str, int]: ... words = text.split() ... return {"total": len(words)} ... ''' await runtime.register_code_tool("word_count", code)

Source code in src/llmling/config/runtime.py
async def register_code_tool(
    self,
    name: str,
    code: str,
    description: str | None = None,
) -> str:
    """Register a new tool from Python code.

    The provided code should define a function that will be converted into a tool.
    The function's docstring will be used as the tool's description if no description
    is provided.

    Args:
        name: Name for the new tool
        code: Python code defining the tool function
        description: Optional description override

    Returns:
        Message confirming the registration

    Raises:
        ToolError: If registration fails

    Example:
        >>> code = '''
        ... async def count_words(text: str) -> dict[str, int]:
        ...     words = text.split()
        ...     return {"total": len(words)}
        ... '''
        >>> await runtime.register_code_tool("word_count", code)
    """
    try:
        namespace: dict[str, Any] = {}
        exec(code, namespace)
        func = next((v for v in namespace.values() if callable(v)), None)
        if not func:
            msg = "No callable found in provided code"
            raise ValueError(msg)  # noqa: TRY301

        tool = LLMCallableTool.from_callable(
            func, name_override=name, description_override=description
        )
        self._tool_registry.register(name, tool)
        return f"Successfully registered tool: {name}"  # noqa: TRY300

    except Exception as exc:
        msg = f"Failed to register tool: {exc}"
        raise ToolError(msg) from exc

register_dynamic_prompt

register_dynamic_prompt(
    name: str,
    fn: str | Callable[..., Any],
    *,
    description: str | None = None,
    template: str | None = None,
    replace: bool = False
) -> None

Register a function-based prompt.

Parameters:

Name Type Description Default
name str

Name to register under

required
fn str | Callable[..., Any]

Function or import path (e.g., "module.submodule.function")

required
description str | None

Optional description (extracted from docstring if not provided)

None
template str | None

Optional template for formatting output

None
replace bool

Whether to replace existing prompt

False
Example

def get_info(url: str) -> str: ... '''Fetch info from URL.''' ... return "info" ... runtime.register_dynamic_prompt("fetch", get_info)

or

runtime.register_dynamic_prompt( ... "github", ... "my_module.get_github_info", ... description="Fetch GitHub repository information" ... )

Source code in src/llmling/config/runtime.py
def register_dynamic_prompt(
    self,
    name: str,
    fn: str | Callable[..., Any],
    *,
    description: str | None = None,
    template: str | None = None,
    replace: bool = False,
) -> None:
    """Register a function-based prompt.

    Args:
        name: Name to register under
        fn: Function or import path (e.g., "module.submodule.function")
        description: Optional description (extracted from docstring if not provided)
        template: Optional template for formatting output
        replace: Whether to replace existing prompt

    Example:
        >>> def get_info(url: str) -> str:
        ...     '''Fetch info from URL.'''
        ...     return "info"
        ...
        >>> runtime.register_dynamic_prompt("fetch", get_info)
        >>> # or
        >>> runtime.register_dynamic_prompt(
        ...     "github",
        ...     "my_module.get_github_info",
        ...     description="Fetch GitHub repository information"
        ... )
    """
    try:
        prompt = DynamicPrompt.from_callable(
            fn,
            name_override=name,
            description_override=description,
            template_override=template,
        )
        self._prompt_registry.register(name, prompt, replace=replace)

    except Exception as exc:
        msg = f"Failed to register dynamic prompt {name!r}: {exc}"
        raise exceptions.LLMLingError(msg) from exc

register_file_prompt

register_file_prompt(
    name: str,
    path: JoinablePathLike,
    *,
    description: str,
    output_format: Literal["text", "markdown", "jinja2"] = "text",
    watch: bool = False,
    replace: bool = False
) -> None

Register a file-based prompt.

Parameters:

Name Type Description Default
name str

Name to register under

required
path JoinablePathLike

Path to the prompt file

required
description str

Human-readable description

required
output_format Literal['text', 'markdown', 'jinja2']

Format of the file content

'text'
watch bool

Whether to watch file for changes

False
replace bool

Whether to replace existing prompt

False
Example

runtime.register_file_prompt( ... "analyze", ... "prompts/analysis.md", ... description="Code analysis prompt", ... format="markdown" ... )

Source code in src/llmling/config/runtime.py
def register_file_prompt(
    self,
    name: str,
    path: JoinablePathLike,
    *,
    description: str,
    output_format: Literal["text", "markdown", "jinja2"] = "text",
    watch: bool = False,
    replace: bool = False,
) -> None:
    """Register a file-based prompt.

    Args:
        name: Name to register under
        path: Path to the prompt file
        description: Human-readable description
        output_format: Format of the file content
        watch: Whether to watch file for changes
        replace: Whether to replace existing prompt

    Example:
        >>> runtime.register_file_prompt(
        ...     "analyze",
        ...     "prompts/analysis.md",
        ...     description="Code analysis prompt",
        ...     format="markdown"
        ... )
    """
    from upathtools import to_upath

    try:
        if not to_upath(path).exists():
            msg = f"Prompt file not found: {path}"
            raise FileNotFoundError(msg)  # noqa: TRY301

        prompt = FilePrompt(
            name=name,
            path=upath.UPath(path),
            description=description,
            format=output_format,
            watch=watch,
        )
        self._prompt_registry.register(name, prompt, replace=replace)

    except Exception as exc:
        msg = f"Failed to register file prompt {name!r}: {exc}"
        raise exceptions.LLMLingError(msg) from exc

register_prompt

register_prompt(name: str, prompt: BasePrompt, *, replace: bool = False) -> None

Register a pre-configured prompt.

Note

The specialized registration methods should be preferred: - register_dynamic_prompt() for function-based prompts - register_static_prompt() for message-based prompts - register_file_prompt() for file-based prompts

This method is provided for advanced use cases where you need to register an already configured prompt instance.

Parameters:

Name Type Description Default
name str

Name to register under

required
prompt BasePrompt

Configured prompt instance

required
replace bool

Whether to replace existing prompt

False
Source code in src/llmling/config/runtime.py
def register_prompt(
    self,
    name: str,
    prompt: BasePrompt,
    *,
    replace: bool = False,
) -> None:
    """Register a pre-configured prompt.

    Note:
        The specialized registration methods should be preferred:
        - register_dynamic_prompt() for function-based prompts
        - register_static_prompt() for message-based prompts
        - register_file_prompt() for file-based prompts

    This method is provided for advanced use cases where you need
    to register an already configured prompt instance.

    Args:
        name: Name to register under
        prompt: Configured prompt instance
        replace: Whether to replace existing prompt
    """
    if isinstance(prompt, dict):
        if "type" not in prompt:
            msg = "Missing prompt type in configuration"
            raise exceptions.ConfigError(msg)
        from llmling.prompts.models import DynamicPrompt, FilePrompt, StaticPrompt

        match prompt["type"]:
            case "text":
                prompt_obj: BasePrompt = StaticPrompt.model_validate(prompt)
            case "function":
                prompt_obj = DynamicPrompt.model_validate(prompt)
            case "file":
                prompt_obj = FilePrompt.model_validate(prompt)
            case _:
                msg = f"Unknown prompt type: {prompt['type']}"
                raise exceptions.ConfigError(msg)
    else:
        prompt_obj = prompt

    self._prompt_registry.register(name, prompt_obj, replace=replace)

register_resource

register_resource(name: str, resource: BaseResource, *, replace: bool = False) -> None

Register a new resource.

Parameters:

Name Type Description Default
name str

Name for the resource

required
resource BaseResource

Resource to register

required
replace bool

Whether to replace existing resource

False

Raises:

Type Description
ResourceError

If name exists and replace=False

Source code in src/llmling/config/runtime.py
def register_resource(
    self,
    name: str,
    resource: BaseResource,
    *,
    replace: bool = False,
) -> None:
    """Register a new resource.

    Args:
        name: Name for the resource
        resource: Resource to register
        replace: Whether to replace existing resource

    Raises:
        ResourceError: If name exists and replace=False
    """
    self._resource_registry.register(name, resource, replace=replace)

register_resource_by_loader async

register_resource_by_loader(
    loader_type: str, name: str, *, description: str = "", **params: Any
) -> BaseResource

Register a resource using a loader type.

Provides a parameter-based interface for registering resources without requiring resource objects.

Parameters:

Name Type Description Default
loader_type str

Type of loader to use ("path", "text", "cli", etc.)

required
name str

Name for the resource

required
description str

Optional description

''
**params Any

Loader-specific parameters

{}
Example

await runtime.register_resource_by_loader( "path", "readme", description="Project readme", path="README.md" )

await runtime.register_resource_by_loader( "text", "greeting", content="Hello, world!" )

Source code in src/llmling/config/runtime.py
async def register_resource_by_loader(
    self,
    loader_type: str,
    name: str,
    *,
    description: str = "",
    **params: Any,
) -> BaseResource:
    """Register a resource using a loader type.

    Provides a parameter-based interface for registering resources
    without requiring resource objects.

    Args:
        loader_type: Type of loader to use ("path", "text", "cli", etc.)
        name: Name for the resource
        description: Optional description
        **params: Loader-specific parameters

    Example:
        await runtime.register_resource_by_loader(
            "path",
            "readme",
            description="Project readme",
            path="README.md"
        )

        await runtime.register_resource_by_loader(
            "text",
            "greeting",
            content="Hello, world!"
        )
    """
    try:
        # Get loader class from registry
        loader_cls = self._loader_registry[loader_type]

        # Get the resource class from the loader
        resource_class = loader_cls.context_class

        # Create resource instance with just the essential fields
        resource = resource_class(description=description, **params)
        self._resource_registry.register(name, resource)
    except KeyError as exc:
        msg = f"Unknown loader type: {loader_type}"
        raise exceptions.ResourceError(msg) from exc
    except Exception as exc:
        msg = f"Failed to create resource: {exc}"
        raise exceptions.ResourceError(msg) from exc
    else:
        return resource

register_static_prompt

register_static_prompt(
    name: str, content: str, description: str | None = None, *, replace: bool = False
) -> None

Register a static prompt with text content.

A static prompt is a simple text template that can be used as-is or with Python's string formatting (using {placeholder} syntax).

Parameters:

Name Type Description Default
name str

Name to register under

required
content str

Prompt text content

required
description str | None

Optional description of what the prompt does

None
replace bool

Whether to replace existing prompt

False
Example

runtime.register_static_prompt( ... "summarize", ... "Please summarize the following text in 3 bullet points:\n{text}", ... description="Create a bullet-point summary", ... ) runtime.register_static_prompt( ... "greet", ... "Hello {name}! Welcome to {company}.", ... description="Simple greeting template", ... )

Raises:

Type Description
LLMLingError

If registration fails

Source code in src/llmling/config/runtime.py
def register_static_prompt(
    self,
    name: str,
    content: str,
    description: str | None = None,
    *,
    replace: bool = False,
) -> None:
    r"""Register a static prompt with text content.

    A static prompt is a simple text template that can be used as-is or with
    Python's string formatting (using {placeholder} syntax).

    Args:
        name: Name to register under
        content: Prompt text content
        description: Optional description of what the prompt does
        replace: Whether to replace existing prompt

    Example:
        >>> runtime.register_static_prompt(
        ...     "summarize",
        ...     "Please summarize the following text in 3 bullet points:\\n{text}",
        ...     description="Create a bullet-point summary",
        ... )
        >>> runtime.register_static_prompt(
        ...     "greet",
        ...     "Hello {name}! Welcome to {company}.",
        ...     description="Simple greeting template",
        ... )

    Raises:
        LLMLingError: If registration fails
    """
    try:
        # Create standard user message from content
        messages = [PromptMessage(role="user", content=content)]

        # Use content's first line as description if none provided
        if not description:
            first_line = content.split("\n", 1)[0]
            description = (
                first_line[:100] + "..." if len(first_line) > 100 else first_line  # noqa: PLR2004
            )

        prompt = StaticPrompt(name=name, description=description, messages=messages)
        self._prompt_registry.register(name, prompt, replace=replace)

    except Exception as exc:
        msg = f"Failed to register static prompt {name!r}: {exc}"
        raise exceptions.LLMLingError(msg) from exc

register_tool async

register_tool(
    function: str | Callable[..., Any],
    name: str | None = None,
    description: str | None = None,
    *,
    auto_install: bool = False
) -> str

Register a new tool from a function or import path.

Parameters:

Name Type Description Default
function str | Callable[..., Any]

Function to register (callable or import path)

required
name str | None

Optional name override (uses function name if None)

None
description str | None

Optional description override (uses docstring if None)

None
auto_install bool

Whether to attempt installing missing package

False

Returns:

Type Description
str

Message confirming the registration

Raises:

Type Description
ToolError

If registration fails

Example

await runtime.register_tool("webbrowser.open", "open_url") await runtime.register_tool(my_function)

Source code in src/llmling/config/runtime.py
async def register_tool(
    self,
    function: str | Callable[..., Any],
    name: str | None = None,
    description: str | None = None,
    *,
    auto_install: bool = False,
) -> str:
    """Register a new tool from a function or import path.

    Args:
        function: Function to register (callable or import path)
        name: Optional name override (uses function name if None)
        description: Optional description override (uses docstring if None)
        auto_install: Whether to attempt installing missing package

    Returns:
        Message confirming the registration

    Raises:
        ToolError: If registration fails

    Example:
        >>> await runtime.register_tool("webbrowser.open", "open_url")
        >>> await runtime.register_tool(my_function)
    """
    try:
        if auto_install and isinstance(function, str):
            # Try to import root module, install if missing
            package = function.split(".")[0]
            try:
                importlib.import_module(package)
            except ImportError:
                logger.info("Attempting to install package: %s", package)
                await self.install_package(package)

        tool = LLMCallableTool.from_callable(
            function, name_override=name, description_override=description
        )
        self._tool_registry.register(name or tool.name, tool)
        source = (
            function
            if isinstance(function, str)
            else getattr(function, "__name__", str(function))
        )
    except Exception as exc:
        msg = f"Failed to register tool: {exc}"
        raise ToolError(msg) from exc
    else:
        return f"Successfully registered tool: {tool.name} from {source}"

render_prompt async

render_prompt(name: str, arguments: dict[str, Any] | None = None) -> Sequence[PromptMessage]

Format a prompt with arguments.

Parameters:

Name Type Description Default
name str

Name of the prompt

required
arguments dict[str, Any] | None

Optional arguments for formatting

None

Returns:

Type Description
Sequence[PromptMessage]

List of formatted messages

Raises:

Type Description
LLMLingError

If prompt not found or formatting fails

Source code in src/llmling/config/runtime.py
async def render_prompt(
    self,
    name: str,
    arguments: dict[str, Any] | None = None,
) -> Sequence[PromptMessage]:
    """Format a prompt with arguments.

    Args:
        name: Name of the prompt
        arguments: Optional arguments for formatting

    Returns:
        List of formatted messages

    Raises:
        LLMLingError: If prompt not found or formatting fails
    """
    try:
        prompt = self._prompt_registry[name]
        return await prompt.format(arguments)
    except KeyError as exc:
        msg = f"Prompt not found: {name}"
        raise exceptions.LLMLingError(msg) from exc
    except Exception as exc:
        msg = f"Failed to format prompt {name}: {exc}"
        raise exceptions.LLMLingError(msg) from exc

resolve_resource_uri async

resolve_resource_uri(uri_or_name: str) -> tuple[str, BaseResource]

Resolve a resource identifier to a proper URI and resource.

Parameters:

Name Type Description Default
uri_or_name str

Can be: - Resource name: "test.txt" - Full URI: "file:///test.txt" - Local path: "/path/to/file.txt"

required

Returns:

Type Description
tuple[str, BaseResource]

Tuple of (resolved URI, resource object)

Raises:

Type Description
ResourceError

If resolution fails

Source code in src/llmling/config/runtime.py
async def resolve_resource_uri(self, uri_or_name: str) -> tuple[str, BaseResource]:
    """Resolve a resource identifier to a proper URI and resource.

    Args:
        uri_or_name: Can be:
            - Resource name: "test.txt"
            - Full URI: "file:///test.txt"
            - Local path: "/path/to/file.txt"

    Returns:
        Tuple of (resolved URI, resource object)

    Raises:
        ResourceError: If resolution fails
    """
    logger.debug("Resolving resource identifier: %s", uri_or_name)

    # 1. If it's already a URI, use directly
    if "://" in uri_or_name:
        logger.debug("Using direct URI")
        loader = self._loader_registry.find_loader_for_uri(uri_or_name)
        name = loader.get_name_from_uri(uri_or_name)
        if name in self._resource_registry:
            return uri_or_name, self._resource_registry[name]
        # Create temporary resource for the URI
        resource: BaseResource = PathResource(path=uri_or_name)  # pyright: ignore
        return uri_or_name, resource

    # 2. Try as resource name
    try:
        logger.debug("Trying as resource name")
        resource = self._resource_registry[uri_or_name]
        loader = self._loader_registry.get_loader(resource)
        loader = loader.create(resource, uri_or_name)  # Create instance
        uri = loader.create_uri(name=uri_or_name)
    except KeyError:
        pass
    else:
        return uri, resource

    # 3. If it looks like a path, try as file
    if "/" in uri_or_name or "\\" in uri_or_name or "." in uri_or_name:
        try:
            logger.debug("Trying as file path")
            resource = PathResource(path=uri_or_name)  # pyright: ignore
            loader = PathResourceLoader.create(resource, uri_or_name)
            uri = loader.create_uri(name=uri_or_name)
        except Exception as exc:  # noqa: BLE001
            logger.debug("Failed to create file URI: %s", exc)
        else:
            return uri, resource
    msg = f"Could not resolve resource {uri_or_name!r}. Expected resource name or path."
    raise exceptions.ResourceError(msg)

shutdown async

shutdown() -> None

Shut down all runtime components.

Source code in src/llmling/config/runtime.py
async def shutdown(self) -> None:
    """Shut down all runtime components."""
    await self._prompt_registry.shutdown()
    await self._resource_registry.shutdown()
    await self._tool_registry.shutdown()
    await self._processor_registry.shutdown()

startup async

startup() -> None

Start all runtime components.

Source code in src/llmling/config/runtime.py
async def startup(self) -> None:
    """Start all runtime components."""
    await self._processor_registry.startup()
    await self._tool_registry.startup()
    await self._resource_registry.startup()
    await self._prompt_registry.startup()

StaticPrompt

Bases: BasePrompt

Static prompt defined by message list.

Source code in src/llmling/prompts/models.py
class StaticPrompt(BasePrompt):
    """Static prompt defined by message list."""

    messages: list[PromptMessage]
    """List of messages that make up this prompt."""

    type: Literal["text"] = Field("text", init=False)
    """Discriminator field identifying this as a static text prompt."""

    model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)

    def to_fastmcp_prompt(self) -> FastMCPPrompt:
        params = [
            FastMCPArgument(name=p.name, description=p.description, required=p.required)
            for p in self.arguments
        ]
        return FastMCPPrompt(
            name=self.name or "",
            title=self.title,
            description=self.description,
            arguments=params,
            icons=None,
            tags=set(),
        )

    async def format(self, arguments: dict[str, Any] | None = None) -> list[PromptMessage]:
        """Format static prompt messages with arguments."""
        args = arguments or {}
        self.validate_arguments(args)

        # Add default values for optional arguments
        for arg in self.arguments:
            if arg.name not in args and not arg.required:
                args[arg.name] = arg.default if arg.default is not None else ""

        # Format all messages
        formatted_messages = []
        for msg in self.messages:
            match msg.content:
                case str():
                    content: MessageContent | list[MessageContent] = MessageContent(
                        type="text", content=msg.content.format(**args)
                    )
                case MessageContent() if msg.content.type == "text":
                    msg_content = msg.content.content.format(**args)
                    content = MessageContent(type="text", content=msg_content)
                case list():
                    content = [
                        MessageContent(
                            type=item.type,
                            content=item.content.format(**args)
                            if item.type == "text"
                            else item.content,
                            alt_text=item.alt_text,
                        )
                        for item in msg.content
                        if isinstance(item, MessageContent)
                    ]
                case _:
                    content = msg.content

            formatted_messages.append(PromptMessage(role=msg.role, content=content))

        return formatted_messages

messages instance-attribute

messages: list[PromptMessage]

List of messages that make up this prompt.

type class-attribute instance-attribute

type: Literal['text'] = Field('text', init=False)

Discriminator field identifying this as a static text prompt.

format async

format(arguments: dict[str, Any] | None = None) -> list[PromptMessage]

Format static prompt messages with arguments.

Source code in src/llmling/prompts/models.py
async def format(self, arguments: dict[str, Any] | None = None) -> list[PromptMessage]:
    """Format static prompt messages with arguments."""
    args = arguments or {}
    self.validate_arguments(args)

    # Add default values for optional arguments
    for arg in self.arguments:
        if arg.name not in args and not arg.required:
            args[arg.name] = arg.default if arg.default is not None else ""

    # Format all messages
    formatted_messages = []
    for msg in self.messages:
        match msg.content:
            case str():
                content: MessageContent | list[MessageContent] = MessageContent(
                    type="text", content=msg.content.format(**args)
                )
            case MessageContent() if msg.content.type == "text":
                msg_content = msg.content.content.format(**args)
                content = MessageContent(type="text", content=msg_content)
            case list():
                content = [
                    MessageContent(
                        type=item.type,
                        content=item.content.format(**args)
                        if item.type == "text"
                        else item.content,
                        alt_text=item.alt_text,
                    )
                    for item in msg.content
                    if isinstance(item, MessageContent)
                ]
            case _:
                content = msg.content

        formatted_messages.append(PromptMessage(role=msg.role, content=content))

    return formatted_messages

ToolError

Bases: LLMLingError

Base exception for tool-related errors.

Source code in src/llmling/tools/exceptions.py
class ToolError(LLMLingError):
    """Base exception for tool-related errors."""