Skip to content

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 environment
config = KliraConfig.from_env()
# Validate configuration
errors = config.validate()
if errors:
print(f"Configuration errors: {errors}")
# Set as global configuration
set_config(config)

KliraConfig Class

Class Definition

@dataclass
class 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

FieldTypeDefaultEnvironment VariableDescription
app_namestr"KliraApp"-Application name for identification
api_keyOptional[str]NoneKLIRA_API_KEYKlira AI API key for authentication

OpenTelemetry Settings

FieldTypeDefaultEnvironment VariableDescription
opentelemetry_endpointOptional[str]NoneKLIRA_OPENTELEMETRY_ENDPOINTCustom OTLP endpoint
tracing_enabledboolTrueKLIRA_TRACING_ENABLEDEnable/disable distributed tracing
trace_contentboolTrueKLIRA_TRACE_CONTENTInclude content in traces
metrics_enabledboolTrueKLIRA_METRICS_ENABLEDEnable/disable metrics collection

Guardrails Settings

FieldTypeDefaultEnvironment VariableDescription
policies_pathOptional[str]Auto-detectedKLIRA_POLICIES_PATHPath to custom policies directory
policy_enforcementboolTrueKLIRA_POLICY_ENFORCEMENTEnable/disable policy enforcement

Performance Settings

FieldTypeDefaultEnvironment VariableDescription
lazy_loadingboolTrueKLIRA_LAZY_LOADINGEnable lazy component loading
framework_detection_cache_sizeint1000KLIRA_FRAMEWORK_CACHE_SIZECache size for framework detection

Debug Settings

FieldTypeDefaultEnvironment VariableDescription
debug_modeboolFalseKLIRA_DEBUGEnable debug mode
verboseboolFalseKLIRA_VERBOSEEnable verbose logging
logging_enabledboolFalseKLIRA_LOGGING_ENABLEDEnable SDK internal logging
telemetry_enabledboolFalseKLIRA_TELEMETRYEnable 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) -> bool

Returns

  • 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.

@classmethod
def from_dict(cls, config_dict: Dict[str, Any]) -> "KliraConfig"

Parameters

ParameterTypeDescription
config_dictDict[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.

@classmethod
def from_env(cls, **overrides: Any) -> "KliraConfig"

Parameters

ParameterTypeDescription
**overridesAnyOverride values for specific configuration fields

Returns

  • KliraConfig: Configuration instance

Example

# Create from environment with overrides
config = 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() -> KliraConfig

Returns

  • 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) -> None

Parameters

ParameterTypeDescription
configKliraConfigConfiguration instance to set globally

Example

from klira.sdk.config import set_config, KliraConfig
# Create and set configuration
config = KliraConfig(
app_name="GlobalApp",
api_key="klira_live_key123"
)
set_config(config)

reset_config()

Reset the global configuration (clears current config).

def reset_config() -> None

Example

from klira.sdk.config import reset_config
# Clear global configuration
reset_config()

Utility Functions

get_policies_path()

Get the policies path with automatic detection.

def get_policies_path() -> str

Returns

  • str: Path to policies directory

Path Resolution

  1. KLIRA_POLICIES_PATH environment variable
  2. ./policies directory if it exists
  3. ./klira_policies directory if it exists
  4. 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

Terminal window
# Core Configuration
export KLIRA_API_KEY="klira_live_your_key_here"
# OpenTelemetry Configuration
export KLIRA_OPENTELEMETRY_ENDPOINT="https://custom-otlp.company.com"
export KLIRA_TRACING_ENABLED="true"
export KLIRA_TRACE_CONTENT="false" # Disable for privacy
export KLIRA_METRICS_ENABLED="true"
# Guardrails Configuration
export KLIRA_POLICIES_PATH="/app/custom-policies"
export KLIRA_POLICY_ENFORCEMENT="true"
# Performance Configuration
export KLIRA_LAZY_LOADING="true"
export KLIRA_FRAMEWORK_CACHE_SIZE="5000"
# Debug Configuration
export KLIRA_DEBUG="false"
export KLIRA_VERBOSE="false"
export KLIRA_LOGGING_ENABLED="false"
export KLIRA_TELEMETRY="false"

Environment-Specific Examples

Development Environment

Terminal window
# development.env
export 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

Terminal window
# staging.env
export 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

Terminal window
# production.env
export 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 os
from 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 config

Configuration 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
# Usage
config = 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
)
# Usage
config = 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
# Usage
update_config(
debug_mode=True,
verbose=True
)

Configuration Logging

import logging
from 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}")
# Usage
log_configuration()

Best Practices

1. Environment Variable Management

# Good - use environment variables
config = KliraConfig.from_env()
# Avoid - hardcoded secrets
config = 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 None

3. 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_config

4. 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)
""")