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.
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/v1timeout(float, optional): Request timeout in seconds. Default:60.0max_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 messagesmodel(str): Model identifier (e.g., "gpt-4", "claude-3-opus")temperature(float, optional): Sampling temperature (0-2)max_tokens(int, optional): Maximum tokens to generatetop_p(float, optional): Nucleus sampling parameterstream(bool, optional): Enable streaming. Default:Falsefrequency_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 embedmodel(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 modemodel(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 imagemodel(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_afterin 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
- Documentation: https://docs.obscura.ai
- Issues: https://github.com/obscura/obscura-python/issues
- Email: support@obscura.ai
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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2018fc53cb1b22b1d63d3ec9e7024a684d4991e3015ba4db588391b885e7c5f8
|
|
| MD5 |
293f8f32e3d6c4ad4627fefc71d1e7d6
|
|
| BLAKE2b-256 |
41486fe2b1db59c7665c23185a3a82c0b795211e20285582356439c0802c5e78
|
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
de8482c5624514f67c7151ba692e4f2ed0e55f2b4ec74d233e1eaa12264e8768
|
|
| MD5 |
7c084040d69a78e7a63ec362bc3360d1
|
|
| BLAKE2b-256 |
7dee216e5e9eccbfd2b0b80b743ec135e206222f2fa64a07a32722e734f326d8
|