NexusAPI Python SDK
Официальный Python SDK для NexusAPI — единый API для генерации видео и изображений через Veo, Kling, Seedance, Nano-Banana и др.
Установка
pip install nexusapi-sdk
Пакет на PyPI называется
nexusapi-sdk(имяnexusapiзарезервировано похожим проектом). Импорт остаётсяfrom nexusapi import ....
Quickstart — sync
from nexusapi import NexusClient
with NexusClient(api_key="ВАШ_КЛЮЧ") as client: # создать в panel.nexusapi.dev
# Изображение (sync — SDK сам опрашивает статус)
img = client.images.generate(
model="nano-banana",
prompt="Минималистичный логотип кофейни",
aspect_ratio="1:1",
)
print(img.image_url)
# → https://nexusapi-s3.../result.png
# Видео — получаем Task, ждём отдельно (до 10 минут на генерацию)
task = client.videos.create(
model="veo-3-fast",
prompt="Кот играет на пианино",
duration=8,
aspect_ratio="16:9",
)
task.wait(timeout=600)
print(task.video_url)
Quickstart — async (FastAPI / aiohttp / asyncio)
import asyncio
from nexusapi import AsyncNexusClient
async def main():
async with AsyncNexusClient(api_key="ВАШ_КЛЮЧ") as client:
task = await client.videos.create(
model="veo-3-fast",
prompt="Кот играет на пианино",
duration=8,
)
await task.wait()
print(task.video_url)
asyncio.run(main())
Публичный API идентичен sync — все методы те же, отличается только await.
Возможности
- Sync (
NexusClient) и async (AsyncNexusClient) — одинаковый API, можно использовать в скриптах или внутри FastAPI/aiohttp без блокировки event loop. - Auto-retries — на 5xx, 429 и сетевые ошибки. По умолчанию до 3 попыток
с экспоненциальным backoff (0.5s, 1s, 2s + jitter). Учитывает
Retry-Afterheader. Настраивается черезmax_retries=N. - Auto Idempotency-Key — для каждого POST автоматически генерируется UUID v4 если не передан свой. Retry безопасен — двойного списания не будет.
- Все native-параметры через
**kwargs—webhook_url,negative_prompt,image_url,cfg_scale,video_urlsдля seedance,source_video_urlдля veo-extend, и т.д. Передаются прямо вcreate()/generate(). - Auto-polling для image-моделей (sync UX). Для видео —
task.wait(). - Типизированные ошибки —
NexusError(база),BillingError,RateLimitError,ValidationError,NotFoundError,AuthenticationError,NexusPermissionError,NexusTimeoutError(client-side wait timeout),TaskFailedError(провайдер не справился),NetworkError(retries исчерпаны). - Context manager —
with NexusClient(...) as c:/async with AsyncNexusClient(...) as c:закрывает HTTP-соединение автоматически.
Примеры
Webhook вместо polling
task = client.videos.create(
model="veo-3-fast",
prompt="...",
duration=8,
webhook_url="https://your-app.com/nexus-callback",
)
# Не вызываем .wait() — NexusAPI POST'нет на webhook_url когда видео готово
return task.id # сохраним в БД, дождёмся колбэка
Image-to-video (Kling motion)
video = client.videos.create(
model="kling-v2.6-motion-1080p",
prompt="Камера медленно отъезжает, раскрывая пейзаж",
duration=8,
image_url="https://your-bucket.s3.../start-frame.jpg",
).wait(timeout=600)
print(video.video_url)
Image edit (nano-banana)
edited = client.images.generate(
model="nano-banana-pro",
prompt="Сделай небо более драматичным",
image_url="https://your-bucket.s3.../photo.jpg",
)
print(edited.image_url)
Извлечение результата
task = client.videos.create(...).wait()
print(task.video_url) # для видео-моделей
print(task.image_url) # для image-моделей (берёт первое из image_urls)
print(task.image_urls) # для image-моделей с несколькими изображениями
print(task.result) # сырой dict с провайдер-специфичным контентом
Обработка ошибок
from nexusapi import NexusClient, BillingError, RateLimitError, ValidationError
try:
task = client.videos.create(model="veo-3-fast", prompt="...", duration=8).wait()
except BillingError:
print("Недостаточно средств — пополни баланс в боте")
except RateLimitError:
print("Превышен rate-limit ключа — подожди минуту")
except ValidationError as e:
print(f"Невалидные параметры: {e}")
Каталог моделей
models = client.models.list()
for m in models:
print(f"{m['id']}: {m['priceRub']}₽ за {m['unit']}")
Документация
- docs.nexusapi.dev — гайды и каталог моделей
- docs.nexusapi.dev/api-reference — полный API reference
- docs.nexusapi.dev/models — параметры каждой модели
Лицензия
MIT
Metadata
Release files for nexusapi-sdk 0.2.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 |
|---|---|---|---|---|
| nexusapi_sdk-0.2.0.tar.gz | 17.7 kB | Without provenance | Details for nexusapi_sdk-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| nexusapi_sdk-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for nexusapi_sdk-0.2.0-py3-none-any.whl |
Total release size: 31.9 kB
Release files / nexusapi_sdk-0.2.0.tar.gz
| Download URL | nexusapi_sdk-0.2.0.tar.gz |
|---|---|
| Size | 17.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
63b0e40e28f4cb1eab91d5b6388b797cd887461bc10433174e6e5737c6b75b42
|
|
BLAKE2b-256 checksum How to use checksums |
5b4454fa3620b6a3ee24fc1e64f66f74b79ada3879a8aabbe3260bbd1b62e36d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.12.13
|
Release files / nexusapi_sdk-0.2.0-py3-none-any.whl
| Download URL | nexusapi_sdk-0.2.0-py3-none-any.whl |
|---|---|
| Size | 14.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
23c3ddb8c4715205498e88ebc002aa3f6fa2db8753461cbd151ff18a48315440
|
|
BLAKE2b-256 checksum How to use checksums |
ffc3216efbb3512da52dcc81148cbda73c3d826641f6a68afe045ce5b9c8d6ae
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.12.13
|
Security for nexusapi-sdk 0.2.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.