Skip to content

config

Class info

Re-exported classes

Class Module Description
CallableResource llmling.config.models Resource from executing a Python callable.
Config llmling.config.models Root configuration model.
ConfigManager llmling.config.manager Manages configuration state and lifecycle.
GlobalSettings llmling.config.models Global settings that apply to all components.
SourceResource llmling.config.models Resource from Python source code.

🛈 DocStrings

Configuration management for LLMling.

CallableResource

Bases: BaseResource

Resource from executing a Python callable.

Source code in src/llmling/config/models.py
class CallableResource(BaseResource):
    """Resource from executing a Python callable."""

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

    import_path: str
    """Dotted import path to the callable to execute."""

    keyword_args: dict[str, Any] = Field(default_factory=dict)
    """Keyword arguments to pass to the callable."""

    @model_validator(mode="after")
    def validate_import_path(self) -> CallableResource:
        """Validate that the import path is properly formatted."""
        if not all(part.isidentifier() for part in self.import_path.split(".")):
            msg = f"Invalid import path: {self.import_path}"
            raise ValueError(msg)
        return self

    def is_templated(self) -> bool:
        """Callable resources are templated if they take parameters."""
        fn = import_callable(self.import_path)
        sig = inspect.signature(fn, annotation_format=annotationlib.Format.FORWARDREF)
        return bool(sig.parameters)

import_path instance-attribute

import_path: str

Dotted import path to the callable to execute.

keyword_args class-attribute instance-attribute

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

Keyword arguments to pass to the callable.

type class-attribute instance-attribute

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

Discriminator field identifying this as a callable-based resource.

is_templated

is_templated() -> bool

Callable resources are templated if they take parameters.

Source code in src/llmling/config/models.py
def is_templated(self) -> bool:
    """Callable resources are templated if they take parameters."""
    fn = import_callable(self.import_path)
    sig = inspect.signature(fn, annotation_format=annotationlib.Format.FORWARDREF)
    return bool(sig.parameters)

validate_import_path

validate_import_path() -> CallableResource

Validate that the import path is properly formatted.

Source code in src/llmling/config/models.py
@model_validator(mode="after")
def validate_import_path(self) -> CallableResource:
    """Validate that the import path is properly formatted."""
    if not all(part.isidentifier() for part in self.import_path.split(".")):
        msg = f"Invalid import path: {self.import_path}"
        raise ValueError(msg)
    return self

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

ConfigManager

Manages configuration state and lifecycle.

Handles loading, storing and validating configurations. Foundation for future features like watching and overlays.

Source code in src/llmling/config/manager.py
class ConfigManager:
    """Manages configuration state and lifecycle.

    Handles loading, storing and validating configurations.
    Foundation for future features like watching and overlays.
    """

    def __init__(self, config: Config | None = None) -> None:
        """Initialize config manager.

        Args:
            config: Optional initial configuration (backward compatibility)
        """
        super().__init__()
        self._configs: list[Config] = []
        if config is not None:
            self._configs.append(config)

    def save(
        self,
        path: JoinablePathLike,
        *,
        validate: bool = True,
    ) -> None:
        """Save configuration to file.

        Args:
            path: Path to save to
            validate: Whether to validate before saving

        Raises:
            ConfigError: If validation fails
        """
        if validate:
            self.validate_or_raise()
        self.config.save(path)

    def validate_or_raise(self) -> None:
        """Run validations and raise on warnings.

        Raises:
            ConfigError: If any validation warnings are found
        """
        if warnings := self.validate():
            msg = "Configuration validation failed:\n" + "\n".join(warnings)
            raise exceptions.ConfigError(msg)

    @property
    def config(self) -> Config:
        """Get first loaded configuration (backward compatibility).

        Returns:
            The first loaded configuration

        Raises:
            ValueError: If no configurations are loaded
        """
        if not self._configs:
            msg = "No configurations loaded"
            raise ValueError(msg)
        return self._configs[0]

    @classmethod
    def load(
        cls,
        path: JoinablePathLike,
        *,
        validate: bool = True,
        strict: bool = False,
    ) -> ConfigManager:
        """Load configuration from file (backward compatibility).

        This classmethod maintains the existing pattern for backward compatibility.
        For new code, prefer using the instance method add_config() instead.

        Args:
            path: Path to configuration file
            validate: Whether to validate the configuration
            strict: Whether to raise on validation warnings

        Returns:
            Configured manager instance

        Raises:
            ConfigError: If loading fails or validation fails with strict=True
        """
        manager = cls()
        manager.add_config(path, validate=validate, strict=strict)
        return manager

    def add_config(
        self,
        path: JoinablePathLike,
        *,
        validate: bool = True,
        strict: bool = False,
    ) -> Config:
        """Add a new configuration.

        Args:
            path: Path to configuration file
            validate: Whether to validate the configuration
            strict: Whether to raise on validation warnings

        Returns:
            Loaded configuration

        Raises:
            ConfigError: If loading fails or validation fails with strict=True
        """
        config = Config.from_file(path)
        # First add to list so validate() works
        self._configs.append(config)

        if validate:
            try:
                if warnings := self.validate():
                    if strict:
                        msg = "Config validation failed:\n" + "\n".join(warnings)
                        raise exceptions.ConfigError(msg)  # noqa: TRY301
                    logger.warning("Config warnings:\n%s", "\n".join(warnings))
            except Exception:
                # Remove config on validation failure
                self._configs.remove(config)
                raise

        setup_logging(level=config.global_settings.log_level)
        return config

    def validate(self) -> list[str]:
        """Validate configuration.

        Performs various validation checks on the configuration including:
        - Resource reference validation
        - Processor configuration validation
        - Tool configuration validation

        Returns:
            List of validation warnings
        """
        config = self.config
        warnings: list[str] = []
        warnings.extend(self._validate_requirements(config))
        warnings.extend(self._validate_resources(config))
        warnings.extend(self._validate_processors(config))
        warnings.extend(self._validate_tools(config))
        return warnings

    def _validate_requirements(self, config: Config) -> list[str]:
        """Validate requirement specifications."""
        from upath import UPath

        warnings = [
            f"Invalid requirement format: {req}"
            for req in config.global_settings.requirements
            if not REQ_PATTERN.match(req)
        ]

        # Validate pip index URL if specified
        if (index_url := config.global_settings.pip_index_url) and not str(index_url).startswith((
            "http://",
            "https://",
        )):
            warnings.append(f"Invalid pip index URL: {index_url}")

        # Validate extra paths exist
        for path in config.global_settings.extra_paths:
            try:
                path_obj = UPath(path)
                if not path_obj.exists():
                    warnings.append(f"Extra path does not exist: {path}")
            except Exception as exc:  # noqa: BLE001
                warnings.append(f"Invalid extra path {path}: {exc}")

        return warnings

    def _validate_resources(self, config: Config) -> list[str]:
        """Validate resource configuration."""
        warnings: list[str] = []

        # Check resource group references
        warnings.extend(
            f"Resource {resource} in group {group} not found"
            for group, resources in config.resource_groups.items()
            for resource in resources
            if resource not in config.resources
        )

        # Check processor references in resources
        warnings.extend(
            f"Processor {proc.name} in resource {name} not found"
            for name, resource in config.resources.items()
            for proc in resource.processors
            if proc.name not in config.context_processors
        )

        # Resource-specific validation
        for resource in config.resources.values():
            warnings.extend(resource.validate_resource())

        return warnings

    def _validate_processors(self, config: Config) -> list[str]:
        """Validate processor configuration."""
        warnings = []
        for name, processor in config.context_processors.items():
            if not processor.import_path:
                warnings.append(f"Processor {name} missing import_path")
                continue

            # Try to import the module
            try:
                importlib.import_module(processor.import_path.split(".")[0])
            except ImportError:
                path = processor.import_path
                msg = f"Cannot import module for processor {name}: {path}"
                warnings.append(msg)

        return warnings

    def _validate_tools(self, config: Config) -> list[str]:
        """Validate tool configuration."""
        warnings = []

        for name, tool in config.tools.items():
            if not tool.import_path:
                warnings.append(f"Tool {name} missing import_path")
                # Check for duplicate tool names
            warnings.extend(
                f"Tool {name} defined both explicitly and in toolset"
                for toolset_tool in config.toolsets
                if toolset_tool == name
            )

        return warnings

    async def __aenter__(self) -> Self:
        """Enter async context."""
        return self

    async def __aexit__(self, *exc_info: object) -> None:
        """Exit async context."""
        self._configs.clear()

config property

config: Config

Get first loaded configuration (backward compatibility).

Returns:

Type Description
Config

The first loaded configuration

Raises:

Type Description
ValueError

If no configurations are loaded

__aenter__ async

__aenter__() -> Self

Enter async context.

Source code in src/llmling/config/manager.py
async def __aenter__(self) -> Self:
    """Enter async context."""
    return self

__aexit__ async

__aexit__(*exc_info: object) -> None

Exit async context.

Source code in src/llmling/config/manager.py
async def __aexit__(self, *exc_info: object) -> None:
    """Exit async context."""
    self._configs.clear()

__init__

__init__(config: Config | None = None) -> None

Initialize config manager.

Parameters:

Name Type Description Default
config Config | None

Optional initial configuration (backward compatibility)

None
Source code in src/llmling/config/manager.py
def __init__(self, config: Config | None = None) -> None:
    """Initialize config manager.

    Args:
        config: Optional initial configuration (backward compatibility)
    """
    super().__init__()
    self._configs: list[Config] = []
    if config is not None:
        self._configs.append(config)

add_config

add_config(path: JoinablePathLike, *, validate: bool = True, strict: bool = False) -> Config

Add a new configuration.

Parameters:

Name Type Description Default
path JoinablePathLike

Path to configuration file

required
validate bool

Whether to validate the configuration

True
strict bool

Whether to raise on validation warnings

False

Returns:

Type Description
Config

Loaded configuration

Raises:

Type Description
ConfigError

If loading fails or validation fails with strict=True

Source code in src/llmling/config/manager.py
def add_config(
    self,
    path: JoinablePathLike,
    *,
    validate: bool = True,
    strict: bool = False,
) -> Config:
    """Add a new configuration.

    Args:
        path: Path to configuration file
        validate: Whether to validate the configuration
        strict: Whether to raise on validation warnings

    Returns:
        Loaded configuration

    Raises:
        ConfigError: If loading fails or validation fails with strict=True
    """
    config = Config.from_file(path)
    # First add to list so validate() works
    self._configs.append(config)

    if validate:
        try:
            if warnings := self.validate():
                if strict:
                    msg = "Config validation failed:\n" + "\n".join(warnings)
                    raise exceptions.ConfigError(msg)  # noqa: TRY301
                logger.warning("Config warnings:\n%s", "\n".join(warnings))
        except Exception:
            # Remove config on validation failure
            self._configs.remove(config)
            raise

    setup_logging(level=config.global_settings.log_level)
    return config

load classmethod

load(path: JoinablePathLike, *, validate: bool = True, strict: bool = False) -> ConfigManager

Load configuration from file (backward compatibility).

This classmethod maintains the existing pattern for backward compatibility. For new code, prefer using the instance method add_config() instead.

Parameters:

Name Type Description Default
path JoinablePathLike

Path to configuration file

required
validate bool

Whether to validate the configuration

True
strict bool

Whether to raise on validation warnings

False

Returns:

Type Description
ConfigManager

Configured manager instance

Raises:

Type Description
ConfigError

If loading fails or validation fails with strict=True

Source code in src/llmling/config/manager.py
@classmethod
def load(
    cls,
    path: JoinablePathLike,
    *,
    validate: bool = True,
    strict: bool = False,
) -> ConfigManager:
    """Load configuration from file (backward compatibility).

    This classmethod maintains the existing pattern for backward compatibility.
    For new code, prefer using the instance method add_config() instead.

    Args:
        path: Path to configuration file
        validate: Whether to validate the configuration
        strict: Whether to raise on validation warnings

    Returns:
        Configured manager instance

    Raises:
        ConfigError: If loading fails or validation fails with strict=True
    """
    manager = cls()
    manager.add_config(path, validate=validate, strict=strict)
    return manager

save

save(path: JoinablePathLike, *, validate: bool = True) -> None

Save configuration to file.

Parameters:

Name Type Description Default
path JoinablePathLike

Path to save to

required
validate bool

Whether to validate before saving

True

Raises:

Type Description
ConfigError

If validation fails

Source code in src/llmling/config/manager.py
def save(
    self,
    path: JoinablePathLike,
    *,
    validate: bool = True,
) -> None:
    """Save configuration to file.

    Args:
        path: Path to save to
        validate: Whether to validate before saving

    Raises:
        ConfigError: If validation fails
    """
    if validate:
        self.validate_or_raise()
    self.config.save(path)

validate

validate() -> list[str]

Validate configuration.

Performs various validation checks on the configuration including: - Resource reference validation - Processor configuration validation - Tool configuration validation

Returns:

Type Description
list[str]

List of validation warnings

Source code in src/llmling/config/manager.py
def validate(self) -> list[str]:
    """Validate configuration.

    Performs various validation checks on the configuration including:
    - Resource reference validation
    - Processor configuration validation
    - Tool configuration validation

    Returns:
        List of validation warnings
    """
    config = self.config
    warnings: list[str] = []
    warnings.extend(self._validate_requirements(config))
    warnings.extend(self._validate_resources(config))
    warnings.extend(self._validate_processors(config))
    warnings.extend(self._validate_tools(config))
    return warnings

validate_or_raise

validate_or_raise() -> None

Run validations and raise on warnings.

Raises:

Type Description
ConfigError

If any validation warnings are found

Source code in src/llmling/config/manager.py
def validate_or_raise(self) -> None:
    """Run validations and raise on warnings.

    Raises:
        ConfigError: If any validation warnings are found
    """
    if warnings := self.validate():
        msg = "Configuration validation failed:\n" + "\n".join(warnings)
        raise exceptions.ConfigError(msg)

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

SourceResource

Bases: BaseResource

Resource from Python source code.

Source code in src/llmling/config/models.py
class SourceResource(BaseResource):
    """Resource from Python source code."""

    type: Literal["source"] = Field(default="source", init=False)
    """Discriminator field identifying this as a source code resource."""

    import_path: str
    """Dotted import path to the Python module or object."""

    recursive: bool = False
    """Whether to include submodules recursively."""

    include_tests: bool = False
    """Whether to include test files and directories."""

    @model_validator(mode="after")
    def validate_import_path(self) -> SourceResource:
        """Validate that the import path is properly formatted."""
        if not all(part.isidentifier() for part in self.import_path.split(".")):
            msg = f"Invalid import path: {self.import_path}"
            raise ValueError(msg)
        return self

import_path instance-attribute

import_path: str

Dotted import path to the Python module or object.

include_tests class-attribute instance-attribute

include_tests: bool = False

Whether to include test files and directories.

recursive class-attribute instance-attribute

recursive: bool = False

Whether to include submodules recursively.

type class-attribute instance-attribute

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

Discriminator field identifying this as a source code resource.

validate_import_path

validate_import_path() -> SourceResource

Validate that the import path is properly formatted.

Source code in src/llmling/config/models.py
@model_validator(mode="after")
def validate_import_path(self) -> SourceResource:
    """Validate that the import path is properly formatted."""
    if not all(part.isidentifier() for part in self.import_path.split(".")):
        msg = f"Invalid import path: {self.import_path}"
        raise ValueError(msg)
    return self