Metadata-Version: 2.4
Name: nexaapi
Version: 1.0.0
Summary: Official Python SDK for NexaAPI — unified AI inference API for 50+ models including Flux, Stable Diffusion, Veo, Sora, Whisper, and more.
Author-email: NexaAPI <support@nexa-api.com>
License: MIT
Project-URL: Homepage, https://nexa-api.com
Project-URL: Documentation, https://nexa-api.com/docs
Project-URL: Repository, https://github.com/nexa-api/nexa-ai-python
Project-URL: Issues, https://github.com/nexa-api/nexa-ai-python/issues
Project-URL: Changelog, https://github.com/nexa-api/nexa-ai-python/blob/main/CHANGELOG.md
Keywords: nexa,nexaapi,nexa-ai,ai,api,sdk,image-generation,video-generation,text-to-speech,speech-to-text,flux,flux-api,flux-pro,stable-diffusion,sdxl,veo,sora,whisper,elevenlabs,kling,ideogram,recraft,ai-image-generator,ai-video-generator,text-to-image,text-to-video,image-upscaler,background-removal,music-generation,tts,stt,inference-api,machine-learning,deep-learning,generative-ai
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx>=0.24.0
Requires-Dist: pydantic>=2.0.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
Requires-Dist: pytest-httpx>=0.21; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: mypy>=1.0; extra == "dev"
Dynamic: license-file

# NexaAI Python SDK

[![PyPI version](https://img.shields.io/pypi/v/nexa-ai.svg)](https://pypi.org/project/nexa-ai/)
[![Python versions](https://img.shields.io/pypi/pyversions/nexa-ai.svg)](https://pypi.org/project/nexa-ai/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Downloads](https://img.shields.io/pypi/dm/nexa-ai.svg)](https://pypi.org/project/nexa-ai/)

The official Python SDK for **[NexaAPI](https://nexa-api.com)** — the unified AI inference API. Access **77+ AI models** through a single API key: image generation (Flux, Stable Diffusion, SDXL, Imagen 4), video generation (Kling, Veo 3.1, Sora 2), text-to-speech, speech-to-text, music generation, and image tools.

**5× cheaper than official APIs. No subscriptions. Credits never expire.**

---

## ✨ Features

- 🎨 **Image Generation** — 35+ models: Flux 2 Pro, Flux Schnell, SD 3.5, SDXL, Ideogram v2, Recraft v3, GPT-Image 1.5, Gemini 3 Pro Image, Imagen 4, and more
- 🎬 **Video Generation** — 17 models: Kling Video v3 Pro, Veo 3.1, Sora 2, Minimax, Pika 2.2, Hunyuan, and more
- 🔊 **Text-to-Speech** — OpenAI TTS HD, ElevenLabs Multilingual v3, Kokoro TTS, Gemini TTS
- 📝 **Speech-to-Text** — Whisper Large v3 Turbo, Deepgram Nova 3, AssemblyAI Universal 2
- 🎵 **Music Generation** — Suno v4.5, Udio v2, MusicGen Large, AudioCraft Stereo, Lyria 2
- 🛠️ **Image Tools** — Background removal, 4x upscaling, face enhancement, style transfer, inpainting, outpainting, object removal, colorization
- ⚡ **Sync + Async** — Both `NexaAI` and `AsyncNexaAI` clients
- 🔄 **Auto-polling** — Automatic job completion polling with configurable timeouts
- 🔁 **Retry logic** — Exponential backoff with jitter for transient errors
- 📦 **Typed** — Full Pydantic models and type hints

---

## 📦 Installation

```bash
pip install nexa-ai
```

**Requirements:** Python 3.8+

---

## 🚀 Quick Start

Get your free API key at [nexa-api.com](https://nexa-api.com) ($5 free credits, no credit card required).

### Image Generation

```python
from nexa_ai import NexaAI

client = NexaAI(api_key="your-api-key")

# Generate with Flux 2 Pro
result = client.images.generate(
    model="flux-2-pro",
    prompt="a majestic cat sitting on the moon, photorealistic",
    width=1024,
    height=1024,
)
print(result.url)   # https://cdn.nexa-api.com/...
print(result.cost)  # 0.06
```

### Video Generation

```python
result = client.videos.generate(
    model="kling-video-v3-pro",
    prompt="a golden retriever running through wildflowers, cinematic slow motion",
    duration=5.0,
    aspect_ratio="16:9",
)
print(result.url)
```

### Text-to-Speech

```python
result = client.audio.speech(
    model="openai-tts-hd",
    text="Welcome to NexaAPI!",
    voice="alloy",
)
print(result.url)  # Direct link to MP3
```

### Speech-to-Text

```python
result = client.audio.transcribe(
    model="whisper-large-v3-turbo",
    audio_url="https://example.com/audio.mp3",
)
print(result.text)      # "Hello world..."
print(result.language)  # "en"
```

### Music Generation

```python
result = client.audio.generate_music(
    model="suno-v4.5",
    prompt="upbeat electronic dance music, catchy synth melody, 120 BPM",
    duration=30.0,
)
print(result.url)
```

### Image Tools

```python
# Upscale 4x
upscaled = client.images.upscale(image_url="https://example.com/photo.jpg")

# Remove background
no_bg = client.images.remove_background(image_url="https://example.com/photo.jpg")

# Face enhancement
enhanced = client.images.enhance_face(image_url="https://example.com/portrait.jpg")

# Style transfer
styled = client.images.style_transfer(
    image_url="https://example.com/photo.jpg",
    style_url="https://example.com/style.jpg",
)

# Inpainting
inpainted = client.images.inpaint(
    image_url="https://example.com/photo.jpg",
    mask_url="https://example.com/mask.png",
    prompt="a beautiful garden",
)

# Colorize B&W photos
colorized = client.images.colorize(image_url="https://example.com/bw-photo.jpg")
```

### List Available Models

```python
# List all models
response = client.models.list()
for model in response.data:
    print(f"{model.name} ({model.category}) — ${model.pricing_per_unit}/unit")

# Filter by category
image_models = client.models.list(category="image")
video_models = client.models.list(category="video")
audio_models = client.models.list(category="audio")

# Fetch all models at once
all_models = client.models.list_all()
print(f"Total: {len(all_models)} models")
```

---

## ⚡ Async Usage

```python
import asyncio
from nexa_ai import AsyncNexaAI

async def main():
    async with AsyncNexaAI(api_key="your-api-key") as client:
        # Generate an image
        result = await client.images.generate(
            model="flux-schnell",
            prompt="a futuristic city at night",
        )
        print(result.url)

        # Concurrent generation (3 images at once!)
        tasks = [
            client.images.generate(model="flux-schnell", prompt=p)
            for p in ["red car", "blue ocean", "green forest"]
        ]
        results = await asyncio.gather(*tasks)
        for r in results:
            print(r.url)

asyncio.run(main())
```

---

## 🔧 Configuration

### Environment Variable

```bash
export NEXA_API_KEY="your-api-key"
```

```python
from nexa_ai import NexaAI
client = NexaAI()  # Automatically reads NEXA_API_KEY
```

### Custom Settings

```python
client = NexaAI(
    api_key="your-api-key",
    base_url="https://nexa-api.com",    # Custom base URL
    timeout=120.0,                       # Request timeout (seconds)
    max_retries=3,                       # Retry count for transient errors
    poll_interval=2.0,                   # Job polling interval (seconds)
    poll_timeout=600.0,                  # Max wait for job completion (seconds)
)
```

### RapidAPI Access

```python
client = NexaAI(
    rapidapi_key="your-rapidapi-key",
    rapidapi_host="nexa-api.p.rapidapi.com",
)
```

---

## 📖 API Reference

### `NexaAI` / `AsyncNexaAI`

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `api_key` | `str` | `NEXA_API_KEY` env | Your NexaAPI key |
| `base_url` | `str` | `https://nexa-api.com` | API base URL |
| `timeout` | `float` | `120.0` | HTTP timeout (seconds) |
| `max_retries` | `int` | `3` | Max retries for transient errors |
| `poll_interval` | `float` | `2.0` | Job polling interval (seconds) |
| `poll_timeout` | `float` | `600.0` | Max job wait time (seconds) |

### `client.images.generate()`

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `model` | `str` | ✅ | Model ID (e.g., `"flux-2-pro"`, `"flux-schnell"`) |
| `prompt` | `str` | ✅ | Text description of the image |
| `negative_prompt` | `str` | | Things to exclude |
| `width` | `int` | | Image width in pixels |
| `height` | `int` | | Image height in pixels |
| `num_images` | `int` | | Number of images (default 1) |
| `guidance_scale` | `float` | | CFG scale |
| `num_inference_steps` | `int` | | Denoising steps |
| `seed` | `int` | | Random seed |
| `style` | `str` | | Style preset |
| `lora_url` | `str` | | LoRA weights URL |
| `lora_scale` | `float` | | LoRA influence (0–1) |
| `image_url` | `str` | | Input image for img2img |
| `strength` | `float` | | Denoising strength (0–1) |
| `wait` | `bool` | | Auto-poll for result (default `True`) |

**Returns:** `ImageResult` with `.url`, `.job_id`, `.model`, `.width`, `.height`, `.seed`, `.cost`

### `client.videos.generate()`

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `model` | `str` | ✅ | Model ID (e.g., `"kling-video-v3-pro"`, `"veo-3.1"`) |
| `prompt` | `str` | ✅ | Text description of the video |
| `image_url` | `str` | | Input image for image-to-video |
| `duration` | `float` | | Duration in seconds |
| `fps` | `int` | | Frames per second |
| `aspect_ratio` | `str` | | e.g., `"16:9"`, `"9:16"`, `"1:1"` |
| `wait` | `bool` | | Auto-poll (default `True`) |

**Returns:** `VideoResult` with `.url`, `.job_id`, `.model`, `.duration`, `.cost`

### `client.audio.speech()`

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `model` | `str` | ✅ | TTS model (e.g., `"openai-tts-hd"`) |
| `text` | `str` | ✅ | Text to speak |
| `voice` | `str` | | Voice ID |
| `language` | `str` | | Language code |
| `speed` | `float` | | Speed multiplier |
| `format` | `str` | | Output format (`"mp3"`, `"wav"`) |

**Returns:** `AudioResult` with `.url`, `.duration`, `.cost`

### `client.audio.transcribe()`

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `model` | `str` | ✅ | STT model (e.g., `"whisper-large-v3-turbo"`) |
| `audio_url` | `str` | ✅ | URL of audio to transcribe |
| `language` | `str` | | Language hint |

**Returns:** `TranscriptionResult` with `.text`, `.language`, `.segments`, `.cost`

### `client.audio.generate_music()`

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `model` | `str` | ✅ | Music model (e.g., `"suno-v4.5"`) |
| `prompt` | `str` | ✅ | Music description |
| `duration` | `float` | | Duration in seconds |
| `genre` | `str` | | Genre hint |
| `lyrics` | `str` | | Optional lyrics |
| `instrumental` | `bool` | | Instrumental only |

**Returns:** `AudioResult` with `.url`, `.duration`, `.cost`

### Image Tools

| Method | Description | Key Parameters |
|--------|-------------|----------------|
| `client.images.upscale()` | Upscale image 4x | `image_url`, `model`, `scale` |
| `client.images.remove_background()` | Remove background | `image_url` |
| `client.images.enhance_face()` | Enhance faces | `image_url` |
| `client.images.colorize()` | Colorize B&W | `image_url` |
| `client.images.inpaint()` | Fill masked region | `image_url`, `mask_url`, `prompt` |
| `client.images.outpaint()` | Extend image | `image_url`, `prompt` |
| `client.images.remove_object()` | Remove object | `image_url`, `mask_url` |
| `client.images.style_transfer()` | Apply style | `image_url`, `style_url` |

---

## 🎯 Supported Models

### Image Generation (35+ models)

| Model | ID | Price/image |
|-------|----|-------------|
| **Flux 2 Pro** | `flux-2-pro` | $0.060 |
| **Flux 2 Max** | `flux-2-max` | $0.100 |
| **Flux 2 Flash** | `flux-2-flash` | $0.010 |
| **Flux 2 Turbo** | `flux-2-turbo` | $0.020 |
| **Flux Pro** | `flux-pro` | $0.050 |
| **Flux Pro Ultra** | `flux-pro-ultra` | $0.080 |
| **Flux Schnell** | `flux-schnell` | $0.003 |
| **Flux Dev** | `flux-dev` | $0.025 |
| **Flux Dev LoRA** | `flux-dev-lora` | $0.030 |
| **Flux Pro LoRA** | `flux-pro-lora` | $0.070 |
| **Flux Kontext Pro** | `flux-kontext-pro` | $0.040 |
| **Flux Kontext Max** | `flux-kontext-max` | $0.080 |
| **Stable Diffusion 3.5 Large** | `sd-3.5-large` | $0.065 |
| **Stable Diffusion 3.5 Medium** | `sd-3.5-medium` | $0.035 |
| **Stable Diffusion 3.5 Turbo** | `sd-3.5-turbo` | $0.015 |
| **SDXL** | `sdxl` | $0.020 |
| **SDXL Lightning** | `sdxl-lightning` | $0.008 |
| **Ideogram v2** | `ideogram-v2` | $0.080 |
| **Ideogram v2 Turbo** | `ideogram-v2-turbo` | $0.050 |
| **Recraft v3** | `recraft-v3` | $0.040 |
| **GPT-Image 1.5** | `gpt-image-1.5` | $0.040 |
| **Gemini 2.5 Flash Image** | `gemini-2.5-flash-image` | $0.039 |
| **Gemini 3 Pro Image** | `gemini-3-pro-image` | $0.050 |
| **Gemini 3.1 Flash Image** | `gemini-3.1-flash-image` | $0.080 |
| **Imagen 4** | `imagen-4` | $0.040 |
| **Kling Image V3** | `kling-image-v3` | $0.050 |
| **Seedream 4.5** | `seedream-4.5` | $0.040 |
| **Seedream V5 Lite** | `seedream-v5-lite` | $0.030 |
| **Aurora** | `aurora` | $0.060 |
| **Playground v3** | `playground-v3` | $0.030 |
| **Aura Flow** | `aura-flow` | $0.020 |
| **Kolors** | `kolors` | $0.025 |
| **Nano Banana** | `nano-banana` | $0.039 |
| **Nano Banana 2** | `nano-banana-2` | $0.080 |
| **Nano Banana Pro** | `nano-banana-pro` | $0.150 |

### Video Generation (17 models)

| Model | ID | Price/video |
|-------|----|-------------|
| **Kling Video v3 Pro** | `kling-video-v3-pro` | $0.500 |
| **Kling Video v3 Standard** | `kling-video-v3-standard` | $0.250 |
| **Kling Video v2.6 Pro** | `kling-video-v2.6-pro` | $0.070 |
| **Kling Video v2.5 Turbo** | `kling-video-v2.5-turbo` | $0.070 |
| **Kling O3 Video** | `kling-o3-video` | $0.100 |
| **Kling AI Avatar** | `kling-ai-avatar` | $0.150 |
| **Veo 3.1** | `veo-3.1` | $0.800 |
| **Veo 3.1 Fast** | `veo-3.1-fast` | $0.400 |
| **Sora 2** | `sora-2` | $1.000 |
| **Minimax Video 01** | `minimax-video-01` | $0.350 |
| **Seedance v1.5** | `seedance-v1.5` | $0.300 |
| **Pika 2.2** | `pika-2.2` | $0.300 |
| **Hunyuan Video** | `hunyuan-video` | $0.200 |
| **Wan 2.2** | `wan-2.2` | $0.250 |
| **CogVideoX 5B** | `cogvideox-5b` | $0.150 |
| **LTX Video** | `ltx-video` | $0.120 |

### Audio Models (16 models)

| Model | ID | Price/unit |
|-------|----|------------|
| **OpenAI TTS HD** | `openai-tts-hd` | $0.0003/char |
| **OpenAI TTS Standard** | `openai-tts-standard` | $0.00015/char |
| **ElevenLabs Multilingual v3** | `elevenlabs-multilingual-v3` | $0.0003/char |
| **ElevenLabs Turbo v3** | `elevenlabs-turbo-v3` | $0.00015/char |
| **ElevenLabs Sound Effects** | `elevenlabs-sound-effects` | $0.020/gen |
| **ElevenLabs Music** | `elevenlabs-music` | — |
| **Kokoro TTS** | `kokoro-tts` | $0.0001/char |
| **Gemini TTS** | `gemini-tts` | $0.010/gen |
| **Whisper Large v3 Turbo** | `whisper-large-v3-turbo` | $0.0001/sec |
| **Deepgram Nova 3** | `deepgram-nova-3` | $0.00008/sec |
| **AssemblyAI Universal 2** | `assemblyai-universal-2` | $0.00012/sec |
| **Suno v4.5** | `suno-v4.5` | $0.100/gen |
| **Udio v2** | `udio-v2` | $0.080/gen |
| **MusicGen Large** | `musicgen-large` | $0.050/gen |
| **AudioCraft Stereo** | `audiocraft-stereo` | $0.040/gen |
| **Lyria 2** | `lyria-2` | $0.050/gen |

### Image Tools (9 tools)

| Tool | ID | Price/use |
|------|----|-----------|
| **Background Removal** | `background-removal` | $0.010 |
| **Image Upscaler 4x** | `image-upscaler-4x` | $0.020 |
| **SeedVR2 Upscaler** | `seedvr2-upscaler` | $0.030 |
| **Face Enhancement** | `face-enhancement` | $0.015 |
| **Style Transfer** | `style-transfer` | $0.040 |
| **Image Inpainting** | `image-inpainting` | $0.030 |
| **Image Outpainting** | `image-outpainting` | $0.040 |
| **Object Removal** | `object-removal` | $0.025 |
| **Image Colorization** | `image-colorization` | $0.020 |

---

## 💰 Pricing

NexaAPI is **5× cheaper** than official APIs. No subscriptions — buy credits once, use them forever.

| Plan | Price | Credits | ~Flux Pro Images | ~Veo 3.1 Video |
|------|-------|---------|------------------|-----------------|
| **Starter** | $20 | $20 | ~5,000 images | ~25 seconds |
| **Pro** | $100 | $100 | ~25,000 images | ~125 seconds |
| **Enterprise** | Custom | Custom | Volume discounts 20%+ | Dedicated infra |

All plans include access to all 77+ models. Credits never expire.

👉 [Get started at nexa-api.com](https://nexa-api.com) — $5 free credits, no credit card required.

---

## 🔒 Error Handling

```python
from nexa_ai import NexaAI
from nexa_ai.exceptions import (
    AuthenticationError,
    RateLimitError,
    InsufficientCreditsError,
    ValidationError,
    ServerError,
    TimeoutError,
    JobFailedError,
)

client = NexaAI(api_key="your-key")

try:
    result = client.images.generate(model="flux-2-pro", prompt="hello")
except AuthenticationError:
    print("Invalid API key!")
except InsufficientCreditsError:
    print("Top up at https://nexa-api.com")
except RateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after}s")
except ValidationError as e:
    print(f"Invalid params: {e.message}")
except TimeoutError:
    print("Job took too long")
except JobFailedError as e:
    print(f"Job {e.job_id} failed: {e.error_detail}")
except ServerError:
    print("Server error, try again later")
```

---

## 🔗 Links

- **Website:** [nexa-api.com](https://nexa-api.com)
- **API Docs:** [nexa-api.com/docs](https://nexa-api.com/docs)
- **Pricing:** [nexa-api.com/pricing](https://nexa-api.com/pricing)
- **GitHub:** [github.com/nexa-api/nexa-ai-python](https://github.com/nexa-api/nexa-ai-python)
- **PyPI:** [pypi.org/project/nexa-ai](https://pypi.org/project/nexa-ai/)
- **RapidAPI:** [rapidapi.com/nexa-api](https://rapidapi.com/nexa-api)
- **Status:** [status.nexa-api.com](https://status.nexa-api.com)

---

## 📄 License

MIT License. See [LICENSE](LICENSE) for details.

---

## 🤝 Contributing

Contributions welcome! Please open an issue or submit a pull request on [GitHub](https://github.com/nexa-api/nexa-ai-python).

```bash
# Development setup
git clone https://github.com/nexa-api/nexa-ai-python.git
cd nexa-ai-python
pip install -e ".[dev]"
pytest
```

---

<p align="center">
  Built with ❤️ by <a href="https://nexa-api.com">NexaAPI</a><br>
  <sub>AI Image Generation API • Flux API • Stable Diffusion API • Video Generation API • Text-to-Speech API • AI Inference Platform</sub>
</p>
