Klira Class API Reference
Klira Class API Reference
The Klira class is the main entry point for initializing and configuring the Klira SDK. It provides static methods for SDK initialization, configuration management, and access to core components.
Class Overview
from klira.sdk import Klira
# Initialize the SDKKlira.init( app_name="MyApplication", api_key="klira_live_your_key",)
# Access guardrails engineguardrails = Klira.get_guardrails()
# Check initialization statusif Klira.is_initialized(): config = Klira.get_config()Methods
Klira.init()
Static method to initialize the Klira SDK with configuration options.
@staticmethoddef init( app_name: str = sys.argv[0], api_key: Optional[str] = None, opentelemetry_endpoint: Optional[str] = None, telemetry_enabled: bool = False, policies_path: Optional[str] = None, anonymization: Optional[str] = None, clinical_domain: Optional[str] = None, evals_run: Optional[str] = None, dataset_id: Optional[str] = None, llm_fallback_model: Optional[str] = None, llm_fallback_api_key: Optional[str] = None, llm_fallback_endpoint: Optional[str] = None, phi_export_entity_details: bool = False,) -> NoneParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
app_name | str | sys.argv[0] | Name of your application for identification in traces |
api_key | Optional[str] | None | Your Klira API key. If not provided, reads from KLIRA_API_KEY environment variable |
opentelemetry_endpoint | Optional[str] | None | Custom OTLP endpoint. Defaults to https://api.getklira.com when api_key is set |
telemetry_enabled | bool | False | Whether to allow anonymous telemetry collection |
policies_path | Optional[str] | None | Path to custom guardrail policies directory |
anonymization | Optional[str] | None | PHI anonymization strategy: "redact", "mask", "replace", or "hash" |
clinical_domain | Optional[str] | None | Default clinical domain for healthcare guardrails routing |
evals_run | Optional[str] | None | Default experiment identifier for evaluation runs |
dataset_id | Optional[str] | None | Default dataset identifier for evaluation runs |
llm_fallback_model | Optional[str] | None | Model name for LLM-based guardrails fallback evaluation |
llm_fallback_api_key | Optional[str] | None | API key for the LLM fallback service |
llm_fallback_endpoint | Optional[str] | None | Endpoint URL for the LLM fallback service |
phi_export_entity_details | bool | False | Include PHI entity type/count metadata in exported spans |
Returns
None
Examples
Basic initialization:
from klira.sdk import Klira
Klira.init( app_name="ChatBot", api_key="klira_live_your_key_here",)Production configuration:
Klira.init( app_name="ProductionApp", api_key=os.getenv("KLIRA_API_KEY"), policies_path="/app/policies", telemetry_enabled=False,)Healthcare configuration:
Klira.init( app_name="ClinicalAssistant", api_key=os.getenv("KLIRA_API_KEY"), clinical_domain="emergency_medicine", anonymization="redact", phi_export_entity_details=True,)Custom OTLP endpoint:
Klira.init( app_name="CustomTelemetry", opentelemetry_endpoint="https://otel.company.com:4317",)Note: When
api_keyis provided, traces are automatically sent tohttps://api.getklira.com. Setopentelemetry_endpointonly if you want to use a different OTLP collector.
Raises
KliraInitError: If SDK is already initialized or configuration validation fails
Klira.get()
Static method to get the initialized Klira client instance.
@staticmethoddef get() -> ClientReturns
Client: The initialized Klira client instance
Raises
KliraInitError: If SDK not initialized or client not available
Example
Klira.init(app_name="MyApp", api_key="your-key")client = Klira.get()Klira.get_guardrails()
Static method to get the initialized GuardrailsEngine instance.
@staticmethoddef get_guardrails() -> GuardrailsEngineReturns
GuardrailsEngine: The initialized guardrails engine instance
Raises
KliraInitError: If SDK not initialized or guardrails engine not available
Example
Klira.init(app_name="MyApp", api_key="your-key")
guardrails = Klira.get_guardrails()result = await guardrails.process_message("Hello world")print(f"Allowed: {result['allowed']}")Klira.get_config()
Static method to get the current SDK configuration.
@staticmethoddef get_config() -> KliraConfigReturns
KliraConfig: The current configuration instance
Example
config = Klira.get_config()print(f"App name: {config.app_name}")print(f"Tracing enabled: {config.tracing_enabled}")Klira.is_initialized()
Static method to check if the SDK has been initialized.
@staticmethoddef is_initialized() -> boolReturns
bool:Trueif SDK is initialized,Falseotherwise
Example
if not Klira.is_initialized(): Klira.init(app_name="MyApp", api_key="your-key")Klira.shutdown()
Static method to cleanly shut down the SDK, flushing pending telemetry.
@staticmethoddef shutdown() -> NoneExample
# At application exitKlira.shutdown()Klira.session()
Context manager for scoped SDK sessions. Automatically calls shutdown() on exit.
@staticmethoddef session(**init_kwargs) -> ContextManagerParameters
Same parameters as Klira.init().
Example
with Klira.session(app_name="MyApp", api_key="your-key"): # SDK is initialized here result = await run_workflow()# SDK is automatically shut down hereKlira.force_flush()
Static method to force-flush all pending telemetry data.
@staticmethoddef force_flush() -> NoneExample
# Flush before a long-running operationKlira.force_flush()Configuration Management
The Klira class integrates with the centralized configuration system. Configuration is validated on initialization and stored globally.
Environment Variables
The following environment variables are automatically read during initialization:
| Variable | Default | Description |
|---|---|---|
KLIRA_API_KEY | - | Klira API key for authentication |
KLIRA_OPENTELEMETRY_ENDPOINT | - | Custom OTLP endpoint |
KLIRA_TRACING_ENABLED | "true" | Enable/disable tracing |
KLIRA_TRACE_CONTENT | "true" | Include content in traces |
KLIRA_TELEMETRY | "false" | Enable anonymous telemetry |
KLIRA_POLICIES_PATH | - | Custom policies directory |
Configuration Validation
The Klira class validates configuration on initialization:
- API Key Format: Must start with
"klira_" - Endpoint URL: Must be valid HTTP/HTTPS URL if provided
- Policies Path: Must exist if specified
- App Name: Cannot be empty
Error Handling
The Klira class uses the @handle_errors decorator for graceful error handling:
Klira.init( app_name="MyApp", api_key="invalid-key", # Won't crash — logs a warning)
# Check if initialization was successfulif Klira.is_initialized(): print("SDK initialized successfully")else: print("SDK initialization failed — check logs")Thread Safety
The Klira class implements thread-safe singleton pattern:
- Double-checked locking for instance creation
- Reentrant locks for configuration updates
- Thread-safe lazy initialization of components
Integration with Framework Detection
The Klira class automatically registers and patches framework adapters:
Klira.init(app_name="MyApp", api_key="your-key")
# Framework adapters are automatically registered for:# - OpenAI Agents SDK# - LangChain# - LlamaIndex# - Custom frameworks via pluginsBest Practices
Initialize Early
Initialize the SDK as early as possible in your application:
from klira.sdk import Klira
Klira.init( app_name="MyApp", api_key=os.getenv("KLIRA_API_KEY"),)
# Now import and use other modulesfrom my_agents import ChatAgentUse Environment Variables
Store sensitive configuration in environment variables:
Klira.init( app_name="ProductionApp", api_key=os.getenv("KLIRA_API_KEY"), policies_path=os.getenv("KLIRA_POLICIES_PATH", "./policies"),)Handle Initialization Errors
try: Klira.init(app_name="MyApp") print("Klira SDK initialized successfully")except KliraInitError as e: print(f"Klira SDK initialization failed: {e}")Configure for Environment
import os
if os.getenv("ENVIRONMENT") == "production": Klira.init( app_name="MyApp-Prod", api_key=os.getenv("KLIRA_API_KEY"), telemetry_enabled=False, )else: Klira.init( app_name="MyApp-Dev", api_key=os.getenv("KLIRA_API_KEY"), policies_path="./dev-policies", )Related APIs
- Configuration API —
KliraConfigclass and configuration management - GuardrailsEngine API — Policy enforcement and evaluation
- Decorators API — Function and class decorators
- Types — Type definitions and error classes