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
Metadata
Release files for obscura-ai 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| obscura_ai-0.1.0.tar.gz | 10.0 kB | Without provenance | Details for obscura_ai-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| obscura_ai-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for obscura_ai-0.1.0-py3-none-any.whl |
Total release size: 23.2 kB
Release files / obscura_ai-0.1.0.tar.gz
| Download URL | obscura_ai-0.1.0.tar.gz |
|---|---|
| Size | 10.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
2018fc53cb1b22b1d63d3ec9e7024a684d4991e3015ba4db588391b885e7c5f8
|
|
BLAKE2b-256 checksum How to use checksums |
41486fe2b1db59c7665c23185a3a82c0b795211e20285582356439c0802c5e78
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.11.14
|
Release files / obscura_ai-0.1.0-py3-none-any.whl
| Download URL | obscura_ai-0.1.0-py3-none-any.whl |
|---|---|
| Size | 13.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
de8482c5624514f67c7151ba692e4f2ed0e55f2b4ec74d233e1eaa12264e8768
|
|
BLAKE2b-256 checksum How to use checksums |
7dee216e5e9eccbfd2b0b80b743ec135e206222f2fa64a07a32722e734f326d8
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.11.14
|
Security for obscura-ai 0.1.0
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.