Python Examples

Complete code examples for integrating Skej Studio API with Python

Setup

Install dependencies and configure your client

Install Requests:

pip install requests

Create API Client:

import os
import requests
from typing import Optional, Dict, Any

class StudioClient:
    def __init__(self, service_key: Optional[str] = None):
        self.base_url = "https://api.staging.agnt.ai"
        self.service_key = service_key or os.getenv("STUDIO_SERVICE_KEY")
        self.session = requests.Session()
        self.session.headers.update({
            "Authorization": f"Bearer {self.service_key}",
            "Content-Type": "application/json"
        })

    def get(self, endpoint: str, params: Optional[Dict] = None) -> Dict[str, Any]:
        response = self.session.get(f"{self.base_url}{endpoint}", params=params)
        response.raise_for_status()
        return response.json()

    def post(self, endpoint: str, data: Dict[str, Any]) -> Dict[str, Any]:
        response = self.session.post(f"{self.base_url}{endpoint}", json=data)
        response.raise_for_status()
        return response.json()

    def put(self, endpoint: str, data: Dict[str, Any]) -> Dict[str, Any]:
        response = self.session.put(f"{self.base_url}{endpoint}", json=data)
        response.raise_for_status()
        return response.json()

    def delete(self, endpoint: str) -> Dict[str, Any]:
        response = self.session.delete(f"{self.base_url}{endpoint}")
        response.raise_for_status()
        return response.json()

# Initialize client
client = StudioClient()

List Prompts

def list_prompts(tenant_id: str, page: int = 1, per_page: int = 20):
    """List all prompts for a tenant"""
    try:
        response = client.get(
            f"/tenants/{tenant_id}/prompts",
            params={
                "page": page,
                "per_page": per_page
            }
        )

        prompts = response.get("data", [])
        print(f"Found {len(prompts)} prompts")

        for prompt in prompts:
            print(f"  - {prompt['displayName']} ({prompt['promptName']})")

        return prompts
    except requests.exceptions.HTTPError as e:
        print(f"Error: {e.response.status_code} - {e.response.json()}")
        raise

# Usage
list_prompts("tenant_123")

Create a Prompt

def create_prompt(tenant_id: str, prompt_data: Dict[str, Any]):
    """Create a new prompt"""
    try:
        response = client.post(
            f"/tenants/{tenant_id}/prompts",
            data={
                "promptName": prompt_data["name"],
                "displayName": prompt_data["display_name"],
                "description": prompt_data.get("description"),
                "template": prompt_data["template"],
                "category": prompt_data.get("category"),
                "variables": prompt_data.get("variables", [])
            }
        )

        print(f"Prompt created: {response['promptName']}")
        return response
    except requests.exceptions.HTTPError as e:
        print(f"Failed to create prompt: {e.response.json()}")
        raise

# Usage
create_prompt("tenant_123", {
    "name": "customer_support_agent",
    "display_name": "Customer Support Agent",
    "description": "Handles customer inquiries",
    "template": "You are a helpful customer support agent...",
    "category": "Support",
    "variables": ["customer_name", "issue_type"]
})

Monitor Activity Traces

def get_traces(tenant_id: str, page: int = 1, per_page: int = 10):
    """Get activity traces for a tenant"""
    try:
        response = client.get(
            f"/tenants/{tenant_id}/traces",
            params={
                "page": page,
                "per_page": per_page
            }
        )

        traces = response.get("data", [])

        for trace in traces:
            print(f"Trace ${trace['traceId']}:")
            print(f"  Model: ${trace['model']}")
            print(f"  Duration: ${trace['duration']}ms")
            print(f"  Cost: $${trace['cost']}")
            print(f"  Tokens: ${trace['totalTokens']}")
            print()

        return traces
    except requests.exceptions.HTTPError as e:
        print(f"Failed to fetch traces: {e.response.json()}")
        raise

# Usage
get_traces("tenant_123")

Complete Error Handling Example

from requests.exceptions import HTTPError, ConnectionError, Timeout

def make_studio_request(method: str, endpoint: str, **kwargs):
    """Make a request with comprehensive error handling"""
    try:
        if method == "GET":
            response = client.get(endpoint, **kwargs)
        elif method == "POST":
            response = client.post(endpoint, **kwargs)
        elif method == "PUT":
            response = client.put(endpoint, **kwargs)
        elif method == "DELETE":
            response = client.delete(endpoint, **kwargs)
        else:
            raise ValueError(f"Unsupported method: {method}")

        return response

    except HTTPError as e:
        status_code = e.response.status_code

        if status_code == 401:
            print("Unauthorized: Check your Service Key")
        elif status_code == 403:
            print("Forbidden: Insufficient permissions")
        elif status_code == 404:
            print("Not Found: Resource does not exist")
        elif status_code == 429:
            print("Rate Limited: Too many requests")
        elif status_code >= 500:
            print("Server Error: Try again later")
        else:
            print(f"Error {status_code}: {e.response.json()}")

        raise

    except ConnectionError:
        print("Connection Error: Could not reach the API")
        raise

    except Timeout:
        print("Timeout: Request took too long")
        raise

    except Exception as e:
        print(f"Unexpected error: {str(e)}")
        raise

# Usage
try:
    prompts = make_studio_request("GET", "/tenants/tenant_123/prompts")
    print(f"Success: Found {len(prompts['data'])} prompts")
except Exception:
    print("Operation failed")