Configuration API Reference
Configuration API Reference
The Klira AI SDK provides centralized configuration management with validation, environment variable parsing, and sensible defaults through the KliraConfig class and related utilities.
Overview
from klira.sdk.config import KliraConfig, get_config, set_config, reset_config
# Create configuration from environmentconfig = KliraConfig.from_env()
# Validate configurationerrors = config.validate()if errors: print(f"Configuration errors: {errors}")
# Set as global configurationset_config(config)KliraConfig Class
Class Definition
@dataclassclass KliraConfig: """Centralized configuration for the Klira AI SDK."""
# Core settings app_name: str = "KliraApp" api_key: Optional[str] = field(default_factory=lambda: os.getenv("KLIRA_API_KEY"))
# OpenTelemetry settings opentelemetry_endpoint: Optional[str] = field(default_factory=lambda: os.getenv("KLIRA_OPENTELEMETRY_ENDPOINT")) tracing_enabled: bool = field(default_factory=lambda: os.getenv("KLIRA_TRACING_ENABLED", "true").lower() == "true") trace_content: bool = field(default_factory=lambda: os.getenv("KLIRA_TRACE_CONTENT", "true").lower() == "true") metrics_enabled: bool = field(default_factory=lambda: os.getenv("KLIRA_METRICS_ENABLED", "true").lower() == "true")
# Logging settings logging_enabled: bool = field(default_factory=lambda: os.getenv("KLIRA_LOGGING_ENABLED", "false").lower() == "true")
# Guardrails settings policies_path: Optional[str] = field(default=None) policy_enforcement: bool = field(default_factory=lambda: os.getenv("KLIRA_POLICY_ENFORCEMENT", "true").lower() == "true")
# Telemetry settings telemetry_enabled: bool = field(default_factory=lambda: os.getenv("KLIRA_TELEMETRY", "false").lower() == "true")
# Performance settings lazy_loading: bool = field(default_factory=lambda: os.getenv("KLIRA_LAZY_LOADING", "true").lower() == "true") framework_detection_cache_size: int = field(default_factory=lambda: int(os.getenv("KLIRA_FRAMEWORK_CACHE_SIZE", "1000")))
# Debug settings debug_mode: bool = field(default_factory=lambda: os.getenv("KLIRA_DEBUG", "false").lower() == "true") verbose: bool = field(default_factory=lambda: os.getenv("KLIRA_VERBOSE", "false").lower() == "true")Configuration Fields
Core Settings
| Field | Type | Default | Environment Variable | Description |
|---|---|---|---|---|
app_name | str | "KliraApp" | - | Application name for identification |
api_key | Optional[str] | None | KLIRA_API_KEY | Klira AI API key for authentication |
OpenTelemetry Settings
| Field | Type | Default | Environment Variable | Description |
|---|---|---|---|---|
opentelemetry_endpoint | Optional[str] | None | KLIRA_OPENTELEMETRY_ENDPOINT | Custom OTLP endpoint |
tracing_enabled | bool | True | KLIRA_TRACING_ENABLED | Enable/disable distributed tracing |
trace_content | bool | True | KLIRA_TRACE_CONTENT | Include content in traces |
metrics_enabled | bool | True | KLIRA_METRICS_ENABLED | Enable/disable metrics collection |
Guardrails Settings
| Field | Type | Default | Environment Variable | Description |
|---|---|---|---|---|
policies_path | Optional[str] | Auto-detected | KLIRA_POLICIES_PATH | Path to custom policies directory |
policy_enforcement | bool | True | KLIRA_POLICY_ENFORCEMENT | Enable/disable policy enforcement |
Performance Settings
| Field | Type | Default | Environment Variable | Description |
|---|---|---|---|---|
lazy_loading | bool | True | KLIRA_LAZY_LOADING | Enable lazy component loading |
framework_detection_cache_size | int | 1000 | KLIRA_FRAMEWORK_CACHE_SIZE | Cache size for framework detection |
Debug Settings
| Field | Type | Default | Environment Variable | Description |
|---|---|---|---|---|
debug_mode | bool | False | KLIRA_DEBUG | Enable debug mode |
verbose | bool | False | KLIRA_VERBOSE | Enable verbose logging |
logging_enabled | bool | False | KLIRA_LOGGING_ENABLED | Enable SDK internal logging |
telemetry_enabled | bool | False | KLIRA_TELEMETRY | Enable anonymous telemetry |
Class Methods
validate()
Validate configuration and return list of errors.
def validate(self) -> List[str]Returns
List[str]: List of validation error messages. Empty if valid.
Validation Rules
- API Key Format: Must start with
"klira_"if provided - Endpoint URL: Must be valid HTTP/HTTPS URL if provided
- Policies Path: Must exist if specified
- Cache Size: Must be non-negative
- App Name: Cannot be empty
Example
config = KliraConfig( app_name="MyApp", api_key="invalid-key", opentelemetry_endpoint="not-a-url", framework_detection_cache_size=-1)
errors = config.validate()print(errors)# Output: [# "API key must start with 'klira_'",# "OpenTelemetry endpoint must be a valid HTTP/HTTPS URL",# "Framework detection cache size must be non-negative"# ]is_valid()
Check if configuration is valid.
def is_valid(self) -> boolReturns
bool: True if configuration is valid, False otherwise
Example
config = KliraConfig.from_env()if config.is_valid(): print("Configuration is valid")else: print("Configuration has errors:") for error in config.validate(): print(f" - {error}")to_dict()
Convert configuration to dictionary (with sensitive data masked).
def to_dict(self) -> Dict[str, Any]Returns
Dict[str, Any]: Configuration as dictionary with API key masked
Example
config = KliraConfig(api_key="klira_live_secret123")config_dict = config.to_dict()print(config_dict["api_key"]) # Output: "***"from_dict()
Create configuration from dictionary.
@classmethoddef from_dict(cls, config_dict: Dict[str, Any]) -> "KliraConfig"Parameters
| Parameter | Type | Description |
|---|---|---|
config_dict | Dict[str, Any] | Configuration dictionary |
Returns
KliraConfig: Configuration instance
Example
config_dict = { "app_name": "ProductionApp", "api_key": "klira_live_key123", "tracing_enabled": True, "debug_mode": False}
config = KliraConfig.from_dict(config_dict)print(config.app_name) # Output: "ProductionApp"from_env()
Create configuration from environment variables with optional overrides.
@classmethoddef from_env(cls, **overrides: Any) -> "KliraConfig"Parameters
| Parameter | Type | Description |
|---|---|---|
**overrides | Any | Override values for specific configuration fields |
Returns
KliraConfig: Configuration instance
Example
# Create from environment with overridesconfig = KliraConfig.from_env( app_name="CustomApp", debug_mode=True)
# Environment variables are read automatically# KLIRA_API_KEY, KLIRA_TRACING_ENABLED, etc.Global Configuration Management
get_config()
Get the current global configuration.
def get_config() -> KliraConfigReturns
KliraConfig: Current global configuration instance
Raises
Exception: If no configuration has been set
Example
from klira.sdk.config import get_config
try: config = get_config() print(f"App name: {config.app_name}")except Exception: print("No configuration set")set_config()
Set the global configuration.
def set_config(config: KliraConfig) -> NoneParameters
| Parameter | Type | Description |
|---|---|---|
config | KliraConfig | Configuration instance to set globally |
Example
from klira.sdk.config import set_config, KliraConfig
# Create and set configurationconfig = KliraConfig( app_name="GlobalApp", api_key="klira_live_key123")set_config(config)reset_config()
Reset the global configuration (clears current config).
def reset_config() -> NoneExample
from klira.sdk.config import reset_config
# Clear global configurationreset_config()Utility Functions
get_policies_path()
Get the policies path with automatic detection.
def get_policies_path() -> strReturns
str: Path to policies directory
Path Resolution
KLIRA_POLICIES_PATHenvironment variable./policiesdirectory if it exists./klira_policiesdirectory if it exists- SDK default policies
Example
from klira.sdk.config import get_policies_path
policies_path = get_policies_path()print(f"Using policies from: {policies_path}")get_api_key()
Get the Klira AI API key from global configuration.
def get_api_key() -> Optional[str]Returns
Optional[str]: API key if available, None otherwise
Example
from klira.sdk.config import get_api_key
api_key = get_api_key()if api_key: print("API key is configured")else: print("No API key found")Environment Variable Reference
Complete Environment Variables List
# Core Configurationexport KLIRA_API_KEY="klira_live_your_key_here"
# OpenTelemetry Configurationexport KLIRA_OPENTELEMETRY_ENDPOINT="https://custom-otlp.company.com"export KLIRA_TRACING_ENABLED="true"export KLIRA_TRACE_CONTENT="false" # Disable for privacyexport KLIRA_METRICS_ENABLED="true"
# Guardrails Configurationexport KLIRA_POLICIES_PATH="/app/custom-policies"export KLIRA_POLICY_ENFORCEMENT="true"
# Performance Configurationexport KLIRA_LAZY_LOADING="true"export KLIRA_FRAMEWORK_CACHE_SIZE="5000"
# Debug Configurationexport KLIRA_DEBUG="false"export KLIRA_VERBOSE="false"export KLIRA_LOGGING_ENABLED="false"export KLIRA_TELEMETRY="false"Environment-Specific Examples
Development Environment
# development.envexport KLIRA_API_KEY="klira_dev_your_key_here"export KLIRA_DEBUG="true"export KLIRA_VERBOSE="true"export KLIRA_TRACE_CONTENT="true"export KLIRA_POLICIES_PATH="./dev-policies"Staging Environment
# staging.envexport KLIRA_API_KEY="klira_staging_your_key_here"export KLIRA_DEBUG="false"export KLIRA_VERBOSE="false"export KLIRA_TRACE_CONTENT="false"export KLIRA_FRAMEWORK_CACHE_SIZE="3000"Production Environment
# production.envexport KLIRA_API_KEY="klira_prod_your_key_here"export KLIRA_DEBUG="false"export KLIRA_VERBOSE="false"export KLIRA_LOGGING_ENABLED="false"export KLIRA_TRACE_CONTENT="false"export KLIRA_TELEMETRY="false"export KLIRA_FRAMEWORK_CACHE_SIZE="10000"export KLIRA_POLICIES_PATH="/app/policies"Configuration Patterns
Environment-Based Configuration
import osfrom klira.sdk.config import KliraConfig, set_config
def setup_config(): """Setup configuration based on environment.""" env = os.getenv("ENVIRONMENT", "development")
if env == "production": config = KliraConfig.from_env( debug_mode=False, verbose=False, trace_content=False, telemetry_enabled=False ) elif env == "staging": config = KliraConfig.from_env( debug_mode=False, verbose=False, trace_content=False ) else: # development config = KliraConfig.from_env( debug_mode=True, verbose=True, trace_content=True )
# Validate and set errors = config.validate() if errors: raise ValueError(f"Configuration errors: {errors}")
set_config(config) return configConfiguration Validation
from klira.sdk.config import KliraConfig
def validate_production_config(config: KliraConfig) -> List[str]: """Validate production-specific requirements.""" errors = config.validate() # Base validation
# Additional production checks if not config.api_key: errors.append("API key is required in production")
if config.debug_mode: errors.append("Debug mode must be disabled in production")
if config.trace_content: errors.append("Content tracing should be disabled in production for privacy")
if config.framework_detection_cache_size < 5000: errors.append("Cache size should be >= 5000 in production")
return errors
# Usageconfig = KliraConfig.from_env()prod_errors = validate_production_config(config)if prod_errors: print("Production validation failed:") for error in prod_errors: print(f" - {error}")Configuration Templates
from klira.sdk.config import KliraConfig
class ConfigTemplates: """Predefined configuration templates."""
@staticmethod def development() -> KliraConfig: """Development configuration template.""" return KliraConfig( app_name="MyApp-Dev", debug_mode=True, verbose=True, trace_content=True, framework_detection_cache_size=1000, policies_path="./dev-policies" )
@staticmethod def production() -> KliraConfig: """Production configuration template.""" return KliraConfig( app_name="MyApp-Prod", debug_mode=False, verbose=False, trace_content=False, telemetry_enabled=False, framework_detection_cache_size=10000, policies_path="/app/policies" )
@staticmethod def testing() -> KliraConfig: """Testing configuration template.""" return KliraConfig( app_name="MyApp-Test", tracing_enabled=False, policy_enforcement=False, debug_mode=True )
# Usageconfig = ConfigTemplates.production()config.api_key = os.getenv("KLIRA_API_KEY")set_config(config)Configuration Monitoring
Runtime Configuration Changes
from klira.sdk.config import get_config, set_config
def update_config(**changes): """Update configuration at runtime.""" current_config = get_config()
# Create new config with changes new_config = KliraConfig.from_dict({ **current_config.to_dict(), **changes })
# Validate before applying errors = new_config.validate() if errors: raise ValueError(f"Invalid configuration changes: {errors}")
set_config(new_config) return new_config
# Usageupdate_config( debug_mode=True, verbose=True)Configuration Logging
import loggingfrom klira.sdk.config import get_config
def log_configuration(): """Log current configuration (safely).""" config = get_config() config_dict = config.to_dict()
logger = logging.getLogger("klira.config") logger.info("Current Klira AI SDK configuration:") for key, value in config_dict.items(): logger.info(f" {key}: {value}")
# Usagelog_configuration()Best Practices
1. Environment Variable Management
# Good - use environment variablesconfig = KliraConfig.from_env()
# Avoid - hardcoded secretsconfig = KliraConfig(api_key="klira_live_secret123") # Don't do this!2. Configuration Validation
def safe_config_setup(): """Setup configuration with proper validation.""" try: config = KliraConfig.from_env()
# Validate configuration errors = config.validate() if errors: print("Configuration errors found:") for error in errors: print(f" - {error}") return None
# Set as global configuration set_config(config) print(" Configuration loaded successfully") return config
except Exception as e: print(f"â Failed to load configuration: {e}") return None3. Environment-Specific Settings
import os
def create_environment_config(): """Create configuration based on deployment environment.""" env = os.getenv("DEPLOYMENT_ENV", "development")
base_config = KliraConfig.from_env()
if env == "production": # Production-specific overrides base_config.debug_mode = False base_config.verbose = False base_config.trace_content = False base_config.telemetry_enabled = False
elif env == "staging": # Staging-specific overrides base_config.debug_mode = False base_config.verbose = False
# Development uses defaults
return base_config4. Configuration Documentation
def print_config_help(): """Print help for configuration options.""" print(""" Klira AI SDK Configuration Environment Variables:
Core Settings: KLIRA_API_KEY - Your Klira AI API key (required)
OpenTelemetry Settings: KLIRA_OPENTELEMETRY_ENDPOINT - Custom OTLP endpoint (optional) KLIRA_TRACING_ENABLED - Enable tracing (default: true) KLIRA_TRACE_CONTENT - Include content in traces (default: true)
Guardrails Settings: KLIRA_POLICIES_PATH - Custom policies directory (optional) KLIRA_POLICY_ENFORCEMENT - Enable policy enforcement (default: true)
Performance Settings: KLIRA_FRAMEWORK_CACHE_SIZE - Framework detection cache size (default: 1000)
Debug Settings: KLIRA_DEBUG - Enable debug mode (default: false) KLIRA_VERBOSE - Enable verbose logging (default: false) """)Related APIs
- Klira AI Class API - SDK initialization using configuration
- GuardrailsEngine API - Policy enforcement configuration
- Types API - Configuration type definitions