Skip to main content

Obscura AI Gateway Python SDK - Unified interface for multiple AI model providers

Project description

Obscura Python SDK

Official Python SDK for Obscura AI Gateway - A unified interface for multiple AI model providers.

PyPI version Python Support License: MIT

Features

  • 🚀 OpenAI-Compatible API - Drop-in replacement for OpenAI SDK
  • 🔄 Streaming Support - Full SSE streaming for real-time responses
  • Async/Sync - Both synchronous and asynchronous interfaces
  • 🎯 Type Safe - Complete type hints for better IDE support
  • 🔌 Multi-Provider - Access OpenAI, Anthropic, Google, and more through one API
  • 🛡️ Error Handling - Granular exception types for better error management
  • 🔁 Auto-Retry - Built-in retry logic for transient failures

Installation

pip install obscura-ai

Or install from source:

git clone https://github.com/obscura/obscura-python.git
cd obscura-python/sdk/python
pip install -e .

Quick Start

Basic Chat Completion

from obscura import Obscura

client = Obscura(api_key="obscura_xxx")

response = client.chat.completions.create(
    model="gpt-4",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello! How are you?"}
    ]
)

print(response.choices[0].message.content)

Streaming Chat

from obscura import Obscura

client = Obscura(api_key="obscura_xxx")

print("AI: ", end="")
for chunk in client.chat.completions.create(
    model="gpt-4",
    messages=[{"role": "user", "content": "Tell me a story"}],
    stream=True
):
    content = chunk.choices[0].delta.get("content", "")
    print(content, end="", flush=True)
print()

Async Usage

from obscura import AsyncObscura
import asyncio

async def main():
    async with AsyncObscura(api_key="obscura_xxx") as client:
        response = await client.chat.completions.create(
            model="gpt-4",
            messages=[{"role": "user", "content": "Hello!"}]
        )
        print(response.choices[0].message.content)

asyncio.run(main())

Embeddings

from obscura import Obscura

client = Obscura(api_key="obscura_xxx")

response = client.embeddings.create(
    input=["Hello world", "Goodbye world"],
    model="text-embedding-3-small"
)

for embedding in response.data:
    print(f"Embedding {embedding.index}: {len(embedding.embedding)} dimensions")

List Available Models

from obscura import Obscura

client = Obscura(api_key="obscura_xxx")

models = client.models.list()
for model in models:
    print(f"{model.id} - {model.owned_by}")

Audio Transcription

from obscura import Obscura

client = Obscura(api_key="obscura_xxx")

with open("audio.mp3", "rb") as audio_file:
    response = client.audio.transcriptions.create(
        file=audio_file,
        model="whisper-1"
    )
    print(response.text)

Image Generation

from obscura import Obscura

client = Obscura(api_key="obscura_xxx")

response = client.images.generate(
    prompt="A beautiful sunset over mountains",
    model="dall-e-3"
)

print(f"Generated image: {response.data[0]['url']}")

Advanced Usage

Custom Base URL

from obscura import Obscura

client = Obscura(
    api_key="obscura_xxx",
    base_url="https://custom-endpoint.com/functions/v1",
    timeout=120.0
)

Context Manager

from obscura import Obscura

with Obscura(api_key="obscura_xxx") as client:
    response = client.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": "Hello"}]
    )
    print(response.choices[0].message.content)
# Client automatically closed

Error Handling

from obscura import Obscura
from obscura.exceptions import (
    AuthenticationError,
    RateLimitError,
    QuotaExceededError,
    APIError
)

client = Obscura(api_key="obscura_xxx")

try:
    response = client.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": "Hello"}]
    )
except AuthenticationError:
    print("Invalid API key")
except RateLimitError as e:
    print(f"Rate limit exceeded. Retry after {e.retry_after}s")
except QuotaExceededError:
    print("Quota exceeded. Please top up your account")
except APIError as e:
    print(f"API error: {e.message}")

API Reference

Client

Obscura(api_key, base_url, timeout, max_retries)

Synchronous client for Obscura API.

Parameters:

  • api_key (str): Your Obscura API token (format: obscura_xxx)
  • base_url (str, optional): API base URL. Default: https://emorprdwdukhmrgeclyg.supabase.co/functions/v1
  • timeout (float, optional): Request timeout in seconds. Default: 60.0
  • max_retries (int, optional): Maximum retry attempts. Default: 2

AsyncObscura(api_key, base_url, timeout, max_retries)

Asynchronous client for Obscura API. Same parameters as Obscura.

Chat Completions

client.chat.completions.create(**kwargs)

Create a chat completion.

Parameters:

  • messages (List[dict]): Conversation messages
  • model (str): Model identifier (e.g., "gpt-4", "claude-3-opus")
  • temperature (float, optional): Sampling temperature (0-2)
  • max_tokens (int, optional): Maximum tokens to generate
  • top_p (float, optional): Nucleus sampling parameter
  • stream (bool, optional): Enable streaming. Default: False
  • frequency_penalty (float, optional): Frequency penalty (-2.0 to 2.0)
  • presence_penalty (float, optional): Presence penalty (-2.0 to 2.0)

Returns: ChatCompletion or Iterator[ChatCompletionChunk] if streaming

Embeddings

client.embeddings.create(input, model, **kwargs)

Create embeddings for input text(s).

Parameters:

  • input (str | List[str]): Text or list of texts to embed
  • model (str): Embedding model identifier

Returns: Embedding

Models

client.models.list()

List all available models.

Returns: List[Model]

Audio

client.audio.transcriptions.create(file, model, **kwargs)

Transcribe audio file.

Parameters:

  • file (BinaryIO): Audio file opened in binary mode
  • model (str, optional): Transcription model. Default: "whisper-1"

Returns: TranscriptionResponse

Images

client.images.generate(prompt, model, **kwargs)

Generate image from text prompt.

Parameters:

  • prompt (str): Text description of desired image
  • model (str, optional): Image generation model. Default: "dall-e-3"

Returns: ImageGenerationResponse

Exception Hierarchy

ObscuraError
├── AuthenticationError (401)
├── RateLimitError (429)
├── QuotaExceededError (402)
├── ModelNotFoundError
├── ValidationError
└── APIError (general API errors)

Supported Models

The SDK supports all models available through Obscura AI Gateway:

  • OpenAI: GPT-4, GPT-3.5, GPT-4 Vision, DALL-E, Whisper
  • Anthropic: Claude 3 Opus, Sonnet, Haiku
  • Google: Gemini Pro, Gemini Pro Vision
  • And more: Check client.models.list() for complete list

Rate Limits & Quotas

  • Rate limits are enforced per token and can be configured in your dashboard
  • When rate limited (429), the SDK includes retry_after in the exception
  • Quota exceeded (402) indicates you need to add credits to your account

Development

# Install dev dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Format code
black obscura/

# Type checking
mypy obscura/

License

MIT License - see LICENSE file for details.

Support

Changelog

0.1.0 (2024-12-01)

  • Initial release
  • Chat completions with streaming support
  • Embeddings API
  • Audio transcription
  • Image generation
  • Models listing
  • Full async/sync support

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

obscura_ai-0.1.0.tar.gz (10.0 kB view details)

Uploaded Source

Built Distribution

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

obscura_ai-0.1.0-py3-none-any.whl (13.2 kB view details)

Uploaded Python 3

File details

Details for the file obscura_ai-0.1.0.tar.gz.

File metadata

  • Download URL: obscura_ai-0.1.0.tar.gz
  • Upload date:
  • Size: 10.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.14

File hashes

Hashes for obscura_ai-0.1.0.tar.gz
Algorithm Hash digest
SHA256 2018fc53cb1b22b1d63d3ec9e7024a684d4991e3015ba4db588391b885e7c5f8
MD5 293f8f32e3d6c4ad4627fefc71d1e7d6
BLAKE2b-256 41486fe2b1db59c7665c23185a3a82c0b795211e20285582356439c0802c5e78

See more details on using hashes here.

File details

Details for the file obscura_ai-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: obscura_ai-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 13.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.14

File hashes

Hashes for obscura_ai-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 de8482c5624514f67c7151ba692e4f2ed0e55f2b4ec74d233e1eaa12264e8768
MD5 7c084040d69a78e7a63ec362bc3360d1
BLAKE2b-256 7dee216e5e9eccbfd2b0b80b743ec135e206222f2fa64a07a32722e734f326d8

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