Skip to content

Environment Variables Reference

Environment Variables Reference

Complete reference for all Klira AI SDK environment variables for production deployments.

Core Configuration

Required Variables

VariableDescriptionExampleRequired
KLIRA_API_KEYYour Klira AI API key for authenticationklira_prod_abc123...Yes

Application Settings

VariableDefaultDescriptionExample
KLIRA_APP_NAME"KliraApp"Application name for identification"MyApp-Production"

OpenTelemetry Configuration

Tracing Settings

VariableDefaultDescriptionExample
KLIRA_OPENTELEMETRY_ENDPOINTUses https://api.getklira.com when KLIRA_API_KEY is setCustom OTLP endpoint (overrides default)"https://otlp.company.com"
KLIRA_TRACING_ENABLED"true"Enable/disable distributed tracing"true"
KLIRA_TRACE_CONTENT"true"Include content in traces (disable for privacy)"false"
KLIRA_METRICS_ENABLED"true"Enable/disable metrics collection"true"

Note: When you set KLIRA_API_KEY, traces are automatically sent to https://api.getklira.com. Set KLIRA_OPENTELEMETRY_ENDPOINT only if you want to use a different endpoint.

Example Configuration

Terminal window
# Using Klira AI's default endpoint (recommended)
export KLIRA_API_KEY="klira_prod_your_key_here"
# Traces automatically sent to https://api.getklira.com
# Advanced: Disable content tracing for privacy
export KLIRA_TRACING_ENABLED="true"
export KLIRA_TRACE_CONTENT="false" # Privacy in production
export KLIRA_METRICS_ENABLED="true"

Note: To use a custom OTLP collector instead of Klira AI’s default endpoint:

Terminal window
export KLIRA_API_KEY="" # Clear API key when using custom endpoint
export KLIRA_OPENTELEMETRY_ENDPOINT="https://otel-collector.company.com:4317"

Performance Settings

Framework Detection

VariableDefaultDescriptionExample
KLIRA_LAZY_LOADING"true"Enable lazy loading of adapters"true"
KLIRA_FRAMEWORK_CACHE_SIZE"1000"Framework detection cache size"5000"

Example Configuration

Terminal window
# High-performance production settings
export KLIRA_LAZY_LOADING="true"
export KLIRA_FRAMEWORK_CACHE_SIZE="10000"

Guardrails Configuration

Policy Settings

VariableDefaultDescriptionExample
KLIRA_POLICY_ENFORCEMENT"true"Enable/disable policy enforcement"true"
KLIRA_POLICIES_PATHAuto-detectedPath to custom policies directory"/app/policies"

Example Configuration

Terminal window
# Guardrails configuration
export KLIRA_POLICY_ENFORCEMENT="true"
export KLIRA_POLICIES_PATH="/opt/klira/policies"

Security and Privacy

Debug and Logging

VariableDefaultDescriptionExample
KLIRA_DEBUG"false"Enable debug mode"false"
KLIRA_VERBOSE"false"Enable verbose logging"false"
KLIRA_LOGGING_ENABLED"false"Enable SDK internal logging"false"

Telemetry

VariableDefaultDescriptionExample
KLIRA_TELEMETRY"false"Enable anonymous telemetry"false"

Production Security Example

Terminal window
# Secure production configuration
export KLIRA_DEBUG="false"
export KLIRA_VERBOSE="false"
export KLIRA_LOGGING_ENABLED="false"
export KLIRA_TELEMETRY="false"
export KLIRA_TRACE_CONTENT="false"

Cache Configuration

Redis Settings

Redis caching is configured through the SDK’s cache initialization, not environment variables. Redis connection is handled automatically when available.

Redis Installation:

Terminal window
# Install Redis support (optional)
pip install redis

Redis Configuration in Code:

from klira.cache.redis_adapter import RedisAdapter, RedisConfig
# Custom Redis configuration
redis_config = RedisConfig(
url="redis://redis-cluster:6379",
max_connections=50,
socket_timeout=2.0,
retry_attempts=3
)
adapter = RedisAdapter(redis_config)

Note: Klira AI SDK gracefully handles missing Redis dependencies. If Redis is not available, the SDK uses in-memory caching as fallback.

Analytics Configuration

Klira AI Hub Integration

Analytics data is sent to Klira AI Hub using your existing API key. No additional configuration required.

Built-in Analytics:

import os
from klira import Klira
# Analytics automatically enabled with API key
klira = Klira.init(
app_name="MyApp",
api_key=os.getenv("KLIRA_API_KEY") # Enables Klira AI Hub analytics
)

Note: Analytics data includes blocked messages, policy violations, and performance metrics. All data is sent to https://api.getklira.com using your Klira AI API key.

Streaming Configuration

Performance Settings

Streaming is configured through the SDK’s StreamConfig class, not environment variables.

Stream Configuration in Code:

from klira.streaming import StreamProcessor, StreamConfig
# Custom streaming configuration
stream_config = StreamConfig(
buffer_size=20,
validation_interval=2,
timeout_seconds=60.0,
enable_guardrails=True,
enable_caching=True
)
processor = StreamProcessor(stream_config)

Available StreamConfig Options:

  • buffer_size: Chunk buffer size (default: 10)
  • validation_interval: Validate every N chunks (default: 1)
  • timeout_seconds: Stream timeout (default: 30.0)
  • enable_guardrails: Enable real-time guardrails (default: True)
  • enable_caching: Enable partial response caching (default: True)

Environment-Specific Configurations

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_FRAMEWORK_CACHE_SIZE="1000"

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"

Note: To use custom OTLP endpoints in staging/production instead of Klira AI’s default:

Terminal window
# Staging with custom endpoint
export KLIRA_OPENTELEMETRY_ENDPOINT="https://otlp-staging.company.com"
# Production with custom endpoint
export KLIRA_OPENTELEMETRY_ENDPOINT="https://otlp.company.com"

Container and Kubernetes Configuration

Docker Compose

docker-compose.yml
version: '3.8'
services:
app:
image: your-app:latest
environment:
- KLIRA_API_KEY=${KLIRA_API_KEY}
- KLIRA_TRACING_ENABLED=true
- KLIRA_TRACE_CONTENT=false
- KLIRA_DEBUG=false
- KLIRA_VERBOSE=false
depends_on:
- redis
redis:
image: redis:7-alpine
ports:
- "6379:6379"

Kubernetes ConfigMap

configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: klira-config
data:
KLIRA_TRACING_ENABLED: "true"
KLIRA_TRACE_CONTENT: "false"
KLIRA_METRICS_ENABLED: "true"
KLIRA_DEBUG: "false"
KLIRA_VERBOSE: "false"
KLIRA_FRAMEWORK_CACHE_SIZE: "5000"
---
apiVersion: v1
kind: Secret
metadata:
name: klira-secrets
type: Opaque
stringData:
KLIRA_API_KEY: "klira_prod_your_key_here"

Configuration Validation

Python Validation Script

#!/usr/bin/env python3
"""Validate Klira AI SDK environment configuration."""
import os
import sys
from typing import List, Tuple
def validate_config() -> List[Tuple[str, str]]:
"""Validate environment configuration."""
errors = []
# Required variables
if not os.getenv("KLIRA_API_KEY"):
errors.append(("KLIRA_API_KEY", "Required but not set"))
elif not os.getenv("KLIRA_API_KEY", "").startswith("klira_"):
errors.append(("KLIRA_API_KEY", "Must start with 'klira_'"))
# Boolean validations
bool_vars = [
"KLIRA_TRACING_ENABLED", "KLIRA_TRACE_CONTENT", "KLIRA_METRICS_ENABLED",
"KLIRA_DEBUG", "KLIRA_VERBOSE", "KLIRA_LOGGING_ENABLED", "KLIRA_TELEMETRY",
"KLIRA_POLICY_ENFORCEMENT", "KLIRA_LAZY_LOADING"
]
for var in bool_vars:
value = os.getenv(var)
if value and value.lower() not in ["true", "false"]:
errors.append((var, f"Must be 'true' or 'false', got '{value}'"))
# Numeric validations
numeric_vars = {
"KLIRA_FRAMEWORK_CACHE_SIZE": (1, 100000),
"REDIS_MAX_CONNECTIONS": (1, 1000),
"REDIS_SOCKET_TIMEOUT": (0.1, 60.0),
"REDIS_RETRY_ATTEMPTS": (1, 10),
"KLIRA_HUB_BATCH_SIZE": (1, 1000),
"KLIRA_HUB_FLUSH_INTERVAL": (1, 3600),
"KLIRA_STREAM_MAX_CHUNK_SIZE": (1, 10000),
"KLIRA_STREAM_BUFFER_SIZE": (1, 100),
}
for var, (min_val, max_val) in numeric_vars.items():
value = os.getenv(var)
if value:
try:
num_val = float(value)
if not (min_val <= num_val <= max_val):
errors.append((var, f"Must be between {min_val} and {max_val}"))
except ValueError:
errors.append((var, f"Must be a number, got '{value}'"))
# URL validations
url_vars = ["KLIRA_OPENTELEMETRY_ENDPOINT", "REDIS_URL", "KLIRA_HUB_ENDPOINT"]
for var in url_vars:
value = os.getenv(var)
if value and not (value.startswith("http://") or value.startswith("https://") or value.startswith("redis://")):
errors.append((var, f"Must be a valid URL, got '{value}'"))
# Path validations
policies_path = os.getenv("KLIRA_POLICIES_PATH")
if policies_path and not os.path.exists(policies_path):
errors.append(("KLIRA_POLICIES_PATH", f"Path does not exist: {policies_path}"))
return errors
if __name__ == "__main__":
errors = validate_config()
if errors:
print("❠Configuration validation failed:")
for var, error in errors:
print(f" {var}: {error}")
sys.exit(1)
else:
print(" Configuration validation passed")
# Print current configuration
print("\n Current configuration:")
config_vars = [
"KLIRA_API_KEY", "KLIRA_APP_NAME", "KLIRA_TRACING_ENABLED",
"KLIRA_TRACE_CONTENT", "KLIRA_DEBUG", "KLIRA_FRAMEWORK_CACHE_SIZE"
]
for var in config_vars:
value = os.getenv(var, "Not set")
if var == "KLIRA_API_KEY" and value != "Not set":
value = f"{value[:10]}..." if len(value) > 10 else value
print(f" {var}: {value}")

Shell Validation Script

#!/bin/bash
# validate_config.sh - Validate Klira AI SDK configuration
set -e
echo " Validating Klira AI SDK configuration..."
# Check required variables
if [ -z "$KLIRA_API_KEY" ]; then
echo "❠KLIRA_API_KEY is required but not set"
exit 1
fi
if [[ ! "$KLIRA_API_KEY" =~ ^klira_ ]]; then
echo "❠KLIRA_API_KEY must start with 'klira_'"
exit 1
fi
# Check boolean variables
check_boolean() {
local var_name=$1
local var_value=${!var_name}
if [ -n "$var_value" ] && [ "$var_value" != "true" ] && [ "$var_value" != "false" ]; then
echo "❠$var_name must be 'true' or 'false', got '$var_value'"
exit 1
fi
}
check_boolean KLIRA_TRACING_ENABLED
check_boolean KLIRA_TRACE_CONTENT
check_boolean KLIRA_DEBUG
check_boolean KLIRA_VERBOSE
# Check numeric variables
check_numeric() {
local var_name=$1
local var_value=${!var_name}
local min_val=$2
local max_val=$3
if [ -n "$var_value" ]; then
if ! [[ "$var_value" =~ ^[0-9]+$ ]] || [ "$var_value" -lt "$min_val" ] || [ "$var_value" -gt "$max_val" ]; then
echo "❠$var_name must be between $min_val and $max_val, got '$var_value'"
exit 1
fi
fi
}
check_numeric KLIRA_FRAMEWORK_CACHE_SIZE 1 100000
check_numeric REDIS_MAX_CONNECTIONS 1 1000
# Check paths
if [ -n "$KLIRA_POLICIES_PATH" ] && [ ! -d "$KLIRA_POLICIES_PATH" ]; then
echo "❠KLIRA_POLICIES_PATH directory does not exist: $KLIRA_POLICIES_PATH"
exit 1
fi
echo " Configuration validation passed"
# Display current configuration
echo ""
echo " Current configuration:"
echo " KLIRA_API_KEY: ${KLIRA_API_KEY:0:10}..."
echo " KLIRA_APP_NAME: ${KLIRA_APP_NAME:-Not set}"
echo " KLIRA_TRACING_ENABLED: ${KLIRA_TRACING_ENABLED:-Not set}"
echo " KLIRA_DEBUG: ${KLIRA_DEBUG:-Not set}"
echo " REDIS_URL: ${REDIS_URL:-Not set}"

Best Practices

1. Environment Separation

Terminal window
# Use different prefixes for different environments
# Development
export KLIRA_API_KEY="klira_dev_..."
# Staging
export KLIRA_API_KEY="klira_staging_..."
# Production
export KLIRA_API_KEY="klira_prod_..."

2. Secrets Management

Terminal window
# ❠Never commit secrets to version control
echo "KLIRA_API_KEY=klira_secret_key" >> .env
# Use secrets management systems
# AWS Secrets Manager
export KLIRA_API_KEY=$(aws secretsmanager get-secret-value --secret-id klira/api-key --query SecretString --output text)
# HashiCorp Vault
export KLIRA_API_KEY=$(vault kv get -field=api_key secret/klira)
# Kubernetes Secrets
kubectl create secret generic klira-secrets --from-literal=api-key=klira_your_key_here

3. Configuration Templates

Terminal window
# config-template.env
KLIRA_API_KEY=__REPLACE_WITH_ACTUAL_KEY__
KLIRA_APP_NAME=__REPLACE_WITH_APP_NAME__
KLIRA_OPENTELEMETRY_ENDPOINT=__REPLACE_WITH_OTLP_ENDPOINT__
REDIS_URL=__REPLACE_WITH_REDIS_URL__
# Use with envsubst or similar tools
envsubst < config-template.env > production.env

Troubleshooting

Common Issues

  1. API Key Format Error
Error: API key must start with 'klira_'
Solution: Ensure your API key has the correct format
  1. Boolean Value Error
Error: KLIRA_DEBUG must be 'true' or 'false'
Solution: Use lowercase 'true' or 'false', not 'True'/'False'
  1. Numeric Range Error
Error: KLIRA_FRAMEWORK_CACHE_SIZE must be between 1 and 100000
Solution: Use a reasonable cache size value

Debugging Configuration

from klira.config import get_config
# Print current configuration
config = get_config()
print("Current Klira AI configuration:")
for key, value in config.to_dict().items():
print(f" {key}: {value}")
# Validate configuration
errors = config.validate()
if errors:
print("Configuration errors:")
for error in errors:
print(f" - {error}")

Next Steps

  1. Production Setup - Complete production deployment guide
  2. Performance Tuning - Optimize configuration for performance
  3. Security Best Practices - Secure your configuration

Complete environment variable reference for enterprise Klira AI SDK deployments