Python client for sunra.ai
Project description
sunra.ai Python Client
This is a Python client library for interacting with ML models deployed on sunra.ai.
Getting Started
To install the client, run:
pip install sunra-client
Before using the client, you'll need to:
- Sign up at sunra.ai
- Get your API key from the dashboard
- Set your API key as an environment variable:
export SUNRA_KEY=your-api-key
Configuration
There are two ways to configure your API key:
Method 1: Global Configuration (Recommended)
import sunra_client
# Configure the client with your API key
sunra_client.config(credentials="your-api-key")
# Now you can use the client without passing the key explicitly
response = sunra_client.subscribe(
"black-forest-labs/flux-kontext-pro/text-to-image",
arguments={"prompt": "a cute cat, realistic, orange"}
)
Method 2: Environment Variable
Set your API key as an environment variable:
export SUNRA_KEY=your-api-key
Method 3: Explicit Client Configuration
import sunra_client
# Create a client with explicit API key
client = sunra_client.SyncClient(key="your-api-key")
# Or for async client
async_client = sunra_client.AsyncClient(key="your-api-key")
Usage Examples
Now you can use the client to interact with your models. Here's an example of how to use it:
import sunra_client
response = sunra_client.subscribe(
"black-forest-labs/flux-kontext-pro/text-to-image",
arguments={
"prompt": "a cute cat, realistic, orange"
},
with_logs=True,
on_enqueue=print,
on_queue_update=print
)
print(response["images"][0]["url"])
Streaming Responses
You can stream real-time updates as your request is being processed:
import sunra_client
application = "black-forest-labs/flux-kontext-pro/text-to-image"
arguments = {"prompt": "a cute cat, realistic, orange"}
for event in sunra_client.stream(application, arguments):
print(f"Received event: {event}")
Asynchronous Requests
The client also supports asynchronous requests out of the box. Here's an example:
import asyncio
import sunra_client
async def main():
response = await sunra_client.subscribe_async(
"black-forest-labs/flux-kontext-pro/text-to-image",
arguments={"prompt": "a cute cat, realistic, orange"}
with_logs=True,
on_enqueue=print,
on_queue_update=print
)
print(response["images"][0]["url"])
asyncio.run(main())
Queuing Requests
When you want to send a request and keep receiving updates on its status, you can use the submit method:
import asyncio
import sunra_client
async def main():
response = await sunra_client.submit_async(
"black-forest-labs/flux-kontext-pro/text-to-image",
arguments={"prompt": "a cute cat, realistic, orange"}
)
async for event in response.iter_events():
if isinstance(event, sunra_client.Queued):
print("Queued. Position:", event.position)
elif isinstance(event, (sunra_client.InProgress, sunra_client.Completed)):
print(event)
result = await response.get()
print(result["images"][0]["url"])
asyncio.run(main())
File Upload Support
The client supports uploading files to sunra.ai:
import sunra_client
from PIL import Image
# Create a sync client
client = sunra_client.SyncClient()
# Upload an image file
image = Image.new("RGB", (100, 100), color="red")
image_url = client.upload_image(image)
# Upload any file from local path
file_url = client.upload_file("path/to/your/file.txt")
# Upload raw data
data_url = client.upload(
data=b"Hello, World!",
content_type="text/plain",
file_name="hello.txt"
)
File Upload Limits:
- Maximum file size: 100MB
- Supported formats: Images, videos, audio, documents, and other file types as supported by the specific model
Error Handling
The client provides comprehensive error handling with detailed error information:
import sunra_client
try:
response = sunra_client.subscribe(
"black-forest-labs/flux-kontext-pro/text-to-image",
arguments={
"prompt": "a cute cat, realistic, orange",
"seed": -2 # Invalid seed (should be >= 0)
},
with_logs=True,
on_enqueue=print,
on_queue_update=print
)
print(response["images"][0]["url"])
except sunra_client.SunraClientError as e:
print(f"Error: {e}")
# Access detailed error information
print(f"Error Code: {e.code}") # e.g., "invalid_input"
print(f"Error Message: {e.message}") # e.g., "Validation error: seed must be >= 0"
print(f"Error Details: {e.details}") # Additional error details
print(f"Timestamp: {e.timestamp}") # When the error occurred
Error Types
The client handles different types of errors:
Validation Errors (from model processing):
try:
response = sunra_client.subscribe(
"black-forest-labs/flux-kontext-pro/text-to-image",
arguments={"prompt": "test", "seed": -1} # Invalid seed
)
except sunra_client.SunraClientError as e:
# e.code: "invalid_input"
# e.message: "Validation error: seed must be >= 0"
pass
HTTP Errors (from API requests):
try:
response = sunra_client.subscribe(
"non-existent-model/endpoint",
arguments={"prompt": "test"}
)
except sunra_client.SunraClientError as e:
# e.code: "Bad Request"
# e.message: "Model endpoint is required"
# e.timestamp: "2025-01-16T12:00:00.000Z"
pass
Conditional Error Handling:
try:
response = sunra_client.subscribe("model/endpoint", arguments={})
except sunra_client.SunraClientError as e:
if e.code == "invalid_input":
print("Please check your input parameters")
elif e.code == "Bad Request":
print("Invalid API request")
else:
print(f"Unexpected error: {e}")
Credits
This project is derived from:
and adapted to work with sunra.ai. The original projects are licensed under the MIT/Apache 2.0 License. We extend our gratitude to the original authors for their contributions.
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 sunra_client-0.2.1.tar.gz.
File metadata
- Download URL: sunra_client-0.2.1.tar.gz
- Upload date:
- Size: 13.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
92dac488a0f2656d9cc316b57c090bfcac4fb1ae71421e05a59d758804c92231
|
|
| MD5 |
10c30b31a6bd6254aadec3941b7a6d6b
|
|
| BLAKE2b-256 |
525a58ef51cac5a507e421b79bfcc07d65ccc6b0bc589870e702bec3acabf841
|
File details
Details for the file sunra_client-0.2.1-py3-none-any.whl.
File metadata
- Download URL: sunra_client-0.2.1-py3-none-any.whl
- Upload date:
- Size: 9.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
fbfcbacd16ce7c6a3dabe23987e6bf1b170ad8d121ed2a482d890f9752def9de
|
|
| MD5 |
77592ff2ff4d67531e4be16551ad0096
|
|
| BLAKE2b-256 |
da664ba0a00a35e401fe9e0421550119d194d1f5e7e3729d08b89dcbcd896b94
|