Skip to main content

Aliyah SDK

Aaliyah SDK provides comprehensive AI agent management, compliance monitoring, and observability. Track LLM calls, manage agent sessions, and ensure compliance with automatic instrumentation and manual event tracking.

Installation

pip install aliyah-sdk

Quick Start

1. Environment Configuration

Create a .env file in your project root:

# Required - Get from Mensterra dashboard
ALIYAH_API_KEY=your_aliyah_api_key

# Agent Configuration
AGENT_ID=1                    # Your agent's unique ID from app.mensterra.com
AGENT_NAME=my_support_agent   # Descriptive name for your agent

1. Basic Setup

import aliyah_sdk


# Initialize the SDK
aliyah_sdk.init(
    auto_start_session=False,
    instrument_llm_calls=True,  # Enable automatic LLM instrumentation
    agent_id=12345,  # Your agent ID from the Aliyah dashboard
    agent_name="my_ai_agent"
)

3. Basic Agent with Automatic LLM Tracking

import os
from dotenv import load_dotenv
import aliyah_sdk
from openai import OpenAI

# Load environment variables
load_dotenv()

# Initialize Aaliyah SDK - this enables automatic LLM call tracking
aliyah_sdk.init(
    auto_start_session=True,     # Automatically manage sessions
    instrument_llm_calls=True,   # Track all OpenAI/LLM calls automatically
    agent_id=int(os.getenv("AGENT_ID", 1)),
    agent_name=os.getenv("AGENT_NAME", "my_agent")
)

def simple_agent():
    """Basic agent with automatic tracking"""
    client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
    
    # This LLM call is automatically tracked by Aaliyah
    response = client.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": "What's the weather like?"}]
    )
    
    return response.choices[0].message.content

if __name__ == "__main__":
    result = simple_agent()
    print(f"Agent response: {result}")

4. Manual Session Management

Sessions help you group related AI interactions and trace them as a single workflow:

# Start a session
session = aliyah_sdk.start_session(
    tags=["chatbot", "customer_support", "production"]
)

# Your AI application logic here...

# End the session
aliyah_sdk.end_session(
    session, 
    end_state="Completed", 
    end_state_reason="User query resolved successfully"
)

Advanced Usage

Manual Session Management

For production agents that need precise control over session lifecycle:

import os
from dotenv import load_dotenv
import aliyah_sdk
from openai import OpenAI
import time

load_dotenv()

# Initialize without auto-session for manual control
aaliyah_sdk.init(
    auto_start_session=False,    # We'll manage sessions manually
    instrument_llm_calls=True,   # Still auto-track LLM calls
    agent_id=int(os.getenv("AGENT_ID", 1)),
    agent_name=os.getenv("AGENT_NAME", "advanced_agent")
)

def advanced_agent_with_session():
    """Agent with manual session management and custom events"""
    
    # Start a session with custom tags and metadata
    session = aaliyah_sdk.start_session(
        tags=["customer_support", "production"],
        metadata={
            "customer_id": "12345",
            "priority": "high",
            "channel": "chat"
        }
    )
    
    try:
        client = OpenAI()
        
        # Record custom business event
        aaliyah_sdk.record(aaliyah_sdk.BusinessEvent(
            event_type="customer_inquiry_started",
            details="Customer asking about order status",
            metadata={"order_id": "ORD-789"}
        ))
        
        # LLM call - automatically tracked
        response = client.chat.completions.create(
            model="gpt-4",
            messages=[
                {"role": "system", "content": "You are a helpful customer support agent."},
                {"role": "user", "content": "Where is my order #ORD-789?"}
            ]
        )
        
        answer = response.choices[0].message.content
        
        # Record successful resolution
        aaliyah_sdk.record(aaliyah_sdk.BusinessEvent(
            event_type="inquiry_resolved",
            details="Successfully provided order status",
            metadata={"resolution_time_ms": 1500}
        ))
        
        return answer
        
    except Exception as e:
        # Record error for debugging and compliance
        aaliyah_sdk.record(aaliyah_sdk.ErrorEvent(
            error_type=type(e).__name__,
            details=str(e),
            logs="Failed to process customer inquiry"
        ))
        raise
        
    finally:
        # Always end the session with proper state
        aaliyah_sdk.end_session(
            session, 
            end_state="completed",
            end_state_reason="Customer inquiry processed successfully"
        )

if __name__ == "__main__":
    result = advanced_agent_with_session()
    print(f"Agent response: {result}")

Integration Examples

With OpenAI

import aliyah_sdk
import openai

# Initialize Aliyah
aliyah_sdk.init(
    instrument_llm_calls=True,
    agent_id=12345,
    agent_name="openai_chatbot"
)

# Start session
session = aliyah_sdk.start_session(tags=["chatbot"])

try:
    # This call is automatically traced
    response = openai.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": "Hello!"}]
    )
    print(response.choices[0].message.content)
    
finally:
    aliyah_sdk.end_session(session, end_state="Completed")

With Custom AI Frameworks

The SDK automatically instruments most popular LLM providers. For custom frameworks, manual instrumentation may be needed.

Event Types Reference

Automatic Events

  • LLM Calls: Automatically tracked when instrument_llm_calls=True
  • Session Start/End: Automatically managed when auto_start_session=True

Manual Events

Tool Events

aaliyah_sdk.record(aaliyah_sdk.ToolEvent(
    tool_name="database",
    action="query",
    input_data={"table": "customers", "filter": "active=true"},
    output_data={"row_count": 150}
))

Error Events

aaliyah_sdk.record(aaliyah_sdk.ErrorEvent(
    error_type="ValidationError",
    details="Invalid customer email format",
    severity="medium",
    logs="Email validation failed: invalid@domain"
))

Best Practices

1. Session Management

  • Use auto_start_session=True for simple agents
  • Use manual sessions for complex workflows that need precise control
  • Always include relevant tags and metadata in sessions

2. Error Handling

  • Wrap agent logic in try/catch blocks
  • Record errors with appropriate severity levels
  • Include debugging information in error metadata

3. Performance

  • Sessions automatically batch and send events efficiently
  • Use end_session() to ensure all data is flushed
  • Consider using manual sessions for long-running agents

Troubleshooting

Common Issues

SDK Not Initializing

# Check if client is properly initialized
client = aliyah_sdk.get_client()
if client and client.initialized:
    print("✓ SDK initialized successfully")
else:
    print("✗ SDK initialization failed")

Traces Not Appearing

  • Verify your agent ID exists in the dashboard
  • Check network connectivity
  • Ensure API key is set correctly
  • Try force flushing traces

Session Management Issues

  • Always call end_session() in a finally block
  • Check session object is valid before ending
  • Use appropriate end states and reasons

Debug Mode

Enable verbose logging for troubleshooting:

import logging
logging.basicConfig(level=logging.DEBUG)

# Your Aliyah SDK code here

Configuration Options

SDK Initialization

aliyah_sdk.init(
    auto_start_session=True,      # Auto-manage sessions (default: True)
    instrument_llm_calls=True,    # Auto-track LLM calls (default: True)
    agent_id=1,                   # Your agent's unique ID
    agent_name="my_agent",        # Descriptive agent name
    api_key="your_key",          # Aliyah API key (or use env var)
)

Monitoring and Dashboards

After instrumenting your agent:

  1. View in Mensterra Dashboard: Monitor agent performance, compliance, and errors
  2. Session Traces: See detailed traces of each agent session
  3. Compliance Reports: Generate compliance reports for audits
  4. Performance Metrics: Track LLM usage, response times, and error rates
  5. Alerts: Set up alerts for compliance violations or errors

Need Help?

License

Apache 2.0

Happy tracing! 🚀

Metadata

Release files for aliyah-sdk 0.1.5

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for aliyah-sdk 0.1.5
File Size Uploaded Provenance Actions
aliyah_sdk-0.1.5.tar.gz 126.6 kB Without provenance Details for aliyah_sdk-0.1.5.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for aliyah-sdk 0.1.5
File Interpreter ABI Platform Actions
aliyah_sdk-0.1.5-py3-none-any.whl Python 3 none any Details for aliyah_sdk-0.1.5-py3-none-any.whl

Total release size: 282.7 kB

Release files / aliyah_sdk-0.1.5.tar.gz

Download URL aliyah_sdk-0.1.5.tar.gz
Size 126.6 kB
Tags Source
SHA-256 checksum
How to use checksums
696bc93a9ade2e409f8772edae515746f9bb5068f93c4d82a81a7d5347524935
BLAKE2b-256 checksum
How to use checksums
e0d4400b8d60a4a528601675b4f90d588a06dc9bd7c9dbf0ef7575ed3687fbcb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.13.3

Release files / aliyah_sdk-0.1.5-py3-none-any.whl

Download URL aliyah_sdk-0.1.5-py3-none-any.whl
Size 156.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
143cea993531d52fc1dec23043954e774c0a456909e1b3b61d70c11eafaedb9d
BLAKE2b-256 checksum
How to use checksums
abc0b3dd6f9e3ca8ccf69baab0adcf51018089f5dc51def65855a1223db45e40
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.13.3

Security for aliyah-sdk 0.1.5

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page