Skip to content

Klira AI Class API Reference

Klira AI Class API Reference

The Klira class is the main entry point for initializing and configuring the Klira AI SDK. It provides static methods for SDK initialization, configuration management, and access to core components.

Class Overview

from klira.sdk import Klira
# Initialize the SDK
klira = Klira.init(
app_name="MyApplication",
api_key="your-api-key",
enabled=True
)
# Access guardrails engine
guardrails = Klira.get_guardrails()
# Access client instance
client = Klira.get()

Methods

Klira.init()

Static method to initialize the Klira AI SDK with configuration options.

@staticmethod
def init(
app_name: str = sys.argv[0],
api_key: Optional[str] = None,
opentelemetry_endpoint: Optional[str] = None,
enabled: bool = True,
telemetry_enabled: bool = False,
headers: Dict[str, str] = {},
disable_batch: bool = False,
exporter: Optional[SpanExporter] = None,
processor: Optional[SpanProcessor] = None,
propagator: Optional[TextMapPropagator] = None,
instruments: Optional[Set[Any]] = None,
block_instruments: Optional[Set[Any]] = None,
resource_attributes: Dict[str, Any] = {},
policies_path: Optional[str] = None,
llm_service: Optional["LLMServiceProtocol"] = None,
verbose: bool = False,
**kwargs: Any,
) -> Optional[Client]

Parameters

ParameterTypeDefaultDescription
app_namestrsys.argv[0]Name of your application for identification in traces
api_keyOptional[str]NoneYour Klira AI API key. If not provided, reads from KLIRA_API_KEY environment variable
opentelemetry_endpointOptional[str]NoneCustom OTLP endpoint. Defaults to https://api.getklira.com when api_key is set
enabledboolTrueWhether tracing is enabled
telemetry_enabledboolFalseWhether to allow anonymous telemetry collection
headersDict[str, str]{}Custom headers for API requests
disable_batchboolFalseDisable batch processing for traces
exporterOptional[SpanExporter]NoneCustom OpenTelemetry span exporter
processorOptional[SpanProcessor]NoneCustom OpenTelemetry span processor
propagatorOptional[TextMapPropagator]NoneCustom OpenTelemetry propagator
instrumentsOptional[Set[Any]]NoneSpecific instruments to enable
block_instrumentsOptional[Set[Any]]NoneSpecific instruments to disable
resource_attributesDict[str, Any]{}Additional OpenTelemetry resource attributes
policies_pathOptional[str]NonePath to custom guardrail policies directory
llm_serviceOptional["LLMServiceProtocol"]NoneCustom LLM service for guardrails evaluation
verboseboolFalseEnable detailed INFO-level logging
**kwargsAny-Additional arguments passed to Traceloop SDK

Returns

  • Optional[Client]: Klira AI client instance if initialization successful, None otherwise

Examples

Basic initialization:

from klira.sdk import Klira
# Basic setup with API key
klira = Klira.init(
app_name="ChatBot",
api_key="klira_live_your_key_here",
enabled=True
)

Production configuration:

# Production setup with custom policies
klira = Klira.init(
app_name="ProductionApp",
api_key=os.getenv("KLIRA_API_KEY"),
policies_path="/app/policies",
verbose=False,
telemetry_enabled=False
)

Custom endpoint configuration:

# Using custom OTLP endpoint
klira = Klira.init(
app_name="CustomTelemetry",
opentelemetry_endpoint="https://otel.company.com:4317",
enabled=True
)

Note: When api_key is provided, traces are automatically sent to https://api.getklira.com. Set opentelemetry_endpoint only if you want to use a different OTLP collector.

Raises

  • Exception: If SDK is already initialized or configuration validation fails

Klira.get()

Static method to get the initialized Klira AI client instance.

@staticmethod
def get() -> Client

Returns

  • Client: The initialized Klira AI client instance

Raises

  • Exception: If SDK not initialized or client not available

Example

# Initialize first
Klira.init(app_name="MyApp", api_key="your-key")
# Get client instance
client = Klira.get()

Klira.get_guardrails()

Static method to get the initialized GuardrailsEngine instance.

@staticmethod
def get_guardrails() -> GuardrailsEngine

Returns

  • GuardrailsEngine: The initialized guardrails engine instance

Raises

  • Exception: If SDK not initialized or guardrails engine not available

Example

# Initialize first
Klira.init(app_name="MyApp", api_key="your-key")
# Get guardrails engine
guardrails = Klira.get_guardrails()
# Process a message
result = await guardrails.process_message("Hello world")
print(f"Allowed: {result['allowed']}")

Klira.set_association_properties()

Static method to set association properties for the current trace context.

@staticmethod
def set_association_properties(properties: Dict[str, Any]) -> None

Parameters

ParameterTypeDescription
propertiesDict[str, Any]Dictionary of properties to associate with current trace

Example

# Set context properties for tracing
Klira.set_association_properties({
"user_id": "user_123",
"conversation_id": "conv_456",
"organization_id": "org_789",
"project_id": "proj_abc"
})

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:

VariableDefaultDescription
KLIRA_API_KEY-Klira AI 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
KLIRA_VERBOSE"false"Enable verbose logging

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:

# Initialization errors are handled gracefully
klira = Klira.init(
app_name="MyApp",
api_key="invalid-key" # Won't fail initialization
)
# Check if initialization was successful
try:
client = Klira.get()
print("SDK initialized successfully")
except Exception as e:
print(f"SDK initialization failed: {e}")

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:

# Automatic framework detection and patching
klira = Klira.init(app_name="MyApp", api_key="your-key")
# Framework adapters are automatically registered for:
# - OpenAI Agents SDK
# - LangChain
# - CrewAI
# - LlamaIndex
# - Custom frameworks via plugins

Best Practices

1. Initialize Early

Initialize the SDK as early as possible in your application:

# At the top of your main module
from klira.sdk import Klira
# Initialize before importing other modules
klira = Klira.init(
app_name="MyApp",
api_key=os.getenv("KLIRA_API_KEY")
)
# Now import and use other modules
from my_agents import ChatAgent

2. Use Environment Variables

Store sensitive configuration in environment variables:

# Good - secure configuration
klira = Klira.init(
app_name="ProductionApp",
api_key=os.getenv("KLIRA_API_KEY"),
policies_path=os.getenv("KLIRA_POLICIES_PATH", "./policies")
)

3. Handle Initialization Errors

Always check if initialization was successful:

# Initialize with error handling
try:
klira = Klira.init(app_name="MyApp")
client = Klira.get()
print(" Klira AI SDK initialized successfully")
except Exception as e:
print(f"❠Klira AI SDK initialization failed: {e}")
# Implement fallback behavior

4. Configure for Environment

Use different configurations for different environments:

import os
# Environment-specific configuration
if os.getenv("ENVIRONMENT") == "production":
klira = Klira.init(
app_name="MyApp-Prod",
api_key=os.getenv("KLIRA_API_KEY"),
verbose=False,
telemetry_enabled=False
)
else:
klira = Klira.init(
app_name="MyApp-Dev",
api_key=os.getenv("KLIRA_API_KEY"),
verbose=True,
policies_path="./dev-policies"
)