"""Model with service configuration.""" # pylint: disable=too-many-lines import os import re from enum import StrEnum from functools import cached_property from pathlib import Path from re import Pattern from string import Formatter from typing import Annotated, Any, Literal, Optional, Self import jsonpath_ng import yaml from jsonpath_ng.exceptions import JSONPathError from pydantic import ( AnyHttpUrl, BaseModel, ConfigDict, Field, FilePath, NonNegativeInt, PositiveInt, PrivateAttr, SecretStr, StrictBool, StringConstraints, field_validator, model_validator, ) from pydantic.dataclasses import dataclass import constants from log import get_logger from utils import checks from utils.types import CompiledPatterns logger = get_logger(__name__) class ConfigurationBase(BaseModel): """Base class for all configuration models that rejects unknown fields.""" model_config = ConfigDict(extra="forbid") class TLSConfiguration(ConfigurationBase): """TLS configuration. Transport Layer Security (TLS) is a cryptographic protocol designed to provide communications security over a computer network, such as the Internet. The protocol is widely used in applications such as email, instant messaging, and voice over IP, but its use in securing HTTPS remains the most publicly visible. Useful resources: - [FastAPI HTTPS Deployment](https://fastapi.tiangolo.com/deployment/https/) - [Transport Layer Security Overview](https://en.wikipedia.org/wiki/Transport_Layer_Security) - [What is TLS](https://www.ssltrust.eu/learning/ssl/transport-layer-security-tls) """ tls_certificate_path: Optional[FilePath] = Field( None, title="TLS certificate path", description="SSL/TLS certificate file path for HTTPS support.", ) tls_key_path: Optional[FilePath] = Field( None, title="TLS key path", description="SSL/TLS private key file path for HTTPS support.", ) tls_key_password: Optional[FilePath] = Field( None, title="SSL/TLS key password path", description="Path to file containing the password to decrypt the SSL/TLS private key.", ) @model_validator(mode="after") def check_tls_configuration(self) -> Self: """ Perform post-validation checks for the TLS configuration. Currently a no-op that returns the model unchanged. Returns: Self: The validated model instance. """ return self class CORSConfiguration(ConfigurationBase): """CORS configuration. CORS or 'Cross-Origin Resource Sharing' refers to the situations when a frontend running in a browser has JavaScript code that communicates with a backend, and the backend is in a different 'origin' than the frontend. Useful resources: - [CORS in FastAPI](https://fastapi.tiangolo.com/tutorial/cors/) - [Wikipedia article](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) - [What is CORS?](https://dev.to/akshay_chauhan/what-is-cors-explained-8f1) """ # not AnyHttpUrl: we need to support "*" that is not valid URL allow_origins: list[str] = Field( ["*"], title="Allow origins", description="A list of origins allowed for cross-origin requests. An origin " "is the combination of protocol (http, https), domain " "(myapp.com, localhost, localhost.tiangolo.com), and port (80, 443, 8080). " "Use ['*'] to allow all origins.", ) allow_credentials: bool = Field( False, title="Allow credentials", description="Indicate that cookies should be supported for cross-origin requests", ) allow_methods: list[str] = Field( ["*"], title="Allow methods", description="A list of HTTP methods that should be allowed for " "cross-origin requests. You can use ['*'] to allow " "all standard methods.", ) allow_headers: list[str] = Field( ["*"], title="Allow headers", description="A list of HTTP request headers that should be supported " "for cross-origin requests. You can use ['*'] to allow all headers. The " "Accept, Accept-Language, Content-Language and Content-Type headers are " "always allowed for simple CORS requests.", ) @model_validator(mode="after") def check_cors_configuration(self) -> Self: """ Validate CORS settings and enforce that credentials are not allowed. Raises: ValueError: If `allow_credentials` is true while `allow_origins` contains the "*" wildcard. Returns: Self: The validated configuration instance. """ # credentials are not allowed with wildcard origins per CORS/Fetch spec. # see https://fastapi.tiangolo.com/tutorial/cors/ if self.allow_credentials and "*" in self.allow_origins: raise ValueError( "Invalid CORS configuration: allow_credentials can not be set to true when " "allow origins contains the '*' wildcard." "Use explicit origins or disable credentials." ) return self class SQLiteDatabaseConfiguration(ConfigurationBase): """SQLite database configuration.""" db_path: str = Field( ..., title="DB path", description="Path to file where SQLite database is stored", ) class InMemoryCacheConfig(ConfigurationBase): """In-memory cache configuration.""" max_entries: PositiveInt = Field( ..., title="Max entries", description="Maximum number of entries stored in the in-memory cache", ) class PostgreSQLDatabaseConfiguration(ConfigurationBase): """PostgreSQL database configuration. PostgreSQL database is used by Lightspeed Core Stack service for storing information about conversation IDs. It can also be leveraged to store conversation history and information about quota usage. Useful resources: - [Psycopg: connection classes](https://www.psycopg.org/psycopg3/docs/api/connections.html) - [PostgreSQL connection strings](https://www.connectionstrings.com/postgresql/) - [How to Use PostgreSQL in Python](https://www.freecodecamp.org/news/postgresql-in-python/) """ host: str = Field( "localhost", title="Hostname", description="Database server host or socket directory", ) port: PositiveInt = Field( 5432, title="Port", description="Database server port", ) db: str = Field( ..., title="Database name", description="Database name to connect to", ) user: str = Field( ..., title="User name", description="Database user name used to authenticate", ) password: SecretStr = Field( ..., title="Password", description="Password used to authenticate", ) namespace: Annotated[ Optional[str], StringConstraints(pattern=r"^[A-Za-z_][A-Za-z0-9_]*$") ] = Field( "public", title="Name space", description="Database namespace", ) ssl_mode: Literal[ "disable", "allow", "prefer", "require", "verify-ca", "verify-full" ] = Field( default=constants.POSTGRES_DEFAULT_SSL_MODE, title="SSL mode", description="SSL mode", ) gss_encmode: Literal["disable", "prefer", "require"] = Field( constants.POSTGRES_DEFAULT_GSS_ENCMODE, title="GSS encmode", description="This option determines whether or with what priority a secure GSS " "TCP/IP connection will be negotiated with the server.", ) ca_cert_path: Optional[FilePath] = Field( None, title="CA certificate path", description="Path to CA certificate", ) @model_validator(mode="after") def check_postgres_configuration(self) -> Self: """ Validate PostgreSQL configuration constraints. Ensures the configured port is within the valid TCP port range. Returns: self: The validated configuration instance. Raises: ValueError: If `port` is greater than 65535. """ if self.port > 65535: raise ValueError("Port value should be less than 65536") return self class DatabaseConfiguration(ConfigurationBase): """Database configuration.""" sqlite: Optional[SQLiteDatabaseConfiguration] = Field( None, title="SQLite configuration", description="SQLite database configuration", ) postgres: Optional[PostgreSQLDatabaseConfiguration] = Field( None, title="PostgreSQL configuration", description="PostgreSQL database configuration", ) @model_validator(mode="after") def check_database_configuration(self) -> Self: """ Ensure exactly one database backend is configured, defaulting to a temporary SQLite one. If neither `sqlite` nor `postgres` is set, assigns a default SQLite configuration using the file path "/tmp/lightspeed-stack.db". If both backends are configured, raises a `ValueError`. Returns: self: The configuration instance with exactly one database backend set. """ total_configured_dbs = sum([self.sqlite is not None, self.postgres is not None]) if total_configured_dbs == 0: # Default to SQLite in a (hopefully) tmpfs if no database configuration is provided. # This is good for backwards compatibility for deployments that do not mind having # no persistent database. sqlite_file_name = "/tmp/lightspeed-stack.db" self.sqlite = SQLiteDatabaseConfiguration(db_path=sqlite_file_name) elif total_configured_dbs > 1: raise ValueError("Only one database configuration can be provided") return self @property def db_type(self) -> Literal["sqlite", "postgres"]: """ Determine which database backend is configured. Returns: The string "sqlite" if a SQLite configuration is present, "postgres" if a PostgreSQL configuration is present. Raises: ValueError: If neither SQLite nor PostgreSQL configuration is set. """ if self.sqlite is not None: return "sqlite" if self.postgres is not None: return "postgres" raise ValueError("No database configuration found") @property def config(self) -> SQLiteDatabaseConfiguration | PostgreSQLDatabaseConfiguration: """ Get the active database backend configuration. Returns: SQLiteDatabaseConfiguration or PostgreSQLDatabaseConfiguration: The configured SQLite configuration if `sqlite` is set, otherwise the configured PostgreSQL configuration if `postgres` is set. Raises: ValueError: If neither `sqlite` nor `postgres` is configured. """ if self.sqlite is not None: return self.sqlite if self.postgres is not None: return self.postgres raise ValueError("No database configuration found") class ServiceConfiguration(ConfigurationBase): """Service configuration. Lightspeed Core Stack is a REST API service that accepts requests on a specified hostname and port. It is also possible to enable authentication and specify the number of Uvicorn workers. When more workers are specified, the service can handle requests concurrently. """ host: str = Field( "localhost", title="Host", description="Service hostname", ) port: PositiveInt = Field( 8080, title="Port", description="Service port", ) base_url: Optional[str] = Field( None, title="Base URL", description="Externally reachable base URL for the service; needed for A2A support.", ) auth_enabled: bool = Field( False, title="Authentication enabled", description="Enables the authentication subsystem", ) workers: PositiveInt = Field( 1, title="Number of workers", description="Number of Uvicorn worker processes to start", ) max_concurrent_file_uploads: PositiveInt = Field( 5, title="Maximum concurrent file uploads", description="Maximum number of file uploads (POST /v1/files) processed " "concurrently per worker. Each in-flight upload can hold up to the " "configured maximum file size in memory, so this bounds worst-case " "memory usage from concurrent uploads. Additional uploads are " "rejected with 429 until a slot frees up.", ) max_concurrent_vector_store_attaches: PositiveInt = Field( 5, title="Maximum concurrent vector store file attachments", description="Maximum number of vector store file attachments " "(POST /v1/vector-stores/{id}/files) processed concurrently per " "worker. Each in-flight attachment re-reads and chunks the source " "file, so this bounds worst-case memory usage independently of " "max_concurrent_file_uploads. Additional attachments are rejected " "with 429 until a slot frees up.", ) delete_file_after_vector_store_attach: bool = Field( False, title="Delete file after vector store attach", description="When true, deletes a file (POST /v1/files) once it has " "been successfully attached to a vector store, since the vector " "store keeps its own chunked/embedded copy of the content. " "Defaults to false to match the OpenAI Files API, where a file " "remains reusable across multiple vector stores until the caller " "explicitly deletes it - enabling this makes attached files " "single-use: re-attaching the same file_id to another vector store " "will fail once it has been deleted.", ) color_log: bool = Field( True, title="Color log", description="Enables colorized logging", ) access_log: bool = Field( True, title="Access log", description="Enables logging of all access information", ) tls_config: TLSConfiguration = Field( default_factory=lambda: TLSConfiguration( tls_certificate_path=None, tls_key_path=None, tls_key_password=None ), title="TLS configuration", description="Transport Layer Security configuration for HTTPS support", ) root_path: str = Field( "", title="Root path", description="ASGI root path for serving behind a reverse proxy on a subpath", ) @field_validator("root_path") @classmethod def validate_root_path(cls, value: str) -> str: """Validate root_path format. Ensures the root path is either empty or starts with a leading slash and does not end with a trailing slash. Parameters: ---------- value: The root path value to validate. Returns: ------- The validated root path value. Raises: ------ ValueError: If root_path is missing a leading slash or has a trailing slash. """ if value and not value.startswith("/"): raise ValueError("root_path must start with '/'") if value.endswith("/"): raise ValueError("root_path must not end with '/'") return value cors: CORSConfiguration = Field( default_factory=lambda: CORSConfiguration( allow_origins=["*"], allow_credentials=False, allow_methods=["*"], allow_headers=["*"], ), title="CORS configuration", description="Cross-Origin Resource Sharing configuration for cross-domain requests", ) @model_validator(mode="after") def check_service_configuration(self) -> Self: """ Validate service configuration and enforce allowed port range. Raises: ValueError: If `port` is greater than 65535. Returns: self: The validated model instance. """ if self.port > 65535: raise ValueError("Port value should be less than 65536") return self class ApprovalFilter(ConfigurationBase): """Granular approval control for specific MCP tools. Attributes: always: Tool names that always require human approval before execution. never: Tool names that never require approval (pre-approved). """ always: list[str] = Field( default_factory=list, title="Always require approval", description="List of tool names that always require human approval", ) never: list[str] = Field( default_factory=list, title="Never require approval", description="List of tool names that never require approval", ) @model_validator(mode="after") def validate_no_overlap(self) -> Self: """Ensure no tool appears in both always and never lists. Raises: ValueError: If any tool name is present in both lists. Returns: Self: The validated model instance. """ overlap = set(self.always) & set(self.never) if overlap: raise ValueError( f"Tools cannot be in both always and never lists: {overlap}" ) return self class ApprovalsConfiguration(ConfigurationBase): """Configuration for human-in-the-loop approvals. Attributes: approval_timeout_seconds: How long approval requests remain pending before expiring. approval_retention_days: How long to retain decided approvals for audit purposes before cleanup. """ approval_timeout_seconds: PositiveInt = Field( default=300, title="Approval timeout", description="Seconds before pending approval requests expire", ) approval_retention_days: PositiveInt = Field( default=30, title="Retention period", description="Days to retain decided approvals before cleanup", ) class ModelContextProtocolServer(ConfigurationBase): """Model context protocol server configuration. MCP (Model Context Protocol) servers provide tools and capabilities to the AI agents. These are configured by this structure. Only MCP servers defined in the lightspeed-stack.yaml configuration are available to the agents. Tools configured in the OGX run.yaml are not accessible to lightspeed-core agents. Useful resources: - [Model Context Protocol](https://modelcontextprotocol.io/docs/getting-started/intro) - [MCP FAQs](https://modelcontextprotocol.io/faqs) - [Wikipedia article](https://en.wikipedia.org/wiki/Model_Context_Protocol) """ name: str = Field( ..., title="MCP name", description="MCP server name that must be unique", ) provider_id: str = Field( "model-context-protocol", title="Provider ID", description="MCP provider identification", ) url: str = Field( ..., title="MCP server URL", description="URL of the MCP server", ) authorization_headers: dict[str, str] = Field( default_factory=dict, title="Authorization headers", description=( "Headers to send to the MCP server. " "The map contains the header name and the path to a file containing " "the header value (secret). " "There are 3 special cases: " "1. Usage of the kubernetes token in the header. " "To specify this use a string 'kubernetes' instead of the file path. " "2. Usage of the client-provided token in the header. " "To specify this use a string 'client' instead of the file path. " "3. Usage of the oauth token in the header. " "To specify this use a string 'oauth' instead of the file path. " ), ) headers: list[str] = Field( default_factory=list, title="Propagated headers", description=( "List of HTTP header names to automatically forward from the incoming " "request to this MCP server. Headers listed here are extracted from " "the original client request and included when calling the MCP server. " "This is useful when infrastructure components (e.g. API gateways) " "inject headers that MCP servers need, such as x-rh-identity in HCC. " "Header matching is case-insensitive. " "These headers are additive with authorization_headers and MCP-HEADERS." ), ) @field_validator("headers") @classmethod def validate_headers(cls, value: list[str]) -> list[str]: """Validate propagated headers: no empty strings, no case-insensitive duplicates.""" seen: set[str] = set() for header in value: if not header.strip(): msg = "Header names must not be empty" raise ValueError(msg) lower = header.lower() if lower in seen: msg = f"Duplicate header name (case-insensitive): '{header}'" raise ValueError(msg) seen.add(lower) return value require_approval: Literal["always", "never"] | ApprovalFilter = Field( default="never", title="Approval requirement", description=( "When to require human approval for tool invocations. " "'always' requires approval for all tools, 'never' auto-approves, " "or use ApprovalFilter for granular control." ), ) timeout: Optional[PositiveInt] = Field( default=None, title="Request timeout", description=( "Timeout in seconds for requests to the MCP server. If not " "specified, the default timeout from OGX will be used. Note: This " "field is reserved for future use when OGX adds timeout support." ), ) class AllowedModel(ConfigurationBase): """Configuration for an allowed inference model. Accepts string IDs or dictionaries. String IDs populate both `name` and `provider_model_id`; dictionary inputs default `name` to `provider_model_id`. """ name: str = Field( ..., min_length=1, title="Local model name", description="Model name exposed by Lightspeed.", ) provider_model_id: str = Field( ..., min_length=1, title="Backend model id", description="Model identifier expected by the inference provider.", ) model_type: Optional[Literal["llm", "embedding", "rerank"]] = Field( None, title="Model type", description="Optional capability override (llm, embedding, or rerank).", ) metadata: dict[str, Any] = Field( default_factory=dict, title="Model metadata", description="Optional catalog metadata. context_window: the model's " "context window in tokens, used by conversation compaction.", ) @model_validator(mode="before") @classmethod def normalize_input(cls, data: Any) -> Any: """Normalize string and dictionary inputs.""" if isinstance(data, str): return {"name": data, "provider_model_id": data} if isinstance(data, dict): normalized = dict(data) provider_model_id = normalized.get("provider_model_id") if not provider_model_id: raise ValueError("provider_model_id must be provided and non-empty") normalized.setdefault("name", provider_model_id) return normalized return data @field_validator("name", "provider_model_id") @classmethod def strip_nonempty(cls, value: str) -> str: """Strip whitespace and reject empty identifiers.""" stripped = value.strip() if not stripped: raise ValueError("must be non-empty after stripping whitespace") return stripped @field_validator("metadata") @classmethod def validate_metadata(cls, value: dict[str, Any]) -> dict[str, Any]: """Validate metadata values.""" context_window = value.get("context_window") if context_window is not None and ( not isinstance(context_window, int) or isinstance(context_window, bool) or context_window <= 0 ): raise ValueError("metadata.context_window must be a positive int") return value class AzureEntraIdConfiguration(ConfigurationBase): """Microsoft Entra ID authentication attributes for Azure.""" tenant_id: SecretStr = Field( ..., title="Tenant ID", description="Microsoft Entra tenant ID used to request access tokens.", ) client_id: SecretStr = Field( ..., title="Client ID", description="Application client ID used to authenticate with Microsoft Entra ID.", ) client_secret: SecretStr = Field( ..., title="Client secret", description="Application client secret used to authenticate with Microsoft Entra ID.", ) scope: str = Field( "https://cognitiveservices.azure.com/.default", title="Token scope", description="Azure Cognitive Services scope for token requests. " "Override only if using a different Azure service.", ) class OpenAIInferenceProviderConfig(ConfigurationBase): """Connection settings for an OpenAI inference provider.""" api_key: Optional[SecretStr] = Field( default=None, title="API key", description="API key used to authenticate requests to OpenAI.", ) base_url: Optional[str] = Field( default=None, title="Base URL", description="Base URL for OpenAI API requests." ) class AzureInferenceProviderConfig(ConfigurationBase): """Connection settings for an Azure OpenAI inference provider.""" base_url: Optional[str] = Field( default=None, title="Azure OpenAI endpoint", description="Azure OpenAI endpoint URL for inference requests.", ) api_key: Optional[SecretStr] = Field( default=None, title="API key", description="API key used to authenticate requests to Azure OpenAI.", ) api_version: Optional[str] = Field( default=None, title="API version", description="Azure OpenAI API version used for requests.", ) entra_id: Optional[AzureEntraIdConfiguration] = Field( default=None, title="Entra ID", description="Preferred Entra ID auth for this provider. Takes " "precedence over the legacy top-level Azure Entra ID settings.", ) class VertexAIInferenceProviderConfig(ConfigurationBase): """Connection settings for a Vertex AI inference provider. Authentication uses Google Application Default Credentials. Set GOOGLE_APPLICATION_CREDENTIALS in the environment when a credentials file is required; there is no credentials path field in config. """ project: Optional[str] = Field( default=None, title="GCP project", description="Google Cloud project ID used for Vertex AI requests.", ) location: Optional[str] = Field( default=None, title="GCP location", description="Google Cloud location used for Vertex AI requests.", ) class BedrockInferenceProviderConfig(ConfigurationBase): """Connection settings for an AWS Bedrock inference provider.""" region: Optional[str] = Field( default=None, title="AWS region", description="AWS region used for Bedrock requests.", ) profile_name: Optional[str] = Field( default=None, title="AWS profile", description="AWS credentials profile used to authenticate Bedrock requests.", ) api_key: Optional[SecretStr] = Field( default=None, title="Bearer token", description="Optional Bedrock bearer token (alternative to SigV4).", ) class VllmInferenceProviderConfig(ConfigurationBase): """Connection settings for a vLLM inference provider.""" base_url: Optional[str] = Field( default=None, title="Base URL", description="Base URL for the vLLM API." ) api_key: Optional[SecretStr] = Field( default=None, title="API key", description="API key used to authenticate requests to vLLM.", ) class WatsonxInferenceProviderConfig(ConfigurationBase): """Connection settings for a WatsonX inference provider.""" api_key: Optional[SecretStr] = Field( default=None, title="API key", description="API key used to authenticate requests to watsonx.ai.", ) project_id: Optional[str] = Field( default=None, title="Project ID", description="IBM Cloud project ID used for watsonx.ai requests.", ) base_url: Optional[str] = Field( default=None, title="Base URL", description="Base URL for the watsonx.ai API." ) class SentenceTransformersInferenceProviderConfig(ConfigurationBase): """Settings for the local sentence-transformers inference provider.""" device: Optional[str] = Field( default=None, title="Device", description="Device on which to run sentence-transformers models.", ) cache_dir: Optional[str] = Field( default=None, title="Hugging Face cache directory", description="Directory where Hugging Face model files are cached.", ) class InferenceProviderEntryBase(ConfigurationBase): """Shared fields for inference provider entries.""" id: str = Field( ..., title="Provider ID", description="Identifier for this inference provider instance.", ) skip_model_discovery: bool = Field( False, title="Skip model discovery", description="Disable automatic model discovery for this provider.", ) allowed_models: list[AllowedModel] = Field( default_factory=list, title="Allowed models", description="Models explicitly made available through this provider.", ) model_profiles_path: Optional[FilePath] = Field( None, title="Model profiles path", description="Path to the file containing model profiles for this provider.", ) api_key_env: Optional[str] = Field( None, title="API key environment variable", description="Deprecated: prefer config.api_key with ${env.VAR}.", ) extra: Optional[dict[str, object]] = Field( None, title="Extra provider config", description="Deprecated escape hatch for unmodeled provider knobs.", ) @model_validator(mode="before") @classmethod def default_id_from_type(cls, data: Any) -> Any: """Set provider ID from type when omitted.""" if isinstance(data, dict) and data.get("id") is None: normalized = dict(data) normalized["id"] = normalized.get("type", cls.model_fields["type"].default) return normalized return data @field_validator("id") @classmethod def validate_id(cls, value: str) -> str: """Validate the provider ID.""" value = value.strip() if not value or not re.fullmatch(r"[a-z0-9_-]+", value): raise ValueError( "id must contain only lowercase letters, digits, " "underscores, and hyphens" ) return value @model_validator(mode="after") def validate_allowed_models(self) -> Self: """Require unique names; nonempty allow-list when skipping discovery.""" names = [model.name for model in self.allowed_models] if len(names) != len(set(names)): raise ValueError("allowed model names must be unique") if self.skip_model_discovery and not self.allowed_models: raise ValueError( "allowed_models must be non-empty when skip_model_discovery is true" ) return self class OpenAIInferenceProviderEntry(InferenceProviderEntryBase): """OpenAI inference provider.""" type: Literal["openai"] = Field( "openai", title="Provider type", description="OpenAI remote inference provider.", ) config: OpenAIInferenceProviderConfig = Field( default_factory=OpenAIInferenceProviderConfig, title="Connection settings", description="API key and optional base URL.", ) class AzureInferenceProviderEntry(InferenceProviderEntryBase): """Azure OpenAI inference provider.""" type: Literal["azure"] = Field( "azure", title="Provider type", description="Azure OpenAI remote inference provider.", ) config: AzureInferenceProviderConfig = Field( default_factory=AzureInferenceProviderConfig, title="Connection settings", description="Endpoint, API key or Entra ID, and API version.", ) class VertexAIInferenceProviderEntry(InferenceProviderEntryBase): """Vertex AI inference provider.""" type: Literal["vertexai"] = Field( "vertexai", title="Provider type", description="Google Vertex AI remote inference provider.", ) config: VertexAIInferenceProviderConfig = Field( default_factory=VertexAIInferenceProviderConfig, title="Connection settings", description="GCP project and location.", ) class BedrockInferenceProviderEntry(InferenceProviderEntryBase): """AWS Bedrock inference provider.""" type: Literal["bedrock"] = Field( "bedrock", title="Provider type", description="AWS Bedrock remote inference provider.", ) config: BedrockInferenceProviderConfig = Field( default_factory=BedrockInferenceProviderConfig, title="Connection settings", description="AWS region, optional profile, and optional bearer token.", ) class VllmInferenceProviderEntry(InferenceProviderEntryBase): """vLLM inference provider.""" type: Literal["vllm"] = Field( "vllm", title="Provider type", description="vLLM OpenAI-compatible remote inference provider.", ) config: VllmInferenceProviderConfig = Field( default_factory=VllmInferenceProviderConfig, title="Connection settings", description="Base URL and optional API key.", ) class WatsonxInferenceProviderEntry(InferenceProviderEntryBase): """WatsonX inference provider.""" type: Literal["watsonx"] = Field( "watsonx", title="Provider type", description="IBM WatsonX remote inference provider.", ) config: WatsonxInferenceProviderConfig = Field( default_factory=WatsonxInferenceProviderConfig, title="Connection settings", description="API key, project ID, and base URL.", ) class SentenceTransformersInferenceProviderEntry(InferenceProviderEntryBase): """Local sentence-transformers inference provider.""" type: Literal["sentence_transformers"] = Field( "sentence_transformers", title="Provider type", description="Local sentence-transformers embedding and rerank provider.", ) config: SentenceTransformersInferenceProviderConfig = Field( default_factory=SentenceTransformersInferenceProviderConfig, title="Connection settings", description="Optional device and Hugging Face cache directory.", ) @model_validator(mode="after") def require_allowed_models(self) -> Self: """Require explicitly configured models.""" if not self.allowed_models: raise ValueError( "allowed_models must be non-empty for sentence_transformers" ) return self UnifiedInferenceProviderEntry = Annotated[ OpenAIInferenceProviderEntry | AzureInferenceProviderEntry | VertexAIInferenceProviderEntry | BedrockInferenceProviderEntry | VllmInferenceProviderEntry | WatsonxInferenceProviderEntry | SentenceTransformersInferenceProviderEntry, Field(discriminator="type"), ] class UnifiedOgxConfig(ConfigurationBase): """Backend-specific knobs for unified-mode OGX synthesis. Per Decision S5 of the design spike, backend-agnostic high-level sections (inference, ...) live at the configuration root, not here. This block holds only the OGX-specific synthesis controls: which baseline to start from, an optional profile file, and a raw native_override escape hatch. Attributes: baseline: Synthesis starting point. "default" begins from LCORE's built-in baseline (src/data/default_run.yaml) including the conditional OpenAI inference provider. "byo-llm" begins from the same file with that OpenAI row removed. "empty" begins from an empty dict (used by the migration tool for an exact round-trip). Ignored when `profile` is set. profile: Optional path to a user-authored run.yaml-shaped file used as the synthesis baseline. Relative paths resolve against the directory of the loaded lightspeed-stack.yaml. native_override: Raw OGX schema deep-merged last (maps merge recursively, lists and scalars replace). The escape hatch for anything the high-level sections do not express. Note: `registered_resources.models` is a list, so a native_override that sets it replaces — not merges with — any LLM models LCORE auto-registered from `inference.providers[].allowed_models`. """ baseline: Literal["default", "empty", "byo-llm"] = Field( "default", title="Baseline selector", description="Synthesis starting point: 'default' uses LCORE's built-in " "baseline including the conditional OpenAI provider, 'byo-llm' uses " "the same baseline without that OpenAI row, 'empty' starts from {}. " "Ignored when 'profile' is set.", ) profile: Optional[str] = Field( None, title="Profile path", description="Path to a run.yaml-shaped baseline file. Relative paths " "resolve against the directory of the loaded lightspeed-stack.yaml.", ) native_override: dict[str, object] = Field( default_factory=dict, title="Native override", description="Raw OGX schema deep-merged last (maps " "merge recursively; lists and scalars replace). Note: setting " "registered_resources.models here replaces, not merges with, any " "LLM models LCORE auto-registered from " "inference.providers[].allowed_models.", ) class OgxConfiguration(ConfigurationBase): """OGX configuration. OGX is a comprehensive system that provides a uniform set of tools for building, scaling, and deploying generative AI applications, enabling developers to create, integrate, and orchestrate multiple AI services and capabilities into an adaptable setup. Useful resources: - [OGX](https://ogx-ai.github.io/) - [Python OGX client](https://github.com/ogx-ai/ogx-client-python) - [Build AI Applications with OGX](https://ogx-ai.github.io/docs/building_applications) """ url: Optional[AnyHttpUrl] = Field( None, title="OGX URL", description="URL to OGX service; used when library mode is " "disabled. Must be a valid HTTP or HTTPS URL.", ) api_key: Optional[SecretStr] = Field( None, title="API key", description="API key to access OGX service", ) use_as_library_client: Optional[bool] = Field( None, title="Use as library", description="When set to true OGX will be used " "in library mode, not in server mode (default)", ) library_client_config_path: Optional[str] = Field( None, title="OGX configuration path (legacy, deprecated)", description="Path to configuration file used when OGX is run " "in library mode. DEPRECATED legacy two-file setup: logs a " "startup warning since 0.6 and is removed in 0.8 " "— use unified mode instead (the config block below, " "and/or the root-level inference.providers section); " "migrate with lightspeed-stack --migrate-config.", ) timeout: PositiveInt = Field( 180, title="Request timeout", description="Timeout in seconds for requests to OGX service. Default is " "180 seconds (3 minutes) to accommodate long-running RAG queries.", ) max_retries: PositiveInt = Field( constants.DEFAULT_MAX_RETRIES, title="Maximum number of connection attempts before giving up", description="Maximum number of connection attempts before giving up. Used on startup to " "connect to OGX and retrieve its version. Connection attempts are retried with " "a fixed delay to handle the case where OGX is still starting " "up (e.g., when running as a sidecar in the same pod).", ) retry_delay: PositiveInt = Field( constants.DEFAULT_RETRY_DELAY, title="Delay in seconds between retry attempts", description="Delay in seconds between retry attempts. Used on startup to connect to " "OGX and retrieve its version. Connection attempts are retried with a fixed " "delay to handle the case where OGX is still starting up (e.g., " "when running as a sidecar in the same pod).", ) config: Optional["UnifiedOgxConfig"] = Field( None, title="Unified OGX configuration", description="Backend-specific knobs for unified mode, where LCORE synthesizes " "the OGX run.yaml instead of reading an external " "file. Holds the baseline selector, an optional profile " "path, and a raw native_override escape hatch. Backend-agnostic " "high-level sections (e.g. inference.providers) live at the configuration " "root, not here. Mutually exclusive with library_client_config_path; that " "cross-field check lives on the root Configuration model. " "When set in library mode, library_client_config_path is not " "required.", ) @model_validator(mode="after") def check_ogx_model(self) -> Self: """ Validate the OGX configuration and enforce mode-specific requirements. If no URL is provided, requires explicit library-client mode selection. When a legacy `library_client_config_path` is given (and no unified `config` block), it must point to a regular, readable YAML file (checked via checks.file_check). Also normalizes a None `use_as_library_client` to False. This validator does NOT require a run-configuration source in library mode: a config may instead be driven by the root-level `inference.providers` (which this nested model cannot see). The requirement that library mode have *some* run source — and the mutual exclusion between unified synthesis inputs and the legacy path — is therefore enforced on the root Configuration model (`check_unified_vs_legacy`). Returns: Self: The validated OgxConfiguration instance. Raises: ValueError: If no URL is provided and library-client mode is unspecified or disabled. """ if self.url is None: # when URL is not set, it is supposed that OGX should be run in library mode # it means that use_as_library_client attribute must be set to True if self.use_as_library_client is None: raise ValueError( "OGX URL is not specified and library client mode is not specified" ) if self.use_as_library_client is False: raise ValueError( "OGX URL is not specified and library client mode is not enabled" ) # None -> False conversion if self.use_as_library_client is None: self.use_as_library_client = False if self.use_as_library_client: # In library mode OGX runs embedded. A legacy # library_client_config_path (with no unified config block) must # point to a regular readable YAML file. A unified config — driven # by a config block here or by inference.providers at the root — # needs no external file; whether *some* run source exists is # checked on the root Configuration model. if self.library_client_config_path is not None and self.config is None: checks.file_check( Path(self.library_client_config_path), "OGX configuration file", ) return self class SplunkConfiguration(ConfigurationBase): """Splunk HEC (HTTP Event Collector) configuration. Splunk HEC allows sending events directly to Splunk over HTTP/HTTPS. This configuration is used to send telemetry events for inference requests to the corporate Splunk deployment. Useful resources: - [Splunk HEC Docs](https://docs.splunk.com/Documentation/SplunkCloud) - [About HEC](https://docs.splunk.com/Documentation/Splunk/latest/Data) """ enabled: bool = Field( False, title="Enabled", description="Enable or disable Splunk HEC integration.", ) url: Optional[str] = Field( None, title="HEC URL", description="Splunk HEC endpoint URL.", ) token_path: Optional[FilePath] = Field( None, title="Token path", description="Path to file containing the Splunk HEC authentication token.", ) index: Optional[str] = Field( None, title="Index", description="Target Splunk index for events.", ) source: str = Field( "lightspeed-stack", title="Source", description="Event source identifier.", ) timeout: PositiveInt = Field( 5, title="Timeout", description="HTTP timeout in seconds for HEC requests.", ) verify_ssl: bool = Field( True, title="Verify SSL", description="Whether to verify SSL certificates for HEC endpoint.", ) @model_validator(mode="after") def check_splunk_configuration(self) -> Self: """Validate that required fields are set when Splunk is enabled. Returns: Self: The validated configuration instance. Raises: ValueError: If enabled is True but required fields are missing. """ if self.enabled: missing_fields = [] if not self.url: missing_fields.append("url") if not self.token_path: missing_fields.append("token_path") if not self.index: missing_fields.append("index") if missing_fields: raise ValueError( f"Splunk is enabled but required fields are missing: " f"{', '.join(missing_fields)}" ) return self class UserDataCollection(ConfigurationBase): """User data collection configuration.""" feedback_enabled: bool = Field( False, title="Feedback enabled", description="When set to true the user feedback is stored and later sent for analysis.", ) feedback_storage: Optional[str] = Field( None, title="Feedback storage directory", description="Path to directory where feedback will be saved for further processing.", ) transcripts_enabled: bool = Field( False, title="Transcripts enabled", description="When set to true the conversation history is stored and later sent for " "analysis.", ) transcripts_storage: Optional[str] = Field( None, title="Transcripts storage directory", description="Path to directory where conversation history will be saved for further " "processing.", ) @model_validator(mode="after") def check_storage_location_is_set_when_needed(self) -> Self: """ Ensure storage locations are configured and writable when feedback is enabled. If feedback collection is enabled, `feedback_storage` must be provided and refer to a directory that exists or can be created and is writable. If transcript collection is enabled, `transcripts_storage` must be provided and refer to a directory that exists or can be created and is writable. Returns: self: The validated UserDataCollection instance. """ if self.feedback_enabled: if self.feedback_storage is None: raise ValueError( "feedback_storage is required when feedback is enabled" ) checks.directory_check( Path(self.feedback_storage), desc="Check directory to store feedback", must_exists=False, must_be_writable=True, ) if self.transcripts_enabled: if self.transcripts_storage is None: raise ValueError( "transcripts_storage is required when transcripts is enabled" ) checks.directory_check( Path(self.transcripts_storage), desc="Check directory to store transcripts", must_exists=False, must_be_writable=True, ) return self class JsonPathOperator(StrEnum): """Supported operators for JSONPath evaluation. Note: this is not a real model, just an enumeration of all supported JSONPath operators. """ EQUALS = "equals" CONTAINS = "contains" IN = "in" MATCH = "match" class JwtRoleRule(ConfigurationBase): """Rule for extracting roles from JWT claims.""" jsonpath: str = Field( ..., title="JSON path", description="JSONPath expression to evaluate against the JWT payload", ) operator: JsonPathOperator = Field( ..., title="Operator", description="JSON path comparison operator", ) negate: bool = Field( False, title="Negate rule", description="If set to true, the meaning of the rule is negated", ) value: Any = Field( ..., title="Value", description="Value to compare against", ) roles: list[str] = Field( ..., title="List of roles", description="Roles to be assigned if the rule matches", ) @model_validator(mode="after") def check_jsonpath(self) -> Self: """ Validate that the `jsonpath` expression parses as a JSONPath. Returns: self: The same model instance when the JSONPath expression is valid. Raises: ValueError: If the `jsonpath` cannot be parsed; the message includes the offending expression and parser error. """ try: # try to parse the JSONPath jsonpath_ng.parse(self.jsonpath) return self except JSONPathError as e: raise ValueError( f"Invalid JSONPath expression: {self.jsonpath}: {e}" ) from e @model_validator(mode="after") def check_roles(self) -> Self: """ Validate the rule's roles list and enforce required constraints. Performs three checks: ensures at least one role is present, enforces that all roles are unique, and prohibits the wildcard role `"*"`. Returns: self: The same `JwtRoleRule` instance when validation succeeds. """ if not self.roles: raise ValueError("At least one role must be specified in the rule") if len(self.roles) != len(set(self.roles)): raise ValueError("Roles must be unique in the rule") if any(role == "*" for role in self.roles): raise ValueError( "The wildcard '*' role is not allowed in role rules, " "everyone automatically gets this role" ) return self @model_validator(mode="after") def check_regex_pattern(self) -> Self: """ Validate that when the operator is MATCH, the rule is a valid regular expression string. Raises: ValueError: If the operator is MATCH and `value` is not a string or is not a valid regular expression. Returns: Self: The same JwtRoleRule instance. """ if self.operator == JsonPathOperator.MATCH: if not isinstance(self.value, str): raise ValueError( f"MATCH operator requires a string pattern, {type(self.value).__name__}" ) try: re.compile(self.value) except re.error as e: raise ValueError( f"Invalid regex pattern for MATCH operator: {self.value}: {e}" ) from e return self @cached_property def compiled_regex(self) -> Optional[Pattern[str]]: """ Provide a compiled regex when the rule uses the MATCH operator and the value is a string. Returns: Optional[Pattern[str]]: Compiled `re.Pattern` of `value` if `operator` is `JsonPathOperator.MATCH` and `value` is a `str`, `None` otherwise. """ if self.operator == JsonPathOperator.MATCH and isinstance(self.value, str): return re.compile(self.value) return None class Action(StrEnum): """Available actions in the system. Note: this is not a real model, just an enumeration of all action names. """ # Special action to allow unrestricted access to all actions ADMIN = "admin" # List the conversations of other users LIST_OTHERS_CONVERSATIONS = "list_other_conversations" # Read the contents of conversations of other users READ_OTHERS_CONVERSATIONS = "read_other_conversations" # Continue the conversations of other users QUERY_OTHERS_CONVERSATIONS = "query_other_conversations" # Delete the conversations of other users DELETE_OTHERS_CONVERSATIONS = "delete_other_conversations" # Access the query endpoint QUERY = "query" # Access the responses endpoint RESPONSES = "responses" # Access the streaming query endpoint STREAMING_QUERY = "streaming_query" # Access the conversation endpoint GET_CONVERSATION = "get_conversation" # List own conversations LIST_CONVERSATIONS = "list_conversations" # Access the conversation delete endpoint DELETE_CONVERSATION = "delete_conversation" # Access the conversation update endpoint UPDATE_CONVERSATION = "update_conversation" FEEDBACK = "feedback" GET_MODELS = "get_models" GET_TOOLS = "get_tools" GET_SKILLS = "get_skills" GET_SHIELDS = "get_shields" LIST_RAGS = "list_rags" GET_RAG = "get_rag" GET_METRICS = "get_metrics" GET_CONFIG = "get_config" INFO = "info" # Allow overriding model/provider via request MODEL_OVERRIDE = "model_override" # RHEL Lightspeed rlsapi v1 compatibility - stateless inference (no history/RAG) RLSAPI_V1_INFER = "rlsapi_v1_infer" # Dynamic MCP server management REGISTER_MCP_SERVER = "register_mcp_server" LIST_MCP_SERVERS = "list_mcp_servers" DELETE_MCP_SERVER = "delete_mcp_server" # A2A (Agent-to-Agent) protocol actions A2A_AGENT_CARD = "a2a_agent_card" A2A_TASK_EXECUTION = "a2a_task_execution" A2A_MESSAGE = "a2a_message" A2A_JSONRPC = "a2a_jsonrpc" # Vector store management MANAGE_VECTOR_STORES = "manage_vector_stores" READ_VECTOR_STORES = "read_vector_stores" MANAGE_FILES = "manage_files" # OGX stored prompt templates (/v1/prompts) MANAGE_PROMPTS = "manage_prompts" READ_PROMPTS = "read_prompts" # User saved prompts (/v1/saved-prompts) MANAGE_SAVED_PROMPTS = "manage_saved_prompts" class AccessRule(ConfigurationBase): """Rule defining what actions a role can perform.""" role: str = Field( ..., title="Role name", description="Name of the role", ) actions: list[Action] = Field( ..., title="Allowed actions", description="Allowed actions for this role", ) class AuthorizationConfiguration(ConfigurationBase): """Authorization configuration.""" access_rules: list[AccessRule] = Field( default_factory=list, title="Access rules", description="Rules for role-based access control", ) class JwtConfiguration(ConfigurationBase): """JWT (JSON Web Token) configuration. JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted. Useful resources: - [JSON Web Token](https://en.wikipedia.org/wiki/JSON_Web_Token) - [RFC 7519](https://datatracker.ietf.org/doc/html/rfc7519) - [JSON Web Tokens](https://auth0.com/docs/secure/tokens/json-web-tokens) """ user_id_claim: str = Field( constants.DEFAULT_JWT_UID_CLAIM, title="User ID claim", description="JWT claim name that uniquely identifies the user (subject ID).", ) username_claim: str = Field( constants.DEFAULT_JWT_USER_NAME_CLAIM, title="Username claim", description="JWT claim name that provides the human-readable username.", ) role_rules: list[JwtRoleRule] = Field( default_factory=list, title="Role rules", description="Rules for extracting roles from JWT claims", ) class JwkConfiguration(ConfigurationBase): """JWK (JSON Web Key) configuration. A JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data structure that represents a cryptographic key. Useful resources: - [JSON Web Key](https://openid.net/specs/draft-jones-json-web-key-03.html) - [RFC 7517](https://www.rfc-editor.org/rfc/rfc7517) """ url: AnyHttpUrl = Field( ..., title="URL", description="HTTPS URL of the JWK (JSON Web Key) set used to validate JWTs.", ) jwt_configuration: JwtConfiguration = Field( default_factory=lambda: JwtConfiguration( user_id_claim=constants.DEFAULT_JWT_UID_CLAIM, username_claim=constants.DEFAULT_JWT_USER_NAME_CLAIM, ), title="JWT configuration", description="JWT (JSON Web Token) configuration", ) class RHIdentityConfiguration(ConfigurationBase): """Red Hat Identity authentication configuration.""" required_entitlements: Optional[list[str]] = Field( None, title="Required entitlements", description="List of all required entitlements.", ) max_header_size: PositiveInt = Field( default=constants.DEFAULT_RH_IDENTITY_MAX_HEADER_SIZE, title="Maximum header size", description="Maximum allowed size in bytes for the base64-encoded x-rh-identity header. " "Headers exceeding this size are rejected before decoding.", ) class APIKeyTokenConfiguration(ConfigurationBase): """API Key Token configuration.""" # Use SecretStr to prevent accidental exposure in logs or error messages. api_key: SecretStr = Field( description="API key that clients must present to authenticate.", min_length=1, title="API key", json_schema_extra={ "format": "password", "writeOnly": True, "examples": ["some-api-key"], }, ) class TrustedProxyServiceAccount(ConfigurationBase): """A Kubernetes ServiceAccount identity for trusted-proxy allowlist.""" namespace: str = Field( ..., title="Namespace", description="Kubernetes namespace of the ServiceAccount.", ) name: str = Field( ..., title="Name", description="Name of the Kubernetes ServiceAccount.", ) class TrustedProxyConfiguration(ConfigurationBase): """Configuration for trusted-proxy auth module.""" user_header: str = Field( "X-Forwarded-User", title="User identity header", description="HTTP header containing the forwarded user identity.", ) allowed_service_accounts: Optional[list[TrustedProxyServiceAccount]] = Field( None, title="Allowed service accounts", description="Optional allowlist of Kubernetes ServiceAccount identities " "permitted to act as trusted proxies. " "When set to null/omitted, any ServiceAccount with a valid token is accepted. " "When set to a non-empty list, only the listed ServiceAccounts are allowed. " "An empty list behaves the same as null (no restriction).", ) class AuthenticationConfiguration(ConfigurationBase): """Authentication configuration.""" module: str = Field( default=constants.DEFAULT_AUTHENTICATION_MODULE, description="Authentication module used to verify incoming requests.", ) skip_tls_verification: bool = Field( default=False, description="Skip TLS certificate verification for Kubernetes authentication requests.", ) # LCORE-694: Config option to skip authorization for readiness and liveness probe skip_for_health_probes: bool = Field( False, title="Skip authorization for probes", description="Skip authorization for readiness and liveness probes", ) skip_for_metrics: bool = Field( False, title="Skip authorization for metrics", description="Skip authorization for the /metrics endpoint", ) k8s_cluster_api: Optional[AnyHttpUrl] = Field( default=None, description="URL of the Kubernetes API server used for authentication.", ) k8s_ca_cert_path: Optional[FilePath] = Field( default=None, description="Path to the CA certificate used to verify the Kubernetes API server.", ) jwk_config: Optional[JwkConfiguration] = Field( default=None, description="Settings for JWT authentication using JSON Web Keys." ) api_key_config: Optional[APIKeyTokenConfiguration] = Field( default=None, description="Settings for API key token authentication." ) rh_identity_config: Optional[RHIdentityConfiguration] = Field( default=None, description="Settings for Red Hat Identity header authentication." ) trusted_proxy_config: Optional[TrustedProxyConfiguration] = Field( default=None, description="Settings for authentication through a trusted proxy." ) @model_validator(mode="after") def check_authentication_model(self) -> Self: """ Validate authentication configuration and enforce module-specific requirements. Checks that the selected authentication module is supported and that any module-specific configuration (JWK or RH Identity) is present when required. Returns: self: The validated AuthenticationConfiguration instance. Raises: ValueError: If the module is unsupported, or if a required module-specific configuration (jwk_config for JWK token or rh_identity_config for RH Identity) is missing. """ if self.module not in constants.SUPPORTED_AUTHENTICATION_MODULES: supported_modules = ", ".join(constants.SUPPORTED_AUTHENTICATION_MODULES) raise ValueError( f"Unsupported authentication module '{self.module}'. " f"Supported modules: {supported_modules}" ) if self.module == constants.AUTH_MOD_JWK_TOKEN: if self.jwk_config is None: raise ValueError( "JWK configuration must be specified when using JWK token authentication" ) if self.module == constants.AUTH_MOD_RH_IDENTITY: if self.rh_identity_config is None: raise ValueError( "RH Identity configuration must be specified " "when using RH Identity authentication" ) if self.module == constants.AUTH_MOD_APIKEY_TOKEN: if self.api_key_config is None: raise ValueError( "API Key configuration section must be specified " "when using API Key token authentication" ) if self.api_key_config.api_key.get_secret_value() is None: raise ValueError( "api_key parameter must be specified when using API_KEY token authentication" ) if self.module == constants.AUTH_MOD_TRUSTED_PROXY: if self.trusted_proxy_config is None: raise ValueError( "Trusted proxy configuration must be specified " "when using trusted-proxy authentication" ) return self @property def jwk_configuration(self) -> JwkConfiguration: """ Return the active JWK configuration for JWK-token authentication. Raises: ValueError: If the authentication module is not the JWK token module or if the JWK configuration is not set. Returns: JwkConfiguration: The configured JWK settings. """ if self.module != constants.AUTH_MOD_JWK_TOKEN: raise ValueError( "JWK configuration is only available for JWK token authentication module" ) if self.jwk_config is None: raise ValueError("JWK configuration should not be None") return self.jwk_config @property def rh_identity_configuration(self) -> RHIdentityConfiguration: """ Access the RH Identity configuration for RH Identity authentication. Returns: RHIdentityConfiguration: The configured RH Identity configuration object. Raises: ValueError: If the active authentication module is not RH Identity. ValueError: If the RH Identity configuration is missing when the module is RH Identity. """ if self.module != constants.AUTH_MOD_RH_IDENTITY: raise ValueError( "RH Identity configuration is only available for RH Identity authentication module" ) if self.rh_identity_config is None: raise ValueError("RH Identity configuration should not be None") return self.rh_identity_config @property def api_key_configuration(self) -> APIKeyTokenConfiguration: """Return API_KEY configuration if the module is API_KEY token.""" if self.module != constants.AUTH_MOD_APIKEY_TOKEN: raise ValueError( "API Key configuration is only available for API Key token authentication module" ) if self.api_key_config is None: raise ValueError("API Key configuration should not be None") return self.api_key_config @property def trusted_proxy_configuration(self) -> TrustedProxyConfiguration: """Return trusted-proxy configuration if the module is trusted-proxy. Returns: TrustedProxyConfiguration: The configured trusted-proxy settings. Raises: ValueError: If the active authentication module is not trusted-proxy. ValueError: If the trusted-proxy configuration is missing. """ if self.module != constants.AUTH_MOD_TRUSTED_PROXY: raise ValueError( "Trusted proxy configuration is only available " "for trusted-proxy authentication module" ) if self.trusted_proxy_config is None: raise ValueError("Trusted proxy configuration should not be None") return self.trusted_proxy_config @dataclass class CustomProfile: """Custom profile customization for prompts and validation.""" path: str = Field( ..., title="Path to custom profile", description="Path to Python modules containing custom profile.", ) prompts: dict[str, str] = Field( default={}, init=False, title="System prompts", description="Dictionary containing map of system prompts", ) def __post_init__(self) -> None: """Validate and load profile.""" self._validate_and_process() def _validate_and_process(self) -> None: """Validate and load the profile.""" checks.file_check(Path(self.path), "custom profile") profile_module = checks.import_python_module("profile", self.path) if profile_module is not None and checks.is_valid_profile(profile_module): self.prompts = profile_module.PROFILE_CONFIG.get("system_prompts", {}) def get_prompts(self) -> dict[str, str]: """ Get the loaded prompt mappings for the custom profile. Returns: dict[str, str]: Mapping from prompt names to prompt text. """ return self.prompts class Customization(ConfigurationBase): """Service customization.""" profile_path: Optional[str] = Field( default=None, description="Path to the service customization profile." ) disable_query_system_prompt: bool = Field( default=False, description="Reject custom system prompts in query requests." ) disable_shield_ids_override: bool = Field( default=False, description="Reject shield ID overrides in query requests." ) system_prompt_path: Optional[FilePath] = Field( default=None, description="Path to the file containing the service system prompt.", ) system_prompt: Optional[str] = Field( default=None, description="System prompt text configured for the service." ) agent_card_path: Optional[FilePath] = Field( default=None, description="Path to the file containing the A2A agent card." ) agent_card_config: Optional[dict[str, Any]] = Field( default=None, description="A2A agent card configuration loaded from the agent card file.", ) custom_profile: Optional[CustomProfile] = Field( default=None, init=False, description="Service customization profile loaded from the configured path.", ) responses_request_max_size: int = Field( default=constants.RESPONSES_REQUEST_MAX_SIZE, title="Maximum character length for the serialized responses request body", description="Maximum character length for the serialized /v1/response responses " "request body", ) @model_validator(mode="after") def check_customization_model(self) -> Self: """ Load and apply service customization sources to the model. If `profile_path` is set, constructs a CustomProfile from that path and assigns it to `custom_profile`. Otherwise, if `system_prompt_path` is provided, validates the file and reads `system_prompt` from it. Returns: self: The model instance, potentially with `custom_profile` or `system_prompt` populated. """ if self.profile_path: self.custom_profile = CustomProfile(path=self.profile_path) elif self.system_prompt_path is not None: checks.file_check(self.system_prompt_path, "system prompt") self.system_prompt = checks.get_attribute_from_file( dict(self), "system_prompt_path" ) # Load agent card configuration from YAML file if self.agent_card_path is not None: checks.file_check(self.agent_card_path, "agent card") try: with open(self.agent_card_path, encoding="utf-8") as f: self.agent_card_config = yaml.safe_load(f) except yaml.YAMLError as e: raise ValueError( f"Invalid YAML in agent card file '{self.agent_card_path}': {e}" ) from e except OSError as e: raise ValueError( f"Unable to read agent card file '{self.agent_card_path}': {e}" ) from e return self class RlsapiV1Configuration(ConfigurationBase): """Configuration for the rlsapi v1 /infer endpoint. Settings specific to the RHEL Lightspeed Command Line Assistant (CLA) stateless inference endpoint. Kept separate from shared configuration sections so that CLA-specific options do not affect other endpoints. """ allow_verbose_infer: bool = Field( default=False, title="Allow verbose infer", description="Allow /v1/infer to return extended metadata " "(tool_calls, rag_chunks, token_usage) when the client sends " '"include_metadata": true. Should NOT be enabled in production. ' "If production use is needed, consider RBAC-based access control " "via an Action.RLSAPI_V1_INFER authorization rule.", ) quota_subject: Optional[Literal["user_id", "org_id", "system_id"]] = Field( default=None, title="Quota subject", description="Identity field used as the quota subject for /v1/infer. " "When set, token quota enforcement is enabled for this endpoint. " "Requires quota_handlers to be configured. " '"org_id" and "system_id" require rh-identity authentication; ' "falls back to user_id when rh-identity data is unavailable.", ) class InferenceConfiguration(ConfigurationBase): """Inference configuration.""" default_model: Optional[str] = Field( None, title="Default model", description="Identification of default model used when no other model is specified.", ) default_provider: Optional[str] = Field( None, title="Default provider", description="Identification of default provider used when no other model is specified.", ) context_windows: dict[str, PositiveInt] = Field( default_factory=dict, title="Per-model context window sizes (tokens, deprecated)", description="Deprecated: set metadata.context_window on the model's " "inference.providers[].allowed_models entry instead. Map of " 'fully-qualified model identifier (e.g., "openai/gpt-5.6-luna") to ' "context window size in tokens, used by conversation compaction " "when the model's catalog metadata has no context_window.", ) providers: list[UnifiedInferenceProviderEntry] = Field( default_factory=list, title="Inference providers", description=( "Discriminated list of inference providers. Empty by default. " "The sibling default_model / default_provider keep their " "query-time routing meaning and are independent of this list." ), ) max_infer_iters: Optional[PositiveInt] = Field( default=10, title="Default max inference iterations", description="Server-side default for the maximum number of inference " "iterations a model can perform in a single request. Prevents small " "models from looping indefinitely on tool calls. " "Per-request values take precedence over this default. " "Set to None to disable the limit.", ) max_tool_calls: Optional[PositiveInt] = Field( default=30, title="Default max tool calls", description="Server-side default for the maximum number of tool calls " "allowed in a single response. Prevents small models from exhausting " "the context window with repeated tool calls. " "Per-request values take precedence over this default. " "Set to None to disable the limit.", ) @model_validator(mode="after") def check_default_model_and_provider(self) -> Self: """ Validate that default_model and default_provider are configured together: both set or unset. Raises: ValueError: If one is set while the other is not. Returns: self (Self): The validated configuration instance. """ if self.default_model is None and self.default_provider is not None: raise ValueError( "Default model must be specified when default provider is set" ) if self.default_model is not None and self.default_provider is None: raise ValueError( "Default provider must be specified when default model is set" ) return self @field_validator("providers") @classmethod def validate_unique_provider_ids( cls, providers: list[UnifiedInferenceProviderEntry] ) -> list[UnifiedInferenceProviderEntry]: """Reject two providers that share the same local provider id.""" seen: set[str] = set() for provider in providers: if provider.id in seen: raise ValueError( f"duplicate inference provider id {provider.id!r}: two " "inference.providers entries resolve to the same " "provider_id; set a distinct 'id' on one of them" ) seen.add(provider.id) return providers class CompactionConfiguration(ConfigurationBase): """Configuration for conversation history compaction. Compaction summarizes older conversation turns when their estimated token count approaches the context window limit, keeping the conversation usable instead of failing with HTTP 413. The configuration here controls when compaction triggers and how much recent context is preserved verbatim. Attributes: enabled: Master switch. When False, compaction never triggers and other fields are inert. threshold_ratio: Trigger compaction when estimated input tokens exceed this fraction of the model's context window (clamped to 0.0..1.0). token_floor: Minimum estimated token count before compaction can trigger, regardless of threshold_ratio. Prevents triggering on very small context windows. buffer_turns: Initial number of recent turns to keep verbatim. The runtime applies a degrading guard — if these turns exceed the available budget, it reduces buffer_turns by one repeatedly until the budget fits, down to zero. buffer_max_ratio: Hard cap on the fraction of the context window the buffer zone may occupy, regardless of buffer_turns. summary_prompt: Optional prompt template for summarizing older turns in the Pydantic AI compaction. It must contain the ``{messages}`` placeholder and no other replacement field; when unset, the default prompt is used. """ enabled: bool = Field( False, title="Enable compaction", description="When true, older conversation turns are summarized " "when estimated tokens approach the context window limit.", ) threshold_ratio: float = Field( 0.7, title="Threshold ratio", description="Trigger compaction when estimated tokens exceed " "this fraction of the model's context window (0.0-1.0).", ) token_floor: NonNegativeInt = Field( 4096, title="Token floor", description="Minimum token count before compaction can trigger. " "Prevents triggering on very small context windows.", ) buffer_turns: NonNegativeInt = Field( 4, title="Buffer turns", description="Number of recent turns to keep verbatim.", ) buffer_max_ratio: float = Field( 0.3, title="Buffer max ratio", description="Maximum fraction of context window the buffer zone " "can occupy, regardless of buffer_turns.", ) summary_prompt: Optional[str] = Field( default=None, title="Summary prompt", description="Prompt template for summarizing older turns in the Pydantic " "AI compaction. The conversation transcript replaces the {messages} " "placeholder, which is required; no other replacement field is allowed, " "so double any literal braces. When unset, the default prompt is used.", ) @field_validator("threshold_ratio") @classmethod def _validate_threshold_ratio(cls, value: float) -> float: """Reject threshold ratios outside the inclusive 0..1 range.""" if not 0.0 <= value <= 1.0: raise ValueError("threshold_ratio must be between 0.0 and 1.0 (inclusive)") return value @field_validator("buffer_max_ratio") @classmethod def _validate_buffer_max_ratio(cls, value: float) -> float: """Reject buffer-max ratios outside the inclusive 0..1 range.""" if not 0.0 <= value <= 1.0: raise ValueError("buffer_max_ratio must be between 0.0 and 1.0 (inclusive)") return value @field_validator("summary_prompt") @classmethod def _validate_summary_prompt(cls, value: Optional[str]) -> Optional[str]: """Check that a summary prompt formats the transcript and nothing else. The prompt is filled with ``str.format(messages=...)``. Without the placeholder the transcript would be silently dropped, and any other replacement field would fail only when a conversation is summarized, so both are rejected when the configuration is loaded. Parameters: value: Prompt template, or None for the default prompt. Returns: The prompt, unchanged. Raises: ValueError: If the prompt does not contain ``{messages}``, contains any other replacement field, or is not a valid format string. """ if value is None: return value try: fields = [ (name, spec, conversion) for _, name, spec, conversion in Formatter().parse(value) if name is not None ] except ValueError as e: raise ValueError(f"summary_prompt is not a valid format string: {e}") from e if not fields or any(field != ("messages", "", None) for field in fields): raise ValueError( "summary_prompt must contain the {messages} placeholder and no other " "replacement field; double any literal braces" ) return value class ConversationHistoryConfiguration(ConfigurationBase): """Conversation history configuration.""" type: Optional[Literal["noop", "memory", "sqlite", "postgres"]] = Field( None, title="Conversation history database type", description="Type of database where the conversation history is to be stored.", ) memory: Optional[InMemoryCacheConfig] = Field( None, title="In-memory cache configuration", description="In-memory cache configuration", ) sqlite: Optional[SQLiteDatabaseConfiguration] = Field( None, title="SQLite configuration", description="SQLite database configuration", ) postgres: Optional[PostgreSQLDatabaseConfiguration] = Field( None, title="PostgreSQL configuration", description="PostgreSQL database configuration", ) @model_validator(mode="after") def check_cache_configuration(self) -> Self: """ Validate the conversation cache configuration and enforce the selected cache type backend. Raises: ValueError: If a backend is provided but `type` is None. ValueError: If `type` is "memory" but `memory` config is missing, or if other backend configs are present. ValueError: If `type` is "sqlite" but `sqlite` config is missing, or if other backend configs are present. ValueError: If `type` is "postgres" but `postgres` config is missing, or if other backend configs are present. Returns: The validated model instance. """ # if any backend config is provided, type must be explicitly selected if self.type is None: if any([self.memory, self.sqlite, self.postgres]): raise ValueError( "Conversation cache type must be set when backend configuration is provided" ) # no type selected + no configuration is expected and fully supported return self match self.type: case constants.CACHE_TYPE_MEMORY: if self.memory is None: raise ValueError("Memory cache is selected, but not configured") # no other DBs configuration allowed if any([self.sqlite, self.postgres]): raise ValueError("Only memory cache config must be provided") case constants.CACHE_TYPE_SQLITE: if self.sqlite is None: raise ValueError("SQLite cache is selected, but not configured") # no other DBs configuration allowed if any([self.memory, self.postgres]): raise ValueError("Only SQLite cache config must be provided") case constants.CACHE_TYPE_POSTGRES: if self.postgres is None: raise ValueError("PostgreSQL cache is selected, but not configured") # no other DBs configuration allowed if any([self.memory, self.sqlite]): raise ValueError("Only PostgreSQL cache config must be provided") return self class AgentStepPersistenceNoopConfiguration(ConfigurationBase): """Agent step persistence disabled (no harness store).""" type: Literal["noop"] = Field( default="noop", description="Disable persistence of agent steps." ) class AgentStepPersistenceSqliteConfiguration(ConfigurationBase): """SQLite-backed harness step store.""" type: Literal["sqlite"] = Field( default="sqlite", description="Persist agent steps in a SQLite database." ) sqlite: SQLiteDatabaseConfiguration = Field( ..., title="SQLite database", description="SQLite file for harness step persistence.", ) AgentStepPersistenceConfiguration = Annotated[ AgentStepPersistenceNoopConfiguration | AgentStepPersistenceSqliteConfiguration, Field(discriminator="type"), ] class A2AStateConfiguration(ConfigurationBase): """A2A protocol persistent state configuration. Configures how A2A task state and context-to-conversation mappings are stored. For multi-worker deployments, use SQLite or PostgreSQL to ensure state is shared across all workers. If no configuration is provided, in-memory storage is used (default). This is suitable for single-worker deployments but state will be lost on restarts and not shared across workers. Attributes: sqlite: SQLite database configuration for A2A state storage. postgres: PostgreSQL database configuration for A2A state storage. """ sqlite: Optional[SQLiteDatabaseConfiguration] = Field( default=None, title="SQLite configuration", description="SQLite database configuration for A2A state storage.", ) postgres: Optional[PostgreSQLDatabaseConfiguration] = Field( default=None, title="PostgreSQL configuration", description="PostgreSQL database configuration for A2A state storage.", ) @model_validator(mode="after") def check_a2a_state_configuration(self) -> Self: """Validate A2A state configuration - only one type can be configured.""" total_configured = sum([self.sqlite is not None, self.postgres is not None]) if total_configured > 1: raise ValueError("Only one A2A state storage configuration can be provided") return self @property def storage_type(self) -> Literal["memory", "sqlite", "postgres"]: """Return the configured storage type.""" if self.sqlite is not None: return "sqlite" if self.postgres is not None: return "postgres" return "memory" @property def config( self, ) -> Optional[SQLiteDatabaseConfiguration | PostgreSQLDatabaseConfiguration]: """Return the active storage configuration, or None for memory storage.""" if self.sqlite is not None: return self.sqlite if self.postgres is not None: return self.postgres return None class RagStore(ConfigurationBase): """BYOK (Bring Your Own Knowledge) RAG store configuration.""" rag_id: str = Field( ..., min_length=1, title="RAG ID", description="Unique RAG ID", ) backend: str = Field( constants.DEFAULT_RAG_BACKEND, min_length=1, title="RAG backend", description="Type of RAG database (e.g. 'faiss', 'pgvector').", ) @field_validator("backend") @classmethod def validate_backend(cls, value: str) -> str: """Reject unsupported backend values at config load time.""" if value not in constants.SUPPORTED_RAG_BACKENDS: raise ValueError( f"Unsupported RAG backend '{value}'. " f"Supported backends: {sorted(constants.SUPPORTED_RAG_BACKENDS)}" ) return value embedding_model: str = Field( constants.DEFAULT_EMBEDDING_MODEL, min_length=1, title="Embedding model", description="Embedding model identification", ) embedding_dimension: PositiveInt = Field( constants.DEFAULT_EMBEDDING_DIMENSION, title="Embedding dimension", description="Dimensionality of embedding vectors.", ) vector_db_id: str = Field( ..., min_length=1, title="Vector DB ID", description="Vector database identification.", ) db_path: Optional[str] = Field( default=None, title="DB path", description="Path to RAG database. Required for faiss backend.", ) score_multiplier: float = Field( constants.DEFAULT_SCORE_MULTIPLIER, gt=0, title="Score multiplier", description="Multiplier applied to relevance scores from this vector store. " "Used to weight results when querying multiple knowledge sources. " "Values > 1 boost this store's results; values < 1 reduce them.", ) relevance_cutoff_score: float = Field( constants.DEFAULT_BYOK_RAG_RELEVANCE_CUTOFF_SCORE, gt=0, title="Relevance cutoff score", description="Minimum raw similarity score to consider a result relevant. " "Results with a similarity score below this threshold are not returned.", ) host: Optional[str] = Field( default=None, title="PostgreSQL host", description="PostgreSQL host for pgvector backend. " "Defaults to ${env.POSTGRES_HOST} when backend is pgvector.", ) port: Optional[str | int] = Field( default=None, title="PostgreSQL port", description="PostgreSQL port for pgvector backend. " "Defaults to ${env.POSTGRES_PORT} when backend is pgvector.", ) db: Optional[str] = Field( default=None, title="PostgreSQL database", description="PostgreSQL database name for pgvector backend. " "Defaults to ${env.POSTGRES_DATABASE} when backend is pgvector.", ) user: Optional[str] = Field( default=None, title="PostgreSQL user", description="PostgreSQL user for pgvector backend. " "Defaults to ${env.POSTGRES_USER} when backend is pgvector.", ) password: Optional[SecretStr] = Field( default=None, title="PostgreSQL password", description="PostgreSQL password for pgvector backend. " "Defaults to ${env.POSTGRES_PASSWORD} when backend is pgvector.", ) @model_validator(mode="after") def validate_backend_fields(self) -> Self: """Validate and populate fields based on backend.""" if self.backend == "faiss": if not self.db_path: raise ValueError("db_path is required when backend is 'faiss'") elif self.backend == "pgvector": pgvector_defaults: dict[str, str | SecretStr] = { "host": "${env.POSTGRES_HOST}", "port": "${env.POSTGRES_PORT}", "db": "${env.POSTGRES_DATABASE}", "user": "${env.POSTGRES_USER}", "password": SecretStr("${env.POSTGRES_PASSWORD}"), } for field_name, default_value in pgvector_defaults.items(): if getattr(self, field_name) is None: object.__setattr__(self, field_name, default_value) return self class FaissVectorStoreProviderConfig(ConfigurationBase): """Storage config for a FAISS dynamic vector-store provider.""" path: str = Field( ..., min_length=1, title="DB path", description="On-disk FAISS/SQLite path for this provider.", ) class PgvectorVectorStoreProviderConfig(ConfigurationBase): """Storage config for a pgvector dynamic vector-store provider.""" host: Optional[str] = Field( default=None, title="PostgreSQL host", description="PostgreSQL host. Defaults to ${env.POSTGRES_HOST}.", ) port: Optional[str | int] = Field( default=None, title="PostgreSQL port", description="PostgreSQL port. Defaults to ${env.POSTGRES_PORT}. " "Accepts string placeholders and integer values.", ) db: Optional[str] = Field( default=None, title="PostgreSQL database", description="PostgreSQL database name. Defaults to ${env.POSTGRES_DATABASE}.", ) user: Optional[str] = Field( default=None, title="PostgreSQL user", description="PostgreSQL user. Defaults to ${env.POSTGRES_USER}.", ) password: Optional[SecretStr] = Field( default=None, title="PostgreSQL password", description="PostgreSQL password. Defaults to ${env.POSTGRES_PASSWORD}.", ) @model_validator(mode="after") def apply_pgvector_env_defaults(self) -> Self: """Fill unset connection fields with ${env.POSTGRES_*} references.""" pgvector_defaults: dict[str, str | SecretStr] = { "host": "${env.POSTGRES_HOST}", "port": "${env.POSTGRES_PORT}", "db": "${env.POSTGRES_DATABASE}", "user": "${env.POSTGRES_USER}", "password": SecretStr("${env.POSTGRES_PASSWORD}"), } for field_name, default_value in pgvector_defaults.items(): if getattr(self, field_name) is None: object.__setattr__(self, field_name, default_value) return self class VectorStoreProviderBase(ConfigurationBase): """Shared fields for dynamic vector-store provider capacity entries. Attributes: id: OGX vector_io provider_id. Surrounding whitespace is stripped before validation and emission. embedding_model: Embedding model identification used for stores created against this provider. embedding_dimension: Dimensionality of embedding vectors for this provider. """ id: str = Field( ..., min_length=1, title="Provider ID", description=( "OGX vector_io provider_id. Surrounding whitespace is " "stripped before validation and emission." ), ) embedding_model: str = Field( ..., min_length=1, title="Embedding model", description="Embedding model identification used for stores created " "against this provider.", ) embedding_dimension: PositiveInt = Field( ..., title="Embedding dimension", description="Dimensionality of embedding vectors for this provider.", ) @field_validator("id") @classmethod def validate_id(cls, value: str) -> str: """Validate and normalize the provider id. Parameters: value: Raw provider id from configuration. Returns: Stripped provider id. Raises: ValueError: If the id is empty, uses the reserved ``byok_`` prefix, or contains characters outside ``[a-z0-9_-]``. """ stripped = value.strip() if not stripped: raise ValueError("id must be non-empty after stripping whitespace") if stripped.startswith("byok_"): raise ValueError("id must not start with 'byok_' (reserved for BYOK RAG)") if not re.fullmatch(r"[a-z0-9_-]+", stripped): raise ValueError( "id may contain only lowercase letters, digits, " "underscores, and hyphens" ) return stripped class FaissVectorStoreProvider(VectorStoreProviderBase): """Dynamic FAISS vector-store provider (runtime create capacity).""" type: Literal["faiss"] = Field( "faiss", title="Provider type", description="Product type for this dynamic vector-store provider.", ) config: FaissVectorStoreProviderConfig = Field( ..., title="Storage config", description="FAISS storage settings for this provider.", ) class PgvectorVectorStoreProvider(VectorStoreProviderBase): """Dynamic pgvector vector-store provider (runtime create capacity).""" type: Literal["pgvector"] = Field( "pgvector", title="Provider type", description="Product type for this dynamic vector-store provider.", ) config: PgvectorVectorStoreProviderConfig = Field( ..., title="Storage config", description="pgvector connection settings for this provider.", ) VectorStoreProvider = Annotated[ FaissVectorStoreProvider | PgvectorVectorStoreProvider, Field(discriminator="type"), ] class VectorStoreConfiguration(ConfigurationBase): """Configuration for dynamic vector-store providers. Mirrors ``InferenceConfiguration``: a providers list plus a sibling ``default_provider`` pointer, rather than a per-entry default flag. Attributes: default_provider: Provider id used for vector_stores.default_* in the synthesized OGX config. Required when providers is non-empty; must match one of providers[].id. Must be omitted when providers is empty. providers: Dynamic vector-store provider capacity for runtime POST /v1/vector-stores creates. Not the same as rag.byok.stores (static registered corpora). """ default_provider: Optional[str] = Field( None, title="Default provider", description=( "Provider id used for vector_stores.default_* in the " "synthesized OGX config. Required when providers is " "non-empty; must match one of providers[].id." ), ) providers: list[VectorStoreProvider] = Field( default_factory=list, title="Vector store providers", description=( "Dynamic vector-store provider capacity for runtime " "POST /v1/vector-stores creates. " "Not the same as rag.byok.stores (static registered corpora)." ), ) @model_validator(mode="after") def validate_providers_and_default(self) -> Self: """Validate providers list and default_provider pointer. When providers is empty, default_provider must be unset. When providers is non-empty, default_provider is required and must match exactly one providers[].id. Provider ids must be unique. Returns: Self: The validated configuration instance. Raises: ValueError: If ids are duplicated, default_provider is missing for a non-empty list, is set for an empty list, or does not match a provider id. """ # pylint: disable=no-member if not self.providers: if self.default_provider is not None: raise ValueError( "vector_store.default_provider must not be set when " "providers is empty" ) return self if self.default_provider is None: raise ValueError( "vector_store.default_provider is required when providers is non-empty" ) ids = [provider.id for provider in self.providers] if len(ids) != len(set(ids)): raise ValueError(f"vector_store.providers ids must be unique; got {ids}") default_provider = self.default_provider.strip() if not default_provider: raise ValueError( "vector_store.default_provider must be non-empty after " "stripping whitespace" ) if default_provider not in ids: raise ValueError( "vector_store.default_provider must match one of " f"providers[].id; got {default_provider!r}, known ids: {ids}" ) object.__setattr__(self, "default_provider", default_provider) return self class QuotaLimiterConfiguration(ConfigurationBase): """Configuration for one quota limiter. There are three configuration options for each limiter: 1. ``period`` is specified in a human-readable form, see https://www.postgresql.org/docs/current/datatype-datetime.html#DATATYPE-INTERVAL-INPUT for all possible options. When the end of the period is reached, the quota is reset or increased. With the SQLite storage the period must be a modifier of the SQLite function ``datetime()`` that moves the time forward, for example ``7 days``; ``1 week`` is rejected. 2. ``initial_quota`` is the value set at the beginning of the period. 3. ``quota_increase`` is the value (if specified) used to increase the quota when the period is reached. There are two basic use cases: 1. When the quota needs to be reset to a specific value periodically (for example on a weekly or monthly basis), set ``initial_quota`` to the required value. 2. When the quota needs to be increased by a specific value periodically (for example on a daily basis), set ``quota_increase``. """ type: Literal["user_limiter", "cluster_limiter"] = Field( ..., title="Quota limiter type", description="Quota limiter type, either user_limiter or cluster_limiter", ) name: str = Field( ..., title="Quota limiter name", description="Human readable quota limiter name", ) initial_quota: NonNegativeInt = Field( ..., title="Initial quota", description="Quota set at beginning of the period", ) quota_increase: NonNegativeInt = Field( ..., title="Quota increase", description="Delta value used to increase quota when period is reached", ) period: str = Field( ..., title="Period", description="Period specified in human readable form", ) class QuotaSchedulerConfiguration(ConfigurationBase): """Quota scheduler configuration.""" period: PositiveInt = Field( 1, title="Period", description="Quota scheduler period specified in seconds", ) database_reconnection_count: PositiveInt = Field( 10, title="Database reconnection count on startup", description="Database reconnection count on startup. When database for " "quota is not available on startup, the service tries to reconnect N " "times with specified delay.", ) database_reconnection_delay: PositiveInt = Field( 1, title="Database reconnection delay", description="Database reconnection delay specified in seconds. When database for " "quota is not available on startup, the service tries to reconnect N " "times with specified delay.", ) class QuotaHandlersConfiguration(ConfigurationBase): """Quota limiter configuration. It is possible to limit quota usage per user or per service or services (that typically run in one cluster). Each limit is configured as a separate _quota limiter_. It can be of type `user_limiter` or `cluster_limiter` (which is name that makes sense in OpenShift deployment). """ sqlite: Optional[SQLiteDatabaseConfiguration] = Field( None, title="SQLite configuration", description="SQLite database configuration", ) postgres: Optional[PostgreSQLDatabaseConfiguration] = Field( None, title="PostgreSQL configuration", description="PostgreSQL database configuration", ) limiters: list[QuotaLimiterConfiguration] = Field( default_factory=list, title="Quota limiters", description="Quota limiters configuration", ) scheduler: QuotaSchedulerConfiguration = Field( default_factory=lambda: QuotaSchedulerConfiguration( period=1, database_reconnection_count=10, database_reconnection_delay=1 ), title="Quota scheduler", description="Quota scheduler configuration", ) enable_token_history: bool = Field( False, title="Enable token history", description="Enables storing information about token usage history", ) @model_validator(mode="after") def check_limiter_periods(self) -> Self: """ Ensure that the SQLite storage can use the period of every limiter. The quota scheduler passes the period to the SQLite function datetime() as a modifier. For a period SQLite can not parse datetime() returns NULL and the quota is never renewed, without any error. Such a period is rejected, and so is a period that does not move the time forward. Nothing is checked when SQLite is not configured: PostgreSQL accepts a wider syntax. Returns: Self: The validated configuration instance. Raises: ValueError: If SQLite is configured and it can not use the period of a limiter. """ if self.sqlite is None: return self for limiter in self.limiters: if not checks.is_valid_sqlite_period(limiter.period): raise ValueError( f"Quota limiter '{limiter.name}': period '{limiter.period}' " "can not be used with the SQLite storage. Use one positive " "number followed by seconds, minutes, hours, days, months " "or years, for example '7 days'." ) return self class RerankerConfiguration(ConfigurationBase): """Reranker configuration for RAG chunk reranking.""" enabled: bool = Field( default=False, title="Reranker enabled", description="When True, reranking applied to RAG chunks. " "When False, reranking is disabled and original scoring used.", ) provider: str = Field( default=constants.DEFAULT_RERANK_PROVIDER, title="Rerank model provider", description="The `id` of the inference provider in `inference.providers` " "that loads this cross-encoder (typically `sentence_transformers`).", ) model: str = Field( default=constants.DEFAULT_CROSS_ENCODER_MODEL, title="Cross-encoder model id", description="Hugging Face cross-encoder model id used for reranking. " "When it matches `provider`, the sentence-transformers provider also " "registers it in its catalog at startup (`name` and backend id both " "set to this value) if not already listed in `allowed_models`.", ) _explicitly_configured: bool = PrivateAttr(default=False) @model_validator(mode="after") def mark_as_explicitly_configured(self) -> Self: """Mark this configuration as explicitly set when instantiated from user input.""" if self.model_fields_set: self._explicitly_configured = True return self class RetrievalStrategyConfiguration(ConfigurationBase): """Configuration for a single retrieval strategy (inline or tool).""" sources: list[str] = Field( default_factory=list, title="RAG source IDs", description="RAG IDs to use for this retrieval strategy. " f"Use '{constants.OKP_RAG_ID}' to include the OKP vector store.", ) max_chunks: PositiveInt = Field( default=constants.DEFAULT_INLINE_RAG_MAX_CHUNKS, title="Max chunks", description="Maximum number of chunks returned by this retrieval strategy.", ) reranker: Optional[RerankerConfiguration] = Field( default=None, title="Reranker configuration", description="Neural reranking of RAG chunks using cross-encoder. " "Only applicable to inline retrieval.", ) class RetrievalConfiguration(ConfigurationBase): """Configuration for inline and tool retrieval strategies.""" inline: RetrievalStrategyConfiguration = Field( default_factory=lambda: RetrievalStrategyConfiguration( max_chunks=constants.DEFAULT_INLINE_RAG_MAX_CHUNKS, reranker=RerankerConfiguration(), ), title="Inline retrieval", description="Inline RAG: context injected before the LLM request.", ) tool: RetrievalStrategyConfiguration = Field( default_factory=lambda: RetrievalStrategyConfiguration( max_chunks=constants.DEFAULT_TOOL_RAG_MAX_CHUNKS, ), title="Tool retrieval", description="Tool RAG: LLM can call file_search on demand.", ) class ByokConfiguration(ConfigurationBase): """BYOK (Bring Your Own Knowledge) configuration.""" max_chunks: PositiveInt = Field( default=constants.DEFAULT_BYOK_RAG_MAX_CHUNKS, title="Max BYOK chunks", description="Maximum total number of chunks returned across all BYOK stores.", ) stores: list[RagStore] = Field( default_factory=list, title="BYOK RAG stores", description="List of BYOK RAG store configurations.", ) @model_validator(mode="after") def validate_unique_rag_ids(self) -> Self: """Reject duplicate rag_id values across stores.""" seen: set[str] = set() for store in self.stores: if store.rag_id in seen: raise ValueError( f"Duplicate rag_id '{store.rag_id}' in rag.byok.stores. " "Each store must have a unique rag_id." ) seen.add(store.rag_id) return self class OkpConfiguration(ConfigurationBase): """OKP (Offline Knowledge Portal) provider configuration. Controls provider-specific behaviour for the OKP vector store. Only relevant when ``"okp"`` is listed in ``rag.retrieval.inline.sources`` or ``rag.retrieval.tool.sources``. """ rhokp_url: Optional[AnyHttpUrl] = Field( default=None, title="OKP base URL", description="Base URL for the OKP server (http or https). " "Set to `${env.RH_SERVER_OKP}` in YAML to use the environment variable. " "When unset, the default from constants is used.", ) offline: bool = Field( default=True, title="OKP offline mode", description="When True, use parent_id for OKP chunk source URLs. " "When False, use reference_url for chunk source URLs.", ) chunk_filter_query: Optional[str] = Field( default=None, title="OKP chunk filter query", description="Additional OKP filter query applied to every OKP search request. " "Use Solr boolean syntax, e.g. 'product:ansible AND product:*openshift*'.", ) search_mode: Optional[Literal["semantic", "hybrid", "keyword"]] = Field( default=None, title="OKP search mode", description="Default Solr search mode for OKP queries. " "'keyword' uses BM25 text search (no embedding model needed). " "'hybrid' combines vector + keyword search. " "'semantic' uses pure vector search. " "When unset, falls back to the global default ('hybrid').", ) max_chunks: PositiveInt = Field( default=constants.DEFAULT_OKP_RAG_MAX_CHUNKS, title="Max OKP chunks", description="Maximum number of chunks fetched from OKP.", ) class DynamicRagConfiguration(ConfigurationBase): """Writable database shared by every runtime vector store. One object, not a list. Stores created through the vector-store API live in this database and use this embedding model. The block is omitted when runtime stores are not used. Attributes: backend: ``faiss`` (one sqlite file) or ``pgvector`` (one PostgreSQL database). embedding_model: Model used to ingest documents and embed queries. embedding_dimension: Dimensionality of those embedding vectors. relevance_cutoff_score: Minimum raw similarity score returned from a runtime store. score_multiplier: Weight applied after merged matches are ranked. db_path: Sqlite file for the FAISS backend. host: PostgreSQL host for the pgvector backend. port: PostgreSQL port for the pgvector backend. db: PostgreSQL database name for the pgvector backend. user: PostgreSQL user for the pgvector backend. password: PostgreSQL password for the pgvector backend. """ backend: Literal["faiss", "pgvector"] = Field( ..., title="Backend", description=( "Vector database that holds every runtime store. " "'faiss' uses one sqlite file. 'pgvector' uses one PostgreSQL database." ), ) embedding_model: str = Field( constants.DEFAULT_EMBEDDING_MODEL, min_length=1, title="Embedding model", description=( "Embedding model used to ingest documents and search every runtime store." ), ) embedding_dimension: PositiveInt = Field( constants.DEFAULT_EMBEDDING_DIMENSION, title="Embedding dimension", description="Dimensionality of embedding vectors for every runtime store.", ) relevance_cutoff_score: float = Field( constants.DEFAULT_BYOK_RAG_RELEVANCE_CUTOFF_SCORE, gt=0, title="Relevance cutoff score", description="Minimum raw similarity score to return from a runtime store.", ) score_multiplier: float = Field( constants.DEFAULT_SCORE_MULTIPLIER, gt=0, title="Score multiplier", description=( "Weight applied to runtime-store scores after merged matches are ranked." ), ) db_path: Optional[str] = Field( default=None, min_length=1, title="DB path", description=( "Sqlite file that holds every runtime store. Required when backend is faiss." ), ) host: Optional[str] = Field( default=None, title="PostgreSQL host", description="PostgreSQL host. Defaults to ${env.POSTGRES_HOST} for pgvector.", ) port: Optional[str | int] = Field( default=None, title="PostgreSQL port", description=( "PostgreSQL port. Defaults to ${env.POSTGRES_PORT} for pgvector. " "Accepts string placeholders and integer values." ), ) db: Optional[str] = Field( default=None, title="PostgreSQL database", description=( "PostgreSQL database name. Defaults to ${env.POSTGRES_DATABASE} for pgvector." ), ) user: Optional[str] = Field( default=None, title="PostgreSQL user", description="PostgreSQL user. Defaults to ${env.POSTGRES_USER} for pgvector.", ) password: Optional[SecretStr] = Field( default=None, title="PostgreSQL password", description=( "PostgreSQL password. Defaults to ${env.POSTGRES_PASSWORD} for pgvector." ), ) @model_validator(mode="after") def validate_backend_fields(self) -> Self: """Require a FAISS path, or fill pgvector connection defaults. Returns: The validated configuration. Raises: ValueError: If the FAISS backend has no ``db_path``. """ if self.backend == "faiss": if not self.db_path: raise ValueError("db_path is required when backend is 'faiss'") return self pgvector_defaults: dict[str, str | SecretStr] = { "host": "${env.POSTGRES_HOST}", "port": "${env.POSTGRES_PORT}", "db": "${env.POSTGRES_DATABASE}", "user": "${env.POSTGRES_USER}", "password": SecretStr("${env.POSTGRES_PASSWORD}"), } for field_name, default_value in pgvector_defaults.items(): if getattr(self, field_name) is None: object.__setattr__(self, field_name, default_value) return self class RagConfiguration(ConfigurationBase): """Unified RAG configuration. Groups all RAG-related settings: BYOK stores, OKP provider, retrieval strategies (inline and tool), and the optional dynamic store database. """ byok: ByokConfiguration = Field( default_factory=ByokConfiguration, title="BYOK configuration", description="Bring Your Own Knowledge store configurations and settings.", ) okp: OkpConfiguration = Field( default_factory=OkpConfiguration, title="OKP configuration", description=f"OKP provider settings. Only used when '{constants.OKP_RAG_ID}' " "is listed in retrieval.inline.sources or retrieval.tool.sources.", ) retrieval: RetrievalConfiguration = Field( default_factory=RetrievalConfiguration, title="Retrieval configuration", description="Inline and tool retrieval strategy settings.", ) dynamic: Optional[DynamicRagConfiguration] = Field( default=None, title="Dynamic RAG configuration", description=( "Optional writable database for runtime vector stores. " "When omitted, creating vector stores at runtime is unavailable. " "Runtime store names are not retrieval source ids." ), ) @model_validator(mode="after") def validate_dynamic_db_path(self) -> Self: """Reject a dynamic FAISS file that is also a static BYOK corpus. Returns: The validated configuration. Raises: ValueError: If ``rag.dynamic.db_path`` equals a BYOK ``db_path``. """ dynamic = self.dynamic if dynamic is None or dynamic.backend != "faiss" or not dynamic.db_path: return self byok_paths = {store.db_path for store in self.byok.stores if store.db_path} if dynamic.db_path in byok_paths: raise ValueError( "rag.dynamic.db_path must not equal a rag.byok.stores db_path; " f"got {dynamic.db_path!r}" ) return self @model_validator(mode="after") def validate_retrieval_sources(self) -> Self: """Reject retrieval source IDs not declared in byok.stores or OKP.""" # pylint: disable=no-member known_ids = {store.rag_id for store in self.byok.stores} known_ids.add(constants.OKP_RAG_ID) for strategy_name in ("inline", "tool"): strategy = getattr(self.retrieval, strategy_name) unknown = set(strategy.sources) - known_ids if unknown: raise ValueError( f"retrieval.{strategy_name}.sources contains unknown RAG IDs: " f"{sorted(unknown)}. " f"Declared IDs: {sorted(known_ids)}" ) return self @model_validator(mode="after") def validate_reranker_auto_enable(self) -> Self: """Automatically enable reranker when both BYOK and OKP RAG are configured.""" # pylint: disable=no-member has_byok = len(self.byok.stores) > 0 has_okp = constants.OKP_RAG_ID in self.retrieval.inline.sources reranker = self.retrieval.inline.reranker if ( has_byok and has_okp and reranker is not None and not reranker._explicitly_configured # pylint: disable=protected-access and not reranker.enabled ): logger.info( "Automatically enabling reranker: Both BYOK RAG (%d stores) and " "OKP are configured. Reranking improves result quality when " "multiple knowledge sources are available.", len(self.byok.stores), ) reranker.enabled = True return self class SkillsConfiguration(ConfigurationBase): """Agent skills configuration. Specifies paths to skill directories. Skill metadata (name, description) is read from SKILL.md frontmatter at startup. Each path can point to either: - A directory containing a SKILL.md file (single skill) - A directory containing subdirectories with SKILL.md files (multiple skills) Paths are validated at startup to ensure they exist and contain valid SKILL.md files. """ paths: list[Path] = Field( default_factory=list, title="Skill paths", description="Paths to skill directories or directories containing skill subdirectories.", ) class SavedPromptsConfiguration(ConfigurationBase): """Configuration for saved prompts feature limits. Controls the maximum number of prompts a user can save, the maximum display name (title) length, and the maximum prompt content length. Omitted fields use the defaults defined in constants. Attributes: max_prompts_per_user: Maximum number of saved prompts allowed per user. max_display_name_length: Maximum character length for the prompt display name. max_content_length: Maximum character length for the prompt content body. """ max_prompts_per_user: PositiveInt = Field( default=constants.SAVED_PROMPTS_DEFAULT_MAX_PER_USER, le=constants.SAVED_PROMPTS_MAX_PER_USER_UPPER_BOUND, title="Max prompts per user", description="Maximum number of saved prompts a user can create. " f"Defaults to {constants.SAVED_PROMPTS_DEFAULT_MAX_PER_USER}. " f"Cannot exceed {constants.SAVED_PROMPTS_MAX_PER_USER_UPPER_BOUND}.", ) max_display_name_length: PositiveInt = Field( default=constants.SAVED_PROMPTS_DEFAULT_MAX_DISPLAY_NAME_LENGTH, le=constants.SAVED_PROMPTS_MAX_DISPLAY_NAME_LENGTH_UPPER_BOUND, title="Max display name length", description="Maximum character length for prompt display name (title). " f"Defaults to {constants.SAVED_PROMPTS_DEFAULT_MAX_DISPLAY_NAME_LENGTH}. " f"Cannot exceed {constants.SAVED_PROMPTS_MAX_DISPLAY_NAME_LENGTH_UPPER_BOUND}.", ) max_content_length: PositiveInt = Field( default=constants.SAVED_PROMPTS_DEFAULT_MAX_CONTENT_LENGTH, le=constants.SAVED_PROMPTS_MAX_CONTENT_LENGTH_UPPER_BOUND, title="Max content length", description="Maximum character length for the prompt content body. " f"Defaults to {constants.SAVED_PROMPTS_DEFAULT_MAX_CONTENT_LENGTH}. " f"Cannot exceed {constants.SAVED_PROMPTS_MAX_CONTENT_LENGTH_UPPER_BOUND}.", ) class QuestionValidityConfig(ConfigurationBase): """Configuration for the question validity guardrail.""" model_id: str = Field( ..., title="Model id", description="The model_id to use for the guard" ) model_prompt: str = Field( default=constants.DEFAULT_MODEL_PROMPT, title="Model prompt", description="The default prompt sent to the LLM used to validate the Users' question.", ) invalid_question_response: str = Field( default=constants.DEFAULT_INVALID_QUESTION_RESPONSE, title="Invalid question response", description="The default response when the Users' question is determined to be invalid.", ) class RedactionRule(ConfigurationBase): """A single regex-based redaction rule. Attributes: pattern: Raw regex pattern string to match sensitive data. replacement: Text to substitute for each match. case_sensitive: Per-rule override for case sensitivity. When None, the global ``RedactionConfig.case_sensitive`` flag applies. """ pattern: str = Field( ..., title="Pattern", description="Regex pattern to match sensitive data", ) replacement: str = Field( ..., title="Replacement", description="Replacement string for matched text", ) case_sensitive: Optional[bool] = Field( None, title="Case sensitive", description=( "Per-rule case sensitivity override. " "When None, the global config flag applies." ), ) class RedactionConfig(ConfigurationBase): """Configuration for PII redaction with regex-based rules. Rules are validated and compiled at construction time. Invalid regex patterns raise a ``ValueError`` immediately. Attributes: rules: Ordered list of redaction rules applied sequentially. case_sensitive: When False, patterns are compiled with ``re.IGNORECASE``. Defaults to False. """ rules: list[RedactionRule] = Field( default_factory=list, title="Redaction rules", description="Ordered list of PII redaction rules", ) case_sensitive: bool = Field( False, title="Case sensitive", description=("When False, patterns are compiled with re.IGNORECASE"), ) _compiled_patterns: CompiledPatterns = PrivateAttr( default_factory=list, ) @model_validator(mode="after") def compile_patterns(self) -> Self: """Compile regex patterns and reject invalid ones. Per-rule ``case_sensitive`` overrides the global flag when set. Raises: ValueError: If any rule contains an invalid regex pattern. Returns: The validated configuration instance. """ global_case_sensitive = self.case_sensitive compiled: CompiledPatterns = [] for rule in self.rules: effective = ( rule.case_sensitive if rule.case_sensitive is not None else global_case_sensitive ) flags = 0 if effective else re.IGNORECASE try: pattern = re.compile(rule.pattern, flags) except re.error as e: raise ValueError(f"Invalid regex pattern: {rule.pattern}: {e}") from e compiled.append((pattern, rule.replacement)) self._compiled_patterns = compiled return self @property def compiled_patterns(self) -> CompiledPatterns: """Pre-compiled (regex, replacement) pairs. Returns a shallow copy to prevent mutation of internal state. """ return list(self._compiled_patterns) class ObservabilityConfiguration(ConfigurationBase): """OpenTelemetry observability configuration. This configuration is automatically populated from OTEL_* environment variables to provide visibility into the active tracing setup. Attributes: otel: Dictionary of OTEL_* environment variables with secrets redacted. """ otel: dict[str, str] = Field( default_factory=dict, title="OpenTelemetry configuration", description="Active OpenTelemetry configuration from OTEL_* environment variables", ) @field_validator("otel", mode="before") @classmethod def redact_secrets(cls, value: dict[str, str]) -> dict[str, str]: """Redact sensitive OTEL environment variables. For headers (e.g., OTEL_EXPORTER_OTLP_HEADERS), redacts values while preserving key names for debugging. For certificates, client keys, and OTEL_ANONYMIZATION_SECRET, redacts the entire value. Parameters: ---------- value: Dictionary of OTEL environment variables Returns: New dictionary with sensitive values redacted """ # Let Pydantic handle type validation for non-dict inputs if not isinstance(value, dict): return value if not value: return value # Create a new dict to avoid mutating caller's data redacted = {} for key, val in value.items(): # Redact generic and signal-specific OTLP headers # Matches: OTEL_EXPORTER_OTLP_HEADERS, # OTEL_EXPORTER_OTLP_TRACES_HEADERS, # OTEL_EXPORTER_OTLP_METRICS_HEADERS, # OTEL_EXPORTER_OTLP_LOGS_HEADERS # Format: "api-key=secret,tenant-id=acme" -> "api-key=[REDACTED],tenant-id=[REDACTED]" if "HEADERS" in key and "OTLP" in key: redacted[key] = cls._redact_header_values(val) # Redact generic and signal-specific certificates # Matches: OTEL_EXPORTER_OTLP_CERTIFICATE, # OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE, etc. elif "CERTIFICATE" in key and "OTLP" in key: redacted[key] = "[REDACTED]" # Redact generic and signal-specific client keys # Matches: OTEL_EXPORTER_OTLP_CLIENT_KEY, # OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY, etc. elif "CLIENT_KEY" in key and "OTLP" in key: redacted[key] = "[REDACTED]" # Redact the HMAC secret used to anonymize span attributes elif key == constants.OTEL_ANONYMIZATION_SECRET_ENV_VAR: redacted[key] = "[REDACTED]" else: redacted[key] = val return redacted @staticmethod def _redact_header_values(header_string: str) -> str: """Redact header values while preserving key names. OTEL headers format: "key1=value1,key2=value2" Result: "key1=[REDACTED],key2=[REDACTED]" Parameters: ---------- header_string: Comma-separated key=value pairs Returns: Header string with values redacted but keys preserved """ if not header_string or "=" not in header_string: # No key=value pairs found, redact entire string return "[REDACTED]" redacted_pairs = [] for pair in header_string.split(","): pair = pair.strip() if "=" in pair: key_part = pair.split("=", 1)[0] redacted_pairs.append(f"{key_part}=[REDACTED]") else: # Malformed pair without =, redact entirely redacted_pairs.append("[REDACTED]") return ",".join(redacted_pairs) @classmethod def from_environment(cls) -> "ObservabilityConfiguration": """Collect all OTEL_* environment variables from the environment. Sensitive variables (headers, certificates, keys) are automatically redacted by the field validator. Returns: ObservabilityConfiguration with otel dict populated from environment. """ otel_vars = {} for key, value in os.environ.items(): if key.startswith("OTEL_"): otel_vars[key] = value return cls(otel=otel_vars) class QuestionValidityShieldConfiguration(ConfigurationBase): """Configuration for a named question-validity guardrail shield. Attributes: name: Unique, user-facing name identifying this shield instance. provider_id: Discriminator identifying this as a question-validity shield. config: Question-validity-specific configuration. """ name: str = Field( ..., title="Shield name", description="Unique, user-facing name identifying this shield instance.", ) provider_id: Literal["question_validity"] = Field( ..., title="Shield provider id", description="Discriminator identifying this as a question-validity shield.", ) config: QuestionValidityConfig = Field( ..., title="Shield configuration", description="Question-validity-specific configuration for this shield.", ) class RedactionShieldConfiguration(ConfigurationBase): """Configuration for a named PII-redaction guardrail shield. Attributes: name: Unique, user-facing name identifying this shield instance. provider_id: Discriminator identifying this as a redaction shield. config: Redaction-specific configuration. """ name: str = Field( ..., title="Shield name", description="Unique, user-facing name identifying this shield instance.", ) provider_id: Literal["redaction"] = Field( ..., title="Shield provider id", description="Discriminator identifying this as a redaction shield.", ) config: RedactionConfig = Field( ..., title="Shield configuration", description="Redaction-specific configuration for this shield.", ) class RiskDefinition(ConfigurationBase): """ Definition for a custom risk category. Custom risks allow applications to add use-case-specific safety checks beyond the standard harm, jailbreak, leetspeak, amnesia, and history_politics checks. Example: liability_risk = RiskDefinition( name="liability", description="Content requesting legal, medical, or financial advice", threshold=0.55, points=["input"], ) pii_risk = RiskDefinition( name="pii_request", description="User is asking the AI to reveal personal information", threshold=0.50, points=["input", "tool"], ) Note: To enable think mode (detailed reasoning) for a risk, add the risk name to the `thinking_enabled` list in `ModerationConfig`. Do not set `enable_thinking` directly - it is managed internally. """ name: str = Field( ..., title="Risk name", description="Unique identifier for this risk (e.g., 'liability', 'competitor_mention')", ) description: str = Field( ..., title="Rist description", description="Risk definition text passed to Granite Guardian as custom_criteria", ) threshold: float = Field( default=0.65, ge=0.0, le=1.0, title="Risk threshold", description="Score threshold for flagging (lower = more sensitive)", ) enabled: bool = Field( default=True, title="Risk enabled", description="Whether to run this check" ) enable_thinking: bool = Field( default=False, title="Risk enable thinking", description=( "Internal field - set via ModerationConfig.thinking_enabled list, " "not directly. When True, Granite Guardian provides detailed " "reasoning before scoring." ), ) points: list[Literal["input", "output", "tool"]] = Field( ..., min_length=1, title="Guardrail points", description=( "Where this risk is evaluated: `input` (user message), " "`output` (model response), or `tool` (tool/MCP content)." ), ) violation_message: str = Field( ..., title="Violation message", description="Message to be displayed when this risk is violated", ) class GraniteGuardianConfig(ConfigurationBase): """Configuration for the Granite Guardian moderation guardrail.""" url: str = Field( ..., title="Base URL", description="Base URL of the OpenAI-compatible inference endpoint.", ) model_id: str = Field( "ibm-granite/granite-guardian-4.1-8b", title="Model name", description=( "Model name sent to the inference server. Override when the " "server registers the model under a different name (e.g. an " "Ollama tag). The prompt template is built for the 4.1 format." ), ) api_key: Optional[SecretStr] = Field( None, title="Granite Guardian API key", description="API key for the inference" ) max_retries: PositiveInt = Field( 2, ge=0, le=5, title="Max retries", description="Maximun number of retries" ) timeout: PositiveInt = Field( 30, ge=5, le=300, title="Timeout", description="Request timeout in seconds" ) verify_ssl: bool | str = Field( True, title="Verify SSL", description=( "SSL certificate verification. Can be:\n" " - True: Verify using system CA bundle (default, recommended)\n" " - False: Disable verification (insecure, for dev only)\n" " - str: Path to custom CA bundle file (for internal PKI)" ), ) parallel: StrictBool | Annotated[int, Field(ge=1, le=10)] = Field( default=3, title="Parallel execution", description=( "True to run all risk checks in parallel, " "False to run sequentially, " "or an integer 1-10 for explicit batch size." ), ) risks: list[RiskDefinition] = Field( ..., title="Defined risks", description="Risks to be considered while applying this guardrail", ) streaming_output_check_interval_tokens: PositiveInt = Field( default=50, title="Streaming output check interval (tokens)", description=( "For risks with `output` in `points`, re-check the response " "against those risks approximately every N generated output " "tokens while streaming, plus once more over any remaining " "text once generation completes. Ignored when no configured " "risk targets the `output` point." ), ) @model_validator(mode="after") def validate_api_key_requires_https(self) -> Self: """Require HTTPS when an API key is configured. Prevents the API key from being sent to the inference endpoint over an unencrypted connection. Raises: ValueError: If ``api_key`` is set but ``url``'s scheme isn't https. Returns: The validated configuration instance. """ # pylint: disable=no-member if self.api_key is not None and not self.url.startswith("https://"): raise ValueError( "Granite Guardian endpoints with an API key must use HTTPS" ) return self class GraniteGuardianShieldConfiguration(ConfigurationBase): """Configuration for a named Granite Guardian guardrail shield. Attributes: name: Unique, user-facing name identifying this shield instance. provider_id: Discriminator identifying this as a granite-guardian shield. config: Granite-guardian-specific configuration. """ name: str = Field( ..., title="Shield name", description="Unique, user-facing name identifying this shield instance.", ) provider_id: Literal["granite_guardian"] = Field( ..., title="Shield provider id", description="Discriminator identifying this as a granite-guardian shield.", ) config: GraniteGuardianConfig = Field( ..., title="Shield configuration", description="Granite-guardian-specific configuration for this shield", ) ShieldConfiguration = Annotated[ QuestionValidityShieldConfiguration | RedactionShieldConfiguration | GraniteGuardianShieldConfiguration, Field(discriminator="provider_id"), ] """Configuration for a single named guardrail shield (question validity or redaction). A discriminated union on ``provider_id``: Pydantic selects ``QuestionValidityShieldConfiguration`` or ``RedactionShieldConfiguration`` and validates ``config`` against the matching model. """ class Configuration(ConfigurationBase): """Global service configuration.""" @model_validator(mode="before") @classmethod def accept_llama_stack_section_alias(cls, data: Any) -> Any: """Map deprecated ``llama_stack`` YAML key to ``ogx``. Parameters: data: Raw configuration mapping from YAML/JSON. Returns: Normalized mapping with the OGX section under ``ogx``. """ if not isinstance(data, dict): return data if data.get("ogx") is not None: return data llama_stack = data.get("llama_stack") if llama_stack is None: return data logger.warning( "The 'llama_stack' configuration key is deprecated and will be " "removed in a future release; use 'ogx' instead." ) data = dict(data) data["ogx"] = llama_stack data.pop("llama_stack") return data name: str = Field( ..., title="Service name", description="Name of the service. That value will be used in REST API endpoints.", ) config_format_version: Optional[Literal["legacy", "unified"]] = Field( None, title="Configuration format version", description="Optional explicit marker of the configuration format. " "When set, it must agree with the shape detected from the " "configuration body: 'unified' requires a synthesis input (a " "non-empty inference.providers, a non-empty vector_store.providers, " "or an ogx.config block), 'legacy' requires no synthesis " "input. Reserved as the lever for a future breaking change of the " "unified schema (R11).", ) service: ServiceConfiguration = Field( ..., title="Service configuration", description="This section contains Lightspeed Core Stack service configuration.", ) ogx: OgxConfiguration = Field( ..., title="OGX configuration", description="This section contains OGX configuration. Lightspeed Core Stack service can " "call OGX in library mode or in server mode.", ) user_data_collection: UserDataCollection = Field( ..., title="User data collection configuration", description="This section contains configuration for subsystem that collects user data" "(transcription history and feedbacks).", ) database: DatabaseConfiguration = Field( default_factory=lambda: DatabaseConfiguration(sqlite=None, postgres=None), title="Database Configuration", description="Configuration for database to store conversation IDs and other runtime data", ) mcp_servers: list[ModelContextProtocolServer] = Field( default_factory=list, title="Model Context Protocol Server and tools configuration", description="MCP (Model Context Protocol) servers provide tools and capabilities " "to the AI agents. These are configured in this " "section. Only MCP servers defined in the lightspeed-stack.yaml configuration " "are available to the agents. Tools configured in the " "OGX run.yaml are not accessible to lightspeed-core agents.", ) authentication: AuthenticationConfiguration = Field( default_factory=lambda: AuthenticationConfiguration( skip_for_health_probes=False, skip_for_metrics=False, ), title="Authentication configuration", description="Authentication configuration", ) authorization: Optional[AuthorizationConfiguration] = Field( None, title="Authorization configuration", description="Lightspeed Core Stack implements a modular " "authentication and authorization system with multiple authentication " "methods. Authorization is configurable through role-based access " "control. Authentication is handled through selectable modules " "configured via the module field in the authentication configuration.", ) customization: Optional[Customization] = Field( None, title="Custom profile configuration", description="It is possible to customize Lightspeed Core Stack via this " "section. System prompt can be customized and also different parts of " "the service can be replaced by custom Python modules.", ) inference: InferenceConfiguration = Field( default_factory=lambda: InferenceConfiguration( default_model=None, default_provider=None ), title="Inference configuration", description="One LLM provider and one its model might be selected as " "default ones. When no provider+model pair is specified in REST API " "calls (query endpoints), the default provider and model are used.", ) conversation_cache: ConversationHistoryConfiguration = Field( default_factory=lambda: ConversationHistoryConfiguration( type=None, memory=None, sqlite=None, postgres=None ), title="Conversation history configuration", description="Conversation history configuration.", ) agent_step_persistence: AgentStepPersistenceConfiguration = Field( default_factory=AgentStepPersistenceNoopConfiguration, title="Agent step persistence", description="Pydantic AI harness StepPersistence storage for agent run history.", ) compaction: CompactionConfiguration = Field( default_factory=lambda: CompactionConfiguration( enabled=False, threshold_ratio=0.7, token_floor=4096, buffer_turns=4, buffer_max_ratio=0.3, ), title="Conversation compaction configuration", description="Controls when conversation history is summarized " "to keep the model's input below the context window limit. " "Disabled by default — when disabled, requests that exceed the " "window continue to surface as HTTP 413.", ) approvals: ApprovalsConfiguration = Field( default_factory=ApprovalsConfiguration, title="Approvals configuration", description="Settings for human-in-the-loop approval of MCP tool invocations", ) vector_store: VectorStoreConfiguration = Field( default_factory=lambda: VectorStoreConfiguration( default_provider=None, providers=[] ), title="Vector store configuration", description=( "Dynamic vector-store provider capacity for runtime " "POST /v1/vector-stores creates. " "Not the same as rag.byok.stores (static registered corpora). " "When providers is non-empty, default_provider is required and " "must match one of providers[].id. Applied in unified synthesis " "only." ), ) a2a_state: A2AStateConfiguration = Field( default_factory=A2AStateConfiguration, title="A2A state configuration", description="Configuration for A2A protocol persistent state storage.", ) quota_handlers: QuotaHandlersConfiguration = Field( default_factory=lambda: QuotaHandlersConfiguration( sqlite=None, postgres=None, enable_token_history=False ), title="Quota handlers", description="Quota handlers configuration", ) azure_entra_id: Optional[AzureEntraIdConfiguration] = Field( default=None, description="Legacy Microsoft Entra ID settings for Azure OpenAI authentication.", ) rlsapi_v1: RlsapiV1Configuration = Field( default_factory=RlsapiV1Configuration, title="rlsapi v1 configuration", description="Configuration for the rlsapi v1 /infer endpoint used by " "the RHEL Lightspeed Command Line Assistant (CLA).", ) splunk: Optional[SplunkConfiguration] = Field( default=None, title="Splunk configuration", description="Splunk HEC configuration for sending telemetry events.", ) observability: ObservabilityConfiguration = Field( default_factory=ObservabilityConfiguration.from_environment, title="Observability configuration", description="OpenTelemetry and observability configuration collected " "from OTEL_* environment variables.", ) deployment_environment: str = Field( "development", title="Deployment environment", description="Deployment environment name (e.g., 'development', 'staging', 'production'). " "Used in telemetry events.", ) rag: RagConfiguration = Field( default_factory=RagConfiguration, title="RAG configuration", description="Unified RAG configuration: BYOK stores, OKP provider, " "and retrieval strategies (inline and tool-based).", ) skills: Optional[SkillsConfiguration] = Field( default=None, title="Agent skills", description="Agent skills configuration. Specifies paths to skill directories.", ) saved_prompts: SavedPromptsConfiguration = Field( default_factory=SavedPromptsConfiguration, title="Saved prompts configuration", description="Configuration for saved prompts feature limits including " "maximum prompts per user, display name length, and content length.", ) shields: list[ShieldConfiguration] = Field( default_factory=list, title="Shields configuration", description="List of pydantic-ai-lightspeed agent guardrail shields " "(question validity and PII redaction). Each entry has a unique " "'name', a 'provider_id' ('question_validity' or 'redaction'), " "and a type-specific 'config'.", ) @model_validator(mode="after") def validate_shield_names_unique(self) -> Self: """Reject shields lists containing duplicate names. Returns: Self: The model instance after validation. Raises: ValueError: If two or more shields share the same name. """ names = [shield.name for shield in self.shields] duplicates = {name for name in names if names.count(name) > 1} if duplicates: raise ValueError( f"Shield names must be unique, found duplicates: {sorted(duplicates)}" ) return self @model_validator(mode="after") def validate_mcp_auth_headers(self) -> Self: """ Validate MCP server authorization headers against authentication module. Removes any MCP server with authorization_headers="kubernetes" when the authentication module is not "k8s" or "noop-with-token". This prevents sending wrong credential types to MCP servers. Note: "noop-with-token" should only be used for testing/development purposes. When using "noop-with-token" with kubernetes authorization headers, a real Kubernetes token must still be passed in the request headers. Returns: Self: The model instance after validation. """ # Get authentication module value auth_module = getattr(self.authentication, "module", None) # Filter out misconfigured MCP servers valid_mcp_servers = [] for mcp_server in self.mcp_servers: is_valid = True if mcp_server.authorization_headers: for value in mcp_server.authorization_headers.values(): if ( value.strip() == constants.MCP_AUTH_KUBERNETES and auth_module not in [ constants.AUTH_MOD_K8S, constants.AUTH_MOD_NOOP_WITH_TOKEN, ] ): logger.warning( "Removing MCP server '%s': has authorization_headers with " "value '%s' but authentication module is '%s' " "(not '%s' or '%s'). Either change authentication.module to " "'%s' or '%s' or update the MCP server's authorization_headers " "to use a file path or '%s'.", mcp_server.name, constants.MCP_AUTH_KUBERNETES, auth_module, constants.AUTH_MOD_K8S, constants.AUTH_MOD_NOOP_WITH_TOKEN, constants.AUTH_MOD_K8S, constants.AUTH_MOD_NOOP_WITH_TOKEN, constants.MCP_AUTH_CLIENT, ) is_valid = False break if is_valid: valid_mcp_servers.append(mcp_server) self.mcp_servers = valid_mcp_servers return self @model_validator(mode="after") def validate_rlsapi_v1_quota_configuration(self) -> Self: """Validate rlsapi_v1 quota settings against authentication and quota handlers. Enforces that quota_subject values requiring rh-identity data ("org_id", "system_id") are only used when rh-identity authentication is active. Warns when quota_subject is set but quota enforcement is not fully configured (missing limiters or missing storage backend). Returns: Self: The validated configuration instance. Raises: ValueError: If quota_subject requires rh-identity but a different authentication module is configured. """ quota_subject = self.rlsapi_v1.quota_subject # pylint: disable=no-member if quota_subject is None: return self auth_module = self.authentication.module # pylint: disable=no-member if quota_subject in ("org_id", "system_id") and ( auth_module != constants.AUTH_MOD_RH_IDENTITY ): raise ValueError( f"rlsapi_v1.quota_subject='{quota_subject}' requires " f"authentication.module='{constants.AUTH_MOD_RH_IDENTITY}', " f"but got '{auth_module}'. Use quota_subject='user_id' or " f"switch authentication to '{constants.AUTH_MOD_RH_IDENTITY}'." ) if not self.quota_handlers.limiters or ( # pylint: disable=no-member self.quota_handlers.sqlite is None # pylint: disable=no-member and self.quota_handlers.postgres is None # pylint: disable=no-member ): logger.warning( "rlsapi_v1.quota_subject is '%s' but quota enforcement is not " "fully configured. Token quota enforcement will not take effect " "until at least one limiter and one quota storage backend " "are configured.", quota_subject, ) return self @model_validator(mode="after") def check_unified_vs_legacy(self) -> Self: """Reconcile unified synthesis inputs, legacy mode, and library-mode needs. Unified-mode *synthesis inputs* span the configuration root: a non-empty top-level ``inference.providers`` (Decision S5), a non-empty ``vector_store.providers``, and/or an ``ogx.config`` block. The legacy path is ``ogx.library_client_config_path`` pointing at an external run.yaml. Both checks live here on the root model rather than on ``OgxConfiguration`` (which cannot see root-level provider lists): - A synthesis input and the legacy path are mutually exclusive — a single file must pick one shape. - Library mode needs *some* run source — a synthesis input or the legacy path. ``inference.providers`` or ``vector_store.providers`` alone is sufficient; no ``ogx.config`` block is required. - An explicit ``config_format_version``, when set, must agree with the detected shape (R11): ``unified`` requires a synthesis input, ``legacy`` requires its absence (remote-only configs count as legacy-compatible). Returns: Self: The validated configuration instance. Raises: ValueError: If a synthesis input and the legacy ``library_client_config_path`` are set together, if library mode has no run source at all, or if ``config_format_version`` contradicts the detected shape. """ # pylint: disable=no-member synthesis_input = ( bool(self.inference.providers) or bool(self.vector_store.providers) or self.ogx.config is not None ) legacy_input = self.ogx.library_client_config_path is not None if synthesis_input and legacy_input: raise ValueError( "OGX configuration is ambiguous: unified synthesis " "inputs (a non-empty inference.providers, a non-empty " "vector_store.providers, or an ogx.config block) are " "mutually exclusive with the legacy " "ogx.library_client_config_path. Use one or the other. " "To convert a legacy two-file setup to unified mode, run " "`lightspeed-stack --migrate-config`." ) if self.ogx.use_as_library_client and not synthesis_input and not legacy_input: raise ValueError( "OGX library mode requires a run-configuration source: " "set a non-empty inference.providers, a non-empty " "vector_store.providers, an ogx.config block, or " "library_client_config_path." ) if self.config_format_version is not None: detected = "unified" if synthesis_input else "legacy" if self.config_format_version != detected: raise ValueError( f"config_format_version is '{self.config_format_version}' " f"but the configuration body is {detected}-shaped: a " "unified configuration carries a synthesis input (a " "non-empty inference.providers, a non-empty " "vector_store.providers, or an ogx.config block), " "a legacy one does not. Fix config_format_version or the " "configuration body." ) return self def dump(self, filename: str | Path = "configuration.json") -> None: """ Write the current Configuration model to a JSON file. The configuration is serialized with an indentation of 4 spaces using the model's JSON representation and written with UTF-8 encoding. If the file exists it will be overwritten. Parameters: ---------- filename (str | Path): Path to the output file (defaults to "configuration.json"). """ with open(filename, "w", encoding="utf-8") as fout: fout.write(self.model_dump_json(indent=4))