Skip to main content

Python SDK for EnkaliPrime Chat API - RAG-enabled AI conversations

Project description

๐Ÿ EnkaliPrime Python SDK

The official Python client for EnkaliPrime Chat API

Build intelligent, RAG-enabled conversational AI experiences in Python

Python 3.8+ PyPI MIT License Documentation

Async Support Streaming Type Hints Stub Files RAG Enabled


Installation โ€ข Quick Start โ€ข Examples โ€ข API Reference โ€ข Contributing


โœจ Features

๐Ÿค– AI-Powered Chat

  • RAG-Enabled โ€” Retrieval-Augmented Generation
  • Knowledge Base โ€” Custom context injection
  • Multi-turn โ€” Conversation history tracking
  • Streaming Support โ€” Real-time response streaming

โšก Modern Python

  • Async/Await โ€” Full async support
  • Type Hints โ€” Complete typing coverage with Literal types
  • Context Managers โ€” Clean resource handling
  • Loading States โ€” Visual progress indicators
  • Cross-Editor Support โ€” Enhanced IntelliSense for all IDEs
  • Runtime Type Guards โ€” Additional type safety
  • Stub Files โ€” Pure type information (.pyi files)

๐ŸŒŠ Real-time Streaming

  • Live Responses โ€” Character-by-character
  • Callbacks โ€” Custom chunk handlers
  • Progress Tracking โ€” Monitor generation

๐Ÿ”Œ Framework Ready

  • FastAPI โ€” Async web apps
  • Flask โ€” Traditional web apps
  • Django โ€” Enterprise applications

๐Ÿ”ง Enhanced Type System

The SDK includes advanced type annotations for superior developer experience across all editors:

from enkaliprime import EnkaliPrimeClient, LoadingConfig, SpinnerStyle, ColorName

# Full type safety with literal types
client.send_message(
    message="Hello!",
    session_id="session_123",
    loading={
        "message": "Thinking",
        "style": "brain",  # Literal type - autocomplete shows all options
        "color": "cyan"    # Literal type - autocomplete shows color options
    }
)

Type Features:

  • Literal Types โ€” Exact value autocomplete for enums and options
  • Generic Types โ€” Type-safe collections and responses
  • Union Types โ€” Precise type unions for flexible APIs
  • Stub Files โ€” Pure type information for all editors (.pyi files)
  • Runtime Guards โ€” Additional type safety at runtime

๐Ÿ—๏ธ Architecture

flowchart TB
    subgraph Client["๐Ÿ Python Application"]
        App[Your App]
        SDK[EnkaliPrime SDK]
        App --> SDK
    end
    
    subgraph EnkaliBridge["โ˜๏ธ EnkaliBridge Gateway"]
        Resolve["/resolve"]
        Chat["/chat"]
    end
    
    subgraph Backend["๐Ÿ”ง EnkaliPrime Backend"]
        Auth[Authentication]
        RAG[RAG Engine]
        KB[(Knowledge Base)]
        AI[AI Model]
    end
    
    SDK -->|"1. Resolve API Key"| Resolve
    Resolve -->|"2. Return Connection"| SDK
    SDK -->|"3. Send Message"| Chat
    Chat --> Auth
    Auth --> RAG
    RAG --> KB
    RAG --> AI
    AI -->|"4. Stream Response"| SDK
    SDK -->|"5. Return to App"| App
    
    style Client fill:#1e293b,stroke:#3b82f6,color:#fff
    style EnkaliBridge fill:#0f172a,stroke:#8b5cf6,color:#fff
    style Backend fill:#0f172a,stroke:#22c55e,color:#fff

๐Ÿ“ฆ Installation

From PyPI (Recommended)

pip install enkaliprime

From Source

pip install git+https://github.com/enkaliprime/python-sdk.git

With Development Dependencies

pip install enkaliprime[dev]

๐Ÿš€ Quick Start

1๏ธโƒฃ Get Your API Key

  1. Log in to EnkaliPrime Dashboard
  2. Navigate to SDK Hub โ†’ Create Connection
  3. Copy your unified_api_key (starts with ek_bridge_)

2๏ธโƒฃ Initialize the Client

from enkaliprime import EnkaliPrimeClient

client = EnkaliPrimeClient({
    "unified_api_key": "ek_bridge_your_key_here",
    "base_url": "https://sdk.enkaliprime.com"
})

3๏ธโƒฃ Start Chatting

# Create a session
session = client.create_session(agent_name="AI Assistant")

# Send a message
response = client.send_message(
    message="Hello! What can you help me with?",
    session_id=session.id
)

print(response)
# "Hi there! I can help you with..."

๐Ÿ”„ Data Flow

sequenceDiagram
    participant App as ๐Ÿ Your App
    participant SDK as ๐Ÿ“ฆ SDK
    participant Bridge as โ˜๏ธ EnkaliBridge
    participant AI as ๐Ÿค– AI Engine

    App->>SDK: EnkaliPrimeClient(config)
    Note over SDK: Initialize client
    
    App->>SDK: create_session()
    SDK-->>App: ChatSession
    
    App->>SDK: send_message("Hello!")
    SDK->>Bridge: POST /resolve (first call)
    Bridge-->>SDK: Connection details
    SDK->>Bridge: POST /chat
    Bridge->>AI: Process with RAG
    AI-->>Bridge: Generate response
    
    alt Streaming Enabled
        Bridge-->>SDK: Stream chunks
        SDK-->>App: on_chunk callback
    else Standard Response
        Bridge-->>SDK: Full response
    end
    
    SDK-->>App: "Hi! How can I help?"
    
    App->>SDK: end_session()
    SDK-->>App: Session closed

๐Ÿ“š Examples

Basic Chat

from enkaliprime import EnkaliPrimeClient

# Initialize
client = EnkaliPrimeClient({
    "unified_api_key": "ek_bridge_xxx",
    "base_url": "https://sdk.enkaliprime.com"
})

# Chat
session = client.create_session()
response = client.send_message("What's the weather?", session.id)
print(response)

# Cleanup
client.close()

Async Usage

import asyncio
from enkaliprime import EnkaliPrimeClient

async def chat():
    async with EnkaliPrimeClient({
        "unified_api_key": "ek_bridge_xxx",
        "base_url": "https://sdk.enkaliprime.com"
    }) as client:
        session = client.create_session()
        
        response = await client.send_message_async(
            message="Tell me a joke",
            session_id=session.id
        )
        print(response)

asyncio.run(chat())

Streaming Responses

from enkaliprime import EnkaliPrimeClient

client = EnkaliPrimeClient({...})
session = client.create_session()

# Stream with callback
def on_chunk(text):
    print(text, end="", flush=True)

client.send_message(
    message="Write a poem about coding",
    session_id=session.id,
    stream=True,
    on_chunk=on_chunk
)

Context Manager

from enkaliprime import EnkaliPrimeClient

# Automatic cleanup
with EnkaliPrimeClient({...}) as client:
    session = client.create_session()
    response = client.send_message("Hello!", session.id)
# Client automatically closed

Loading States

from enkaliprime import EnkaliPrimeClient

client = EnkaliPrimeClient({...})
session = client.create_session()

# Simple loading animation (recommended)
response = client.send_message(
    message="Explain quantum physics",
    session_id=session.id,
    loading=True  # Shows "๐Ÿง  Thinking" with brain animation
)

# Custom loading message
response = client.send_message(
    message="Write a poem",
    session_id=session.id,
    loading="Composing..."  # Custom message
)

# Full customization
response = client.send_message(
    message="Complex analysis",
    session_id=session.id,
    loading={
        "message": "Processing",
        "style": "brain",  # brain, dots, moon, arrows, etc.
        "color": "magenta"  # cyan, green, yellow, blue, magenta, white
    }
)

Interactive Chat

from enkaliprime import EnkaliPrimeClient

client = EnkaliPrimeClient({
    "unified_api_key": "ek_bridge_your_key_here",
    "base_url": "https://sdk.enkaliprime.com"
})

# Session Creation
session = client.create_session(agent_name="Pycon Demo Agent")

# Input Message
message = input("Ask me anything: ")

# Send Message
response = client.send_message(
    message=message,
    session_id=session.id
)

print("Pycon Agent:", response)

๐Ÿ”Œ Framework Integrations

FastAPI

from fastapi import FastAPI
from pydantic import BaseModel
from enkaliprime import EnkaliPrimeClient

app = FastAPI()
client = EnkaliPrimeClient({...})

class ChatRequest(BaseModel):
    message: str
    session_id: str

@app.post("/chat")
async def chat(request: ChatRequest):
    response = await client.send_message_async(
        message=request.message,
        session_id=request.session_id
    )
    return {"response": response}

Flask

from flask import Flask, request, jsonify
from enkaliprime import EnkaliPrimeClient

app = Flask(__name__)
client = EnkaliPrimeClient({...})

@app.route("/chat", methods=["POST"])
def chat():
    data = request.json
    response = client.send_message(
        message=data["message"],
        session_id=data["session_id"]
    )
    return jsonify({"response": response})

Django

# views.py
from django.http import JsonResponse
from enkaliprime import EnkaliPrimeClient
import json

client = EnkaliPrimeClient({...})

def chat_view(request):
    data = json.loads(request.body)
    response = client.send_message(
        message=data["message"],
        session_id=data["session_id"]
    )
    return JsonResponse({"response": response})

๐Ÿ“– API Reference

EnkaliPrimeClient

The main client class for interacting with EnkaliPrime.

client = EnkaliPrimeClient(config)

Config Options

Parameter Type Required Default Description
unified_api_key str โœ… โ€” Your EnkaliBridge API key
base_url str โœ… โ€” EnkaliBridge gateway URL
user_id str โŒ None User identifier for tracking
timeout int โŒ 30 Request timeout (seconds)
max_retries int โŒ 3 Maximum retry attempts

Methods

Method Description Returns
send_message(message, session_id, ...) Send a message synchronously with optional loading animation str
send_message_async(message, session_id, ...) Send a message asynchronously str
create_session(agent_name, ...) Create a new chat session ChatSession
end_session() End the current session ChatSession | None
get_connection() Get resolved connection info ResolvedConnection
clear_history() Clear conversation history None
get_history() Get conversation history list[dict]
close() Close HTTP clients None

send_message() Parameters

Parameter Type Required Default Description
message str โœ… โ€” The user's message text
session_id str โœ… โ€” Current session ID
context list[dict] โŒ None Conversation history as list of {role, content} dicts
stream bool โŒ False Enable streaming response
on_chunk callable โŒ None Callback for streaming chunks
loading bool | str | dict โŒ False Loading animation config

Loading Parameter Options:

  • False (default): No animation
  • True: Default spinner with "Thinking" message
  • "Custom message": Custom loading message
  • {"message": "...", "style": "...", "color": "..."}: Full config

Available Styles: dots, line, dots2, bounce, pulse, moon, brain, arrows, bar, simple
Available Colors: cyan, green, yellow, blue, magenta, white


Data Models

classDiagram
    class ChatMessage {
        +str id
        +str text
        +bool is_user
        +str timestamp
        +MessageStatus status
        +str session_id
        +to_dict() dict
    }
    
    class ChatSession {
        +str id
        +str agent_name
        +bool is_active
        +str start_time
        +str? end_time
        +to_dict() dict
    }
    
    class ResolvedConnection {
        +str connection_id
        +str widget_id
        +str widget_name
        +str base_url
        +bool is_active
    }
    
    class ChatApiConfig {
        +str unified_api_key
        +str base_url
        +str? user_id
        +int timeout
        +validate() None
    }

Exceptions

Exception Description HTTP Code
EnkaliPrimeError Base exception for all SDK errors โ€”
AuthenticationError Invalid or expired API key 401
ConnectionError Network connectivity issues โ€”
APIError API returned an error response varies
StreamingError Error during streaming โ€”
ValidationError Invalid request parameters 400
from enkaliprime import (
    EnkaliPrimeClient,
    AuthenticationError,
    ConnectionError,
    APIError
)

try:
    response = client.send_message(...)
except AuthenticationError:
    print("Check your API key!")
except ConnectionError:
    print("Network issue, retrying...")
except APIError as e:
    print(f"API error {e.status_code}: {e.message}")

๐Ÿงช Testing

Run the Test Suite

# Install dev dependencies
pip install enkaliprime[dev]

# Run tests
pytest

# With coverage
pytest --cov=enkaliprime

Quick Verification

from enkaliprime import EnkaliPrimeClient, __version__

print(f"SDK Version: {__version__}")

client = EnkaliPrimeClient({
    "unified_api_key": "ek_bridge_xxx",
    "base_url": "https://sdk.enkaliprime.com"
})

# Test connection
connection = client.get_connection()
print(f"Connected to: {connection.widget_name}")

๐Ÿ“ Project Structure

enkaliprime/
โ”œโ”€โ”€ __init__.py        # Package exports
โ”œโ”€โ”€ client.py          # EnkaliPrimeClient class
โ”œโ”€โ”€ models.py          # Data models (ChatMessage, etc.)
โ”œโ”€โ”€ exceptions.py      # Custom exceptions
โ””โ”€โ”€ py.typed           # PEP 561 type marker

examples/
โ”œโ”€โ”€ basic_usage.py     # Simple usage example
โ”œโ”€โ”€ streaming_example.py
โ”œโ”€โ”€ async_example.py
โ”œโ”€โ”€ interactive_chat.py
โ””โ”€โ”€ fastapi_integration.py

tests/
โ”œโ”€โ”€ test_client.py
โ””โ”€โ”€ test_models.py

๐Ÿ›ก๏ธ Security

  • โœ… API keys are never logged
  • โœ… HTTPS-only communication
  • โœ… Secure credential handling
  • โœ… No sensitive data in errors

Best Practices

import os
from dotenv import load_dotenv

load_dotenv()

# โœ… Good: Use environment variables
client = EnkaliPrimeClient({
    "unified_api_key": os.getenv("ENKALI_API_KEY"),
    "base_url": os.getenv("ENKALI_BASE_URL")
})

# โŒ Bad: Hardcoded credentials
client = EnkaliPrimeClient({
    "unified_api_key": "ek_bridge_xxx",  # Never do this!
})

๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guide for details.

# Clone the repo
git clone https://github.com/enkaliprime/python-sdk.git
cd python-sdk

# Install in development mode
pip install -e ".[dev]"

# Run tests
pytest

# Format code
black enkaliprime
isort enkaliprime

๐Ÿ“„ License

This project is licensed under the MIT License โ€” see the LICENSE file for details.


๐Ÿ”— Links

Resource Link
๐Ÿ“– Documentation api.enkaliprime.com/docs
๐Ÿ  Website api.enkaliprime.com
๐Ÿ“ฆ PyPI pypi.org/project/enkaliprime
๐Ÿ™ GitHub github.com/enkaliprime/python-sdk
๐Ÿ“ง Support support@enkaliprime.com

Built with โค๏ธ by the EnkaliPrime Team

ยฉ 2024 EnkaliPrime. All rights reserved.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

enkaliprime-1.2.2.tar.gz (22.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

enkaliprime-1.2.2-py3-none-any.whl (24.6 kB view details)

Uploaded Python 3

File details

Details for the file enkaliprime-1.2.2.tar.gz.

File metadata

  • Download URL: enkaliprime-1.2.2.tar.gz
  • Upload date:
  • Size: 22.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.3

File hashes

Hashes for enkaliprime-1.2.2.tar.gz
Algorithm Hash digest
SHA256 c319571097cf74a3e7c28a20f0718c2dc9edd00d2cfe988310659da36b779dca
MD5 cd61c94c32c7b59a24aac7f07ec547f5
BLAKE2b-256 adc238375aba431f663e458cdf7dcbeb5f3731e70f9e9f36f39d7f9b5dee4e2c

See more details on using hashes here.

File details

Details for the file enkaliprime-1.2.2-py3-none-any.whl.

File metadata

  • Download URL: enkaliprime-1.2.2-py3-none-any.whl
  • Upload date:
  • Size: 24.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.3

File hashes

Hashes for enkaliprime-1.2.2-py3-none-any.whl
Algorithm Hash digest
SHA256 a8033233d6707253444aa75f7fe35cd1d394cc90ff152aa9f02b403fbbcb525c
MD5 9f8c0463fcafd79761497736d6bcea72
BLAKE2b-256 74e29e02161561b57b373be403129fb6a25ce5cfcac7a59c9d5c41410149e7ce

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page