Skip to content

Config

Base classes

Name Children Inherits
ConfigModel
llmling.config.base
Base class for all LLMling configuration models.

⋔ Inheritance diagram

graph TD
  2020472667["models.Config"]
  2455074328["base.ConfigModel"]
  330168112["schema.Schema"]
  3879467795["main.BaseModel"]
  2751680898["builtins.object"]
  2455074328 --> 2020472667
  330168112 --> 2455074328
  3879467795 --> 330168112
  2751680898 --> 3879467795

🛈 DocStrings

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

:fa-brands-github: Show source on GitHub