From 03070e7a6e630b15a09d5e689c6745445a713b40 Mon Sep 17 00:00:00 2001 From: Dawid Wenderski Date: Sun, 29 Nov 2026 17:47:19 +0100 Subject: [PATCH 01/13] Add synchronous transcription: transcribe_sync() and its price quote client.transcription.transcribe_sync() (sync and async clients) uploads a short audio file (up to 60 s) to POST /audio/transcriptions/sync and returns the transcript from the response as SyncTranscriptionResult: transcription, detected language, duration, price and, with timestamps, segments with optional words. There is no job to poll. The model defaults to FluidSpeechPro; ts_level implies include_ts, as in create(). transcribe_sync_price() quotes it from the file or from duration_seconds, always as multipart. Synchronous transcription is in limited availability. A 404, or a 422 on model, is raised as SyncTranscriptionUnavailableError, which is also a NotFoundError or a ValidationError so existing handlers keep catching it. Other errors (a clip over 60 s, balance, rate limit) are unchanged. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 14 ++ README.md | 33 ++- docs/api-reference.md | 45 ++++ examples/transcription_sync.py | 45 ++++ src/deapi_sdk/__init__.py | 4 + src/deapi_sdk/_constants.py | 3 + src/deapi_sdk/_exceptions.py | 35 +++ src/deapi_sdk/resources/transcription.py | 140 ++++++++++++ src/deapi_sdk/types/__init__.py | 3 +- src/deapi_sdk/types/transcription.py | 29 ++- tests/test_transcription_sync.py | 264 +++++++++++++++++++++++ 11 files changed, 612 insertions(+), 3 deletions(-) create mode 100644 examples/transcription_sync.py create mode 100644 tests/test_transcription_sync.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f04be5..21f5f15 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,20 @@ All notable changes to this project are documented in this file. Versions follow [Semantic Versioning](https://semver.org/) (pre-1.0: minor versions may contain breaking changes). +## Unreleased + +### Added + +- `client.transcription.transcribe_sync()` (sync and async clients): synchronous transcription of + short audio files (up to 60 seconds). The transcript comes back in the response as the new + `SyncTranscriptionResult` (`transcription`, `language`, `duration`, `price`, optional `segments` + with `words`); there is no job to poll. `transcribe_sync_price()` quotes it from the file or from + `duration_seconds`. The model defaults to `FluidSpeechPro`. +- `SyncTranscriptionUnavailableError`: synchronous transcription is in limited availability; + accounts without access get a 404 or a 422 on `model`, raised as this error. It is also a + `NotFoundError` or a `ValidationError`, so existing handlers keep catching it. +- Example `examples/transcription_sync.py`. + ## [0.6.1] - 2026-11-19 ### Added diff --git a/README.md b/README.md index 4371f99..872d763 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Generate images, videos, audio, transcriptions, embeddings, and more — all thr - **Video generation** — text-to-video, image-to-video (keyframes or reference images/videos/audio), audio-to-video, upscale - **Video description** — timestamped events and scenes of a video - **Audio** — text-to-speech (with voice cloning), text-to-music (with a style reference) -- **Transcription** — URLs and file uploads, plain-text or structured JSON transcripts +- **Transcription** — URLs and file uploads, plain-text or structured JSON transcripts; synchronous transcription of short clips (no job to poll) - **Embeddings, OCR, prompt enhancement** - **Account and keys** — balance, usage, payments, API-key management (ADMIN keys) - **Sync + Async** — both `DeapiClient` and `AsyncDeapiClient` @@ -256,6 +256,31 @@ return plain text with timestamps inline. `client.transcription.get_transcript(r `deapi_sdk.parse_transcript(raw)`) handles both and returns a `Transcript` whose `format` is `"json"` or `"text"` (`segments` is empty for text). Result URLs are downloaded without your API key. +#### Synchronous transcription (short clips) + +For audio up to 60 seconds and 16 MiB, `transcribe_sync()` returns the transcript in the same call: +no job, no polling, no webhook. Use it when you need the text right away (voice notes, commands) +and `create()` for longer audio. The language is detected and returned. + +```python +from pathlib import Path + +result = client.transcription.transcribe_sync( + source_file=Path("voice-note.webm"), # mp3, wav, ogg, flac, aac, m4a/mp4, webm + ts_level="word", # optional: segment | word (implies timestamps) +) # model defaults to "FluidSpeechPro" +print(result.language, result.transcription) +print(result.duration, result.price) # seconds of audio, USD charged +for seg in result.segments or []: # only with timestamps + print(seg.start, seg.end, seg.text, [w.word for w in seg.words or []]) + +quote = client.transcription.transcribe_sync_price(duration_seconds=30) # or source_file=... +``` + +Synchronous transcription is in limited availability; accounts without access get a 404 or a 422 +on `model`. Both are raised as `SyncTranscriptionUnavailableError` (also a `NotFoundError` / +`ValidationError`). A clip longer than 60 seconds is a `ValidationError` on `source_file`. + ### Embeddings and OCR ```python @@ -488,6 +513,11 @@ except DeapiError as e: Existing `except AccountSuspendedError` and `except ValidationError` handlers keep working. +`transcription.transcribe_sync()` and `transcribe_sync_price()` raise +`SyncTranscriptionUnavailableError` when the account cannot use synchronous transcription (a 404, +or a 422 on `model`). It is also a `NotFoundError` or a `ValidationError`, so those handlers still +catch it. + **Retries** (up to `max_retries`): - `GET` requests are retried on 429, 5xx and network errors. @@ -591,6 +621,7 @@ The [`examples/`](https://github.com/deapi-ai/deapi-python-sdk/tree/main/example | [`basic_image.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/basic_image.py) | Image generation, transformation, upscale | | [`async_batch.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/async_batch.py) | Concurrent async job submission | | [`transcription.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/transcription.py) | Transcription with JSON and plain-text transcripts | +| [`transcription_sync.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/transcription_sync.py) | Synchronous transcription of a short clip (no job) | | [`tts_and_audio.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/tts_and_audio.py) | Text-to-speech and music generation | | [`video_generation.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/video_generation.py) | Text-to-video and image-to-video | | [`realtime_status.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/realtime_status.py) | Live job progress over WebSocket | diff --git a/docs/api-reference.md b/docs/api-reference.md index dbc6ced..679f545 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -365,6 +365,47 @@ job = client.transcription.create( source). Pass the same `ts_level` / `diarize` / `lang` / `include_metadata` as the job, otherwise the quote is lower than the charge. +### `transcribe_sync()` / `transcribe_sync_price()` + +Synchronous transcription of a short audio file: the transcript is in the response, there is no +job to poll. For clips up to 60 seconds and 16 MiB; use `create()` for longer audio. + +```python +result = client.transcription.transcribe_sync( + *, + source_file: FileInput, # audio: aac, mpeg, mp4/m4a, ogg, wav, webm, flac + model: str = "FluidSpeechPro", + include_ts: bool | None = None, # implied by ts_level + ts_level: str | None = None, # "segment" (default with timestamps) | "word" +) -> SyncTranscriptionResult + +price = client.transcription.transcribe_sync_price( + *, + model: str = "FluidSpeechPro", + source_file: FileInput | None = None, # exactly one of source_file / duration_seconds + duration_seconds: float | None = None, +) -> PriceResult +``` + +There is no language parameter: the language is detected and returned. Billed per second of audio. + +```python +class SyncTranscriptionResult(BaseModel): + request_id: str + transcription: str + duration: float | None # seconds of audio (the billing unit) + language: str | None # detected language, e.g. "en" + price: float | None # USD charged + ts_level: str | None # only with timestamps + segments: list[TranscriptSegment] | None # only with timestamps; words only at ts_level="word" +``` + +Synchronous transcription is in limited availability; accounts without access get a 404 or a 422 +on `model`, raised as `SyncTranscriptionUnavailableError` (also a `NotFoundError` / +`ValidationError`). Other errors are the usual ones: a clip over 60 seconds or a bad file is a +`ValidationError` on `source_file`, missing credit an `InsufficientBalanceError`, and the rate +limit (shared with `create()`) a `RateLimitError`. + ### `get_transcript()` ```python @@ -759,6 +800,10 @@ authentication failures during the channel authorization surface as the usual `A `KeyLimitExceededError` (402) is the **key's** spend limit; `InsufficientBalanceError` (422) means the **account** has no credit. They need different fixes (raise the key's limit vs. top up). +`SyncTranscriptionUnavailableError` is raised by `transcription.transcribe_sync()` / +`transcribe_sync_price()` when the account cannot use synchronous transcription. Each instance is +also a `NotFoundError` (404) or a `ValidationError` (422 on `model`). + Backward compatibility: `except AccountSuspendedError` (it used to catch every 403) and `except ValidationError` (still catches `InsufficientBalanceError`) keep working. Catch `PermissionDeniedError` to handle every 403. diff --git a/examples/transcription_sync.py b/examples/transcription_sync.py new file mode 100644 index 0000000..36766db --- /dev/null +++ b/examples/transcription_sync.py @@ -0,0 +1,45 @@ +"""Synchronous transcription of a short audio clip. + +The transcript comes back in the same HTTP response: no job, no polling, no webhook. +Use it for clips up to 60 seconds (voice notes, commands); use +``client.transcription.create()`` for longer audio. + +Synchronous transcription is in limited availability; accounts without access get a 404 +or a 422 on ``model`` (raised as ``SyncTranscriptionUnavailableError``). + +Usage: + export DEAPI_API_KEY="sk-dp--" + python examples/transcription_sync.py voice-note.webm +""" + +import sys +from pathlib import Path + +from deapi_sdk import DeapiClient, SyncTranscriptionUnavailableError, ValidationError + +audio = Path(sys.argv[1] if len(sys.argv) > 1 else "voice-note.webm") + +with DeapiClient() as client: + # Free quote, by duration (or pass source_file=audio) + quote = client.transcription.transcribe_sync_price(duration_seconds=30) + print(f"30 s of audio costs ${quote.price}") + + try: + result = client.transcription.transcribe_sync( + source_file=audio, # Path, bytes or a binary file object (a plain str is rejected) + ts_level="word", # optional: segment | word (implies timestamps) + ) + except SyncTranscriptionUnavailableError: + print("Synchronous transcription is not available for this account; use transcription.create().") + raise SystemExit(1) from None + except ValidationError as e: + # e.g. errors["source_file"]: clip longer than 60 s, file too large or unsupported type + print(e.message, e.errors) + raise SystemExit(1) from None + + print(f"[{result.language}] {result.transcription}") + print(f"{result.duration} s of audio, charged ${result.price}") + for seg in result.segments or []: + print(f" [{seg.start} - {seg.end}] {seg.text}") + for word in seg.words or []: + print(f" {word.start:>6} {word.word}") diff --git a/src/deapi_sdk/__init__.py b/src/deapi_sdk/__init__.py index 21fb333..2311a2f 100644 --- a/src/deapi_sdk/__init__.py +++ b/src/deapi_sdk/__init__.py @@ -27,6 +27,7 @@ RateLimitError, RealtimeError, ServerError, + SyncTranscriptionUnavailableError, ValidationError, ) from deapi_sdk._polling import AsyncJob, AsyncJobs, Job, Jobs @@ -50,6 +51,7 @@ ModelsResponse, PriceResult, ) +from deapi_sdk.types.transcription import SyncTranscriptionResult from deapi_sdk.types.video import VideoDescription, VideoEvent, parse_video_description from deapi_sdk.types.websocket import WebSocketConfig, WebSocketConnection from deapi_sdk.webhook import ( @@ -370,6 +372,7 @@ async def __aexit__(self, *args: Any) -> None: "WebSocketConfig", "WebSocketConnection", # Results + "SyncTranscriptionResult", "Transcript", "TranscriptSegment", "TranscriptWord", @@ -396,6 +399,7 @@ async def __aexit__(self, *args: Any) -> None: "RateLimitError", "RealtimeError", "ServerError", + "SyncTranscriptionUnavailableError", "ValidationError", # Webhook "InvalidSignatureError", diff --git a/src/deapi_sdk/_constants.py b/src/deapi_sdk/_constants.py index 60a005f..9593c4d 100644 --- a/src/deapi_sdk/_constants.py +++ b/src/deapi_sdk/_constants.py @@ -34,6 +34,9 @@ # Transcription (one endpoint for audio and video, URL or file) "transcribe": "audio/transcriptions", "transcribe_price": "audio/transcriptions/price", + # Synchronous transcription of short audio files (no job: the transcript is in the response) + "transcribe_sync": "audio/transcriptions/sync", + "transcribe_sync_price": "audio/transcriptions/sync/price", # Embeddings "txt2embedding": "embeddings", "txt2embedding_price": "embeddings/price", diff --git a/src/deapi_sdk/_exceptions.py b/src/deapi_sdk/_exceptions.py index a7c9882..5c3aee4 100644 --- a/src/deapi_sdk/_exceptions.py +++ b/src/deapi_sdk/_exceptions.py @@ -120,6 +120,41 @@ class ActiveKeyLimitReachedError(ValidationError): """422 ``active_key_limit_reached`` — would exceed the maximum number of active API keys.""" +class SyncTranscriptionUnavailableError(DeapiError): + """Synchronous transcription is not available for this account. + + Raised by ``transcription.transcribe_sync()`` and ``transcribe_sync_price()`` for a 404, or for a + 422 that rejects ``model``. Every instance is also a ``NotFoundError`` (404) or a + ``ValidationError`` (422, with ``errors["model"]``), so handlers for those keep working. + Use ``transcription.create()`` (asynchronous jobs) instead. + """ + + +class _SyncTranscriptionNotFoundError(SyncTranscriptionUnavailableError, NotFoundError): + """404 from a synchronous transcription endpoint.""" + + +class _SyncTranscriptionModelError(SyncTranscriptionUnavailableError, ValidationError): + """422 on ``model`` from a synchronous transcription endpoint.""" + + +def sync_transcription_unavailable(exc: DeapiError) -> SyncTranscriptionUnavailableError | None: + """Return the ``SyncTranscriptionUnavailableError`` for ``exc``, or None if it is another error. + + A 404 (``NotFoundError``) or a 422 whose ``errors`` name ``model`` means the account cannot use + synchronous transcription. Other 422s (the file, the balance) are left as they are. + """ + kwargs: dict[str, Any] = {"status_code": exc.status_code, "body": exc.body, "code": exc.code} + if isinstance(exc, NotFoundError): + return _SyncTranscriptionNotFoundError(exc.message, **kwargs) + if ( + type(exc) is ValidationError # not InsufficientBalanceError etc. + and "model" in exc.errors + ): + return _SyncTranscriptionModelError(exc.message, **kwargs, errors=exc.errors) + return None + + class RateLimitError(DeapiError): """429 — Rate limited.""" diff --git a/src/deapi_sdk/resources/transcription.py b/src/deapi_sdk/resources/transcription.py index 2466a6b..f158307 100644 --- a/src/deapi_sdk/resources/transcription.py +++ b/src/deapi_sdk/resources/transcription.py @@ -4,11 +4,16 @@ from deapi_sdk._client import AsyncHTTPClient, SyncHTTPClient from deapi_sdk._download import adownload_text, download_text +from deapi_sdk._exceptions import NotFoundError, ValidationError, sync_transcription_unavailable from deapi_sdk._files import FileInput, normalize_file from deapi_sdk._payload import drop_none, form_bool, webhook_fields from deapi_sdk._polling import AsyncJob, Job from deapi_sdk.transcript import Transcript, parse_transcript from deapi_sdk.types.common import JobResult, PriceResult +from deapi_sdk.types.transcription import SyncTranscriptionResult + +# The model used by ``transcribe_sync()`` unless another is passed. +SYNC_TRANSCRIPTION_MODEL = "FluidSpeechPro" def _transcription_fields( @@ -104,6 +109,52 @@ def _build_price( return {"json": fields} +def _build_sync( + *, + source_file: FileInput, + model: str, + include_ts: bool | None, + ts_level: str | None, +) -> dict[str, Any]: + """Multipart ``post()`` arguments for the synchronous endpoint (always a file upload).""" + if source_file is None: + raise ValueError("'source_file' is required.") + if include_ts is None and ts_level: + include_ts = True + fields = drop_none({"model": model, "include_ts": include_ts, "ts_level": ts_level}) + return {"data": _form(fields), "files": [("source_file", normalize_file(source_file, "source_file"))]} + + +def _build_sync_price( + *, + model: str, + source_file: FileInput | None, + duration_seconds: float | None, +) -> dict[str, Any]: + """Multipart ``post()`` arguments for the synchronous price endpoint. + + The endpoint expects ``multipart/form-data``, so a duration-only quote sends its text fields + as ``(None, value)`` parts in ``files=`` (httpx would otherwise form-encode them). + """ + if source_file is not None and duration_seconds is not None: + raise ValueError("Provide either 'source_file' or 'duration_seconds', not both.") + if source_file is None and duration_seconds is None: + raise ValueError("Either 'source_file' or 'duration_seconds' is required.") + parts: list[tuple[str, Any]] = [("model", (None, model))] + if source_file is not None: + parts.append(("source_file", normalize_file(source_file, "source_file"))) + else: + parts.append(("duration_seconds", (None, str(duration_seconds)))) + return {"files": parts} + + +def _raise_unavailable(exc: NotFoundError | ValidationError) -> None: + """Re-raise a 404 / 422-on-model as ``SyncTranscriptionUnavailableError``; otherwise return.""" + unavailable = sync_transcription_unavailable(exc) + if unavailable is not None: + raise unavailable from exc + + def _pick_result_source(result: JobResult, alt_format: str | None) -> tuple[str | None, str | None]: """Return ``(inline_text, url_to_download)`` for ``get_transcript``.""" if alt_format is not None: @@ -209,6 +260,62 @@ def create_price( resp = self._client.post(self._client._resolve_endpoint("transcribe_price"), **kwargs) return PriceResult.model_validate(resp.get("data", resp)) + def transcribe_sync( + self, + *, + source_file: FileInput, + model: str = SYNC_TRANSCRIPTION_MODEL, + include_ts: bool | None = None, + ts_level: str | None = None, + ) -> SyncTranscriptionResult: + """Transcribe a short audio file and return the transcript in the same call (no job). + + For clips up to 60 seconds and 16 MiB when you need the text right away (voice notes, + commands); use ``create()`` for longer audio. The language is detected and returned. + + Synchronous transcription is in limited availability; accounts without access get a 404 + or a 422 on ``model``, raised as ``SyncTranscriptionUnavailableError``. + + Args: + source_file: Audio file (``Path``, ``bytes`` or a binary file object): mp3, wav, ogg, + flac, aac, m4a/mp4 or webm. A longer clip is rejected with a ``ValidationError`` + on ``source_file``. + model: Synchronous transcription model. + include_ts: Return timed ``segments``. Implied when ``ts_level`` is set. + ts_level: ``segment`` (the default with timestamps) or ``word`` (segments with ``words``). + + Raises: + SyncTranscriptionUnavailableError: The account cannot use synchronous transcription. + ValidationError: Bad file (too long, too large, unsupported type) or other bad input. + InsufficientBalanceError: Not enough credit. + """ + kwargs = _build_sync(source_file=source_file, model=model, include_ts=include_ts, ts_level=ts_level) + try: + resp = self._client.post(self._client._resolve_endpoint("transcribe_sync"), **kwargs) + except (NotFoundError, ValidationError) as exc: + _raise_unavailable(exc) + raise + return SyncTranscriptionResult.model_validate(resp.get("data", resp)) + + def transcribe_sync_price( + self, + *, + model: str = SYNC_TRANSCRIPTION_MODEL, + source_file: FileInput | None = None, + duration_seconds: float | None = None, + ) -> PriceResult: + """Quote a synchronous transcription from the file or from ``duration_seconds`` (not both). + + Billed per second of audio. Raises ``SyncTranscriptionUnavailableError`` like ``transcribe_sync()``. + """ + kwargs = _build_sync_price(model=model, source_file=source_file, duration_seconds=duration_seconds) + try: + resp = self._client.post(self._client._resolve_endpoint("transcribe_sync_price"), **kwargs) + except (NotFoundError, ValidationError) as exc: + _raise_unavailable(exc) + raise + return PriceResult.model_validate(resp.get("data", resp)) + def get_transcript( self, result: JobResult, @@ -291,6 +398,39 @@ async def create_price( resp = await self._client.post(self._client._resolve_endpoint("transcribe_price"), **kwargs) return PriceResult.model_validate(resp.get("data", resp)) + async def transcribe_sync( + self, + *, + source_file: FileInput, + model: str = SYNC_TRANSCRIPTION_MODEL, + include_ts: bool | None = None, + ts_level: str | None = None, + ) -> SyncTranscriptionResult: + """Transcribe a short audio file in one call. See ``Transcription.transcribe_sync``.""" + kwargs = _build_sync(source_file=source_file, model=model, include_ts=include_ts, ts_level=ts_level) + try: + resp = await self._client.post(self._client._resolve_endpoint("transcribe_sync"), **kwargs) + except (NotFoundError, ValidationError) as exc: + _raise_unavailable(exc) + raise + return SyncTranscriptionResult.model_validate(resp.get("data", resp)) + + async def transcribe_sync_price( + self, + *, + model: str = SYNC_TRANSCRIPTION_MODEL, + source_file: FileInput | None = None, + duration_seconds: float | None = None, + ) -> PriceResult: + """Quote a synchronous transcription. See ``Transcription.transcribe_sync_price``.""" + kwargs = _build_sync_price(model=model, source_file=source_file, duration_seconds=duration_seconds) + try: + resp = await self._client.post(self._client._resolve_endpoint("transcribe_sync_price"), **kwargs) + except (NotFoundError, ValidationError) as exc: + _raise_unavailable(exc) + raise + return PriceResult.model_validate(resp.get("data", resp)) + async def get_transcript( self, result: JobResult, diff --git a/src/deapi_sdk/types/__init__.py b/src/deapi_sdk/types/__init__.py index 5c58cf9..c52c264 100644 --- a/src/deapi_sdk/types/__init__.py +++ b/src/deapi_sdk/types/__init__.py @@ -19,7 +19,7 @@ from deapi_sdk.types.keys import ApiKey, ApiKeyCreated, ApiKeysPage from deapi_sdk.types.ocr import Img2TextParams from deapi_sdk.types.prompts import EnhancePromptResult -from deapi_sdk.types.transcription import TranscribeParams +from deapi_sdk.types.transcription import SyncTranscriptionResult, TranscribeParams from deapi_sdk.types.video import ( Aud2VideoParams, Img2VideoParams, @@ -53,6 +53,7 @@ "PaymentsPage", "PriceResult", "PromptBoost", + "SyncTranscriptionResult", "Text2AudioParams", "Text2EmbeddingParams", "Text2ImageParams", diff --git a/src/deapi_sdk/types/transcription.py b/src/deapi_sdk/types/transcription.py index 02aacc0..764478a 100644 --- a/src/deapi_sdk/types/transcription.py +++ b/src/deapi_sdk/types/transcription.py @@ -1,6 +1,10 @@ from __future__ import annotations -from pydantic import BaseModel +from typing import Any + +from pydantic import BaseModel, ConfigDict, field_validator + +from deapi_sdk.transcript import TranscriptSegment class TranscribeParams(BaseModel): @@ -12,3 +16,26 @@ class TranscribeParams(BaseModel): return_result_in_response: bool | None = None webhook_url: str | None = None + +class SyncTranscriptionResult(BaseModel): + """Result of ``transcription.transcribe_sync()``: the transcript itself, no job to poll. + + ``duration`` is the audio length in seconds (the billing unit) and ``price`` the amount + charged in USD. ``ts_level`` and ``segments`` are set only when timestamps were requested; + at ``ts_level="segment"`` the segments carry no ``words``. Words keep their punctuation. + """ + + model_config = ConfigDict(extra="allow") + + request_id: str + transcription: str = "" + duration: float | None = None + language: str | None = None + price: float | None = None + ts_level: str | None = None + segments: list[TranscriptSegment] | None = None + + @field_validator("transcription", mode="before") + @classmethod + def _none_to_empty(cls, value: Any) -> Any: + return "" if value is None else value diff --git a/tests/test_transcription_sync.py b/tests/test_transcription_sync.py new file mode 100644 index 0000000..9c5ba5c --- /dev/null +++ b/tests/test_transcription_sync.py @@ -0,0 +1,264 @@ +from __future__ import annotations + +from pathlib import Path + +import httpx +import pytest +import respx + +from deapi_sdk import ( + AsyncDeapiClient, + DeapiClient, + InsufficientBalanceError, + NotFoundError, + RateLimitError, + SyncTranscriptionResult, + SyncTranscriptionUnavailableError, + TranscriptSegment, + ValidationError, +) +from tests.conftest import TEST_BASE_URL + +SYNC_URL = f"{TEST_BASE_URL}/api/v2/audio/transcriptions/sync" +SYNC_PRICE_URL = f"{TEST_BASE_URL}/api/v2/audio/transcriptions/sync/price" + +PLAIN_RESPONSE = {"data": { + "request_id": "2fb1dd5e-ea5a-4175-aae9-24e16faaac3f", + "transcription": "Good morning. This is a short test.", + "duration": 9.528, + "language": "en", + "price": 0.003812, +}} + +WORD_RESPONSE = {"data": { + **PLAIN_RESPONSE["data"], + "ts_level": "word", + "segments": [ + {"start": 0, "end": 9.02, "text": "Good morning. This is a short test.", + "words": [{"word": "Good", "start": 0, "end": 0.46}, {"word": "morning.", "start": 0.46, "end": 1.1}]}, + ], +}} + + +def _multipart_fields(request: httpx.Request) -> dict[str, str]: + """Text fields of a multipart body (enough for asserting what the SDK sent).""" + content_type = request.headers["content-type"] + assert content_type.startswith("multipart/form-data") + boundary = content_type.split("boundary=")[1].encode() + fields: dict[str, str] = {} + for part in request.content.split(b"--" + boundary): + head, _, body = part.partition(b"\r\n\r\n") + if b'name="' not in head: + continue + name = head.split(b'name="')[1].split(b'"')[0].decode() + if b"filename=" in head: + fields[name] = "" + else: + fields[name] = body.rstrip(b"\r\n").decode() + return fields + + +class TestTranscribeSync: + @respx.mock + def test_plain_transcript(self, client: DeapiClient) -> None: + route = respx.post(SYNC_URL).mock(return_value=httpx.Response(200, json=PLAIN_RESPONSE)) + + result = client.transcription.transcribe_sync(source_file=b"fake-audio") + + assert isinstance(result, SyncTranscriptionResult) + assert result.request_id == "2fb1dd5e-ea5a-4175-aae9-24e16faaac3f" + assert result.transcription == "Good morning. This is a short test." + assert result.duration == 9.528 + assert result.language == "en" + assert result.price == 0.003812 + assert result.ts_level is None + assert result.segments is None + + request = route.calls.last.request + assert request.headers["accept"] == "application/json" + assert _multipart_fields(request) == {"model": "FluidSpeechPro", "source_file": ""} + + @respx.mock + def test_word_timestamps(self, client: DeapiClient) -> None: + route = respx.post(SYNC_URL).mock(return_value=httpx.Response(200, json=WORD_RESPONSE)) + + result = client.transcription.transcribe_sync(source_file=b"fake-audio", ts_level="word") + + # ts_level implies include_ts + assert _multipart_fields(route.calls.last.request) == { + "model": "FluidSpeechPro", "include_ts": "1", "ts_level": "word", "source_file": "", + } + assert result.ts_level == "word" + assert result.segments is not None + seg = result.segments[0] + assert isinstance(seg, TranscriptSegment) + assert (seg.start, seg.end) == (0, 9.02) + assert seg.words is not None + assert [w.word for w in seg.words] == ["Good", "morning."] + assert seg.words[1].end == 1.1 + + @respx.mock + def test_segment_timestamps_have_no_words(self, client: DeapiClient) -> None: + data = {**PLAIN_RESPONSE["data"], "ts_level": "segment", + "segments": [{"start": 0, "end": 9.02, "text": "Good morning."}]} + route = respx.post(SYNC_URL).mock(return_value=httpx.Response(200, json={"data": data})) + + result = client.transcription.transcribe_sync(source_file=b"a", include_ts=True, model="OtherModel") + + assert _multipart_fields(route.calls.last.request) == { + "model": "OtherModel", "include_ts": "1", "source_file": "", + } + assert result.segments is not None + assert result.segments[0].words is None + + @respx.mock + def test_path_upload_keeps_name_and_type(self, client: DeapiClient, tmp_path: Path) -> None: + route = respx.post(SYNC_URL).mock(return_value=httpx.Response(200, json=PLAIN_RESPONSE)) + audio = tmp_path / "note.wav" + audio.write_bytes(b"RIFF") + + client.transcription.transcribe_sync(source_file=audio) + + content = route.calls.last.request.content + assert b'filename="note.wav"' in content + assert b"Content-Type: audio/" in content + + def test_plain_str_is_rejected(self, client: DeapiClient) -> None: + with pytest.raises(TypeError, match="plain str"): + client.transcription.transcribe_sync(source_file="note.wav") + + @respx.mock + def test_extra_fields_and_null_transcription(self, client: DeapiClient) -> None: + data = {"request_id": "r1", "transcription": None, "new_field": 1} + respx.post(SYNC_URL).mock(return_value=httpx.Response(200, json={"data": data})) + + result = client.transcription.transcribe_sync(source_file=b"a") + + assert result.transcription == "" + assert result.model_extra == {"new_field": 1} + + +class TestTranscribeSyncErrors: + @respx.mock + def test_404_is_unavailable_and_not_found(self, client: DeapiClient) -> None: + respx.post(SYNC_URL).mock(return_value=httpx.Response(404, json={"message": "Not Found"})) + + with pytest.raises(SyncTranscriptionUnavailableError) as info: + client.transcription.transcribe_sync(source_file=b"a") + + assert isinstance(info.value, NotFoundError) + assert info.value.status_code == 404 + assert info.value.message == "Not Found" + assert isinstance(info.value.__cause__, NotFoundError) + + @respx.mock + def test_422_on_model_is_unavailable_and_validation(self, client: DeapiClient) -> None: + body = {"message": "This model is not available on your plan.", + "errors": {"model": ["This model is not available on your plan."]}} + respx.post(SYNC_URL).mock(return_value=httpx.Response(422, json=body)) + + with pytest.raises(SyncTranscriptionUnavailableError) as info: + client.transcription.transcribe_sync(source_file=b"a") + + assert isinstance(info.value, ValidationError) + assert info.value.status_code == 422 + assert info.value.errors == {"model": ["This model is not available on your plan."]} + assert info.value.body == body + + @respx.mock + def test_too_long_clip_is_plain_validation_error(self, client: DeapiClient) -> None: + message = "The audio is 66.0 s long; synchronous transcription takes up to 60 s." + respx.post(SYNC_URL).mock(return_value=httpx.Response( + 422, json={"message": message, "errors": {"source_file": [message]}}, + )) + + with pytest.raises(ValidationError) as info: + client.transcription.transcribe_sync(source_file=b"a") + + assert not isinstance(info.value, SyncTranscriptionUnavailableError) + assert info.value.errors["source_file"] == [message] + + @respx.mock + def test_balance_stays_insufficient_balance(self, client: DeapiClient) -> None: + respx.post(SYNC_URL).mock(return_value=httpx.Response( + 422, json={"message": "Not enough balance.", "errors": {"balance": ["Not enough balance."]}}, + )) + + with pytest.raises(InsufficientBalanceError) as info: + client.transcription.transcribe_sync(source_file=b"a") + + assert not isinstance(info.value, SyncTranscriptionUnavailableError) + + @respx.mock + def test_rate_limit_passes_through(self) -> None: + with DeapiClient(api_key="k", base_url=TEST_BASE_URL, max_retries=0) as client: + respx.post(SYNC_URL).mock(return_value=httpx.Response(429, json={"message": "Too Many Attempts."})) + with pytest.raises(RateLimitError): + client.transcription.transcribe_sync(source_file=b"a") + + @respx.mock + def test_server_error_is_not_retried(self, client: DeapiClient) -> None: + # A billed POST: never resent after a 5xx. + route = respx.post(SYNC_URL).mock(return_value=httpx.Response(500, json={"message": "x"})) + with pytest.raises(Exception, match="x"): + client.transcription.transcribe_sync(source_file=b"a") + assert route.call_count == 1 + + +class TestTranscribeSyncPrice: + @respx.mock + def test_price_from_duration_is_multipart(self, client: DeapiClient) -> None: + route = respx.post(SYNC_PRICE_URL).mock(return_value=httpx.Response(200, json={"data": {"price": 0.024}})) + + price = client.transcription.transcribe_sync_price(duration_seconds=60) + + assert price.price == 0.024 + assert _multipart_fields(route.calls.last.request) == {"model": "FluidSpeechPro", "duration_seconds": "60"} + + @respx.mock + def test_price_from_file(self, client: DeapiClient) -> None: + route = respx.post(SYNC_PRICE_URL).mock(return_value=httpx.Response(200, json={"data": {"price": 0.004}})) + + price = client.transcription.transcribe_sync_price(source_file=b"a") + + assert price.price == 0.004 + assert _multipart_fields(route.calls.last.request) == {"model": "FluidSpeechPro", "source_file": ""} + + def test_price_needs_exactly_one_source(self, client: DeapiClient) -> None: + with pytest.raises(ValueError, match="not both"): + client.transcription.transcribe_sync_price(source_file=b"a", duration_seconds=5) + with pytest.raises(ValueError, match="is required"): + client.transcription.transcribe_sync_price() + + @respx.mock + def test_price_404_is_unavailable(self, client: DeapiClient) -> None: + respx.post(SYNC_PRICE_URL).mock(return_value=httpx.Response(404)) + with pytest.raises(SyncTranscriptionUnavailableError): + client.transcription.transcribe_sync_price(duration_seconds=5) + + +class TestAsyncTranscribeSync: + @respx.mock + async def test_async_transcribe_sync(self, async_client: AsyncDeapiClient) -> None: + route = respx.post(SYNC_URL).mock(return_value=httpx.Response(200, json=WORD_RESPONSE)) + + result = await async_client.transcription.transcribe_sync(source_file=b"a", ts_level="word") + + assert result.language == "en" + assert result.segments is not None and result.segments[0].words is not None + assert _multipart_fields(route.calls.last.request)["ts_level"] == "word" + + @respx.mock + async def test_async_price(self, async_client: AsyncDeapiClient) -> None: + respx.post(SYNC_PRICE_URL).mock(return_value=httpx.Response(200, json={"data": {"price": 0.024}})) + price = await async_client.transcription.transcribe_sync_price(duration_seconds=60) + assert price.price == 0.024 + + @respx.mock + async def test_async_unavailable(self, async_client: AsyncDeapiClient) -> None: + respx.post(SYNC_URL).mock(return_value=httpx.Response( + 422, json={"message": "no", "errors": {"model": ["This model is not available on your plan."]}}, + )) + with pytest.raises(SyncTranscriptionUnavailableError) as info: + await async_client.transcription.transcribe_sync(source_file=b"a") + assert isinstance(info.value, ValidationError) From 08245bc0be9a5e926b4e894eb25a6e312170d964 Mon Sep 17 00:00:00 2001 From: Dawid Wenderski Date: Sun, 29 Nov 2026 17:47:44 +0100 Subject: [PATCH 02/13] Use WhisperLargeV3Ct2 in transcription examples and docs WhisperLargeV3 is retired. The examples' file-upload and price calls now use WhisperLargeV3Ct2, the plain-text demo in examples/transcription.py is dropped, and the docs describe plain-text models without naming the retired one. Tests that use the name only as an arbitrary model string are unchanged. Co-Authored-By: Claude Opus 5.5 --- README.md | 6 +++--- docs/api-reference.md | 2 +- examples/transcription.py | 15 ++++++--------- src/deapi_sdk/transcript.py | 2 +- 4 files changed, 11 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 872d763..2ff0e42 100644 --- a/README.md +++ b/README.md @@ -251,8 +251,8 @@ for seg in transcript.segments: **Two transcript formats.** Models whose card has `info.limits.output_format: "json"` (for example `WhisperLargeV3Ct2`) always return a JSON document (`text`, `language`, `segments` with -`start`/`end`/`speaker`/`words`). Models with `output_format: null` (for example `WhisperLargeV3`) -return plain text with timestamps inline. `client.transcription.get_transcript(result)` (or +`start`/`end`/`speaker`/`words`). Models with `output_format: null` return plain text with +timestamps inline. `client.transcription.get_transcript(result)` (or `deapi_sdk.parse_transcript(raw)`) handles both and returns a `Transcript` whose `format` is `"json"` or `"text"` (`segments` is empty for text). Result URLs are downloaded without your API key. @@ -620,7 +620,7 @@ The [`examples/`](https://github.com/deapi-ai/deapi-python-sdk/tree/main/example |------|-------------| | [`basic_image.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/basic_image.py) | Image generation, transformation, upscale | | [`async_batch.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/async_batch.py) | Concurrent async job submission | -| [`transcription.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/transcription.py) | Transcription with JSON and plain-text transcripts | +| [`transcription.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/transcription.py) | Transcription jobs, transcript parsing, price quotes | | [`transcription_sync.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/transcription_sync.py) | Synchronous transcription of a short clip (no job) | | [`tts_and_audio.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/tts_and_audio.py) | Text-to-speech and music generation | | [`video_generation.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/video_generation.py) | Text-to-video and image-to-video | diff --git a/docs/api-reference.md b/docs/api-reference.md index 679f545..b4a2d04 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -425,7 +425,7 @@ Uses the inline `result` if present, otherwise downloads `result_url` with a pla | `info.limits.output_format` | Example model | Result | |-----------------------------|---------------|--------| | `"json"` | `WhisperLargeV3Ct2` | Always a JSON document: `text`, `language`, `segments` (`start`, `end`, `speaker`, `words`) | -| `null` | `WhisperLargeV3` | Plain text; timestamps inline (`[0:50 - 1:49] ...`) when requested | +| `null` | — | Plain text; timestamps inline (`[0:50 - 1:49] ...`) when requested | `deapi_sdk.parse_transcript(raw, output_format=None)` does the parsing without a client and never raises. `deapi_sdk.transcript_output_format(model_card)` reads the card field. diff --git a/examples/transcription.py b/examples/transcription.py index f2ed1e9..14a4af3 100644 --- a/examples/transcription.py +++ b/examples/transcription.py @@ -1,6 +1,6 @@ """Transcription examples. -Demonstrates the unified transcription endpoint and both transcript formats. +Demonstrates the unified transcription endpoint, transcript parsing and price quotes. Usage: export DEAPI_API_KEY="sk-dp--" @@ -17,8 +17,8 @@ # # Models whose card has info.limits.output_format == "json" (e.g. WhisperLargeV3Ct2) # always return a JSON document (text, language, segments with start/end/speaker/words). -# Models with output_format == null (e.g. WhisperLargeV3) return plain text with -# timestamps written inline. get_transcript() handles both and returns a Transcript. +# Models with output_format == null return plain text with timestamps written +# inline. get_transcript() handles both and returns a Transcript. def show(model: str, **options) -> None: @@ -41,9 +41,6 @@ def show(model: str, **options) -> None: print("JSON-format model (segments, optional diarization):") show("WhisperLargeV3Ct2", ts_level="segment", diarize=True, lang="en") -print("\nPlain-text model (timestamps inline in the text):") -show("WhisperLargeV3") - # --- Unified endpoint — file upload --- # Uncomment to run — requires an audio/video file: @@ -52,7 +49,7 @@ def show(model: str, **options) -> None: # job = client.transcription.create( # source_file=Path("interview.mp3"), # Path, bytes or a binary file object (a plain str is rejected) # include_ts=False, -# model="WhisperLargeV3", +# model="WhisperLargeV3Ct2", # return_result_in_response=True, # ) # result = job.wait() @@ -64,14 +61,14 @@ def show(model: str, **options) -> None: price = client.transcription.create_price( source_url="https://www.youtube.com/watch?v=dQw4w9WgXcQ", include_ts=True, - model="WhisperLargeV3", + model="WhisperLargeV3Ct2", ) print(f"Cost: ${price.price}") # Or estimate by duration (skip URL metadata fetch): price = client.transcription.create_price( include_ts=True, - model="WhisperLargeV3", + model="WhisperLargeV3Ct2", duration_seconds=120.0, ) print(f"Cost for 2 min audio: ${price.price}") diff --git a/src/deapi_sdk/transcript.py b/src/deapi_sdk/transcript.py index cebed11..2049f04 100644 --- a/src/deapi_sdk/transcript.py +++ b/src/deapi_sdk/transcript.py @@ -6,7 +6,7 @@ * ``"json"`` (e.g. ``WhisperLargeV3Ct2``): the transcript is always a JSON document ``{"text", "language", "ts_level", "diarization_available", "segments": [...]}`` -- even with timestamps off. -* ``null`` (e.g. ``WhisperLargeV3``): plain text, with timestamps written into +* ``null``: plain text, with timestamps written into the text itself (``[0:50 - 1:49] ...``) when requested. ``parse_transcript`` turns either into one ``Transcript`` object. From d4e9dd680bcbcdf568907bc13639cf833e446ec4 Mon Sep 17 00:00:00 2001 From: Dawid Wenderski Date: Sun, 29 Nov 2026 17:52:23 +0100 Subject: [PATCH 03/13] Present transcribe_sync() as fast transcription for short audio only Docstrings, README, API reference, CHANGELOG and the example now open with the limit: up to 60 s and 16 MiB per file, for voice notes, commands and short clips, with create() for anything longer. Limits are checked locally where it is cheap: a source_file over 16 MiB, or a quote for duration_seconds over 60, raises ValueError before anything is sent. A 422 on source_file (e.g. a clip over 60 s) stays a ValidationError with the API's errors and body, and its message now also points to create(). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 ++- README.md | 17 +++--- docs/api-reference.md | 17 +++--- examples/transcription_sync.py | 14 +++-- src/deapi_sdk/_exceptions.py | 2 +- src/deapi_sdk/resources/transcription.py | 72 +++++++++++++++++------- src/deapi_sdk/types/transcription.py | 4 +- tests/test_transcription_sync.py | 68 ++++++++++++++++++++-- 8 files changed, 154 insertions(+), 49 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 21f5f15..18a47bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,11 +7,14 @@ Versions follow [Semantic Versioning](https://semver.org/) (pre-1.0: minor versi ### Added -- `client.transcription.transcribe_sync()` (sync and async clients): synchronous transcription of - short audio files (up to 60 seconds). The transcript comes back in the response as the new +- `client.transcription.transcribe_sync()` (sync and async clients): fast transcription for short + audio only, up to 60 seconds and 16 MiB per file (voice notes, commands, short clips; use + `create()` for anything longer). The transcript comes back in the response as the new `SyncTranscriptionResult` (`transcription`, `language`, `duration`, `price`, optional `segments` with `words`); there is no job to poll. `transcribe_sync_price()` quotes it from the file or from - `duration_seconds`. The model defaults to `FluidSpeechPro`. + `duration_seconds`. The model defaults to `FluidSpeechPro`. A file over 16 MiB, or a quote for + over 60 seconds, raises `ValueError` before anything is sent; a 422 on `source_file` (e.g. a clip + over 60 seconds) stays a `ValidationError` whose message points to `create()`. - `SyncTranscriptionUnavailableError`: synchronous transcription is in limited availability; accounts without access get a 404 or a 422 on `model`, raised as this error. It is also a `NotFoundError` or a `ValidationError`, so existing handlers keep catching it. diff --git a/README.md b/README.md index 2ff0e42..59ce46e 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Generate images, videos, audio, transcriptions, embeddings, and more — all thr - **Video generation** — text-to-video, image-to-video (keyframes or reference images/videos/audio), audio-to-video, upscale - **Video description** — timestamped events and scenes of a video - **Audio** — text-to-speech (with voice cloning), text-to-music (with a style reference) -- **Transcription** — URLs and file uploads, plain-text or structured JSON transcripts; synchronous transcription of short clips (no job to poll) +- **Transcription** — URLs and file uploads, plain-text or structured JSON transcripts; fast transcription of short audio (up to 60 s, no job to poll) - **Embeddings, OCR, prompt enhancement** - **Account and keys** — balance, usage, payments, API-key management (ADMIN keys) - **Sync + Async** — both `DeapiClient` and `AsyncDeapiClient` @@ -256,11 +256,12 @@ timestamps inline. `client.transcription.get_transcript(result)` (or `deapi_sdk.parse_transcript(raw)`) handles both and returns a `Transcript` whose `format` is `"json"` or `"text"` (`segments` is empty for text). Result URLs are downloaded without your API key. -#### Synchronous transcription (short clips) +#### Fast transcription of short audio (up to 60 s) -For audio up to 60 seconds and 16 MiB, `transcribe_sync()` returns the transcript in the same call: -no job, no polling, no webhook. Use it when you need the text right away (voice notes, commands) -and `create()` for longer audio. The language is detected and returned. +`transcribe_sync()` takes **short audio only: up to 60 seconds and 16 MiB per file**, and returns the +transcript in the same call (no job, no polling, no webhook). Use it for voice notes, commands and +short clips; for anything longer use the regular transcription, `create()`. The language is +detected and returned. ```python from pathlib import Path @@ -279,7 +280,9 @@ quote = client.transcription.transcribe_sync_price(duration_seconds=30) # or s Synchronous transcription is in limited availability; accounts without access get a 404 or a 422 on `model`. Both are raised as `SyncTranscriptionUnavailableError` (also a `NotFoundError` / -`ValidationError`). A clip longer than 60 seconds is a `ValidationError` on `source_file`. +`ValidationError`). A file over 16 MiB (or a quote for over 60 s) raises `ValueError` before anything +is sent; a clip longer than 60 seconds is a `ValidationError` on `source_file`. Both messages point +to `create()`. ### Embeddings and OCR @@ -621,7 +624,7 @@ The [`examples/`](https://github.com/deapi-ai/deapi-python-sdk/tree/main/example | [`basic_image.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/basic_image.py) | Image generation, transformation, upscale | | [`async_batch.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/async_batch.py) | Concurrent async job submission | | [`transcription.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/transcription.py) | Transcription jobs, transcript parsing, price quotes | -| [`transcription_sync.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/transcription_sync.py) | Synchronous transcription of a short clip (no job) | +| [`transcription_sync.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/transcription_sync.py) | Fast transcription of short audio, up to 60 s (no job) | | [`tts_and_audio.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/tts_and_audio.py) | Text-to-speech and music generation | | [`video_generation.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/video_generation.py) | Text-to-video and image-to-video | | [`realtime_status.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/realtime_status.py) | Live job progress over WebSocket | diff --git a/docs/api-reference.md b/docs/api-reference.md index b4a2d04..961c371 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -367,13 +367,14 @@ the quote is lower than the charge. ### `transcribe_sync()` / `transcribe_sync_price()` -Synchronous transcription of a short audio file: the transcript is in the response, there is no -job to poll. For clips up to 60 seconds and 16 MiB; use `create()` for longer audio. +Fast transcription for **short audio only: up to 60 seconds and 16 MiB per file**. The transcript is +in the response; there is no job to poll. For voice notes, commands and short clips; for anything +longer use the regular transcription, `create()`. ```python result = client.transcription.transcribe_sync( *, - source_file: FileInput, # audio: aac, mpeg, mp4/m4a, ogg, wav, webm, flac + source_file: FileInput, # audio up to 60 s / 16 MiB: aac, mpeg, mp4/m4a, ogg, wav, webm, flac model: str = "FluidSpeechPro", include_ts: bool | None = None, # implied by ts_level ts_level: str | None = None, # "segment" (default with timestamps) | "word" @@ -383,7 +384,7 @@ price = client.transcription.transcribe_sync_price( *, model: str = "FluidSpeechPro", source_file: FileInput | None = None, # exactly one of source_file / duration_seconds - duration_seconds: float | None = None, + duration_seconds: float | None = None, # up to 60 ) -> PriceResult ``` @@ -402,9 +403,11 @@ class SyncTranscriptionResult(BaseModel): Synchronous transcription is in limited availability; accounts without access get a 404 or a 422 on `model`, raised as `SyncTranscriptionUnavailableError` (also a `NotFoundError` / -`ValidationError`). Other errors are the usual ones: a clip over 60 seconds or a bad file is a -`ValidationError` on `source_file`, missing credit an `InsufficientBalanceError`, and the rate -limit (shared with `create()`) a `RateLimitError`. +`ValidationError`). Limits are checked locally where it is cheap: a file over 16 MiB, or a +`duration_seconds` over 60 in a quote, raises `ValueError` before anything is sent. A clip over +60 seconds or a bad file is a `ValidationError` on `source_file`; its message points to `create()`. +Missing credit is an `InsufficientBalanceError`, and the rate limit (shared with `create()`) a +`RateLimitError`. ### `get_transcript()` diff --git a/examples/transcription_sync.py b/examples/transcription_sync.py index 36766db..cdfc22d 100644 --- a/examples/transcription_sync.py +++ b/examples/transcription_sync.py @@ -1,8 +1,8 @@ -"""Synchronous transcription of a short audio clip. +"""Fast transcription for short audio only: up to 60 seconds and 16 MiB per file. The transcript comes back in the same HTTP response: no job, no polling, no webhook. -Use it for clips up to 60 seconds (voice notes, commands); use -``client.transcription.create()`` for longer audio. +For voice notes, commands and short clips; for anything longer use the regular +transcription, ``client.transcription.create()`` (see transcription.py). Synchronous transcription is in limited availability; accounts without access get a 404 or a 422 on ``model`` (raised as ``SyncTranscriptionUnavailableError``). @@ -32,9 +32,11 @@ except SyncTranscriptionUnavailableError: print("Synchronous transcription is not available for this account; use transcription.create().") raise SystemExit(1) from None - except ValidationError as e: - # e.g. errors["source_file"]: clip longer than 60 s, file too large or unsupported type - print(e.message, e.errors) + except (ValueError, ValidationError) as e: + # ValueError: file over 16 MiB, refused before upload. + # ValidationError: e.g. errors["source_file"] for a clip over 60 s or an unsupported type. + # Both messages point to transcription.create() for longer audio. + print(e) raise SystemExit(1) from None print(f"[{result.language}] {result.transcription}") diff --git a/src/deapi_sdk/_exceptions.py b/src/deapi_sdk/_exceptions.py index 5c3aee4..775d695 100644 --- a/src/deapi_sdk/_exceptions.py +++ b/src/deapi_sdk/_exceptions.py @@ -126,7 +126,7 @@ class SyncTranscriptionUnavailableError(DeapiError): Raised by ``transcription.transcribe_sync()`` and ``transcribe_sync_price()`` for a 404, or for a 422 that rejects ``model``. Every instance is also a ``NotFoundError`` (404) or a ``ValidationError`` (422, with ``errors["model"]``), so handlers for those keep working. - Use ``transcription.create()`` (asynchronous jobs) instead. + Use the regular transcription, ``transcription.create()``, instead. """ diff --git a/src/deapi_sdk/resources/transcription.py b/src/deapi_sdk/resources/transcription.py index f158307..2fe4824 100644 --- a/src/deapi_sdk/resources/transcription.py +++ b/src/deapi_sdk/resources/transcription.py @@ -14,6 +14,13 @@ # The model used by ``transcribe_sync()`` unless another is passed. SYNC_TRANSCRIPTION_MODEL = "FluidSpeechPro" +# Synchronous (fast) transcription takes short audio only. +SYNC_TRANSCRIPTION_MAX_SECONDS = 60 +SYNC_TRANSCRIPTION_MAX_BYTES = 16 * 1024 * 1024 # 16 MiB +_SYNC_LIMIT_HINT = ( + "Fast (synchronous) transcription takes short audio only: up to 60 s and 16 MiB per file. " + "For longer audio use the regular transcription, client.transcription.create()." +) def _transcription_fields( @@ -122,7 +129,16 @@ def _build_sync( if include_ts is None and ts_level: include_ts = True fields = drop_none({"model": model, "include_ts": include_ts, "ts_level": ts_level}) - return {"data": _form(fields), "files": [("source_file", normalize_file(source_file, "source_file"))]} + return {"data": _form(fields), "files": [("source_file", _sync_file_part(source_file))]} + + +def _sync_file_part(source_file: FileInput) -> tuple[str, bytes, str]: + """Read the upload and refuse a file over 16 MiB before sending it.""" + part = normalize_file(source_file, "source_file") + size = len(part[1]) + if size > SYNC_TRANSCRIPTION_MAX_BYTES: + raise ValueError(f"source_file is {size} bytes, over 16 MiB. {_SYNC_LIMIT_HINT}") + return part def _build_sync_price( @@ -140,19 +156,31 @@ def _build_sync_price( raise ValueError("Provide either 'source_file' or 'duration_seconds', not both.") if source_file is None and duration_seconds is None: raise ValueError("Either 'source_file' or 'duration_seconds' is required.") + if duration_seconds is not None and duration_seconds > SYNC_TRANSCRIPTION_MAX_SECONDS: + raise ValueError(f"duration_seconds is {duration_seconds}. {_SYNC_LIMIT_HINT}") parts: list[tuple[str, Any]] = [("model", (None, model))] if source_file is not None: - parts.append(("source_file", normalize_file(source_file, "source_file"))) + parts.append(("source_file", _sync_file_part(source_file))) else: parts.append(("duration_seconds", (None, str(duration_seconds)))) return {"files": parts} -def _raise_unavailable(exc: NotFoundError | ValidationError) -> None: - """Re-raise a 404 / 422-on-model as ``SyncTranscriptionUnavailableError``; otherwise return.""" +def _raise_sync_error(exc: NotFoundError | ValidationError) -> None: + """Re-raise a synchronous-transcription error in its more useful form; otherwise return. + + A 404 or a 422 on ``model`` becomes ``SyncTranscriptionUnavailableError``. A 422 on + ``source_file`` (audio too long, file too large or unreadable) stays a ``ValidationError`` + whose message also points to ``create()`` for longer audio; ``errors`` and ``body`` are kept. + """ unavailable = sync_transcription_unavailable(exc) if unavailable is not None: raise unavailable from exc + if type(exc) is ValidationError and "source_file" in exc.errors and "create()" not in exc.message: + raise ValidationError( + f"{exc.message} {_SYNC_LIMIT_HINT}", + status_code=exc.status_code, body=exc.body, code=exc.code, errors=exc.errors, + ) from exc def _pick_result_source(result: JobResult, alt_format: str | None) -> tuple[str | None, str | None]: @@ -268,32 +296,35 @@ def transcribe_sync( include_ts: bool | None = None, ts_level: str | None = None, ) -> SyncTranscriptionResult: - """Transcribe a short audio file and return the transcript in the same call (no job). + """Fast transcription for short audio only: up to 60 s and 16 MiB per file. - For clips up to 60 seconds and 16 MiB when you need the text right away (voice notes, - commands); use ``create()`` for longer audio. The language is detected and returned. + The transcript comes back in the same call (no job, no polling). Use it for voice notes, + commands and short clips; for anything longer use the regular transcription, ``create()``. + A file over 16 MiB is refused locally with ``ValueError`` before it is uploaded. The + language is detected and returned. Synchronous transcription is in limited availability; accounts without access get a 404 or a 422 on ``model``, raised as ``SyncTranscriptionUnavailableError``. Args: - source_file: Audio file (``Path``, ``bytes`` or a binary file object): mp3, wav, ogg, - flac, aac, m4a/mp4 or webm. A longer clip is rejected with a ``ValidationError`` - on ``source_file``. + source_file: Audio file up to 60 s and 16 MiB (``Path``, ``bytes`` or a binary file + object): mp3, wav, ogg, flac, aac, m4a/mp4 or webm. A longer clip is rejected with a + ``ValidationError`` on ``source_file`` whose message points to ``create()``. model: Synchronous transcription model. include_ts: Return timed ``segments``. Implied when ``ts_level`` is set. ts_level: ``segment`` (the default with timestamps) or ``word`` (segments with ``words``). Raises: SyncTranscriptionUnavailableError: The account cannot use synchronous transcription. - ValidationError: Bad file (too long, too large, unsupported type) or other bad input. + ValidationError: Bad file (over 60 s, unsupported type) or other bad input. + ValueError: ``source_file`` is over 16 MiB (checked before uploading). InsufficientBalanceError: Not enough credit. """ kwargs = _build_sync(source_file=source_file, model=model, include_ts=include_ts, ts_level=ts_level) try: resp = self._client.post(self._client._resolve_endpoint("transcribe_sync"), **kwargs) except (NotFoundError, ValidationError) as exc: - _raise_unavailable(exc) + _raise_sync_error(exc) raise return SyncTranscriptionResult.model_validate(resp.get("data", resp)) @@ -304,15 +335,18 @@ def transcribe_sync_price( source_file: FileInput | None = None, duration_seconds: float | None = None, ) -> PriceResult: - """Quote a synchronous transcription from the file or from ``duration_seconds`` (not both). + """Price of fast transcription (short audio only: up to 60 s and 16 MiB per file). - Billed per second of audio. Raises ``SyncTranscriptionUnavailableError`` like ``transcribe_sync()``. + Quotes from the file or from ``duration_seconds`` (not both); billed per second of audio. + A ``duration_seconds`` over 60 or a file over 16 MiB raises ``ValueError`` locally (use + ``create_price()`` for longer audio). Raises ``SyncTranscriptionUnavailableError`` like + ``transcribe_sync()``. """ kwargs = _build_sync_price(model=model, source_file=source_file, duration_seconds=duration_seconds) try: resp = self._client.post(self._client._resolve_endpoint("transcribe_sync_price"), **kwargs) except (NotFoundError, ValidationError) as exc: - _raise_unavailable(exc) + _raise_sync_error(exc) raise return PriceResult.model_validate(resp.get("data", resp)) @@ -406,12 +440,12 @@ async def transcribe_sync( include_ts: bool | None = None, ts_level: str | None = None, ) -> SyncTranscriptionResult: - """Transcribe a short audio file in one call. See ``Transcription.transcribe_sync``.""" + """Fast transcription for short audio only (up to 60 s, 16 MiB). See ``Transcription.transcribe_sync``.""" kwargs = _build_sync(source_file=source_file, model=model, include_ts=include_ts, ts_level=ts_level) try: resp = await self._client.post(self._client._resolve_endpoint("transcribe_sync"), **kwargs) except (NotFoundError, ValidationError) as exc: - _raise_unavailable(exc) + _raise_sync_error(exc) raise return SyncTranscriptionResult.model_validate(resp.get("data", resp)) @@ -422,12 +456,12 @@ async def transcribe_sync_price( source_file: FileInput | None = None, duration_seconds: float | None = None, ) -> PriceResult: - """Quote a synchronous transcription. See ``Transcription.transcribe_sync_price``.""" + """Price of fast transcription (up to 60 s, 16 MiB). See ``Transcription.transcribe_sync_price``.""" kwargs = _build_sync_price(model=model, source_file=source_file, duration_seconds=duration_seconds) try: resp = await self._client.post(self._client._resolve_endpoint("transcribe_sync_price"), **kwargs) except (NotFoundError, ValidationError) as exc: - _raise_unavailable(exc) + _raise_sync_error(exc) raise return PriceResult.model_validate(resp.get("data", resp)) diff --git a/src/deapi_sdk/types/transcription.py b/src/deapi_sdk/types/transcription.py index 764478a..8ce862c 100644 --- a/src/deapi_sdk/types/transcription.py +++ b/src/deapi_sdk/types/transcription.py @@ -18,7 +18,9 @@ class TranscribeParams(BaseModel): class SyncTranscriptionResult(BaseModel): - """Result of ``transcription.transcribe_sync()``: the transcript itself, no job to poll. + """Result of ``transcription.transcribe_sync()`` (fast transcription of audio up to 60 s). + + The transcript itself; there is no job to poll. ``duration`` is the audio length in seconds (the billing unit) and ``price`` the amount charged in USD. ``ts_level`` and ``segments`` are set only when timestamps were requested; diff --git a/tests/test_transcription_sync.py b/tests/test_transcription_sync.py index 9c5ba5c..be6274f 100644 --- a/tests/test_transcription_sync.py +++ b/tests/test_transcription_sync.py @@ -166,17 +166,49 @@ def test_422_on_model_is_unavailable_and_validation(self, client: DeapiClient) - assert info.value.body == body @respx.mock - def test_too_long_clip_is_plain_validation_error(self, client: DeapiClient) -> None: + def test_too_long_clip_is_validation_error_pointing_to_create(self, client: DeapiClient) -> None: message = "The audio is 66.0 s long; synchronous transcription takes up to 60 s." - respx.post(SYNC_URL).mock(return_value=httpx.Response( - 422, json={"message": message, "errors": {"source_file": [message]}}, - )) + body = {"message": message, "errors": {"source_file": [message]}} + respx.post(SYNC_URL).mock(return_value=httpx.Response(422, json=body)) with pytest.raises(ValidationError) as info: client.transcription.transcribe_sync(source_file=b"a") - assert not isinstance(info.value, SyncTranscriptionUnavailableError) + assert type(info.value) is ValidationError + assert info.value.message.startswith(message) + assert "up to 60 s and 16 MiB" in info.value.message + assert "client.transcription.create()" in info.value.message + # The API's own data is untouched. assert info.value.errors["source_file"] == [message] + assert info.value.body == body + assert info.value.status_code == 422 + assert isinstance(info.value.__cause__, ValidationError) + + @respx.mock + def test_other_422_is_unchanged(self, client: DeapiClient) -> None: + body = {"message": "The ts level field is invalid.", "errors": {"ts_level": ["invalid"]}} + respx.post(SYNC_URL).mock(return_value=httpx.Response(422, json=body)) + + with pytest.raises(ValidationError) as info: + client.transcription.transcribe_sync(source_file=b"a", ts_level="char") + + assert info.value.message == "The ts level field is invalid." + assert info.value.__cause__ is None + + @respx.mock + def test_file_over_16_mib_is_refused_before_upload(self, client: DeapiClient) -> None: + route = respx.post(SYNC_URL).mock(return_value=httpx.Response(200, json=PLAIN_RESPONSE)) + + with pytest.raises(ValueError, match=r"16777217 bytes, over 16 MiB.*up to 60 s and 16 MiB.*create\(\)"): + client.transcription.transcribe_sync(source_file=b"\0" * (16 * 1024 * 1024 + 1)) + + assert not route.called + + @respx.mock + def test_file_of_exactly_16_mib_is_sent(self, client: DeapiClient) -> None: + route = respx.post(SYNC_URL).mock(return_value=httpx.Response(200, json=PLAIN_RESPONSE)) + client.transcription.transcribe_sync(source_file=b"\0" * (16 * 1024 * 1024)) + assert route.call_count == 1 @respx.mock def test_balance_stays_insufficient_balance(self, client: DeapiClient) -> None: @@ -230,6 +262,19 @@ def test_price_needs_exactly_one_source(self, client: DeapiClient) -> None: with pytest.raises(ValueError, match="is required"): client.transcription.transcribe_sync_price() + @respx.mock + def test_price_over_60_seconds_is_refused_locally(self, client: DeapiClient) -> None: + route = respx.post(SYNC_PRICE_URL).mock(return_value=httpx.Response(200, json={"data": {"price": 0.1}})) + + with pytest.raises(ValueError, match=r"60\.5.*create\(\)"): + client.transcription.transcribe_sync_price(duration_seconds=60.5) + with pytest.raises(ValueError, match="16 MiB"): + client.transcription.transcribe_sync_price(source_file=b"\0" * (16 * 1024 * 1024 + 1)) + assert not route.called + + client.transcription.transcribe_sync_price(duration_seconds=60) + assert route.call_count == 1 + @respx.mock def test_price_404_is_unavailable(self, client: DeapiClient) -> None: respx.post(SYNC_PRICE_URL).mock(return_value=httpx.Response(404)) @@ -262,3 +307,16 @@ async def test_async_unavailable(self, async_client: AsyncDeapiClient) -> None: with pytest.raises(SyncTranscriptionUnavailableError) as info: await async_client.transcription.transcribe_sync(source_file=b"a") assert isinstance(info.value, ValidationError) + + @respx.mock + async def test_async_too_long_points_to_create(self, async_client: AsyncDeapiClient) -> None: + message = "The audio is 66.0 s long; synchronous transcription takes up to 60 s." + respx.post(SYNC_URL).mock(return_value=httpx.Response( + 422, json={"message": message, "errors": {"source_file": [message]}}, + )) + with pytest.raises(ValidationError, match=r"create\(\)"): + await async_client.transcription.transcribe_sync(source_file=b"a") + + async def test_async_file_over_16_mib_is_refused(self, async_client: AsyncDeapiClient) -> None: + with pytest.raises(ValueError, match="16 MiB"): + await async_client.transcription.transcribe_sync(source_file=b"\0" * (16 * 1024 * 1024 + 1)) From 69ea0286b2b3ab0527de622158dbce03fe2da110 Mon Sep 17 00:00:00 2001 From: Dawid Wenderski Date: Sun, 29 Nov 2026 17:55:01 +0100 Subject: [PATCH 04/13] Leave transcribe_sync() clip limits to the API The limits can change on the API side, so the SDK no longer hardcodes them: the local 16 MiB and 60 s checks, their constants and the numbers in docstrings, the hint text and the example are gone. A 422 on source_file still passes the API's message (which states the current limit) through and adds a pointer to create() for longer audio. The README and API reference describe it as fast transcription for short audio clips, "currently up to 60 seconds", with a link to the deAPI docs. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 10 ++--- README.md | 19 ++++---- docs/api-reference.md | 17 +++---- examples/transcription_sync.py | 15 +++---- src/deapi_sdk/resources/transcription.py | 56 +++++++++--------------- src/deapi_sdk/types/transcription.py | 2 +- tests/test_transcription_sync.py | 35 ++++----------- 7 files changed, 61 insertions(+), 93 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 18a47bb..e09359e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,13 +8,13 @@ Versions follow [Semantic Versioning](https://semver.org/) (pre-1.0: minor versi ### Added - `client.transcription.transcribe_sync()` (sync and async clients): fast transcription for short - audio only, up to 60 seconds and 16 MiB per file (voice notes, commands, short clips; use - `create()` for anything longer). The transcript comes back in the response as the new + audio clips (voice notes, commands; use `create()` for longer audio). The transcript comes back + in the response as the new `SyncTranscriptionResult` (`transcription`, `language`, `duration`, `price`, optional `segments` with `words`); there is no job to poll. `transcribe_sync_price()` quotes it from the file or from - `duration_seconds`. The model defaults to `FluidSpeechPro`. A file over 16 MiB, or a quote for - over 60 seconds, raises `ValueError` before anything is sent; a 422 on `source_file` (e.g. a clip - over 60 seconds) stays a `ValidationError` whose message points to `create()`. + `duration_seconds`. The model defaults to `FluidSpeechPro`. Clip limits are set by the API: a + 422 on `source_file` (e.g. a clip that is too long) stays a `ValidationError` with the API's + message, followed by a pointer to `create()`. - `SyncTranscriptionUnavailableError`: synchronous transcription is in limited availability; accounts without access get a 404 or a 422 on `model`, raised as this error. It is also a `NotFoundError` or a `ValidationError`, so existing handlers keep catching it. diff --git a/README.md b/README.md index 59ce46e..bda65c9 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Generate images, videos, audio, transcriptions, embeddings, and more — all thr - **Video generation** — text-to-video, image-to-video (keyframes or reference images/videos/audio), audio-to-video, upscale - **Video description** — timestamped events and scenes of a video - **Audio** — text-to-speech (with voice cloning), text-to-music (with a style reference) -- **Transcription** — URLs and file uploads, plain-text or structured JSON transcripts; fast transcription of short audio (up to 60 s, no job to poll) +- **Transcription** — URLs and file uploads, plain-text or structured JSON transcripts; fast transcription of short audio clips (no job to poll) - **Embeddings, OCR, prompt enhancement** - **Account and keys** — balance, usage, payments, API-key management (ADMIN keys) - **Sync + Async** — both `DeapiClient` and `AsyncDeapiClient` @@ -256,12 +256,12 @@ timestamps inline. `client.transcription.get_transcript(result)` (or `deapi_sdk.parse_transcript(raw)`) handles both and returns a `Transcript` whose `format` is `"json"` or `"text"` (`segments` is empty for text). Result URLs are downloaded without your API key. -#### Fast transcription of short audio (up to 60 s) +#### Fast transcription of short audio clips -`transcribe_sync()` takes **short audio only: up to 60 seconds and 16 MiB per file**, and returns the -transcript in the same call (no job, no polling, no webhook). Use it for voice notes, commands and -short clips; for anything longer use the regular transcription, `create()`. The language is -detected and returned. +`transcribe_sync()` is fast transcription for **short audio clips** (currently up to 60 seconds; see +the [deAPI docs](https://docs.deapi.ai) for the current limits). It returns the transcript in the same call: no +job, no polling, no webhook. Use it for voice notes, commands and short clips; for longer audio use +the regular transcription, `create()`. The language is detected and returned. ```python from pathlib import Path @@ -280,9 +280,8 @@ quote = client.transcription.transcribe_sync_price(duration_seconds=30) # or s Synchronous transcription is in limited availability; accounts without access get a 404 or a 422 on `model`. Both are raised as `SyncTranscriptionUnavailableError` (also a `NotFoundError` / -`ValidationError`). A file over 16 MiB (or a quote for over 60 s) raises `ValueError` before anything -is sent; a clip longer than 60 seconds is a `ValidationError` on `source_file`. Both messages point -to `create()`. +`ValidationError`). Clip limits are enforced by the API: a clip that is too long or too large is a +`ValidationError` on `source_file`; its message states the limit and points to `create()`. ### Embeddings and OCR @@ -624,7 +623,7 @@ The [`examples/`](https://github.com/deapi-ai/deapi-python-sdk/tree/main/example | [`basic_image.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/basic_image.py) | Image generation, transformation, upscale | | [`async_batch.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/async_batch.py) | Concurrent async job submission | | [`transcription.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/transcription.py) | Transcription jobs, transcript parsing, price quotes | -| [`transcription_sync.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/transcription_sync.py) | Fast transcription of short audio, up to 60 s (no job) | +| [`transcription_sync.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/transcription_sync.py) | Fast transcription of a short audio clip (no job) | | [`tts_and_audio.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/tts_and_audio.py) | Text-to-speech and music generation | | [`video_generation.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/video_generation.py) | Text-to-video and image-to-video | | [`realtime_status.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/realtime_status.py) | Live job progress over WebSocket | diff --git a/docs/api-reference.md b/docs/api-reference.md index 961c371..7c04e1d 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -367,14 +367,15 @@ the quote is lower than the charge. ### `transcribe_sync()` / `transcribe_sync_price()` -Fast transcription for **short audio only: up to 60 seconds and 16 MiB per file**. The transcript is -in the response; there is no job to poll. For voice notes, commands and short clips; for anything -longer use the regular transcription, `create()`. +Fast transcription for **short audio clips** (currently up to 60 seconds; see the +[deAPI docs](https://docs.deapi.ai) for the current limits). The transcript is in the response; there is no job +to poll. For voice notes, commands and short clips; for longer audio use the regular +transcription, `create()`. ```python result = client.transcription.transcribe_sync( *, - source_file: FileInput, # audio up to 60 s / 16 MiB: aac, mpeg, mp4/m4a, ogg, wav, webm, flac + source_file: FileInput, # short clip: aac, mpeg, mp4/m4a, ogg, wav, webm, flac model: str = "FluidSpeechPro", include_ts: bool | None = None, # implied by ts_level ts_level: str | None = None, # "segment" (default with timestamps) | "word" @@ -384,7 +385,7 @@ price = client.transcription.transcribe_sync_price( *, model: str = "FluidSpeechPro", source_file: FileInput | None = None, # exactly one of source_file / duration_seconds - duration_seconds: float | None = None, # up to 60 + duration_seconds: float | None = None, ) -> PriceResult ``` @@ -403,9 +404,9 @@ class SyncTranscriptionResult(BaseModel): Synchronous transcription is in limited availability; accounts without access get a 404 or a 422 on `model`, raised as `SyncTranscriptionUnavailableError` (also a `NotFoundError` / -`ValidationError`). Limits are checked locally where it is cheap: a file over 16 MiB, or a -`duration_seconds` over 60 in a quote, raises `ValueError` before anything is sent. A clip over -60 seconds or a bad file is a `ValidationError` on `source_file`; its message points to `create()`. +`ValidationError`). The SDK does not check clip limits itself (the API sets them and they can +change): a clip that is too long or a bad file is a `ValidationError` on `source_file`, with the +API's message (which states the limit) followed by a pointer to `create()`. Missing credit is an `InsufficientBalanceError`, and the rate limit (shared with `create()`) a `RateLimitError`. diff --git a/examples/transcription_sync.py b/examples/transcription_sync.py index cdfc22d..5597fda 100644 --- a/examples/transcription_sync.py +++ b/examples/transcription_sync.py @@ -1,8 +1,8 @@ -"""Fast transcription for short audio only: up to 60 seconds and 16 MiB per file. +"""Fast transcription for short audio clips (voice notes, commands). The transcript comes back in the same HTTP response: no job, no polling, no webhook. -For voice notes, commands and short clips; for anything longer use the regular -transcription, ``client.transcription.create()`` (see transcription.py). +For longer audio use the regular transcription, ``client.transcription.create()`` +(see transcription.py). The current clip limits are in the deAPI docs: https://docs.deapi.ai Synchronous transcription is in limited availability; accounts without access get a 404 or a 422 on ``model`` (raised as ``SyncTranscriptionUnavailableError``). @@ -32,11 +32,10 @@ except SyncTranscriptionUnavailableError: print("Synchronous transcription is not available for this account; use transcription.create().") raise SystemExit(1) from None - except (ValueError, ValidationError) as e: - # ValueError: file over 16 MiB, refused before upload. - # ValidationError: e.g. errors["source_file"] for a clip over 60 s or an unsupported type. - # Both messages point to transcription.create() for longer audio. - print(e) + except ValidationError as e: + # e.g. errors["source_file"]: the clip is too long or too large (the message states the + # limit and points to transcription.create()), or the file type is not supported. + print(e.message, e.errors) raise SystemExit(1) from None print(f"[{result.language}] {result.transcription}") diff --git a/src/deapi_sdk/resources/transcription.py b/src/deapi_sdk/resources/transcription.py index 2fe4824..d8b99db 100644 --- a/src/deapi_sdk/resources/transcription.py +++ b/src/deapi_sdk/resources/transcription.py @@ -14,12 +14,10 @@ # The model used by ``transcribe_sync()`` unless another is passed. SYNC_TRANSCRIPTION_MODEL = "FluidSpeechPro" -# Synchronous (fast) transcription takes short audio only. -SYNC_TRANSCRIPTION_MAX_SECONDS = 60 -SYNC_TRANSCRIPTION_MAX_BYTES = 16 * 1024 * 1024 # 16 MiB +# Appended to a 422 on ``source_file``; the API message itself states the current limit. _SYNC_LIMIT_HINT = ( - "Fast (synchronous) transcription takes short audio only: up to 60 s and 16 MiB per file. " - "For longer audio use the regular transcription, client.transcription.create()." + "Fast transcription takes short audio clips only; " + "for longer audio use the regular transcription, client.transcription.create()." ) @@ -129,16 +127,7 @@ def _build_sync( if include_ts is None and ts_level: include_ts = True fields = drop_none({"model": model, "include_ts": include_ts, "ts_level": ts_level}) - return {"data": _form(fields), "files": [("source_file", _sync_file_part(source_file))]} - - -def _sync_file_part(source_file: FileInput) -> tuple[str, bytes, str]: - """Read the upload and refuse a file over 16 MiB before sending it.""" - part = normalize_file(source_file, "source_file") - size = len(part[1]) - if size > SYNC_TRANSCRIPTION_MAX_BYTES: - raise ValueError(f"source_file is {size} bytes, over 16 MiB. {_SYNC_LIMIT_HINT}") - return part + return {"data": _form(fields), "files": [("source_file", normalize_file(source_file, "source_file"))]} def _build_sync_price( @@ -156,11 +145,9 @@ def _build_sync_price( raise ValueError("Provide either 'source_file' or 'duration_seconds', not both.") if source_file is None and duration_seconds is None: raise ValueError("Either 'source_file' or 'duration_seconds' is required.") - if duration_seconds is not None and duration_seconds > SYNC_TRANSCRIPTION_MAX_SECONDS: - raise ValueError(f"duration_seconds is {duration_seconds}. {_SYNC_LIMIT_HINT}") parts: list[tuple[str, Any]] = [("model", (None, model))] if source_file is not None: - parts.append(("source_file", _sync_file_part(source_file))) + parts.append(("source_file", normalize_file(source_file, "source_file"))) else: parts.append(("duration_seconds", (None, str(duration_seconds)))) return {"files": parts} @@ -170,8 +157,9 @@ def _raise_sync_error(exc: NotFoundError | ValidationError) -> None: """Re-raise a synchronous-transcription error in its more useful form; otherwise return. A 404 or a 422 on ``model`` becomes ``SyncTranscriptionUnavailableError``. A 422 on - ``source_file`` (audio too long, file too large or unreadable) stays a ``ValidationError`` - whose message also points to ``create()`` for longer audio; ``errors`` and ``body`` are kept. + ``source_file`` (audio too long, file too large or unreadable) stays a ``ValidationError``: + the API message (which states the current limit) is kept and followed by a pointer to + ``create()`` for longer audio; ``errors`` and ``body`` are unchanged. """ unavailable = sync_transcription_unavailable(exc) if unavailable is not None: @@ -296,28 +284,27 @@ def transcribe_sync( include_ts: bool | None = None, ts_level: str | None = None, ) -> SyncTranscriptionResult: - """Fast transcription for short audio only: up to 60 s and 16 MiB per file. + """Fast transcription for short audio clips (voice notes, commands). - The transcript comes back in the same call (no job, no polling). Use it for voice notes, - commands and short clips; for anything longer use the regular transcription, ``create()``. - A file over 16 MiB is refused locally with ``ValueError`` before it is uploaded. The + The transcript comes back in the same call (no job, no polling). For longer audio use the + regular transcription, ``create()``. The API sets the length and size limits; a file over + them is rejected with a ``ValidationError`` on ``source_file`` that states the limit. The language is detected and returned. Synchronous transcription is in limited availability; accounts without access get a 404 or a 422 on ``model``, raised as ``SyncTranscriptionUnavailableError``. Args: - source_file: Audio file up to 60 s and 16 MiB (``Path``, ``bytes`` or a binary file - object): mp3, wav, ogg, flac, aac, m4a/mp4 or webm. A longer clip is rejected with a - ``ValidationError`` on ``source_file`` whose message points to ``create()``. + source_file: A short audio clip (``Path``, ``bytes`` or a binary file object): mp3, wav, + ogg, flac, aac, m4a/mp4 or webm. model: Synchronous transcription model. include_ts: Return timed ``segments``. Implied when ``ts_level`` is set. ts_level: ``segment`` (the default with timestamps) or ``word`` (segments with ``words``). Raises: SyncTranscriptionUnavailableError: The account cannot use synchronous transcription. - ValidationError: Bad file (over 60 s, unsupported type) or other bad input. - ValueError: ``source_file`` is over 16 MiB (checked before uploading). + ValidationError: Bad file (too long, too large, unsupported type) or other bad input; + a ``source_file`` error also points to ``create()``. InsufficientBalanceError: Not enough credit. """ kwargs = _build_sync(source_file=source_file, model=model, include_ts=include_ts, ts_level=ts_level) @@ -335,12 +322,11 @@ def transcribe_sync_price( source_file: FileInput | None = None, duration_seconds: float | None = None, ) -> PriceResult: - """Price of fast transcription (short audio only: up to 60 s and 16 MiB per file). + """Price of fast transcription for short audio clips (``transcribe_sync()``). Quotes from the file or from ``duration_seconds`` (not both); billed per second of audio. - A ``duration_seconds`` over 60 or a file over 16 MiB raises ``ValueError`` locally (use - ``create_price()`` for longer audio). Raises ``SyncTranscriptionUnavailableError`` like - ``transcribe_sync()``. + For longer audio quote the regular transcription with ``create_price()``. Raises + ``SyncTranscriptionUnavailableError`` like ``transcribe_sync()``. """ kwargs = _build_sync_price(model=model, source_file=source_file, duration_seconds=duration_seconds) try: @@ -440,7 +426,7 @@ async def transcribe_sync( include_ts: bool | None = None, ts_level: str | None = None, ) -> SyncTranscriptionResult: - """Fast transcription for short audio only (up to 60 s, 16 MiB). See ``Transcription.transcribe_sync``.""" + """Fast transcription for short audio clips. See ``Transcription.transcribe_sync``.""" kwargs = _build_sync(source_file=source_file, model=model, include_ts=include_ts, ts_level=ts_level) try: resp = await self._client.post(self._client._resolve_endpoint("transcribe_sync"), **kwargs) @@ -456,7 +442,7 @@ async def transcribe_sync_price( source_file: FileInput | None = None, duration_seconds: float | None = None, ) -> PriceResult: - """Price of fast transcription (up to 60 s, 16 MiB). See ``Transcription.transcribe_sync_price``.""" + """Price of fast transcription. See ``Transcription.transcribe_sync_price``.""" kwargs = _build_sync_price(model=model, source_file=source_file, duration_seconds=duration_seconds) try: resp = await self._client.post(self._client._resolve_endpoint("transcribe_sync_price"), **kwargs) diff --git a/src/deapi_sdk/types/transcription.py b/src/deapi_sdk/types/transcription.py index 8ce862c..f010730 100644 --- a/src/deapi_sdk/types/transcription.py +++ b/src/deapi_sdk/types/transcription.py @@ -18,7 +18,7 @@ class TranscribeParams(BaseModel): class SyncTranscriptionResult(BaseModel): - """Result of ``transcription.transcribe_sync()`` (fast transcription of audio up to 60 s). + """Result of ``transcription.transcribe_sync()`` (fast transcription of a short audio clip). The transcript itself; there is no job to poll. diff --git a/tests/test_transcription_sync.py b/tests/test_transcription_sync.py index be6274f..b600611 100644 --- a/tests/test_transcription_sync.py +++ b/tests/test_transcription_sync.py @@ -162,6 +162,8 @@ def test_422_on_model_is_unavailable_and_validation(self, client: DeapiClient) - assert isinstance(info.value, ValidationError) assert info.value.status_code == 422 + # The API's text is kept, so e.g. a mistyped model name stays visible. + assert info.value.message == "This model is not available on your plan." assert info.value.errors == {"model": ["This model is not available on your plan."]} assert info.value.body == body @@ -176,7 +178,7 @@ def test_too_long_clip_is_validation_error_pointing_to_create(self, client: Deap assert type(info.value) is ValidationError assert info.value.message.startswith(message) - assert "up to 60 s and 16 MiB" in info.value.message + assert "short audio clips" in info.value.message assert "client.transcription.create()" in info.value.message # The API's own data is untouched. assert info.value.errors["source_file"] == [message] @@ -196,18 +198,10 @@ def test_other_422_is_unchanged(self, client: DeapiClient) -> None: assert info.value.__cause__ is None @respx.mock - def test_file_over_16_mib_is_refused_before_upload(self, client: DeapiClient) -> None: + def test_no_client_side_size_limit(self, client: DeapiClient) -> None: + # Limits are the API's to enforce (they can change); the SDK sends any file. route = respx.post(SYNC_URL).mock(return_value=httpx.Response(200, json=PLAIN_RESPONSE)) - - with pytest.raises(ValueError, match=r"16777217 bytes, over 16 MiB.*up to 60 s and 16 MiB.*create\(\)"): - client.transcription.transcribe_sync(source_file=b"\0" * (16 * 1024 * 1024 + 1)) - - assert not route.called - - @respx.mock - def test_file_of_exactly_16_mib_is_sent(self, client: DeapiClient) -> None: - route = respx.post(SYNC_URL).mock(return_value=httpx.Response(200, json=PLAIN_RESPONSE)) - client.transcription.transcribe_sync(source_file=b"\0" * (16 * 1024 * 1024)) + client.transcription.transcribe_sync(source_file=b"\0" * (17 * 1024 * 1024)) assert route.call_count == 1 @respx.mock @@ -263,17 +257,10 @@ def test_price_needs_exactly_one_source(self, client: DeapiClient) -> None: client.transcription.transcribe_sync_price() @respx.mock - def test_price_over_60_seconds_is_refused_locally(self, client: DeapiClient) -> None: + def test_price_has_no_client_side_duration_limit(self, client: DeapiClient) -> None: route = respx.post(SYNC_PRICE_URL).mock(return_value=httpx.Response(200, json={"data": {"price": 0.1}})) - - with pytest.raises(ValueError, match=r"60\.5.*create\(\)"): - client.transcription.transcribe_sync_price(duration_seconds=60.5) - with pytest.raises(ValueError, match="16 MiB"): - client.transcription.transcribe_sync_price(source_file=b"\0" * (16 * 1024 * 1024 + 1)) - assert not route.called - - client.transcription.transcribe_sync_price(duration_seconds=60) - assert route.call_count == 1 + client.transcription.transcribe_sync_price(duration_seconds=600) + assert _multipart_fields(route.calls.last.request)["duration_seconds"] == "600" @respx.mock def test_price_404_is_unavailable(self, client: DeapiClient) -> None: @@ -316,7 +303,3 @@ async def test_async_too_long_points_to_create(self, async_client: AsyncDeapiCli )) with pytest.raises(ValidationError, match=r"create\(\)"): await async_client.transcription.transcribe_sync(source_file=b"a") - - async def test_async_file_over_16_mib_is_refused(self, async_client: AsyncDeapiClient) -> None: - with pytest.raises(ValueError, match="16 MiB"): - await async_client.transcription.transcribe_sync(source_file=b"\0" * (16 * 1024 * 1024 + 1)) From 34e1b4e564a70d019c4156dbdb98a041131861a7 Mon Sep 17 00:00:00 2001 From: Dawid Wenderski Date: Sun, 29 Nov 2026 18:28:19 +0100 Subject: [PATCH 05/13] Use the same too-long hint wording as the TypeScript SDK Co-Authored-By: Claude Opus 5.5 --- src/deapi_sdk/resources/transcription.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/deapi_sdk/resources/transcription.py b/src/deapi_sdk/resources/transcription.py index d8b99db..507f489 100644 --- a/src/deapi_sdk/resources/transcription.py +++ b/src/deapi_sdk/resources/transcription.py @@ -16,7 +16,7 @@ SYNC_TRANSCRIPTION_MODEL = "FluidSpeechPro" # Appended to a 422 on ``source_file``; the API message itself states the current limit. _SYNC_LIMIT_HINT = ( - "Fast transcription takes short audio clips only; " + "Fast transcription is for short audio clips; " "for longer audio use the regular transcription, client.transcription.create()." ) From fb7083428ebc356c05710716eeaf909fc0a53497 Mon Sep 17 00:00:00 2001 From: Dawid Wenderski Date: Sun, 29 Nov 2026 18:38:41 +0100 Subject: [PATCH 06/13] Fall back to the production realtime server when discovery answers 404 GET /websocket answers 404 where the API does not provide realtime settings, and since 0.6.0 connect() then failed with NotFoundError unless ws_url and app_key were set by hand. On a 404, connect() now fills the missing ws_url / app_key with the built-in production WebSocket server and its public app key (only for the production base_url), so only the Client ID is needed (client_id or DEAPI_CLIENT_ID). Without it, or for another base_url without ws_url / app_key, connect() raises RealtimeError naming the settings to pass (status_code 404, the NotFoundError as its cause) and does not connect. Other HTTP errors from discovery propagate as before; explicit, environment and discovered settings still win. Tests cover the fallback with the fake Pusher server (sync and async), the missing Client ID, a non-production base_url, discovered settings winning and other HTTP errors. README, API reference, .env.example, the realtime example and CHANGELOG (Unreleased, Fixed) are updated. Co-Authored-By: Claude Opus 5.5 --- .env.example | 3 +- CHANGELOG.md | 12 ++ README.md | 12 +- docs/api-reference.md | 19 ++- examples/realtime_status.py | 7 +- src/deapi_sdk/_realtime/_protocol.py | 6 + src/deapi_sdk/_realtime/_session.py | 60 +++++++++- tests/test_realtime.py | 170 +++++++++++++++++++++++++++ 8 files changed, 272 insertions(+), 17 deletions(-) diff --git a/.env.example b/.env.example index 9af10f7..8e24d77 100644 --- a/.env.example +++ b/.env.example @@ -14,7 +14,8 @@ DEAPI_API_KEY=sk-dp-- # DEAPI_FILL_MODEL_DEFAULTS=1 # Real-time status over WebSocket (pip install "deapi-sdk[ws]") -# All optional: anything unset is fetched from the API (GET /websocket) when the connection opens. +# Anything unset is fetched from the API (GET /websocket) when the connection opens. Where the API +# does not provide it (404), the production server is used and only the Client ID is required. # The "Client ID" shown in your dashboard; pass client_id= explicitly when serving many users # DEAPI_CLIENT_ID=your-client-id # Overrides, e.g. for a local WebSocket server diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f04be5..c2cfdc6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,18 @@ All notable changes to this project are documented in this file. Versions follow [Semantic Versioning](https://semver.org/) (pre-1.0: minor versions may contain breaking changes). +## Unreleased + +### Fixed + +- `client.realtime()` works again where the API does not provide realtime settings: when + `GET /websocket` answers 404, `connect()` uses the built-in production WebSocket server and public + app key for whatever is missing (production `base_url` only), so only the Client ID is needed + (`client_id` or `DEAPI_CLIENT_ID`). Without it, or for another `base_url` without `ws_url` / + `app_key`, `connect()` raises `RealtimeError` naming what to set (`status_code` 404). Other HTTP + errors from discovery are raised as before; explicit, environment and discovered settings still + win. 0.6.0 and 0.6.1 needed `ws_url` and `app_key` set by hand in that case. + ## [0.6.1] - 2026-11-19 ### Added diff --git a/README.md b/README.md index 4371f99..00c65b9 100644 --- a/README.md +++ b/README.md @@ -102,8 +102,8 @@ client = DeapiClient( | `api_version` | `DEAPI_API_VERSION` | `v2` | | `fill_model_defaults` | `DEAPI_FILL_MODEL_DEFAULTS` (`0` disables) | on | | `client_id` (`client.realtime()`) | `DEAPI_CLIENT_ID` | discovered from the API | -| `ws_url` (`client.realtime()`) | `DEAPI_WS_URL` | discovered from the API | -| `app_key` (`client.realtime()`) | `DEAPI_WS_APP_KEY` | discovered from the API | +| `ws_url` (`client.realtime()`) | `DEAPI_WS_URL` | discovered from the API, else the production server | +| `app_key` (`client.realtime()`) | `DEAPI_WS_APP_KEY` | discovered from the API, else the production app key | | `timeout` | — | `30.0` | | `max_retries` | — | `3` | | `max_retry_after` | — | `60.0` (cap on a 429 `Retry-After` sleep, in seconds) | @@ -386,7 +386,7 @@ Instead of polling, follow your jobs live over one WebSocket connection. Install from deapi_sdk import DeapiClient with DeapiClient(api_key="sk-dp--") as client: - with client.realtime() as rt: # no other settings needed: the SDK asks the API where to connect + with client.realtime(client_id="your-client-id") as rt: # or DEAPI_CLIENT_ID; see the notes below job = client.images.generate(prompt="a cat in space", model="Flux1schnell", width=1024, height=1024) result = rt.wait(job, on_progress=lambda e: print(e.status, e.progress)) # same JobResult as job.wait() @@ -414,6 +414,12 @@ async with AsyncDeapiClient() as client: set there is no extra request. `rt.client_id` is `None` until then if you did not pass one. `client_id` is the "Client ID" shown in your deAPI dashboard; servers handling many users should pass it explicitly per user. A `client_id` that does not belong to the API key raises `RealtimeError`. +- **Without discovery.** When the API does not provide these settings (`GET /websocket` answers 404), the SDK uses the + built-in production WebSocket server and its public app key for whatever is missing, so only the + Client ID is needed (`client_id` or `DEAPI_CLIENT_ID`). This applies to the production `base_url` + only; for another `base_url`, or without a Client ID, `connect()` raises `RealtimeError` naming the + settings to pass. + Other errors from the discovery call (for example `AuthenticationError`) are raised as usual. - **`rt.wait(job_or_request_id)`** accepts a `Job` or a request id. WebSocket events drive progress and completion; on `done` the SDK fetches the final `JobResult` over HTTP (fresh signed `result_url`, all fields). diff --git a/docs/api-reference.md b/docs/api-reference.md index dbc6ced..f4aa205 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -584,9 +584,18 @@ made. Otherwise the SDK fetches the parameters **once at connect time** (`connec `await connect()` / `async with`; constructors do no I/O), fills only the missing fields and keeps the result for reconnects. When discovery ran, the returned `auth_endpoint` is used to authorize the channel. +When the API does not provide these settings (`GET /websocket` answers 404), the SDK uses the +built-in production WebSocket server and its public app key for whatever is missing, so only the +Client ID is needed (`client_id` or `DEAPI_CLIENT_ID`). This applies to the production `base_url` +only; for another `base_url`, or without a Client ID, `connect()` raises `RealtimeError` naming the +settings to pass. +The error has `status_code` 404 and the `NotFoundError` as its `__cause__`. Discovered and explicit +values always win over the built-in ones. + `client_id` is an opaque string; servers handling many users should pass it per user. Until connect, `rt.client_id` is `None` if it was neither passed nor set in the environment. A failed discovery call -raises the normal API exception (for example `AuthenticationError`); a malformed response, an unsupported +raises the normal API exception (for example `AuthenticationError`), except a 404 (see above); a +malformed response, an unsupported `connection.protocol` or an unexpected `event` raises `RealtimeError`. ### `client.websocket_config()` @@ -847,7 +856,9 @@ it with a TTL longer than `tolerance`) so a retried or replayed delivery is proc | `DEAPI_API_VERSION` | `v2` | API version (only `v2` is accepted) | | `DEAPI_FILL_MODEL_DEFAULTS` | on | `0` stops the SDK filling unset parameters from model-card defaults | | `DEAPI_CLIENT_ID` | *(discovered)* | Client ID for `client.realtime()` when `client_id` is not passed | -| `DEAPI_WS_URL` | *(discovered)* | WebSocket URL override for `client.realtime()` | -| `DEAPI_WS_APP_KEY` | *(discovered)* | WebSocket app key override for `client.realtime()` | +| `DEAPI_WS_URL` | *(discovered, else production)* | WebSocket URL override for `client.realtime()` | +| `DEAPI_WS_APP_KEY` | *(discovered, else production)* | WebSocket app key override for `client.realtime()` | -Unset realtime values are fetched from `GET /websocket` at connect time. +Unset realtime values are fetched from `GET /websocket` at connect time. If that answers 404, the +production WebSocket server and app key fill `ws_url` / `app_key` (production `base_url` only); the +Client ID must then be set. diff --git a/examples/realtime_status.py b/examples/realtime_status.py index 6169b67..0726326 100644 --- a/examples/realtime_status.py +++ b/examples/realtime_status.py @@ -8,8 +8,9 @@ Usage: export DEAPI_API_KEY="sk-dp--" - # Optional: the SDK fetches the connection settings (client id, WebSocket host, app key) from the API. - # export DEAPI_CLIENT_ID="your-client-id" # the "Client ID" shown in your deAPI dashboard + # The SDK fetches the connection settings from the API; where the API does not provide them it + # uses the production server, and then only the Client ID is needed: + export DEAPI_CLIENT_ID="your-client-id" # the "Client ID" shown in your deAPI dashboard python examples/realtime_status.py python examples/realtime_status.py --watch """ @@ -26,7 +27,7 @@ def print_progress(event: JobStatusEvent) -> None: def main() -> None: # Open the connection BEFORE submitting jobs so no event is missed. - # No settings needed: they are fetched from the API on connect (override via client_id= or DEAPI_CLIENT_ID). + # Settings come from DEAPI_CLIENT_ID (or client_id=) and the API; see the module docstring. with DeapiClient() as client, client.realtime() as rt: if "--watch" in sys.argv: print("Watching job events (Ctrl+C to stop)...") diff --git a/src/deapi_sdk/_realtime/_protocol.py b/src/deapi_sdk/_realtime/_protocol.py index 0685a9a..5e25841 100644 --- a/src/deapi_sdk/_realtime/_protocol.py +++ b/src/deapi_sdk/_realtime/_protocol.py @@ -19,6 +19,12 @@ BROADCASTING_AUTH_PATH = "/broadcasting/auth" +# Production WebSocket server and its public Pusher app key (not a secret: every client sends it in +# the connection URL). Used only when GET /websocket answers 404 and the client talks to the +# production API; explicit, environment and discovered settings always win. +DEFAULT_WS_URL = "wss://soketi.deapi.ai" +DEFAULT_APP_KEY = "depin-api-prod-key" + STATUS_EVENT = "request.status.updated" CLIENT_CHANNEL_PREFIX = "private-client." diff --git a/src/deapi_sdk/_realtime/_session.py b/src/deapi_sdk/_realtime/_session.py index c4f2a76..150e0af 100644 --- a/src/deapi_sdk/_realtime/_session.py +++ b/src/deapi_sdk/_realtime/_session.py @@ -13,7 +13,8 @@ from collections.abc import AsyncIterator, Awaitable, Callable, Iterator from typing import TYPE_CHECKING, Any, Protocol, TypeVar -from deapi_sdk._exceptions import RealtimeError +from deapi_sdk._config import _DEFAULT_BASE_URL +from deapi_sdk._exceptions import NotFoundError, RealtimeError from deapi_sdk._polling import AsyncJob, Job, _timeout_error from deapi_sdk._realtime import _protocol as protocol from deapi_sdk._realtime._discovery import parse_websocket_config @@ -70,6 +71,8 @@ class _Settings: Nothing here does I/O. When an argument/environment value is missing, :meth:`apply` fills the gaps from the discovery response at connect time (once; the result is cached). + When discovery is not available (404), :meth:`apply_builtin` fills them from the built-in + production server instead. """ def __init__( @@ -97,6 +100,7 @@ def __init__( self.discovery_url: str = http._resolve_endpoint("websocket") self.user_agent = config._user_agent self.connect_timeout = connect_timeout + self.production = config.base_url.rstrip("/") == _DEFAULT_BASE_URL if self.client_id and self._ws_url and self._app_key: self._finish(self.client_id, self._ws_url, self._app_key, protocol.channel_for(self.client_id)) @@ -122,6 +126,31 @@ def apply(self, discovered: WebSocketConfig) -> None: self.auth_url = discovered.auth_endpoint self.discovered = True + def apply_builtin(self, cause: NotFoundError) -> None: + """``GET /websocket`` answered 404: use the built-in production server for what is missing. + + The Client ID has no default, and a non-production ``base_url`` gets no built-in server; + :class:`RealtimeError` (``status_code`` 404, the ``NotFoundError`` as its cause) names what to set. + """ + ws_url = self._ws_url or (protocol.DEFAULT_WS_URL if self.production else None) + app_key = self._app_key or (protocol.DEFAULT_APP_KEY if self.production else None) + if not (self.client_id and ws_url and app_key): + missing = [ + name + for name, value in ( + ("client_id (or DEAPI_CLIENT_ID; your Client ID is shown in the deAPI dashboard)", self.client_id), + ("ws_url (or DEAPI_WS_URL)", ws_url), + ("app_key (or DEAPI_WS_APP_KEY)", app_key), + ) + if not value + ] + raise RealtimeError( + "The API does not provide realtime connection settings (GET /websocket answered 404). " + f"Pass {', '.join(missing)}.", + status_code=404, + ) from cause + self._finish(self.client_id, ws_url, app_key, protocol.channel_for(self.client_id)) + def _auth_signature(resp: Any) -> str: auth = resp.get("auth") if isinstance(resp, dict) else None @@ -186,6 +215,10 @@ def _discovered(self, config: WebSocketConfig) -> None: self._settings.apply(config) self._engine.configure(self._settings.url or "", self._settings.channel or "") + def _builtin(self, cause: NotFoundError) -> None: + self._settings.apply_builtin(cause) + self._engine.configure(self._settings.url or "", self._settings.channel or "") + @property def connected(self) -> bool: """True while the channel subscription is live (False while reconnecting or after close).""" @@ -194,11 +227,16 @@ def connected(self) -> bool: async def connect(self) -> None: """Open the connection and subscribe. Raises :class:`RealtimeError` if that fails. - Connection parameters that were not supplied are fetched first from ``GET /websocket``. + Connection parameters that were not supplied are fetched first from ``GET /websocket``; when + that answers 404, the built-in production server fills them (only the Client ID is then needed). """ if not self._settings.ready: - resp = await self._http.get(self._settings.discovery_url) - self._discovered(parse_websocket_config(resp)) + try: + resp = await self._http.get(self._settings.discovery_url) + except NotFoundError as exc: + self._builtin(exc) + else: + self._discovered(parse_websocket_config(resp)) await self._engine.start() async def close(self) -> None: @@ -402,6 +440,10 @@ def _discovered(self, config: WebSocketConfig) -> None: self._settings.apply(config) self._engine.configure(self._settings.url or "", self._settings.channel or "") + def _builtin(self, cause: NotFoundError) -> None: + self._settings.apply_builtin(cause) + self._engine.configure(self._settings.url or "", self._settings.channel or "") + @property def connected(self) -> bool: """True while the channel subscription is live (False while reconnecting or after close).""" @@ -411,12 +453,18 @@ def connect(self) -> None: """Open the connection and subscribe. Raises :class:`RealtimeError` if that fails. Connection parameters that were not supplied are fetched first from ``GET /websocket`` - (a blocking HTTP call in the calling thread). + (a blocking HTTP call in the calling thread); when that answers 404, the built-in production + server fills them (only the Client ID is then needed). """ with self._lock: started = self._thread is not None if not started and not self._settings.ready: - self._discovered(parse_websocket_config(self._http.get(self._settings.discovery_url))) + try: + resp = self._http.get(self._settings.discovery_url) + except NotFoundError as exc: + self._builtin(exc) + else: + self._discovered(parse_websocket_config(resp)) with self._lock: if self._thread is not None: raise RealtimeError("This realtime session was already started; create a new one to reconnect.") diff --git a/tests/test_realtime.py b/tests/test_realtime.py index a3b1c82..cb84dda 100644 --- a/tests/test_realtime.py +++ b/tests/test_realtime.py @@ -18,8 +18,10 @@ from deapi_sdk._exceptions import ( # noqa: E402 AuthenticationError, JobTimeoutError, + NotFoundError, PermissionDeniedError, RealtimeError, + ServerError, ) from deapi_sdk._realtime import _protocol as protocol # noqa: E402 from deapi_sdk._realtime import _session as session_module # noqa: E402 @@ -1392,3 +1394,171 @@ def test_connection_url_building(tls: bool, port: int, expected: str) -> None: conn = WebSocketConnection(protocol="pusher", key="k", host="h.example.test", port=port, tls=tls) assert conn.url == expected + + +# =========================================================================== discovery 404 fallback + +PROD_BASE_URL = "https://api.deapi.ai" +PROD_WEBSOCKET_URL = f"{PROD_BASE_URL}/api/v2/websocket" +PROD_AUTH_URL = f"{PROD_BASE_URL}/broadcasting/auth" + + +@pytest.fixture +def prod_client() -> Iterator[DeapiClient]: + with DeapiClient(api_key=TEST_API_KEY, base_url=PROD_BASE_URL, fill_model_defaults=False) as c: + yield c + + +@pytest.fixture +async def prod_async_client() -> Any: + async with AsyncDeapiClient(api_key=TEST_API_KEY, base_url=PROD_BASE_URL, fill_model_defaults=False) as c: + yield c + + +@pytest.fixture +def builtin_server(server: FakePusherServer, monkeypatch: pytest.MonkeyPatch) -> FakePusherServer: + """Point the built-in production defaults at the fake server.""" + monkeypatch.setattr(protocol, "DEFAULT_WS_URL", server.url) + monkeypatch.setattr(protocol, "DEFAULT_APP_KEY", APP_KEY) + return server + + +@pytest.fixture +def no_discovery(api: respx.MockRouter) -> respx.Route: + return api.get(PROD_WEBSOCKET_URL).mock(return_value=httpx.Response(404, json={"message": "Not Found"})) + + +@pytest.fixture +def prod_auth(api: respx.MockRouter) -> AuthEndpoint: + endpoint = AuthEndpoint() + api.post(PROD_AUTH_URL).mock(side_effect=endpoint) + return endpoint + + +def test_builtin_production_defaults() -> None: + assert protocol.DEFAULT_WS_URL == "wss://soketi.deapi.ai" + assert protocol.DEFAULT_APP_KEY == "depin-api-prod-key" + + +class TestDiscoveryFallback: + def test_404_uses_builtin_server_with_client_id( + self, + prod_client: DeapiClient, + builtin_server: FakePusherServer, + no_discovery: respx.Route, + prod_auth: AuthEndpoint, + ) -> None: + with prod_client.realtime(client_id=CLIENT_ID, connect_timeout=2) as rt: + assert rt.connected + assert rt.client_id == CLIENT_ID + assert no_discovery.call_count == 1 + assert builtin_server.last_path == f"/app/{APP_KEY}" + assert builtin_server.subscriptions[0][0] == CHANNEL + assert prod_auth.bodies[0]["channel_name"] == CHANNEL + + def test_env_client_id_is_enough( + self, + prod_client: DeapiClient, + builtin_server: FakePusherServer, + no_discovery: respx.Route, + prod_auth: AuthEndpoint, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + monkeypatch.setenv("DEAPI_CLIENT_ID", CLIENT_ID) + with prod_client.realtime(connect_timeout=2): + pass + assert builtin_server.subscriptions[0][0] == CHANNEL + + def test_explicit_values_win_over_builtin( + self, + prod_client: DeapiClient, + server: FakePusherServer, + no_discovery: respx.Route, + prod_auth: AuthEndpoint, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + # The built-in server is unreachable; the explicit ws_url must be used, the app key filled in. + monkeypatch.setattr(protocol, "DEFAULT_WS_URL", "ws://127.0.0.1:9") + monkeypatch.setattr(protocol, "DEFAULT_APP_KEY", APP_KEY) + with prod_client.realtime(client_id=CLIENT_ID, ws_url=server.url, connect_timeout=2): + pass + assert server.last_path == f"/app/{APP_KEY}" + + def test_without_client_id_names_it( + self, prod_client: DeapiClient, builtin_server: FakePusherServer, no_discovery: respx.Route + ) -> None: + rt = prod_client.realtime(connect_timeout=2) + with pytest.raises(RealtimeError) as info: + rt.connect() + message = str(info.value) + assert "GET /websocket answered 404" in message + assert "client_id (or DEAPI_CLIENT_ID" in message + assert "ws_url" not in message and "app_key" not in message + assert info.value.status_code == 404 + assert isinstance(info.value.__cause__, NotFoundError) + assert not rt.connected + assert builtin_server.subscriptions == [] + + def test_non_production_base_url_gets_no_builtin( + self, client: DeapiClient, builtin_server: FakePusherServer, api: respx.MockRouter + ) -> None: + api.get(WEBSOCKET_URL).mock(return_value=httpx.Response(404)) + with pytest.raises(RealtimeError) as info: + client.realtime(client_id=CLIENT_ID, connect_timeout=2).connect() + message = str(info.value) + assert "ws_url (or DEAPI_WS_URL)" in message and "app_key (or DEAPI_WS_APP_KEY)" in message + assert "client_id" not in message + assert builtin_server.subscriptions == [] + + def test_discovered_settings_win( + self, + prod_client: DeapiClient, + server: FakePusherServer, + api: respx.MockRouter, + discovered_auth: AuthEndpoint, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + monkeypatch.setattr(protocol, "DEFAULT_WS_URL", "ws://127.0.0.1:9") + monkeypatch.setattr(protocol, "DEFAULT_APP_KEY", "unused") + api.get(PROD_WEBSOCKET_URL).mock(return_value=httpx.Response(200, json=websocket_body(server))) + with prod_client.realtime(connect_timeout=2) as rt: + assert rt.client_id == DISCOVERED_ID + assert server.last_path == f"/app/{APP_KEY}" + + @pytest.mark.parametrize( + ("status", "error"), + [(401, AuthenticationError), (403, PermissionDeniedError), (500, ServerError)], + ) + def test_other_http_errors_propagate( + self, + prod_client: DeapiClient, + builtin_server: FakePusherServer, + api: respx.MockRouter, + status: int, + error: type[Exception], + monkeypatch: pytest.MonkeyPatch, + ) -> None: + monkeypatch.setattr("deapi_sdk._client.time.sleep", lambda _s: None) + api.get(PROD_WEBSOCKET_URL).mock( + return_value=httpx.Response(status, json={"message": "nope", "code": "insufficient_permissions"}), + ) + with pytest.raises(error): + prod_client.realtime(client_id=CLIENT_ID, connect_timeout=2).connect() + assert builtin_server.subscriptions == [] + + async def test_async_404_uses_builtin_server( + self, + prod_async_client: AsyncDeapiClient, + builtin_server: FakePusherServer, + no_discovery: respx.Route, + prod_auth: AuthEndpoint, + ) -> None: + async with prod_async_client.realtime(client_id=CLIENT_ID, connect_timeout=2) as rt: + assert rt.connected + assert builtin_server.subscriptions[0][0] == CHANNEL + + async def test_async_without_client_id( + self, prod_async_client: AsyncDeapiClient, builtin_server: FakePusherServer, no_discovery: respx.Route + ) -> None: + with pytest.raises(RealtimeError, match="client_id"): + await prod_async_client.realtime(connect_timeout=2).connect() From fb7a2a9a8a941e5afc093071271aea915c9f783d Mon Sep 17 00:00:00 2001 From: Dawid Wenderski Date: Sun, 29 Nov 2026 21:59:22 +0100 Subject: [PATCH 07/13] Replace retired model slugs in the README and tests Nanonets_Ocr_S_F16, AceStep_1_5_Turbo and WhisperLargeV3 are no longer in the model catalogue. The README OCR example and the OCR tests now use LightOnOcr_3_4B_Q8, the music tests AceStep_1_5_XL_Turbo_INT8 and the transcription payload test WhisperLargeV3Ct2. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- tests/test_media_v2.py | 6 +++--- tests/test_ocr.py | 26 +++++++++++++------------- tests/test_transcript.py | 4 ++-- 4 files changed, 19 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index bda65c9..604236c 100644 --- a/README.md +++ b/README.md @@ -294,7 +294,7 @@ job = client.embeddings.create( return_result_in_response=True, ) -job = client.ocr.extract(image=Path("scan.png"), model="Nanonets_Ocr_S_F16", return_result_in_response=True) +job = client.ocr.extract(image=Path("scan.png"), model="LightOnOcr_3_4B_Q8", return_result_in_response=True) ``` ### Prompt Enhancement diff --git a/tests/test_media_v2.py b/tests/test_media_v2.py index 7ef587a..e595c0e 100644 --- a/tests/test_media_v2.py +++ b/tests/test_media_v2.py @@ -314,10 +314,10 @@ class TestMusic: @respx.mock def test_json_without_reference(self, client: DeapiClient) -> None: route = _mock("audio/music") - client.audio.compose(caption="lofi", model="AceStep_1_5_Turbo", duration=30, lyrics="[Instrumental]") + client.audio.compose(caption="lofi", model="AceStep_1_5_XL_Turbo_INT8", duration=30, lyrics="[Instrumental]") assert not _is_multipart(route) assert _json(route) == { - "caption": "lofi", "model": "AceStep_1_5_Turbo", "duration": 30, "lyrics": "[Instrumental]", + "caption": "lofi", "model": "AceStep_1_5_XL_Turbo_INT8", "duration": 30, "lyrics": "[Instrumental]", } @respx.mock @@ -379,7 +379,7 @@ class TestPrompts: @respx.mock def test_enhance_sends_type_and_model_slug(self, client: DeapiClient) -> None: route = _mock("prompts/enhancements", {"prompt": "better", "negative_prompt": None}) - result = client.prompts.enhance(prompt="a cat", type="audio.music", model_slug="AceStep_1_5_Turbo") + result = client.prompts.enhance(prompt="a cat", type="audio.music", model_slug="AceStep_1_5_XL_Turbo_INT8") assert result.prompt == "better" body = _body(route) assert 'name="type"' in body and "audio.music" in body diff --git a/tests/test_ocr.py b/tests/test_ocr.py index 26f7a3b..59f980e 100644 --- a/tests/test_ocr.py +++ b/tests/test_ocr.py @@ -18,7 +18,7 @@ def test_extract_returns_job(self, client: DeapiClient) -> None: respx.post(f"{TEST_BASE_URL}/api/v2/images/ocr").mock( return_value=httpx.Response(200, json=SUBMIT_RESPONSE) ) - job = client.ocr.extract(image=b"fake-png-data", model="Nanonets_Ocr_S_F16") + job = client.ocr.extract(image=b"fake-png-data", model="LightOnOcr_3_4B_Q8") assert job.request_id == "ocr-uuid-123" @respx.mock @@ -26,7 +26,7 @@ def test_extract_sends_multipart(self, client: DeapiClient) -> None: route = respx.post(f"{TEST_BASE_URL}/api/v2/images/ocr").mock( return_value=httpx.Response(200, json=SUBMIT_RESPONSE) ) - client.ocr.extract(image=b"fake-png-data", model="Nanonets_Ocr_S_F16") + client.ocr.extract(image=b"fake-png-data", model="LightOnOcr_3_4B_Q8") content_type = route.calls.last.request.headers.get("content-type", "") assert "multipart/form-data" in content_type @@ -37,7 +37,7 @@ def test_extract_with_all_params(self, client: DeapiClient) -> None: ) client.ocr.extract( image=b"fake-png-data", - model="Nanonets_Ocr_S_F16", + model="LightOnOcr_3_4B_Q8", language="en", format="json", return_result_in_response=True, @@ -45,7 +45,7 @@ def test_extract_with_all_params(self, client: DeapiClient) -> None: ) request = route.calls.last.request body = request.content.decode("utf-8", errors="replace") - assert "Nanonets_Ocr_S_F16" in body + assert "LightOnOcr_3_4B_Q8" in body assert "en" in body assert "json" in body @@ -54,11 +54,11 @@ def test_extract_minimal_params(self, client: DeapiClient) -> None: route = respx.post(f"{TEST_BASE_URL}/api/v2/images/ocr").mock( return_value=httpx.Response(200, json=SUBMIT_RESPONSE) ) - client.ocr.extract(image=b"fake-png-data", model="Nanonets_Ocr_S_F16") + client.ocr.extract(image=b"fake-png-data", model="LightOnOcr_3_4B_Q8") request = route.calls.last.request body = request.content.decode("utf-8", errors="replace") assert "language" not in body or body.count("language") == 0 - assert "Nanonets_Ocr_S_F16" in body + assert "LightOnOcr_3_4B_Q8" in body class TestOCRExtractPrice: @@ -67,7 +67,7 @@ def test_extract_price_with_image(self, client: DeapiClient) -> None: respx.post(f"{TEST_BASE_URL}/api/v2/images/ocr/price").mock( return_value=httpx.Response(200, json=PRICE_RESPONSE) ) - price = client.ocr.extract_price(model="Nanonets_Ocr_S_F16", image=b"fake-png-data") + price = client.ocr.extract_price(model="LightOnOcr_3_4B_Q8", image=b"fake-png-data") assert price.price == 0.003 @respx.mock @@ -77,10 +77,10 @@ def test_extract_price_with_dimensions(self, client: DeapiClient) -> None: route = respx.post(f"{TEST_BASE_URL}/api/v2/images/ocr/price").mock( return_value=httpx.Response(200, json=PRICE_RESPONSE) ) - price = client.ocr.extract_price(model="Nanonets_Ocr_S_F16", width=1024, height=768) + price = client.ocr.extract_price(model="LightOnOcr_3_4B_Q8", width=1024, height=768) assert price.price == 0.003 body = json.loads(route.calls.last.request.content) - assert body["model"] == "Nanonets_Ocr_S_F16" + assert body["model"] == "LightOnOcr_3_4B_Q8" assert body["width"] == 1024 assert body["height"] == 768 @@ -89,7 +89,7 @@ def test_extract_price_with_image_sends_multipart(self, client: DeapiClient) -> route = respx.post(f"{TEST_BASE_URL}/api/v2/images/ocr/price").mock( return_value=httpx.Response(200, json=PRICE_RESPONSE) ) - client.ocr.extract_price(model="Nanonets_Ocr_S_F16", image=b"fake") + client.ocr.extract_price(model="LightOnOcr_3_4B_Q8", image=b"fake") content_type = route.calls.last.request.headers.get("content-type", "") assert "multipart/form-data" in content_type @@ -98,7 +98,7 @@ def test_extract_price_without_image_sends_json(self, client: DeapiClient) -> No route = respx.post(f"{TEST_BASE_URL}/api/v2/images/ocr/price").mock( return_value=httpx.Response(200, json=PRICE_RESPONSE) ) - client.ocr.extract_price(model="Nanonets_Ocr_S_F16", width=512, height=512) + client.ocr.extract_price(model="LightOnOcr_3_4B_Q8", width=512, height=512) content_type = route.calls.last.request.headers.get("content-type", "") assert "application/json" in content_type @@ -110,7 +110,7 @@ async def test_async_extract(self, async_client: AsyncDeapiClient) -> None: respx.post(f"{TEST_BASE_URL}/api/v2/images/ocr").mock( return_value=httpx.Response(200, json=SUBMIT_RESPONSE) ) - job = await async_client.ocr.extract(image=b"data", model="Nanonets_Ocr_S_F16") + job = await async_client.ocr.extract(image=b"data", model="LightOnOcr_3_4B_Q8") assert job.request_id == "ocr-uuid-123" @respx.mock @@ -119,5 +119,5 @@ async def test_async_extract_price(self, async_client: AsyncDeapiClient) -> None respx.post(f"{TEST_BASE_URL}/api/v2/images/ocr/price").mock( return_value=httpx.Response(200, json=PRICE_RESPONSE) ) - price = await async_client.ocr.extract_price(model="Nanonets_Ocr_S_F16", width=512, height=512) + price = await async_client.ocr.extract_price(model="LightOnOcr_3_4B_Q8", width=512, height=512) assert price.price == 0.003 diff --git a/tests/test_transcript.py b/tests/test_transcript.py index 363b1b3..8bcd119 100644 --- a/tests/test_transcript.py +++ b/tests/test_transcript.py @@ -129,9 +129,9 @@ def test_url_json_payload(self, client: DeapiClient) -> None: @respx.mock def test_unset_fields_omitted(self, client: DeapiClient) -> None: route = respx.post(f"{V2}/audio/transcriptions").mock(return_value=httpx.Response(200, json=JOB)) - client.transcription.create(model="WhisperLargeV3", source_url="https://x.test/a.mp3") + client.transcription.create(model="WhisperLargeV3Ct2", source_url="https://x.test/a.mp3") assert json.loads(route.calls.last.request.content) == { - "source_url": "https://x.test/a.mp3", "model": "WhisperLargeV3", + "source_url": "https://x.test/a.mp3", "model": "WhisperLargeV3Ct2", } @respx.mock From b720bda06fe2ca915caec90c2db6a47a4619c1bc Mon Sep 17 00:00:00 2001 From: Dawid Wenderski Date: Sun, 29 Nov 2026 18:04:49 +0100 Subject: [PATCH 08/13] Add chat (LLMs) through the OpenAI-compatible API: client.chat client.chat.completions.create(model=..., messages=[...], **params) posts to /chat/completions on oai_base_url (default https://oai.deapi.ai/v1, env DEAPI_OAI_BASE_URL) with the same API key, on the sync and async clients. It returns a ChatCompletion in the OpenAI shape with deAPI's extras: usage.cost, the X-DeAPI-Cost header (header_cost), reasoning_content and reasoning_details. Other Chat Completions parameters pass through; a message returned by the SDK can be appended to messages as is, so reasoning_details go back in the next turn. stream=True returns a ChatCompletionStream (AsyncChatCompletionStream) of ChatCompletionChunk parsed from SSE; the final usage chunk sets usage and cost. Errors are raised before the first chunk; an error event inside the stream raises DeapiError. client.chat.models() lists the /models entries that have pricing, as ChatModel with per-1M-token price helpers. The HTTP clients gain request_response() (to read headers), open_stream() and a per-request timeout, all on the existing retry policy: a POST is never resent after a timeout or a 5xx. OpenAI-shaped error bodies map to the existing exceptions; a 400 is a ValidationError and an out-of-credit error (insufficient_quota / insufficient_balance) an InsufficientBalanceError that is not retried. Co-Authored-By: Claude Opus 5.5 --- .env.example | 2 + CHANGELOG.md | 15 + README.md | 55 ++++ docs/api-reference.md | 97 ++++++- examples/chat.py | 49 ++++ src/deapi_sdk/__init__.py | 31 ++ src/deapi_sdk/_client.py | 174 ++++++++++-- src/deapi_sdk/_config.py | 5 + src/deapi_sdk/_streaming.py | 175 ++++++++++++ src/deapi_sdk/resources/__init__.py | 3 + src/deapi_sdk/resources/chat.py | 222 +++++++++++++++ src/deapi_sdk/types/__init__.py | 30 ++ src/deapi_sdk/types/chat.py | 211 ++++++++++++++ tests/test_chat.py | 419 ++++++++++++++++++++++++++++ 14 files changed, 1463 insertions(+), 25 deletions(-) create mode 100644 examples/chat.py create mode 100644 src/deapi_sdk/_streaming.py create mode 100644 src/deapi_sdk/resources/chat.py create mode 100644 src/deapi_sdk/types/chat.py create mode 100644 tests/test_chat.py diff --git a/.env.example b/.env.example index 9af10f7..d12c20b 100644 --- a/.env.example +++ b/.env.example @@ -9,6 +9,8 @@ DEAPI_API_KEY=sk-dp-- # Optional overrides # DEAPI_BASE_URL=https://api.deapi.ai +# OpenAI-compatible API used by client.chat +# DEAPI_OAI_BASE_URL=https://oai.deapi.ai/v1 # DEAPI_API_VERSION=v2 # only "v2" is accepted # Set to 0 to stop the SDK filling unset parameters from the model card defaults # DEAPI_FILL_MODEL_DEFAULTS=1 diff --git a/CHANGELOG.md b/CHANGELOG.md index e09359e..ec664c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,21 @@ Versions follow [Semantic Versioning](https://semver.org/) (pre-1.0: minor versi accounts without access get a 404 or a 422 on `model`, raised as this error. It is also a `NotFoundError` or a `ValidationError`, so existing handlers keep catching it. - Example `examples/transcription_sync.py`. +- `client.chat`: LLM chat through deAPI's OpenAI-compatible API (`https://oai.deapi.ai/v1`, same API + key), on the sync and async clients. + - `chat.completions.create(model=..., messages=[...], **params)` returns a `ChatCompletion` in the + OpenAI shape with deAPI's extras: `usage.cost`, the `X-DeAPI-Cost` header (`header_cost`), + `reasoning_content` and `reasoning_details`. Any other Chat Completions parameter is passed + through; a message returned by the SDK can be appended to `messages` as is. + - `stream=True` returns a `ChatCompletionStream` / `AsyncChatCompletionStream` of + `ChatCompletionChunk`s; with `stream_options={"include_usage": True}` its `usage` and `cost` + come from the final chunk. + - `chat.models()` lists the chat models (`ChatModel`: context length, output limit, supported + parameters, `pricing` with per-1M-token helpers). +- `oai_base_url` client option and `DEAPI_OAI_BASE_URL` environment variable. +- Errors in the OpenAI shape (`{"error": {...}}`) map to the SDK's exceptions; a 400 is a + `ValidationError` and a 429 `insufficient_quota` an `InsufficientBalanceError` (not retried). +- Example `examples/chat.py`. ## [0.6.1] - 2026-11-19 diff --git a/README.md b/README.md index 604236c..c10b9a3 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ Generate images, videos, audio, transcriptions, embeddings, and more — all thr - **Video description** — timestamped events and scenes of a video - **Audio** — text-to-speech (with voice cloning), text-to-music (with a style reference) - **Transcription** — URLs and file uploads, plain-text or structured JSON transcripts; fast transcription of short audio clips (no job to poll) +- **Chat (LLMs)** — OpenAI-compatible chat completions with streaming, reasoning and per-request cost - **Embeddings, OCR, prompt enhancement** - **Account and keys** — balance, usage, payments, API-key management (ADMIN keys) - **Sync + Async** — both `DeapiClient` and `AsyncDeapiClient` @@ -99,6 +100,7 @@ client = DeapiClient( |--------|----------------------|---------| | `api_key` | `DEAPI_API_KEY` | required | | `base_url` | `DEAPI_BASE_URL` | `https://api.deapi.ai` | +| `oai_base_url` (`client.chat`) | `DEAPI_OAI_BASE_URL` | `https://oai.deapi.ai/v1` | | `api_version` | `DEAPI_API_VERSION` | `v2` | | `fill_model_defaults` | `DEAPI_FILL_MODEL_DEFAULTS` (`0` disables) | on | | `client_id` (`client.realtime()`) | `DEAPI_CLIENT_ID` | discovered from the API | @@ -283,6 +285,58 @@ on `model`. Both are raised as `SyncTranscriptionUnavailableError` (also a `NotF `ValidationError`). Clip limits are enforced by the API: a clip that is too long or too large is a `ValidationError` on `source_file`; its message states the limit and points to `create()`. +### Chat (LLMs) + +Chat goes through deAPI's OpenAI-compatible API (`https://oai.deapi.ai/v1`) with the same API key. +Requests and responses have the OpenAI Chat Completions shape, plus deAPI's extras: `usage.cost` +(USD charged), `reasoning_content` and `reasoning_details`. + +```python +completion = client.chat.completions.create( + model="seed-2.0-mini", + messages=[{"role": "user", "content": "Say hello in five words."}], + reasoning_effort="none", # "none" turns reasoning off; low | medium | high | ... per model + max_tokens=32, # any other Chat Completions parameter works the same way +) +print(completion.text) # choices[0].message.content +print(completion.cost) # usage.cost, else the X-DeAPI-Cost header + +# Continue the conversation: append the assistant message as is (keeps reasoning_details) +messages = [{"role": "user", "content": "Hi"}, completion.choices[0].message, {"role": "user", "content": "More"}] + +# Streaming: an iterator of chunks; the final usage chunk carries the cost +with client.chat.completions.create( + model="seed-2.0-mini", messages=messages, max_tokens=64, + stream=True, stream_options={"include_usage": True}, +) as stream: + for chunk in stream: + if chunk.choices and chunk.choices[0].delta.content: + print(chunk.choices[0].delta.content, end="") +print(stream.usage, stream.cost) + +# Chat models with context, output limit and prices +for m in client.chat.models(): + print(m.id, m.context_length, m.max_completion_tokens, m.pricing.prompt_per_1m, m.pricing.completion_per_1m) +``` + +Tools, `tool_choice`, `response_format` (JSON schema) and the other OpenAI parameters are passed +through as keyword arguments. Errors raise the usual SDK exceptions (`AuthenticationError`, +`ValidationError` for a 400, `InsufficientBalanceError` when the account is out of credit, +`RateLimitError`). Like other job-creating calls, a chat request is not resent after a timeout or a +5xx. For long non-streamed answers raise `timeout=` (per call) or use `stream=True`. `max_tokens` +counts reasoning tokens too: with reasoning on, a small cap can end the answer before any text. +See the [OpenAI compatibility docs](https://docs.deapi.ai/openai-compatibility) for the +parameters each model supports. + +The official `openai` package works too, pointed at the same endpoint: + +```python +from openai import OpenAI + +oai = OpenAI(base_url="https://oai.deapi.ai/v1", api_key="sk-dp--") +oai.chat.completions.create(model="seed-2.0-mini", messages=[{"role": "user", "content": "Hi"}]) +``` + ### Embeddings and OCR ```python @@ -624,6 +678,7 @@ The [`examples/`](https://github.com/deapi-ai/deapi-python-sdk/tree/main/example | [`async_batch.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/async_batch.py) | Concurrent async job submission | | [`transcription.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/transcription.py) | Transcription jobs, transcript parsing, price quotes | | [`transcription_sync.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/transcription_sync.py) | Fast transcription of a short audio clip (no job) | +| [`chat.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/chat.py) | Chat completions, streaming with cost, chat model prices | | [`tts_and_audio.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/tts_and_audio.py) | Text-to-speech and music generation | | [`video_generation.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/video_generation.py) | Text-to-video and image-to-video | | [`realtime_status.py`](https://github.com/deapi-ai/deapi-python-sdk/blob/main/examples/realtime_status.py) | Live job progress over WebSocket | diff --git a/docs/api-reference.md b/docs/api-reference.md index 7c04e1d..ed48c74 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -13,6 +13,7 @@ Install: `pip install deapi-sdk` (`pip install deapi` is an unrelated package). - [Resource: audio](#resource-audio) - [Resource: video](#resource-video) - [Resource: transcription](#resource-transcription) +- [Resource: chat](#resource-chat) - [Resource: embeddings](#resource-embeddings) - [Resource: ocr](#resource-ocr) - [Resource: prompts](#resource-prompts) @@ -40,6 +41,8 @@ client = DeapiClient( *, api_key: str | None = None, # Falls back to DEAPI_API_KEY. Format: sk-dp-- base_url: str | None = None, # Falls back to DEAPI_BASE_URL (default "https://api.deapi.ai") + oai_base_url: str | None = None, # client.chat; falls back to DEAPI_OAI_BASE_URL + # (default "https://oai.deapi.ai/v1") timeout: float | None = None, # Request timeout in seconds (default 30.0) max_retries: int | None = None, # Retry attempts (default 3), see "Retry policy" api_version: str | None = None, # Falls back to DEAPI_API_VERSION (only "v2" is accepted, default) @@ -60,8 +63,8 @@ account and key-management endpoints. | `client.websocket_config()` | `WebSocketConfig` | Realtime WebSocket parameters of the account (`GET /websocket`, any key) | | `client.close()` | `None` | Close the HTTP connection | -**Resources:** `images`, `audio`, `video`, `transcription`, `embeddings`, `ocr`, `prompts`, `models`, -`jobs`, `account` and `keys`. +**Resources:** `images`, `audio`, `video`, `transcription`, `chat`, `embeddings`, `ocr`, `prompts`, +`models`, `jobs`, `account` and `keys`. ```python with DeapiClient() as client: @@ -450,6 +453,95 @@ class TranscriptWord(BaseModel): # word, start, end, speaker, score --- +## Resource: chat + +LLM chat through deAPI's OpenAI-compatible API at `oai_base_url` (default +`https://oai.deapi.ai/v1`, env `DEAPI_OAI_BASE_URL`), with the same API key and retry policy. + +### `chat.completions.create()` + +```python +completion = client.chat.completions.create( + *, + model: str, # e.g. "seed-2.0-mini"; see chat.models() + messages: Sequence[dict | BaseModel], # OpenAI-style dicts, or a message returned by the SDK + stream: bool = False, # True -> ChatCompletionStream + timeout: float | None = None, # per request; for a stream, the longest gap between chunks + **params, # any Chat Completions parameter: max_tokens, temperature, + # tools, tool_choice, response_format, stream_options, + # reasoning_effort ("none" turns reasoning off; + # "low", "medium", "high", ... per model), ... +) -> ChatCompletion | ChatCompletionStream +``` + +`None` values in `params` are left out. `max_tokens` counts reasoning tokens too. A message model (e.g. `completion.choices[0].message`) is +sent back with all its fields, including `reasoning_details`. On `AsyncDeapiClient` the call is +awaited and a stream is an `AsyncChatCompletionStream` (`async for`, `async with`). + +```python +class ChatCompletion(BaseModel): # extra fields allowed + id: str | None; created: int | None; model: str | None + choices: list[ChatCompletionChoice] # index, message, finish_reason + usage: ChatCompletionUsage | None + header_cost: float | None # property: the X-DeAPI-Cost header (USD) + cost: float | None # property: usage.cost, else header_cost + text: str | None # property: choices[0].message.content + +class ChatCompletionMessage(BaseModel): + role: str; content: str | None; refusal: str | None + tool_calls: list[ChatCompletionToolCall] | None # id, type, function.name, function.arguments + reasoning_content: str | None # reasoning text + reasoning_details: list[dict] | None # send back in the next turn (some models) + +class ChatCompletionUsage(BaseModel): + prompt_tokens: int | None; completion_tokens: int | None; total_tokens: int | None + cost: float | None # USD charged + prompt_tokens_details: dict | None; completion_tokens_details: dict | None + +class ChatCompletionStream: # iterator of ChatCompletionChunk; context manager; close() + usage: ChatCompletionUsage | None # from the final chunk (stream_options={"include_usage": True}) + cost: float | None # property: usage.cost + response: httpx.Response + +class ChatCompletionChunk(BaseModel): + id; created; model + choices: list[ChatCompletionChunkChoice] # index, delta (role, content, reasoning_content, + # reasoning_details, tool_calls), finish_reason + usage: ChatCompletionUsage | None # only on the final usage chunk (empty choices) +``` + +Errors in the OpenAI shape (`{"error": {"message", "type", "code", "param"}}`) map to the SDK's +exceptions: 401 `AuthenticationError`, 400 `ValidationError` (`errors = {param: [message]}`), +402 `PaymentRequiredError`, 404 `NotFoundError`, `insufficient_quota` / `insufficient_balance` +`InsufficientBalanceError` (not retried), other 429s `RateLimitError`, 5xx `ServerError`. An error event inside a stream +raises `DeapiError`. A chat request is never resent after a timeout or a 5xx. + +### `chat.models()` + +```python +models = client.chat.models() -> list[ChatModel] # GET /models, the entries that have pricing + +class ChatModel(BaseModel): + id: str + context_length: int | None + architecture: ChatModelArchitecture | None # input_modalities, output_modalities + top_provider: ChatModelTopProvider | None # context_length, max_completion_tokens + supported_parameters: list[str] + pricing: ChatModelPricing + max_completion_tokens: int | None # property + input_modalities: list[str] # property + def supports(self, parameter: str) -> bool # e.g. "structured_outputs" + +class ChatModelPricing(BaseModel): # USD per token, as listed + prompt: float | None; completion: float | None + input_cache_read: float | None; input_cache_write: float | None + prompt_per_1m; completion_per_1m; input_cache_read_per_1m; input_cache_write_per_1m # USD per 1M tokens +``` + +The official `openai` package also works against `https://oai.deapi.ai/v1` with a deAPI key. + +--- + ## Resource: embeddings ```python @@ -893,6 +985,7 @@ it with a TTL longer than `tolerance`) so a retried or replayed delivery is proc |----------|---------|-------------| | `DEAPI_API_KEY` | *(required)* | API key, `sk-dp--` | | `DEAPI_BASE_URL` | `https://api.deapi.ai` | API base URL | +| `DEAPI_OAI_BASE_URL` | `https://oai.deapi.ai/v1` | OpenAI-compatible API base URL (`client.chat`) | | `DEAPI_API_VERSION` | `v2` | API version (only `v2` is accepted) | | `DEAPI_FILL_MODEL_DEFAULTS` | on | `0` stops the SDK filling unset parameters from model-card defaults | | `DEAPI_CLIENT_ID` | *(discovered)* | Client ID for `client.realtime()` when `client_id` is not passed | diff --git a/examples/chat.py b/examples/chat.py new file mode 100644 index 0000000..f7efd2a --- /dev/null +++ b/examples/chat.py @@ -0,0 +1,49 @@ +"""Chat with an LLM through deAPI's OpenAI-compatible API. + +Same API key as the rest of the SDK. Every call below is small: a cheap model, reasoning +off and a low max_tokens. + +Usage: + export DEAPI_API_KEY="sk-dp--" + python examples/chat.py +""" + +from deapi_sdk import DeapiClient + +MODEL = "seed-2.0-mini" + +with DeapiClient() as client: + # --- Chat models and their prices (USD per 1M tokens) --- + for m in client.chat.models(): + print( + f"{m.id:<28} in ${m.pricing.prompt_per_1m}/1M out ${m.pricing.completion_per_1m}/1M " + f"context {m.context_length} max output {m.max_completion_tokens}" + ) + + # --- One completion --- + messages = [{"role": "user", "content": "Say hello in five words."}] + completion = client.chat.completions.create( + model=MODEL, + messages=messages, + reasoning_effort="none", # reasoning off (max_tokens also counts reasoning tokens) + max_tokens=32, + ) + print("\n" + (completion.text or "")) + print(f"tokens: {completion.usage.total_tokens if completion.usage else '?'}, cost: ${completion.cost}") + + # Continue the conversation: append the assistant message as is (keeps reasoning_details). + messages += [completion.choices[0].message, {"role": "user", "content": "Now in French."}] + + # --- Streaming, with the cost in the final usage chunk --- + with client.chat.completions.create( + model=MODEL, + messages=messages, + reasoning_effort="none", + max_tokens=32, + stream=True, + stream_options={"include_usage": True}, + ) as stream: + for chunk in stream: + if chunk.choices and chunk.choices[0].delta.content: + print(chunk.choices[0].delta.content, end="", flush=True) + print(f"\ncost: ${stream.cost}") diff --git a/src/deapi_sdk/__init__.py b/src/deapi_sdk/__init__.py index 2311a2f..e99a414 100644 --- a/src/deapi_sdk/__init__.py +++ b/src/deapi_sdk/__init__.py @@ -33,6 +33,7 @@ from deapi_sdk._polling import AsyncJob, AsyncJobs, Job, Jobs from deapi_sdk._realtime import AsyncRealtime, Realtime from deapi_sdk._realtime._discovery import parse_websocket_config +from deapi_sdk._streaming import AsyncChatCompletionStream, ChatCompletionStream from deapi_sdk._types import InferenceType, JobStatus from deapi_sdk._version import __version__ from deapi_sdk.transcript import ( @@ -42,6 +43,14 @@ parse_transcript, transcript_output_format, ) +from deapi_sdk.types.chat import ( + ChatCompletion, + ChatCompletionChunk, + ChatCompletionMessage, + ChatCompletionUsage, + ChatModel, + ChatModelPricing, +) from deapi_sdk.types.common import ( Balance, JobResult, @@ -69,6 +78,7 @@ def _attach_resources_sync(client: DeapiClient) -> None: OCR, AccountResource, Audio, + Chat, Embeddings, Images, KeysResource, @@ -80,6 +90,7 @@ def _attach_resources_sync(client: DeapiClient) -> None: client.images = Images(client._http_client) client.models = Models(client._http_client) client.audio = Audio(client._http_client) + client.chat = Chat(client._http_client) client.transcription = Transcription(client._http_client) client.video = Video(client._http_client) client.embeddings = Embeddings(client._http_client) @@ -94,6 +105,7 @@ def _attach_resources_async(client: AsyncDeapiClient) -> None: from deapi_sdk.resources import ( AsyncAccountResource, AsyncAudio, + AsyncChat, AsyncEmbeddings, AsyncImages, AsyncKeysResource, @@ -106,6 +118,7 @@ def _attach_resources_async(client: AsyncDeapiClient) -> None: client.images = AsyncImages(client._http_client) client.models = AsyncModels(client._http_client) client.audio = AsyncAudio(client._http_client) + client.chat = AsyncChat(client._http_client) client.transcription = AsyncTranscription(client._http_client) client.video = AsyncVideo(client._http_client) client.embeddings = AsyncEmbeddings(client._http_client) @@ -124,6 +137,9 @@ class DeapiClient: model card's ``info.defaults`` (one catalogue request per client, cached), and ``seed`` defaults to -1 (random) where the API requires it. Pass ``False`` to send exactly what you set. + ``client.chat`` (LLM chat) talks to deAPI's OpenAI-compatible API at ``oai_base_url`` + (env ``DEAPI_OAI_BASE_URL``, default ``https://oai.deapi.ai/v1``) with the same API key. + Usage:: client = DeapiClient(api_key="sk-...") @@ -140,6 +156,7 @@ class DeapiClient: images: Any models: Any audio: Any + chat: Any transcription: Any video: Any embeddings: Any @@ -159,6 +176,7 @@ def __init__( api_version: str | None = None, fill_model_defaults: bool | None = None, max_retry_after: float | None = None, + oai_base_url: str | None = None, http_client: httpx.Client | None = None, owns_http_client: bool | None = None, ) -> None: @@ -170,6 +188,7 @@ def __init__( api_version=api_version, fill_model_defaults=fill_model_defaults, max_retry_after=max_retry_after, + oai_base_url=oai_base_url, ) self._http_client = SyncHTTPClient( self._config, http_client, owns_http_client=owns_http_client @@ -251,6 +270,7 @@ class AsyncDeapiClient: images: Any models: Any audio: Any + chat: Any transcription: Any video: Any embeddings: Any @@ -270,6 +290,7 @@ def __init__( api_version: str | None = None, fill_model_defaults: bool | None = None, max_retry_after: float | None = None, + oai_base_url: str | None = None, http_client: httpx.AsyncClient | None = None, owns_http_client: bool | None = None, ) -> None: @@ -281,6 +302,7 @@ def __init__( api_version=api_version, fill_model_defaults=fill_model_defaults, max_retry_after=max_retry_after, + oai_base_url=oai_base_url, ) self._http_client = AsyncHTTPClient( self._config, http_client, owns_http_client=owns_http_client @@ -360,6 +382,15 @@ async def __aexit__(self, *args: Any) -> None: "AsyncRealtime", "Realtime", "JobStatusEvent", + # Chat (LLMs) + "AsyncChatCompletionStream", + "ChatCompletion", + "ChatCompletionChunk", + "ChatCompletionMessage", + "ChatCompletionStream", + "ChatCompletionUsage", + "ChatModel", + "ChatModelPricing", # Types "Balance", "InferenceType", diff --git a/src/deapi_sdk/_client.py b/src/deapi_sdk/_client.py index cbd79f7..607a848 100644 --- a/src/deapi_sdk/_client.py +++ b/src/deapi_sdk/_client.py @@ -58,6 +58,10 @@ def _resolve_endpoint(self, operation: str) -> str: raise DeapiError(f"Unknown API operation '{operation}'") return f"{self._config.base_url}{self._config.api_prefix}/{path}" + def _resolve_oai(self, path: str) -> str: + """Full URL of a path on the OpenAI-compatible API (``oai_base_url``), e.g. ``chat/completions``.""" + return f"{self._config.oai_base_url.rstrip('/')}/{path.lstrip('/')}" + def _default_headers(self) -> dict[str, str]: return { "Authorization": f"Bearer {self._config.api_key}", @@ -106,16 +110,32 @@ def _raise_for_status(self, response: httpx.Response) -> None: parsed = None body: dict[str, Any] = parsed if isinstance(parsed, dict) else {} - message: Any = body.get("message") - if not isinstance(message, str) or not message: + # The OpenAI-compatible API wraps errors as {"error": {"message", "type", "code", "param"}}. + envelope = body.get("error") + oai_error: dict[str, Any] | None = envelope if isinstance(envelope, dict) else None + source = oai_error if oai_error is not None else body + + message: Any = source.get("message") + if (not isinstance(message, str) or not message) and oai_error is None: message = body.get("error") if not isinstance(message, str) or not message: message = response.text or f"HTTP {status}" - raw_code = body.get("code") + raw_code = source.get("code") code = raw_code if isinstance(raw_code, str) and raw_code else None kwargs: dict[str, Any] = {"status_code": status, "body": body, "code": code} + if oai_error is not None: + # "Out of credit" (429 insufficient_quota, or an insufficient_balance code): not a rate + # limit, so never retried. + if oai_error.get("type") == "insufficient_quota" or code in ("insufficient_quota", "insufficient_balance"): + kwargs["code"] = code or "insufficient_quota" + raise InsufficientBalanceError(message, **kwargs) + if status == 400: + param = oai_error.get("param") + errors = {param: [message]} if isinstance(param, str) and param else None + raise ValidationError(message, **kwargs, errors=errors) + if status == 401: raise AuthenticationError(message, **kwargs) @@ -263,21 +283,75 @@ def request( files: RequestFiles | None = None, params: dict[str, Any] | None = None, ) -> Any: + response = self._send(method, url, json=json, data=data, files=files, params=params) + return self._parse_success(response) + + def request_response( + self, + method: str, + url: str, + *, + json: dict[str, Any] | None = None, + params: dict[str, Any] | None = None, + timeout: float | None = None, + ) -> httpx.Response: + """Like ``request()``, but return the read ``httpx.Response`` (to look at headers).""" + return self._send(method, url, json=json, params=params, timeout=timeout) + + def open_stream( + self, + method: str, + url: str, + *, + json: dict[str, Any] | None = None, + timeout: float | None = None, + ) -> httpx.Response: + """Send a request and return the response with its body still unread; the caller closes it. + + Error statuses are raised (with the same retry policy as ``request()``) before returning. + """ + return self._send(method, url, json=json, timeout=timeout, stream=True) + + def _send( + self, + method: str, + url: str, + *, + json: dict[str, Any] | None = None, + data: dict[str, Any] | None = None, + files: RequestFiles | None = None, + params: dict[str, Any] | None = None, + timeout: float | None = None, + stream: bool = False, + ) -> httpx.Response: last_exc: Exception | None = None + request_timeout: Any = httpx.USE_CLIENT_DEFAULT if timeout is None else timeout for attempt in range(self._config.max_retries + 1): try: - response = self._http.request( - method, - url, - json=json, - data=data, - files=files, - params=params, - headers=self._headers, - ) + if stream: + request = self._http.build_request( + method, url, json=json, params=params, headers=self._headers, timeout=request_timeout, + ) + response = self._http.send(request, stream=True) + if not response.is_success: + try: + response.read() + finally: + response.close() + else: + response = self._http.request( + method, + url, + json=json, + data=data, + files=files, + params=params, + headers=self._headers, + timeout=request_timeout, + ) self._raise_for_status(response) - return self._parse_success(response) + return response except (RateLimitError, ServerError, NetworkError) as exc: last_exc = exc wait = self._should_retry(exc, attempt, method) @@ -359,21 +433,75 @@ async def request( files: RequestFiles | None = None, params: dict[str, Any] | None = None, ) -> Any: + response = await self._send(method, url, json=json, data=data, files=files, params=params) + return self._parse_success(response) + + async def request_response( + self, + method: str, + url: str, + *, + json: dict[str, Any] | None = None, + params: dict[str, Any] | None = None, + timeout: float | None = None, + ) -> httpx.Response: + """Like ``request()``, but return the read ``httpx.Response`` (to look at headers).""" + return await self._send(method, url, json=json, params=params, timeout=timeout) + + async def open_stream( + self, + method: str, + url: str, + *, + json: dict[str, Any] | None = None, + timeout: float | None = None, + ) -> httpx.Response: + """Send a request and return the response with its body still unread; the caller closes it. + + Error statuses are raised (with the same retry policy as ``request()``) before returning. + """ + return await self._send(method, url, json=json, timeout=timeout, stream=True) + + async def _send( + self, + method: str, + url: str, + *, + json: dict[str, Any] | None = None, + data: dict[str, Any] | None = None, + files: RequestFiles | None = None, + params: dict[str, Any] | None = None, + timeout: float | None = None, + stream: bool = False, + ) -> httpx.Response: last_exc: Exception | None = None + request_timeout: Any = httpx.USE_CLIENT_DEFAULT if timeout is None else timeout for attempt in range(self._config.max_retries + 1): try: - response = await self._http.request( - method, - url, - json=json, - data=data, - files=files, - params=params, - headers=self._headers, - ) + if stream: + request = self._http.build_request( + method, url, json=json, params=params, headers=self._headers, timeout=request_timeout, + ) + response = await self._http.send(request, stream=True) + if not response.is_success: + try: + await response.aread() + finally: + await response.aclose() + else: + response = await self._http.request( + method, + url, + json=json, + data=data, + files=files, + params=params, + headers=self._headers, + timeout=request_timeout, + ) self._raise_for_status(response) - return self._parse_success(response) + return response except (RateLimitError, ServerError, NetworkError) as exc: last_exc = exc wait = self._should_retry(exc, attempt, method) diff --git a/src/deapi_sdk/_config.py b/src/deapi_sdk/_config.py index 2d86040..1963166 100644 --- a/src/deapi_sdk/_config.py +++ b/src/deapi_sdk/_config.py @@ -8,6 +8,8 @@ from deapi_sdk._version import __version__ _DEFAULT_BASE_URL = "https://api.deapi.ai" +# OpenAI-compatible API (chat completions and the OpenAI-shaped /models list). +_DEFAULT_OAI_BASE_URL = "https://oai.deapi.ai/v1" _DEFAULT_TIMEOUT = 30.0 _DEFAULT_MAX_RETRIES = 3 # Upper bound on how long we actually sleep for a 429 `Retry-After`, regardless of @@ -26,6 +28,7 @@ class ClientConfig: api_version: str = API_VERSION fill_model_defaults: bool = True max_retry_after: float = _DEFAULT_MAX_RETRY_AFTER + oai_base_url: str = _DEFAULT_OAI_BASE_URL _user_agent: str = field(init=False, default=f"deapi-sdk/{__version__}") @classmethod @@ -39,6 +42,7 @@ def from_env( api_version: str | None = None, fill_model_defaults: bool | None = None, max_retry_after: float | None = None, + oai_base_url: str | None = None, ) -> ClientConfig: resolved_key = (api_key or os.environ.get("DEAPI_API_KEY", "")).strip() if not resolved_key: @@ -59,6 +63,7 @@ def from_env( max_retry_after=( max_retry_after if max_retry_after is not None else _DEFAULT_MAX_RETRY_AFTER ), + oai_base_url=oai_base_url or os.environ.get("DEAPI_OAI_BASE_URL", _DEFAULT_OAI_BASE_URL), ) @property diff --git a/src/deapi_sdk/_streaming.py b/src/deapi_sdk/_streaming.py new file mode 100644 index 0000000..4737b86 --- /dev/null +++ b/src/deapi_sdk/_streaming.py @@ -0,0 +1,175 @@ +"""Server-sent events (SSE) for streamed chat completions.""" + +from __future__ import annotations + +import json +from collections.abc import AsyncIterator, Iterator +from types import TracebackType +from typing import Any + +import httpx + +from deapi_sdk._exceptions import DeapiError, NetworkError +from deapi_sdk.types.chat import ChatCompletionChunk, ChatCompletionUsage + +_DONE = "[DONE]" + + +class _SSEDecoder: + """Turn SSE lines into the ``data`` payload of each event (multi-line data joined with ``\\n``).""" + + def __init__(self) -> None: + self._data: list[str] = [] + + def feed(self, line: str) -> str | None: + """Feed one line (without its newline); return an event's data when the event ends.""" + line = line.rstrip("\r") + if not line: + return self.flush() + if line.startswith(":"): # comment / keep-alive + return None + field, _, value = line.partition(":") + if value.startswith(" "): + value = value[1:] + if field == "data": + self._data.append(value) + return None + + def flush(self) -> str | None: + if not self._data: + return None + data = "\n".join(self._data) + self._data = [] + return data + + +def _parse_event(data: str) -> ChatCompletionChunk: + try: + payload: Any = json.loads(data) + except ValueError as exc: + raise DeapiError(f"Invalid JSON in stream event: {data[:200]!r}") from exc + if isinstance(payload, dict) and isinstance(payload.get("error"), dict): + error = payload["error"] + message = error.get("message") if isinstance(error.get("message"), str) else "Error in stream" + code = error.get("code") if isinstance(error.get("code"), str) else error.get("type") + raise DeapiError(message, body=payload, code=code if isinstance(code, str) else None) + return ChatCompletionChunk.model_validate(payload) + + +class ChatCompletionStream: + """Iterator of ``ChatCompletionChunk`` from ``chat.completions.create(stream=True)``. + + Use it in a ``with`` block (or call ``close()``) so the connection is released when you stop + early; it is closed automatically once fully consumed. ``usage`` holds the final usage chunk + (``stream_options={"include_usage": True}``), and ``cost`` its USD charge. + """ + + def __init__(self, response: httpx.Response) -> None: + self.response = response + self.usage: ChatCompletionUsage | None = None + self._iterator = self._iter_chunks() + + @property + def cost(self) -> float | None: + return self.usage.cost if self.usage is not None else None + + def _iter_chunks(self) -> Iterator[ChatCompletionChunk]: + decoder = _SSEDecoder() + try: + for line in self.response.iter_lines(): + data = decoder.feed(line) + if data is None: + continue + if data == _DONE: + return + chunk = _parse_event(data) + if chunk.usage is not None: + self.usage = chunk.usage + yield chunk + data = decoder.flush() + if data is not None and data != _DONE: + chunk = _parse_event(data) + if chunk.usage is not None: + self.usage = chunk.usage + yield chunk + except httpx.TransportError as exc: + raise NetworkError(str(exc)) from exc + finally: + self.response.close() + + def __iter__(self) -> Iterator[ChatCompletionChunk]: + return self._iterator + + def __next__(self) -> ChatCompletionChunk: + return next(self._iterator) + + def close(self) -> None: + self.response.close() + + def __enter__(self) -> ChatCompletionStream: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + self.close() + + +class AsyncChatCompletionStream: + """Async iterator of ``ChatCompletionChunk``. See ``ChatCompletionStream``.""" + + def __init__(self, response: httpx.Response) -> None: + self.response = response + self.usage: ChatCompletionUsage | None = None + self._iterator = self._iter_chunks() + + @property + def cost(self) -> float | None: + return self.usage.cost if self.usage is not None else None + + async def _iter_chunks(self) -> AsyncIterator[ChatCompletionChunk]: + decoder = _SSEDecoder() + try: + async for line in self.response.aiter_lines(): + data = decoder.feed(line) + if data is None: + continue + if data == _DONE: + return + chunk = _parse_event(data) + if chunk.usage is not None: + self.usage = chunk.usage + yield chunk + data = decoder.flush() + if data is not None and data != _DONE: + chunk = _parse_event(data) + if chunk.usage is not None: + self.usage = chunk.usage + yield chunk + except httpx.TransportError as exc: + raise NetworkError(str(exc)) from exc + finally: + await self.response.aclose() + + def __aiter__(self) -> AsyncIterator[ChatCompletionChunk]: + return self._iterator + + async def __anext__(self) -> ChatCompletionChunk: + return await self._iterator.__anext__() + + async def close(self) -> None: + await self.response.aclose() + + async def __aenter__(self) -> AsyncChatCompletionStream: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + await self.close() diff --git a/src/deapi_sdk/resources/__init__.py b/src/deapi_sdk/resources/__init__.py index 55a4c94..2db802f 100644 --- a/src/deapi_sdk/resources/__init__.py +++ b/src/deapi_sdk/resources/__init__.py @@ -2,6 +2,7 @@ from deapi_sdk.resources.account import AccountResource, AsyncAccountResource from deapi_sdk.resources.audio import AsyncAudio, Audio +from deapi_sdk.resources.chat import AsyncChat, Chat from deapi_sdk.resources.embeddings import AsyncEmbeddings, Embeddings from deapi_sdk.resources.images import AsyncImages, Images from deapi_sdk.resources.keys import AsyncKeysResource, KeysResource @@ -16,6 +17,7 @@ "AccountResource", "AsyncAccountResource", "AsyncAudio", + "AsyncChat", "AsyncEmbeddings", "AsyncImages", "AsyncKeysResource", @@ -25,6 +27,7 @@ "AsyncTranscription", "AsyncVideo", "Audio", + "Chat", "Embeddings", "Images", "KeysResource", diff --git a/src/deapi_sdk/resources/chat.py b/src/deapi_sdk/resources/chat.py new file mode 100644 index 0000000..adb6905 --- /dev/null +++ b/src/deapi_sdk/resources/chat.py @@ -0,0 +1,222 @@ +"""Chat (LLMs) through deAPI's OpenAI-compatible API (``oai_base_url``, default ``https://oai.deapi.ai/v1``).""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from typing import Any, Literal, TypeAlias, overload + +import httpx +from pydantic import BaseModel + +from deapi_sdk._client import AsyncHTTPClient, BaseClient, SyncHTTPClient +from deapi_sdk._streaming import AsyncChatCompletionStream, ChatCompletionStream +from deapi_sdk.types.chat import ChatCompletion, ChatModel + +# A message: an OpenAI-style dict ({"role": "user", "content": "..."}) or a message model returned +# by the SDK (e.g. ``completion.choices[0].message``), which is sent back with all its fields. +ChatMessageInput: TypeAlias = Mapping[str, Any] | BaseModel + +COST_HEADER = "X-DeAPI-Cost" + + +def _message(message: ChatMessageInput) -> dict[str, Any]: + if isinstance(message, BaseModel): + return message.model_dump(exclude_none=True) + if isinstance(message, Mapping): + return dict(message) + raise TypeError(f"messages: expected a dict or a message model, got {type(message).__name__}") + + +def _build_body( + model: str, messages: Sequence[ChatMessageInput], stream: bool, params: dict[str, Any], +) -> dict[str, Any]: + if not messages: + raise ValueError("'messages' must not be empty.") + body: dict[str, Any] = {"model": model, "messages": [_message(m) for m in messages]} + body.update({k: v for k, v in params.items() if v is not None}) + if stream: + body["stream"] = True + return body + + +def _header_float(response: httpx.Response, name: str) -> float | None: + value = response.headers.get(name) + if value is None: + return None + try: + return float(value) + except ValueError: + return None + + +def _completion(response: httpx.Response) -> ChatCompletion: + completion = ChatCompletion.model_validate(BaseClient._parse_success(response)) + completion._header_cost = _header_float(response, COST_HEADER) + return completion + + +def _chat_models(resp: Any) -> list[ChatModel]: + """Chat models are the ``/models`` entries that have ``pricing`` (media models have none).""" + entries = resp.get("data", []) if isinstance(resp, dict) else resp + if not isinstance(entries, list): + return [] + return [ + ChatModel.model_validate(entry) + for entry in entries + if isinstance(entry, dict) and isinstance(entry.get("pricing"), dict) + ] + + +class ChatCompletions: + """``client.chat.completions``: OpenAI Chat Completions on deAPI.""" + + def __init__(self, client: SyncHTTPClient) -> None: + self._client = client + + @overload + def create( + self, + *, + model: str, + messages: Sequence[ChatMessageInput], + stream: Literal[False] = False, + timeout: float | None = None, + **params: Any, + ) -> ChatCompletion: ... + + @overload + def create( + self, + *, + model: str, + messages: Sequence[ChatMessageInput], + stream: Literal[True], + timeout: float | None = None, + **params: Any, + ) -> ChatCompletionStream: ... + + @overload + def create( + self, + *, + model: str, + messages: Sequence[ChatMessageInput], + stream: bool, + timeout: float | None = None, + **params: Any, + ) -> ChatCompletion | ChatCompletionStream: ... + + def create( + self, + *, + model: str, + messages: Sequence[ChatMessageInput], + stream: bool = False, + timeout: float | None = None, + **params: Any, + ) -> ChatCompletion | ChatCompletionStream: + """Create a chat completion (``POST /chat/completions`` on the OpenAI-compatible API). + + Args: + model: Chat model id, e.g. ``"seed-2.0-mini"`` (see ``client.chat.models()``). + messages: OpenAI-style message dicts. A message returned by the SDK (e.g. + ``completion.choices[0].message``) can be appended as is; its ``reasoning_details`` + go back with it. + stream: Return a ``ChatCompletionStream`` of chunks instead of a ``ChatCompletion``. + Pass ``stream_options={"include_usage": True}`` to get a final chunk with + ``usage`` (and ``cost``). + timeout: Per-request timeout in seconds (default: the client's). For a stream it is + the longest wait between two chunks. + **params: Any other Chat Completions parameter, sent as is: ``max_tokens``, + ``temperature``, ``top_p``, ``stop``, ``tools``, ``tool_choice``, + ``parallel_tool_calls``, ``response_format``, ``reasoning_effort`` (``"none"`` turns + reasoning off; supported values differ per model), ``stream_options``, ... + ``None`` values are left out. ``max_tokens`` counts reasoning tokens too. + + A failed request is not resent after a timeout or a 5xx (it may already be billed). + """ + body = _build_body(model, messages, stream, params) + url = self._client._resolve_oai("chat/completions") + if stream: + return ChatCompletionStream(self._client.open_stream("POST", url, json=body, timeout=timeout)) + return _completion(self._client.request_response("POST", url, json=body, timeout=timeout)) + + +class AsyncChatCompletions: + """``client.chat.completions`` on ``AsyncDeapiClient``.""" + + def __init__(self, client: AsyncHTTPClient) -> None: + self._client = client + + @overload + async def create( + self, + *, + model: str, + messages: Sequence[ChatMessageInput], + stream: Literal[False] = False, + timeout: float | None = None, + **params: Any, + ) -> ChatCompletion: ... + + @overload + async def create( + self, + *, + model: str, + messages: Sequence[ChatMessageInput], + stream: Literal[True], + timeout: float | None = None, + **params: Any, + ) -> AsyncChatCompletionStream: ... + + @overload + async def create( + self, + *, + model: str, + messages: Sequence[ChatMessageInput], + stream: bool, + timeout: float | None = None, + **params: Any, + ) -> ChatCompletion | AsyncChatCompletionStream: ... + + async def create( + self, + *, + model: str, + messages: Sequence[ChatMessageInput], + stream: bool = False, + timeout: float | None = None, + **params: Any, + ) -> ChatCompletion | AsyncChatCompletionStream: + """Create a chat completion. See ``ChatCompletions.create``; streams are async iterators.""" + body = _build_body(model, messages, stream, params) + url = self._client._resolve_oai("chat/completions") + if stream: + return AsyncChatCompletionStream(await self._client.open_stream("POST", url, json=body, timeout=timeout)) + return _completion(await self._client.request_response("POST", url, json=body, timeout=timeout)) + + +class Chat: + """``client.chat``: LLM chat through deAPI's OpenAI-compatible API (same API key).""" + + def __init__(self, client: SyncHTTPClient) -> None: + self._client = client + self.completions = ChatCompletions(client) + + def models(self) -> list[ChatModel]: + """Chat models with their limits and prices (``GET /models``, entries that have ``pricing``).""" + return _chat_models(self._client.get(self._client._resolve_oai("models"))) + + +class AsyncChat: + """``client.chat`` on ``AsyncDeapiClient``.""" + + def __init__(self, client: AsyncHTTPClient) -> None: + self._client = client + self.completions = AsyncChatCompletions(client) + + async def models(self) -> list[ChatModel]: + """Chat models with their limits and prices. See ``Chat.models``.""" + return _chat_models(await self._client.get(self._client._resolve_oai("models"))) diff --git a/src/deapi_sdk/types/__init__.py b/src/deapi_sdk/types/__init__.py index c52c264..617f326 100644 --- a/src/deapi_sdk/types/__init__.py +++ b/src/deapi_sdk/types/__init__.py @@ -2,6 +2,22 @@ from deapi_sdk.types.account import Account, Payment, PaymentsPage, UsageReport from deapi_sdk.types.audio import Text2AudioParams, Text2MusicParams +from deapi_sdk.types.chat import ( + ChatCompletion, + ChatCompletionChoice, + ChatCompletionChunk, + ChatCompletionChunkChoice, + ChatCompletionMessage, + ChatCompletionToolCall, + ChatCompletionToolCallFunction, + ChatCompletionUsage, + ChatModel, + ChatModelArchitecture, + ChatModelPricing, + ChatModelTopProvider, + ChoiceDelta, + ChoiceDeltaToolCall, +) from deapi_sdk.types.common import ( Balance, JobResult, @@ -37,6 +53,20 @@ "ApiKeysPage", "Aud2VideoParams", "Balance", + "ChatCompletion", + "ChatCompletionChoice", + "ChatCompletionChunk", + "ChatCompletionChunkChoice", + "ChatCompletionMessage", + "ChatCompletionToolCall", + "ChatCompletionToolCallFunction", + "ChatCompletionUsage", + "ChatModel", + "ChatModelArchitecture", + "ChatModelPricing", + "ChatModelTopProvider", + "ChoiceDelta", + "ChoiceDeltaToolCall", "EnhancePromptResult", "Img2ImgParams", "Img2TextParams", diff --git a/src/deapi_sdk/types/chat.py b/src/deapi_sdk/types/chat.py new file mode 100644 index 0000000..ec7bf3c --- /dev/null +++ b/src/deapi_sdk/types/chat.py @@ -0,0 +1,211 @@ +"""Chat (LLM) types: OpenAI Chat Completions shapes plus deAPI's extras. + +Every model allows extra fields, so new response fields are kept (``model_extra``) instead of +being dropped. deAPI extras: ``usage.cost`` (USD charged), ``reasoning_content`` and +``reasoning_details`` on messages and stream deltas, and the ``X-DeAPI-Cost`` response header +(``ChatCompletion.header_cost``). +""" + +from __future__ import annotations + +from typing import Any + +from pydantic import BaseModel, ConfigDict, Field, PrivateAttr + +_ONE_MILLION = 1_000_000 + + +class _Model(BaseModel): + model_config = ConfigDict(extra="allow") + + +# --- Responses ------------------------------------------------------------------------------- + + +class ChatCompletionToolCallFunction(_Model): + name: str | None = None + arguments: str | None = None # JSON text, as the model wrote it + + +class ChatCompletionToolCall(_Model): + id: str | None = None + type: str | None = "function" + function: ChatCompletionToolCallFunction | None = None + + +class ChatCompletionMessage(_Model): + """The assistant's message. Append it to ``messages`` as is to continue the conversation. + + ``reasoning_content`` is the model's reasoning text (when reasoning is on). + ``reasoning_details`` (some models) should be sent back in the next turn, which happens + when you append this message object to ``messages``. + """ + + role: str = "assistant" + content: str | None = None + refusal: str | None = None + tool_calls: list[ChatCompletionToolCall] | None = None + reasoning_content: str | None = None + reasoning_details: list[dict[str, Any]] | None = None + + +class ChatCompletionChoice(_Model): + index: int = 0 + message: ChatCompletionMessage + finish_reason: str | None = None + logprobs: Any = None + + +class ChatCompletionUsage(_Model): + """Token counts and ``cost``: the exact amount charged, in USD.""" + + prompt_tokens: int | None = None + completion_tokens: int | None = None + total_tokens: int | None = None + cost: float | None = None + prompt_tokens_details: dict[str, Any] | None = None # e.g. cached_tokens + completion_tokens_details: dict[str, Any] | None = None # e.g. reasoning_tokens + + +class ChatCompletion(_Model): + """A chat completion (``stream=False``).""" + + id: str | None = None + object: str | None = "chat.completion" + created: int | None = None + model: str | None = None + choices: list[ChatCompletionChoice] = [] + usage: ChatCompletionUsage | None = None + system_fingerprint: str | None = None + + _header_cost: float | None = PrivateAttr(default=None) + + @property + def header_cost(self) -> float | None: + """The ``X-DeAPI-Cost`` response header (USD), or None when absent.""" + return self._header_cost + + @property + def cost(self) -> float | None: + """USD charged: ``usage.cost``, else the ``X-DeAPI-Cost`` header.""" + if self.usage is not None and self.usage.cost is not None: + return self.usage.cost + return self._header_cost + + @property + def text(self) -> str | None: + """``choices[0].message.content``, or None when there is no choice.""" + return self.choices[0].message.content if self.choices else None + + +class ChoiceDeltaToolCall(_Model): + index: int = 0 + id: str | None = None + type: str | None = None + function: ChatCompletionToolCallFunction | None = None + + +class ChoiceDelta(_Model): + role: str | None = None + content: str | None = None + refusal: str | None = None + tool_calls: list[ChoiceDeltaToolCall] | None = None + reasoning_content: str | None = None + reasoning_details: list[dict[str, Any]] | None = None + + +class ChatCompletionChunkChoice(_Model): + index: int = 0 + delta: ChoiceDelta = Field(default_factory=ChoiceDelta) + finish_reason: str | None = None + logprobs: Any = None + + +class ChatCompletionChunk(_Model): + """One streamed chunk (``stream=True``). + + With ``stream_options={"include_usage": True}`` the last chunk has empty ``choices`` and + carries ``usage`` (including ``cost``). + """ + + id: str | None = None + object: str | None = "chat.completion.chunk" + created: int | None = None + model: str | None = None + choices: list[ChatCompletionChunkChoice] = [] + usage: ChatCompletionUsage | None = None + system_fingerprint: str | None = None + + +# --- Models (GET /models on the OpenAI-compatible API) --------------------------------------- + + +class ChatModelPricing(_Model): + """Prices in USD **per token**, as the API lists them. ``*_per_1m`` give USD per 1M tokens.""" + + prompt: float | None = None + completion: float | None = None + input_cache_read: float | None = None + input_cache_write: float | None = None + + @staticmethod + def _per_1m(value: float | None) -> float | None: + return None if value is None else round(value * _ONE_MILLION, 9) + + @property + def prompt_per_1m(self) -> float | None: + """USD per 1M input tokens.""" + return self._per_1m(self.prompt) + + @property + def completion_per_1m(self) -> float | None: + """USD per 1M output tokens.""" + return self._per_1m(self.completion) + + @property + def input_cache_read_per_1m(self) -> float | None: + """USD per 1M cached input tokens read.""" + return self._per_1m(self.input_cache_read) + + @property + def input_cache_write_per_1m(self) -> float | None: + """USD per 1M input tokens written to the cache (only some models list it).""" + return self._per_1m(self.input_cache_write) + + +class ChatModelArchitecture(_Model): + input_modalities: list[str] = [] + output_modalities: list[str] = [] + + +class ChatModelTopProvider(_Model): + context_length: int | None = None + max_completion_tokens: int | None = None + + +class ChatModel(_Model): + """A chat model from ``client.chat.models()``.""" + + id: str + object: str | None = "model" + created: int | None = None + owned_by: str | None = None + context_length: int | None = None + architecture: ChatModelArchitecture | None = None + top_provider: ChatModelTopProvider | None = None + supported_parameters: list[str] = [] + pricing: ChatModelPricing + + @property + def max_completion_tokens(self) -> int | None: + """Largest ``max_tokens`` the model accepts (``top_provider.max_completion_tokens``).""" + return self.top_provider.max_completion_tokens if self.top_provider else None + + @property + def input_modalities(self) -> list[str]: + """E.g. ``["text", "image"]``.""" + return self.architecture.input_modalities if self.architecture else [] + + def supports(self, parameter: str) -> bool: + """Whether ``parameter`` (e.g. ``"tools"``, ``"structured_outputs"``) is in ``supported_parameters``.""" + return parameter in self.supported_parameters diff --git a/tests/test_chat.py b/tests/test_chat.py new file mode 100644 index 0000000..df2476a --- /dev/null +++ b/tests/test_chat.py @@ -0,0 +1,419 @@ +from __future__ import annotations + +import json +from typing import Any + +import httpx +import pytest +import respx + +from deapi_sdk import ( + AsyncChatCompletionStream, + AsyncDeapiClient, + AuthenticationError, + ChatCompletion, + ChatCompletionStream, + DeapiClient, + DeapiError, + InsufficientBalanceError, + PaymentRequiredError, + RateLimitError, + ServerError, + ValidationError, +) +from tests.conftest import TEST_API_KEY, TEST_BASE_URL + +OAI = "https://oai.test.deapi.ai/v1" +CHAT_URL = f"{OAI}/chat/completions" +MODELS_URL = f"{OAI}/models" + +COMPLETION = { + "id": "chatcmpl-1", + "object": "chat.completion", + "created": 1792800000, + "model": "seed-2.0-mini", + "choices": [{ + "index": 0, + "finish_reason": "stop", + "message": { + "role": "assistant", + "content": "Hello!", + "reasoning_content": "The user greets me.", + "reasoning_details": [{"type": "reasoning.text", "text": "The user greets me."}], + }, + }], + "usage": { + "prompt_tokens": 12, "completion_tokens": 3, "total_tokens": 15, "cost": 0.0000123, + "completion_tokens_details": {"reasoning_tokens": 5}, + }, + "provider_extra": {"kept": True}, +} + +# Made-up prices (USD per token), in the shape GET /models returns them. +MODELS = {"object": "list", "data": [ + { + "id": "seed-2.0-mini", "object": "model", "created": 1792800000, "owned_by": "deapi", + "context_length": 262144, + "architecture": {"input_modalities": ["text", "image"], "output_modalities": ["text"]}, + "top_provider": {"context_length": 262144, "max_completion_tokens": 131072}, + "supported_parameters": ["max_tokens", "tools", "response_format", "structured_outputs", "reasoning_effort"], + "pricing": {"prompt": "0.0000001", "completion": "0.0000004", "input_cache_read": "0.00000002"}, + }, + { + "id": "glm-5.3", "object": "model", "created": 1792800000, "owned_by": "deapi", + "context_length": 1000000, + "architecture": {"input_modalities": ["text"], "output_modalities": ["text"]}, + "top_provider": {"context_length": 1000000, "max_completion_tokens": 131072}, + "supported_parameters": ["max_tokens", "tools", "reasoning_effort"], + "pricing": {"prompt": "0.000001", "completion": "0.000003", "input_cache_read": "0.0000002", + "input_cache_write": "0.00000125"}, + }, + {"id": "Flux1schnell", "object": "model", "created": 1792540800, "owned_by": "deapi"}, +]} + + +def _sse(*events: Any, done: bool = True) -> bytes: + parts = [f"data: {json.dumps(e)}\n\n" if not isinstance(e, str) else e for e in events] + if done: + parts.append("data: [DONE]\n\n") + return "".join(parts).encode() + + +def _chunk(content: str | None = None, *, reasoning: str | None = None, finish: str | None = None, + usage: dict[str, Any] | None = None, choices: bool = True) -> dict[str, Any]: + delta: dict[str, Any] = {} + if content is not None: + delta["content"] = content + if reasoning is not None: + delta["reasoning_content"] = reasoning + chunk: dict[str, Any] = { + "id": "chatcmpl-1", "object": "chat.completion.chunk", "created": 1, "model": "seed-2.0-mini", + "choices": [{"index": 0, "delta": delta, "finish_reason": finish}] if choices else [], + } + if usage is not None: + chunk["usage"] = usage + return chunk + + +STREAM_BODY = _sse( + _chunk(reasoning="Thinking"), + ": keep-alive\n\n", + _chunk("Hel"), + _chunk("lo!", finish="stop"), + _chunk(choices=False, usage={"prompt_tokens": 12, "completion_tokens": 3, "total_tokens": 15, "cost": 0.0000123}), +) + + +@pytest.fixture +def chat_client() -> Any: + with DeapiClient(api_key=TEST_API_KEY, base_url=TEST_BASE_URL, oai_base_url=OAI) as c: + yield c + + +@pytest.fixture +async def async_chat_client() -> Any: + async with AsyncDeapiClient(api_key=TEST_API_KEY, base_url=TEST_BASE_URL, oai_base_url=OAI) as c: + yield c + + +class TestConfig: + def test_default_oai_base_url(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("DEAPI_OAI_BASE_URL", raising=False) + with DeapiClient(api_key="k") as client: + assert client._config.oai_base_url == "https://oai.deapi.ai/v1" + assert client._http_client._resolve_oai("chat/completions") == "https://oai.deapi.ai/v1/chat/completions" + + def test_oai_base_url_from_env(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("DEAPI_OAI_BASE_URL", "https://oai.example.test/v1/") + with DeapiClient(api_key="k") as client: + assert client._http_client._resolve_oai("models") == "https://oai.example.test/v1/models" + + +class TestCompletions: + @respx.mock + def test_create(self, chat_client: DeapiClient) -> None: + route = respx.post(CHAT_URL).mock(return_value=httpx.Response( + 200, json=COMPLETION, headers={"X-DeAPI-Cost": "0.0000123"}, + )) + + completion = chat_client.chat.completions.create( + model="seed-2.0-mini", + messages=[{"role": "user", "content": "Hi"}], + max_tokens=32, + reasoning_effort="none", + temperature=None, # None values are left out + ) + + request = route.calls.last.request + assert request.headers["authorization"] == f"Bearer {TEST_API_KEY}" + assert json.loads(request.content) == { + "model": "seed-2.0-mini", + "messages": [{"role": "user", "content": "Hi"}], + "max_tokens": 32, + "reasoning_effort": "none", + } + assert isinstance(completion, ChatCompletion) + assert completion.text == "Hello!" + message = completion.choices[0].message + assert message.reasoning_content == "The user greets me." + assert message.reasoning_details == [{"type": "reasoning.text", "text": "The user greets me."}] + assert completion.choices[0].finish_reason == "stop" + assert completion.usage is not None + assert completion.usage.total_tokens == 15 + assert completion.usage.completion_tokens_details == {"reasoning_tokens": 5} + assert completion.usage.cost == 0.0000123 + assert completion.header_cost == 0.0000123 + assert completion.cost == 0.0000123 + assert completion.model_extra == {"provider_extra": {"kept": True}} + + @respx.mock + def test_cost_falls_back_to_header(self, chat_client: DeapiClient) -> None: + body = {**COMPLETION, "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}} + respx.post(CHAT_URL).mock(return_value=httpx.Response(200, json=body, headers={"X-DeAPI-Cost": "0.5"})) + completion = chat_client.chat.completions.create(model="m", messages=[{"role": "user", "content": "x"}]) + assert completion.cost == 0.5 + + @respx.mock + def test_assistant_message_can_be_sent_back(self, chat_client: DeapiClient) -> None: + route = respx.post(CHAT_URL).mock(return_value=httpx.Response(200, json=COMPLETION)) + messages: list[Any] = [{"role": "user", "content": "Hi"}] + first = chat_client.chat.completions.create(model="seed-2.0-mini", messages=messages) + messages += [first.choices[0].message, {"role": "user", "content": "And?"}] + + chat_client.chat.completions.create(model="seed-2.0-mini", messages=messages) + + sent = json.loads(route.calls.last.request.content)["messages"] + assert sent[1] == { + "role": "assistant", + "content": "Hello!", + "reasoning_content": "The user greets me.", + "reasoning_details": [{"type": "reasoning.text", "text": "The user greets me."}], + } + + @respx.mock + def test_timeout_is_per_request(self, chat_client: DeapiClient) -> None: + route = respx.post(CHAT_URL).mock(return_value=httpx.Response(200, json=COMPLETION)) + chat_client.chat.completions.create(model="m", messages=[{"role": "user", "content": "x"}], timeout=120) + assert route.calls.last.request.extensions["timeout"]["read"] == 120 + + def test_input_checks(self, chat_client: DeapiClient) -> None: + with pytest.raises(ValueError, match="must not be empty"): + chat_client.chat.completions.create(model="m", messages=[]) + with pytest.raises(TypeError, match="expected a dict"): + chat_client.chat.completions.create(model="m", messages=["hi"]) + + +class TestStreaming: + @respx.mock + def test_stream(self, chat_client: DeapiClient) -> None: + route = respx.post(CHAT_URL).mock(return_value=httpx.Response( + 200, content=STREAM_BODY, headers={"Content-Type": "text/event-stream"}, + )) + + stream = chat_client.chat.completions.create( + model="seed-2.0-mini", + messages=[{"role": "user", "content": "Hi"}], + stream=True, + stream_options={"include_usage": True}, + ) + assert isinstance(stream, ChatCompletionStream) + chunks = list(stream) + + assert json.loads(route.calls.last.request.content)["stream"] is True + assert len(chunks) == 4 + assert chunks[0].choices[0].delta.reasoning_content == "Thinking" + assert "".join(c.choices[0].delta.content or "" for c in chunks if c.choices) == "Hello!" + assert chunks[2].choices[0].finish_reason == "stop" + assert chunks[3].choices == [] + assert stream.usage is not None and stream.usage.total_tokens == 15 + assert stream.cost == 0.0000123 + assert stream.response.is_closed + + @respx.mock + def test_stream_without_done_and_multiline_data(self, chat_client: DeapiClient) -> None: + payload = json.dumps(_chunk("a"), indent=1) # spans several lines + body = ("data: " + payload.replace("\n", "\ndata: ") + "\n\n" + "data: " + json.dumps(_chunk("b"))).encode() + respx.post(CHAT_URL).mock(return_value=httpx.Response(200, content=body)) + + with chat_client.chat.completions.create(model="m", messages=[{"role": "user", "content": "x"}], + stream=True) as stream: + texts = [c.choices[0].delta.content for c in stream] + + assert texts == ["a", "b"] + assert stream.usage is None and stream.cost is None + + @respx.mock + def test_error_event_mid_stream(self, chat_client: DeapiClient) -> None: + body = _sse(_chunk("a"), {"error": {"message": "Upstream failed", "type": "api_error", "code": None}}) + respx.post(CHAT_URL).mock(return_value=httpx.Response(200, content=body)) + + stream = chat_client.chat.completions.create(model="m", messages=[{"role": "user", "content": "x"}], + stream=True) + assert next(stream).choices[0].delta.content == "a" + with pytest.raises(DeapiError, match="Upstream failed"): + next(stream) + assert stream.response.is_closed + + @respx.mock + def test_stream_http_error_raises_on_create(self, chat_client: DeapiClient) -> None: + respx.post(CHAT_URL).mock(return_value=_error(401, "authentication_error", "Invalid API key", "invalid_key")) + with pytest.raises(AuthenticationError, match="Invalid API key"): + chat_client.chat.completions.create(model="m", messages=[{"role": "user", "content": "x"}], stream=True) + + @respx.mock + def test_close_early(self, chat_client: DeapiClient) -> None: + respx.post(CHAT_URL).mock(return_value=httpx.Response(200, content=STREAM_BODY)) + with chat_client.chat.completions.create(model="m", messages=[{"role": "user", "content": "x"}], + stream=True) as stream: + next(stream) + assert stream.response.is_closed + + +def _error(status: int, type_: str, message: str, code: str | None = None, param: str | None = None) -> httpx.Response: + return httpx.Response(status, json={"error": {"message": message, "type": type_, "param": param, "code": code}}) + + +class TestErrors: + @respx.mock + def test_401(self, chat_client: DeapiClient) -> None: + respx.post(CHAT_URL).mock(return_value=_error(401, "authentication_error", "Invalid API key", "invalid_key")) + with pytest.raises(AuthenticationError) as info: + chat_client.chat.completions.create(model="m", messages=[{"role": "user", "content": "x"}]) + assert info.value.message == "Invalid API key" + assert info.value.code == "invalid_key" + assert info.value.status_code == 401 + + @respx.mock + def test_400_is_validation_error(self, chat_client: DeapiClient) -> None: + respx.post(CHAT_URL).mock(return_value=_error( + 400, "invalid_request_error", "reasoning_effort 'none' is not supported", param="reasoning_effort", + )) + with pytest.raises(ValidationError) as info: + chat_client.chat.completions.create(model="glm-5.3", messages=[{"role": "user", "content": "x"}], + reasoning_effort="none") + assert info.value.status_code == 400 + assert info.value.errors == {"reasoning_effort": ["reasoning_effort 'none' is not supported"]} + + @respx.mock + def test_insufficient_quota_is_balance_error_and_not_retried(self, chat_client: DeapiClient) -> None: + route = respx.post(CHAT_URL).mock(return_value=_error(429, "insufficient_quota", "Not enough balance.")) + with pytest.raises(InsufficientBalanceError) as info: + chat_client.chat.completions.create(model="m", messages=[{"role": "user", "content": "x"}]) + assert info.value.status_code == 429 + assert info.value.code == "insufficient_quota" + assert route.call_count == 1 + + @respx.mock + def test_402_insufficient_balance_code(self, chat_client: DeapiClient) -> None: + respx.post(CHAT_URL).mock(return_value=_error(402, "invalid_request_error", "Top up", "insufficient_balance")) + with pytest.raises(InsufficientBalanceError) as info: + chat_client.chat.completions.create(model="m", messages=[{"role": "user", "content": "x"}]) + assert info.value.status_code == 402 + + @respx.mock + def test_rate_limit_is_retried(self) -> None: + route = respx.post(CHAT_URL).mock(side_effect=[ + _error(429, "rate_limit_exceeded", "Slow down"), + httpx.Response(200, json=COMPLETION), + ]) + with DeapiClient(api_key="k", oai_base_url=OAI, max_retry_after=0.01) as client: + completion = client.chat.completions.create(model="m", messages=[{"role": "user", "content": "x"}]) + assert completion.text == "Hello!" + assert route.call_count == 2 + + @respx.mock + def test_rate_limit_error(self) -> None: + respx.post(CHAT_URL).mock(return_value=_error(429, "rate_limit_exceeded", "Slow down")) + with DeapiClient(api_key="k", oai_base_url=OAI, max_retries=0) as client, pytest.raises(RateLimitError): + client.chat.completions.create(model="m", messages=[{"role": "user", "content": "x"}]) + + @respx.mock + def test_402(self, chat_client: DeapiClient) -> None: + respx.post(CHAT_URL).mock(return_value=_error(402, "invalid_request_error", "Payment required")) + with pytest.raises(PaymentRequiredError): + chat_client.chat.completions.create(model="m", messages=[{"role": "user", "content": "x"}]) + + @respx.mock + def test_5xx_is_not_resent(self, chat_client: DeapiClient) -> None: + route = respx.post(CHAT_URL).mock(return_value=_error(500, "api_error", "boom")) + with pytest.raises(ServerError, match="boom"): + chat_client.chat.completions.create(model="m", messages=[{"role": "user", "content": "x"}]) + assert route.call_count == 1 + + @respx.mock + def test_timeout_is_not_resent(self, chat_client: DeapiClient) -> None: + route = respx.post(CHAT_URL).mock(side_effect=httpx.ReadTimeout("slow")) + with pytest.raises(DeapiError): + chat_client.chat.completions.create(model="m", messages=[{"role": "user", "content": "x"}], stream=True) + assert route.call_count == 1 + + @respx.mock + def test_native_api_errors_unchanged(self, chat_client: DeapiClient) -> None: + # A v2-style body with a plain string "error" still uses it as the message. + respx.get(f"{TEST_BASE_URL}/api/v2/account/balance").mock( + return_value=httpx.Response(500, json={"error": "Something broke"}), + ) + with DeapiClient(api_key="k", base_url=TEST_BASE_URL, max_retries=0) as client, \ + pytest.raises(ServerError, match="Something broke"): + client.balance() + + +class TestModels: + @respx.mock + def test_models_lists_chat_models_only(self, chat_client: DeapiClient) -> None: + respx.get(MODELS_URL).mock(return_value=httpx.Response(200, json=MODELS)) + + models = chat_client.chat.models() + + assert [m.id for m in models] == ["seed-2.0-mini", "glm-5.3"] + mini, glm = models + assert mini.context_length == 262144 + assert mini.max_completion_tokens == 131072 + assert mini.input_modalities == ["text", "image"] + assert mini.supports("structured_outputs") and not glm.supports("structured_outputs") + assert mini.pricing.prompt == 0.0000001 + assert mini.pricing.prompt_per_1m == 0.1 + assert mini.pricing.completion_per_1m == 0.4 + assert mini.pricing.input_cache_read_per_1m == 0.02 + assert mini.pricing.input_cache_write_per_1m is None + assert glm.pricing.input_cache_write_per_1m == 1.25 + + +class TestAsync: + @respx.mock + async def test_async_create(self, async_chat_client: AsyncDeapiClient) -> None: + respx.post(CHAT_URL).mock(return_value=httpx.Response(200, json=COMPLETION, headers={"X-DeAPI-Cost": "0.1"})) + completion = await async_chat_client.chat.completions.create( + model="seed-2.0-mini", messages=[{"role": "user", "content": "Hi"}], max_tokens=8, + ) + assert completion.text == "Hello!" + assert completion.header_cost == 0.1 + + @respx.mock + async def test_async_stream(self, async_chat_client: AsyncDeapiClient) -> None: + respx.post(CHAT_URL).mock(return_value=httpx.Response(200, content=STREAM_BODY)) + stream = await async_chat_client.chat.completions.create( + model="seed-2.0-mini", messages=[{"role": "user", "content": "Hi"}], stream=True, + stream_options={"include_usage": True}, + ) + assert isinstance(stream, AsyncChatCompletionStream) + async with stream: + text = "".join([c.choices[0].delta.content or "" async for c in stream if c.choices]) + assert text == "Hello!" + assert stream.cost == 0.0000123 + assert stream.response.is_closed + + @respx.mock + async def test_async_stream_error_status(self, async_chat_client: AsyncDeapiClient) -> None: + route = respx.post(CHAT_URL).mock(return_value=_error(429, "insufficient_quota", "Not enough balance.")) + with pytest.raises(InsufficientBalanceError): + await async_chat_client.chat.completions.create( + model="m", messages=[{"role": "user", "content": "x"}], stream=True, + ) + assert route.call_count == 1 + + @respx.mock + async def test_async_models(self, async_chat_client: AsyncDeapiClient) -> None: + respx.get(MODELS_URL).mock(return_value=httpx.Response(200, json=MODELS)) + models = await async_chat_client.chat.models() + assert len(models) == 2 From d6b7c1a5c8b2270849b44d038d6275798553d9fe Mon Sep 17 00:00:00 2001 From: Dawid Wenderski Date: Sun, 29 Nov 2026 18:08:57 +0100 Subject: [PATCH 09/13] Never retry chat requests; type reasoning_effort The OpenAI-compatible API bills every chat request it accepts and does not honour an Idempotency-Key, so chat completions (streamed or not) are now sent exactly once: no automatic retry after a 429 or a connection error either. The HTTP clients' request_response() and open_stream() take retry=False for this; chat.models() is a GET and keeps the usual policy. reasoning_effort is an explicit parameter typed as ReasoningEffort ("none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"), with other strings still accepted. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 ++ README.md | 11 +++++--- docs/api-reference.md | 14 ++++++---- src/deapi_sdk/__init__.py | 2 ++ src/deapi_sdk/_client.py | 44 ++++++++++++++++++++++---------- src/deapi_sdk/resources/chat.py | 40 +++++++++++++++++++++-------- src/deapi_sdk/types/__init__.py | 2 ++ src/deapi_sdk/types/chat.py | 6 ++++- tests/test_chat.py | 45 +++++++++++++++++++++++---------- 9 files changed, 118 insertions(+), 48 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ec664c7..57f4dc2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,8 @@ Versions follow [Semantic Versioning](https://semver.org/) (pre-1.0: minor versi - `stream=True` returns a `ChatCompletionStream` / `AsyncChatCompletionStream` of `ChatCompletionChunk`s; with `stream_options={"include_usage": True}` its `usage` and `cost` come from the final chunk. + - `reasoning_effort` is typed as `ReasoningEffort` (`"none"` ... `"max"`), other strings allowed. + - Chat requests are sent once and never retried automatically (every accepted request is billed). - `chat.models()` lists the chat models (`ChatModel`: context length, output limit, supported parameters, `pricing` with per-1M-token helpers). - `oai_base_url` client option and `DEAPI_OAI_BASE_URL` environment variable. diff --git a/README.md b/README.md index c10b9a3..587d157 100644 --- a/README.md +++ b/README.md @@ -295,7 +295,7 @@ Requests and responses have the OpenAI Chat Completions shape, plus deAPI's extr completion = client.chat.completions.create( model="seed-2.0-mini", messages=[{"role": "user", "content": "Say hello in five words."}], - reasoning_effort="none", # "none" turns reasoning off; low | medium | high | ... per model + reasoning_effort="none", # none | minimal (off) | low | medium | high | xhigh | max max_tokens=32, # any other Chat Completions parameter works the same way ) print(completion.text) # choices[0].message.content @@ -322,9 +322,11 @@ for m in client.chat.models(): Tools, `tool_choice`, `response_format` (JSON schema) and the other OpenAI parameters are passed through as keyword arguments. Errors raise the usual SDK exceptions (`AuthenticationError`, `ValidationError` for a 400, `InsufficientBalanceError` when the account is out of credit, -`RateLimitError`). Like other job-creating calls, a chat request is not resent after a timeout or a -5xx. For long non-streamed answers raise `timeout=` (per call) or use `stream=True`. `max_tokens` -counts reasoning tokens too: with reasoning on, a small cap can end the answer before any text. +`RateLimitError`). A chat request is sent **once** and never retried automatically, not even after +a 429: every accepted request is billed, so retrying is up to you. For long non-streamed answers +raise `timeout=` (per call) or use `stream=True`. Not every model takes every `reasoning_effort` +value (an unsupported one is a `ValidationError` listing the supported ones). `max_tokens` counts +reasoning tokens too: with reasoning on, a small cap can end the answer before any text. See the [OpenAI compatibility docs](https://docs.deapi.ai/openai-compatibility) for the parameters each model supports. @@ -580,6 +582,7 @@ catch it. - Job-creating `POST`s (and `PATCH` / `DELETE`) are retried **only** on 429 or when the connection was never established. They are never retried after a timeout or a 5xx, so one job is never paid for twice. After such an error, check whether the job exists before resubmitting. +- Chat requests (`client.chat.completions.create()`) are never retried. ## Webhooks diff --git a/docs/api-reference.md b/docs/api-reference.md index ed48c74..f132746 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -466,11 +466,13 @@ completion = client.chat.completions.create( model: str, # e.g. "seed-2.0-mini"; see chat.models() messages: Sequence[dict | BaseModel], # OpenAI-style dicts, or a message returned by the SDK stream: bool = False, # True -> ChatCompletionStream + reasoning_effort: ReasoningEffort | str | None = None, + # "none" | "minimal" (off) | "low" | "medium" | "high" + # | "xhigh" | "max"; not every model takes every value timeout: float | None = None, # per request; for a stream, the longest gap between chunks - **params, # any Chat Completions parameter: max_tokens, temperature, - # tools, tool_choice, response_format, stream_options, - # reasoning_effort ("none" turns reasoning off; - # "low", "medium", "high", ... per model), ... + **params, # any other Chat Completions parameter: max_tokens, + # temperature, tools, tool_choice, response_format, + # stream_options, ... ) -> ChatCompletion | ChatCompletionStream ``` @@ -514,7 +516,8 @@ Errors in the OpenAI shape (`{"error": {"message", "type", "code", "param"}}`) m exceptions: 401 `AuthenticationError`, 400 `ValidationError` (`errors = {param: [message]}`), 402 `PaymentRequiredError`, 404 `NotFoundError`, `insufficient_quota` / `insufficient_balance` `InsufficientBalanceError` (not retried), other 429s `RateLimitError`, 5xx `ServerError`. An error event inside a stream -raises `DeapiError`. A chat request is never resent after a timeout or a 5xx. +raises `DeapiError`. A chat request is sent once and **never retried** automatically (not even after +a 429): every accepted request is billed. `chat.models()` is a GET and follows the usual retry policy. ### `chat.models()` @@ -912,6 +915,7 @@ Up to `max_retries` attempts with exponential backoff (429 waits for `Retry-Afte |---------|-----------| | `GET` (job status, models, account, keys) | 429, 5xx, network errors | | Every other method: job-creating `POST` (price quotes are POSTs too), `PATCH`, `DELETE` | 429, or when the connection was never established | +| Chat completions (`client.chat.completions.create()`) | never | Non-idempotent requests are **never** retried after a timeout or a 5xx, because the server may already have accepted (and billed) the job. After a `NetworkError` / `ServerError` on submission, diff --git a/src/deapi_sdk/__init__.py b/src/deapi_sdk/__init__.py index e99a414..0a0a69a 100644 --- a/src/deapi_sdk/__init__.py +++ b/src/deapi_sdk/__init__.py @@ -50,6 +50,7 @@ ChatCompletionUsage, ChatModel, ChatModelPricing, + ReasoningEffort, ) from deapi_sdk.types.common import ( Balance, @@ -391,6 +392,7 @@ async def __aexit__(self, *args: Any) -> None: "ChatCompletionUsage", "ChatModel", "ChatModelPricing", + "ReasoningEffort", # Types "Balance", "InferenceType", diff --git a/src/deapi_sdk/_client.py b/src/deapi_sdk/_client.py index 607a848..002e822 100644 --- a/src/deapi_sdk/_client.py +++ b/src/deapi_sdk/_client.py @@ -294,9 +294,13 @@ def request_response( json: dict[str, Any] | None = None, params: dict[str, Any] | None = None, timeout: float | None = None, + retry: bool = True, ) -> httpx.Response: - """Like ``request()``, but return the read ``httpx.Response`` (to look at headers).""" - return self._send(method, url, json=json, params=params, timeout=timeout) + """Like ``request()``, but return the read ``httpx.Response`` (to look at headers). + + ``retry=False`` sends the request exactly once, whatever the error. + """ + return self._send(method, url, json=json, params=params, timeout=timeout, retry=retry) def open_stream( self, @@ -305,12 +309,14 @@ def open_stream( *, json: dict[str, Any] | None = None, timeout: float | None = None, + retry: bool = True, ) -> httpx.Response: """Send a request and return the response with its body still unread; the caller closes it. - Error statuses are raised (with the same retry policy as ``request()``) before returning. + Error statuses are raised (with the same retry policy as ``request()``, or none with + ``retry=False``) before returning. """ - return self._send(method, url, json=json, timeout=timeout, stream=True) + return self._send(method, url, json=json, timeout=timeout, stream=True, retry=retry) def _send( self, @@ -323,11 +329,13 @@ def _send( params: dict[str, Any] | None = None, timeout: float | None = None, stream: bool = False, + retry: bool = True, ) -> httpx.Response: last_exc: Exception | None = None request_timeout: Any = httpx.USE_CLIENT_DEFAULT if timeout is None else timeout + attempts = self._config.max_retries + 1 if retry else 1 - for attempt in range(self._config.max_retries + 1): + for attempt in range(attempts): try: if stream: request = self._http.build_request( @@ -354,14 +362,14 @@ def _send( return response except (RateLimitError, ServerError, NetworkError) as exc: last_exc = exc - wait = self._should_retry(exc, attempt, method) + wait = self._should_retry(exc, attempt, method) if retry else None if wait is not None: time.sleep(wait) continue raise except httpx.TransportError as exc: last_exc = self._wrap_transport_error(exc) - wait = self._should_retry(last_exc, attempt, method) + wait = self._should_retry(last_exc, attempt, method) if retry else None if wait is not None: time.sleep(wait) continue @@ -444,9 +452,13 @@ async def request_response( json: dict[str, Any] | None = None, params: dict[str, Any] | None = None, timeout: float | None = None, + retry: bool = True, ) -> httpx.Response: - """Like ``request()``, but return the read ``httpx.Response`` (to look at headers).""" - return await self._send(method, url, json=json, params=params, timeout=timeout) + """Like ``request()``, but return the read ``httpx.Response`` (to look at headers). + + ``retry=False`` sends the request exactly once, whatever the error. + """ + return await self._send(method, url, json=json, params=params, timeout=timeout, retry=retry) async def open_stream( self, @@ -455,12 +467,14 @@ async def open_stream( *, json: dict[str, Any] | None = None, timeout: float | None = None, + retry: bool = True, ) -> httpx.Response: """Send a request and return the response with its body still unread; the caller closes it. - Error statuses are raised (with the same retry policy as ``request()``) before returning. + Error statuses are raised (with the same retry policy as ``request()``, or none with + ``retry=False``) before returning. """ - return await self._send(method, url, json=json, timeout=timeout, stream=True) + return await self._send(method, url, json=json, timeout=timeout, stream=True, retry=retry) async def _send( self, @@ -473,11 +487,13 @@ async def _send( params: dict[str, Any] | None = None, timeout: float | None = None, stream: bool = False, + retry: bool = True, ) -> httpx.Response: last_exc: Exception | None = None request_timeout: Any = httpx.USE_CLIENT_DEFAULT if timeout is None else timeout + attempts = self._config.max_retries + 1 if retry else 1 - for attempt in range(self._config.max_retries + 1): + for attempt in range(attempts): try: if stream: request = self._http.build_request( @@ -504,14 +520,14 @@ async def _send( return response except (RateLimitError, ServerError, NetworkError) as exc: last_exc = exc - wait = self._should_retry(exc, attempt, method) + wait = self._should_retry(exc, attempt, method) if retry else None if wait is not None: await asyncio.sleep(wait) continue raise except httpx.TransportError as exc: last_exc = self._wrap_transport_error(exc) - wait = self._should_retry(last_exc, attempt, method) + wait = self._should_retry(last_exc, attempt, method) if retry else None if wait is not None: await asyncio.sleep(wait) continue diff --git a/src/deapi_sdk/resources/chat.py b/src/deapi_sdk/resources/chat.py index adb6905..360fe38 100644 --- a/src/deapi_sdk/resources/chat.py +++ b/src/deapi_sdk/resources/chat.py @@ -10,7 +10,7 @@ from deapi_sdk._client import AsyncHTTPClient, BaseClient, SyncHTTPClient from deapi_sdk._streaming import AsyncChatCompletionStream, ChatCompletionStream -from deapi_sdk.types.chat import ChatCompletion, ChatModel +from deapi_sdk.types.chat import ChatCompletion, ChatModel, ReasoningEffort # A message: an OpenAI-style dict ({"role": "user", "content": "..."}) or a message model returned # by the SDK (e.g. ``completion.choices[0].message``), which is sent back with all its fields. @@ -28,11 +28,17 @@ def _message(message: ChatMessageInput) -> dict[str, Any]: def _build_body( - model: str, messages: Sequence[ChatMessageInput], stream: bool, params: dict[str, Any], + model: str, + messages: Sequence[ChatMessageInput], + stream: bool, + reasoning_effort: str | None, + params: dict[str, Any], ) -> dict[str, Any]: if not messages: raise ValueError("'messages' must not be empty.") body: dict[str, Any] = {"model": model, "messages": [_message(m) for m in messages]} + if reasoning_effort is not None: + body["reasoning_effort"] = reasoning_effort body.update({k: v for k, v in params.items() if v is not None}) if stream: body["stream"] = True @@ -80,6 +86,7 @@ def create( model: str, messages: Sequence[ChatMessageInput], stream: Literal[False] = False, + reasoning_effort: ReasoningEffort | str | None = None, timeout: float | None = None, **params: Any, ) -> ChatCompletion: ... @@ -91,6 +98,7 @@ def create( model: str, messages: Sequence[ChatMessageInput], stream: Literal[True], + reasoning_effort: ReasoningEffort | str | None = None, timeout: float | None = None, **params: Any, ) -> ChatCompletionStream: ... @@ -102,6 +110,7 @@ def create( model: str, messages: Sequence[ChatMessageInput], stream: bool, + reasoning_effort: ReasoningEffort | str | None = None, timeout: float | None = None, **params: Any, ) -> ChatCompletion | ChatCompletionStream: ... @@ -112,6 +121,7 @@ def create( model: str, messages: Sequence[ChatMessageInput], stream: bool = False, + reasoning_effort: ReasoningEffort | str | None = None, timeout: float | None = None, **params: Any, ) -> ChatCompletion | ChatCompletionStream: @@ -125,21 +135,24 @@ def create( stream: Return a ``ChatCompletionStream`` of chunks instead of a ``ChatCompletion``. Pass ``stream_options={"include_usage": True}`` to get a final chunk with ``usage`` (and ``cost``). + reasoning_effort: ``"none"`` | ``"minimal"`` (reasoning off) | ``"low"`` | ``"medium"`` | + ``"high"`` | ``"xhigh"`` | ``"max"``. Not every model takes every value; an + unsupported one is a ``ValidationError`` (400) listing the supported values. timeout: Per-request timeout in seconds (default: the client's). For a stream it is the longest wait between two chunks. **params: Any other Chat Completions parameter, sent as is: ``max_tokens``, ``temperature``, ``top_p``, ``stop``, ``tools``, ``tool_choice``, - ``parallel_tool_calls``, ``response_format``, ``reasoning_effort`` (``"none"`` turns - reasoning off; supported values differ per model), ``stream_options``, ... + ``parallel_tool_calls``, ``response_format``, ``stream_options``, ... ``None`` values are left out. ``max_tokens`` counts reasoning tokens too. - A failed request is not resent after a timeout or a 5xx (it may already be billed). + A chat request is sent once and never retried automatically, not even after a 429: the API + bills every request it accepts, so retrying is left to you. """ - body = _build_body(model, messages, stream, params) + body = _build_body(model, messages, stream, reasoning_effort, params) url = self._client._resolve_oai("chat/completions") if stream: - return ChatCompletionStream(self._client.open_stream("POST", url, json=body, timeout=timeout)) - return _completion(self._client.request_response("POST", url, json=body, timeout=timeout)) + return ChatCompletionStream(self._client.open_stream("POST", url, json=body, timeout=timeout, retry=False)) + return _completion(self._client.request_response("POST", url, json=body, timeout=timeout, retry=False)) class AsyncChatCompletions: @@ -155,6 +168,7 @@ async def create( model: str, messages: Sequence[ChatMessageInput], stream: Literal[False] = False, + reasoning_effort: ReasoningEffort | str | None = None, timeout: float | None = None, **params: Any, ) -> ChatCompletion: ... @@ -166,6 +180,7 @@ async def create( model: str, messages: Sequence[ChatMessageInput], stream: Literal[True], + reasoning_effort: ReasoningEffort | str | None = None, timeout: float | None = None, **params: Any, ) -> AsyncChatCompletionStream: ... @@ -177,6 +192,7 @@ async def create( model: str, messages: Sequence[ChatMessageInput], stream: bool, + reasoning_effort: ReasoningEffort | str | None = None, timeout: float | None = None, **params: Any, ) -> ChatCompletion | AsyncChatCompletionStream: ... @@ -187,15 +203,17 @@ async def create( model: str, messages: Sequence[ChatMessageInput], stream: bool = False, + reasoning_effort: ReasoningEffort | str | None = None, timeout: float | None = None, **params: Any, ) -> ChatCompletion | AsyncChatCompletionStream: """Create a chat completion. See ``ChatCompletions.create``; streams are async iterators.""" - body = _build_body(model, messages, stream, params) + body = _build_body(model, messages, stream, reasoning_effort, params) url = self._client._resolve_oai("chat/completions") if stream: - return AsyncChatCompletionStream(await self._client.open_stream("POST", url, json=body, timeout=timeout)) - return _completion(await self._client.request_response("POST", url, json=body, timeout=timeout)) + response = await self._client.open_stream("POST", url, json=body, timeout=timeout, retry=False) + return AsyncChatCompletionStream(response) + return _completion(await self._client.request_response("POST", url, json=body, timeout=timeout, retry=False)) class Chat: diff --git a/src/deapi_sdk/types/__init__.py b/src/deapi_sdk/types/__init__.py index 617f326..170abfa 100644 --- a/src/deapi_sdk/types/__init__.py +++ b/src/deapi_sdk/types/__init__.py @@ -17,6 +17,7 @@ ChatModelTopProvider, ChoiceDelta, ChoiceDeltaToolCall, + ReasoningEffort, ) from deapi_sdk.types.common import ( Balance, @@ -83,6 +84,7 @@ "PaymentsPage", "PriceResult", "PromptBoost", + "ReasoningEffort", "SyncTranscriptionResult", "Text2AudioParams", "Text2EmbeddingParams", diff --git a/src/deapi_sdk/types/chat.py b/src/deapi_sdk/types/chat.py index ec7bf3c..0a33886 100644 --- a/src/deapi_sdk/types/chat.py +++ b/src/deapi_sdk/types/chat.py @@ -8,12 +8,16 @@ from __future__ import annotations -from typing import Any +from typing import Any, Literal, TypeAlias from pydantic import BaseModel, ConfigDict, Field, PrivateAttr _ONE_MILLION = 1_000_000 +# Values the API accepts for ``reasoning_effort``; "none" and "minimal" turn reasoning off. +# Not every model takes every value (the API answers 400 with the supported list). +ReasoningEffort: TypeAlias = Literal["none", "minimal", "low", "medium", "high", "xhigh", "max"] + class _Model(BaseModel): model_config = ConfigDict(extra="allow") diff --git a/tests/test_chat.py b/tests/test_chat.py index df2476a..022cff6 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -139,8 +139,8 @@ def test_create(self, chat_client: DeapiClient) -> None: completion = chat_client.chat.completions.create( model="seed-2.0-mini", messages=[{"role": "user", "content": "Hi"}], - max_tokens=32, reasoning_effort="none", + max_tokens=32, temperature=None, # None values are left out ) @@ -311,21 +311,40 @@ def test_402_insufficient_balance_code(self, chat_client: DeapiClient) -> None: assert info.value.status_code == 402 @respx.mock - def test_rate_limit_is_retried(self) -> None: - route = respx.post(CHAT_URL).mock(side_effect=[ - _error(429, "rate_limit_exceeded", "Slow down"), - httpx.Response(200, json=COMPLETION), - ]) - with DeapiClient(api_key="k", oai_base_url=OAI, max_retry_after=0.01) as client: - completion = client.chat.completions.create(model="m", messages=[{"role": "user", "content": "x"}]) - assert completion.text == "Hello!" - assert route.call_count == 2 + def test_rate_limit_is_not_retried(self) -> None: + # Chat requests are billed per accepted request, so the SDK never resends one. + route = respx.post(CHAT_URL).mock(return_value=httpx.Response( + 429, json={"error": {"message": "Slow down", "type": "rate_limit_exceeded", "param": None, "code": None}}, + headers={"Retry-After": "1"}, + )) + with DeapiClient(api_key="k", oai_base_url=OAI, max_retries=3) as client: + with pytest.raises(RateLimitError) as info: + client.chat.completions.create(model="m", messages=[{"role": "user", "content": "x"}]) + assert info.value.retry_after == 1.0 + assert route.call_count == 1 + + with pytest.raises(RateLimitError): + client.chat.completions.create(model="m", messages=[{"role": "user", "content": "x"}], stream=True) + assert route.call_count == 2 @respx.mock - def test_rate_limit_error(self) -> None: - respx.post(CHAT_URL).mock(return_value=_error(429, "rate_limit_exceeded", "Slow down")) - with DeapiClient(api_key="k", oai_base_url=OAI, max_retries=0) as client, pytest.raises(RateLimitError): + def test_connect_error_is_not_retried(self) -> None: + route = respx.post(CHAT_URL).mock(side_effect=httpx.ConnectError("refused")) + with DeapiClient(api_key="k", oai_base_url=OAI, max_retries=3) as client, pytest.raises(DeapiError): client.chat.completions.create(model="m", messages=[{"role": "user", "content": "x"}]) + assert route.call_count == 1 + + @respx.mock + def test_models_get_is_still_retried(self) -> None: + route = respx.get(MODELS_URL).mock(side_effect=[ + httpx.Response(503, json={"error": {"message": "busy", "type": "overloaded_error"}}), + httpx.Response(200, json=MODELS), + ]) + with DeapiClient(api_key="k", oai_base_url=OAI) as client, \ + pytest.MonkeyPatch.context() as mp: + mp.setattr("deapi_sdk._client.time.sleep", lambda _s: None) + assert len(client.chat.models()) == 2 + assert route.call_count == 2 @respx.mock def test_402(self, chat_client: DeapiClient) -> None: From 849eb50221cda9491cb13d078beec527b3bc1312 Mon Sep 17 00:00:00 2001 From: Dawid Wenderski Date: Sun, 29 Nov 2026 18:24:55 +0100 Subject: [PATCH 10/13] Ask for the usage chunk by default on streamed chat With stream=True and no stream_options, chat.completions.create() now sends stream_options={"include_usage": true}, so a stream's usage and cost are available without extra arguments. An explicit stream_options (e.g. {"include_usage": false}) is sent as given. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++-- README.md | 6 +++--- docs/api-reference.md | 4 +++- examples/chat.py | 3 +-- src/deapi_sdk/_streaming.py | 2 +- src/deapi_sdk/resources/chat.py | 7 +++++-- src/deapi_sdk/types/chat.py | 2 +- tests/test_chat.py | 26 +++++++++++++++++++++++++- 8 files changed, 41 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 57f4dc2..0807523 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,8 +26,8 @@ Versions follow [Semantic Versioning](https://semver.org/) (pre-1.0: minor versi `reasoning_content` and `reasoning_details`. Any other Chat Completions parameter is passed through; a message returned by the SDK can be appended to `messages` as is. - `stream=True` returns a `ChatCompletionStream` / `AsyncChatCompletionStream` of - `ChatCompletionChunk`s; with `stream_options={"include_usage": True}` its `usage` and `cost` - come from the final chunk. + `ChatCompletionChunk`s. Unless `stream_options` is given, the SDK sends + `{"include_usage": True}`, so the stream's `usage` and `cost` come from the final chunk. - `reasoning_effort` is typed as `ReasoningEffort` (`"none"` ... `"max"`), other strings allowed. - Chat requests are sent once and never retried automatically (every accepted request is billed). - `chat.models()` lists the chat models (`ChatModel`: context length, output limit, supported diff --git a/README.md b/README.md index 587d157..9fa42df 100644 --- a/README.md +++ b/README.md @@ -304,10 +304,10 @@ print(completion.cost) # usage.cost, else the X-DeAPI-Cost header # Continue the conversation: append the assistant message as is (keeps reasoning_details) messages = [{"role": "user", "content": "Hi"}, completion.choices[0].message, {"role": "user", "content": "More"}] -# Streaming: an iterator of chunks; the final usage chunk carries the cost +# Streaming: an iterator of chunks. The SDK asks for the final usage chunk by default +# (stream_options={"include_usage": True}); it has empty choices and carries the cost. with client.chat.completions.create( - model="seed-2.0-mini", messages=messages, max_tokens=64, - stream=True, stream_options={"include_usage": True}, + model="seed-2.0-mini", messages=messages, max_tokens=64, stream=True, ) as stream: for chunk in stream: if chunk.choices and chunk.choices[0].delta.content: diff --git a/docs/api-reference.md b/docs/api-reference.md index f132746..d6f1bc9 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -476,6 +476,8 @@ completion = client.chat.completions.create( ) -> ChatCompletion | ChatCompletionStream ``` +With `stream=True` and no `stream_options`, the SDK sends `stream_options={"include_usage": True}`, so +the last chunk (empty `choices`) carries `usage` and `cost`; pass `{"include_usage": False}` to opt out. `None` values in `params` are left out. `max_tokens` counts reasoning tokens too. A message model (e.g. `completion.choices[0].message`) is sent back with all its fields, including `reasoning_details`. On `AsyncDeapiClient` the call is awaited and a stream is an `AsyncChatCompletionStream` (`async for`, `async with`). @@ -501,7 +503,7 @@ class ChatCompletionUsage(BaseModel): prompt_tokens_details: dict | None; completion_tokens_details: dict | None class ChatCompletionStream: # iterator of ChatCompletionChunk; context manager; close() - usage: ChatCompletionUsage | None # from the final chunk (stream_options={"include_usage": True}) + usage: ChatCompletionUsage | None # from the final usage chunk (requested by default) cost: float | None # property: usage.cost response: httpx.Response diff --git a/examples/chat.py b/examples/chat.py index f7efd2a..22f6ece 100644 --- a/examples/chat.py +++ b/examples/chat.py @@ -40,8 +40,7 @@ messages=messages, reasoning_effort="none", max_tokens=32, - stream=True, - stream_options={"include_usage": True}, + stream=True, # the SDK asks for the final usage chunk (with the cost) by default ) as stream: for chunk in stream: if chunk.choices and chunk.choices[0].delta.content: diff --git a/src/deapi_sdk/_streaming.py b/src/deapi_sdk/_streaming.py index 4737b86..9249086 100644 --- a/src/deapi_sdk/_streaming.py +++ b/src/deapi_sdk/_streaming.py @@ -61,7 +61,7 @@ class ChatCompletionStream: Use it in a ``with`` block (or call ``close()``) so the connection is released when you stop early; it is closed automatically once fully consumed. ``usage`` holds the final usage chunk - (``stream_options={"include_usage": True}``), and ``cost`` its USD charge. + (sent by default; see ``chat.completions.create``), and ``cost`` its USD charge. """ def __init__(self, response: httpx.Response) -> None: diff --git a/src/deapi_sdk/resources/chat.py b/src/deapi_sdk/resources/chat.py index 360fe38..55bfb21 100644 --- a/src/deapi_sdk/resources/chat.py +++ b/src/deapi_sdk/resources/chat.py @@ -42,6 +42,8 @@ def _build_body( body.update({k: v for k, v in params.items() if v is not None}) if stream: body["stream"] = True + # Ask for the final usage chunk (with ``cost``) unless the caller set stream_options. + body.setdefault("stream_options", {"include_usage": True}) return body @@ -133,8 +135,9 @@ def create( ``completion.choices[0].message``) can be appended as is; its ``reasoning_details`` go back with it. stream: Return a ``ChatCompletionStream`` of chunks instead of a ``ChatCompletion``. - Pass ``stream_options={"include_usage": True}`` to get a final chunk with - ``usage`` (and ``cost``). + Unless you pass ``stream_options``, the SDK sends ``{"include_usage": True}``, so + the last chunk (empty ``choices``) carries ``usage`` with ``cost``; pass + ``stream_options={"include_usage": False}`` to leave it out. reasoning_effort: ``"none"`` | ``"minimal"`` (reasoning off) | ``"low"`` | ``"medium"`` | ``"high"`` | ``"xhigh"`` | ``"max"``. Not every model takes every value; an unsupported one is a ``ValidationError`` (400) listing the supported values. diff --git a/src/deapi_sdk/types/chat.py b/src/deapi_sdk/types/chat.py index 0a33886..a86d96b 100644 --- a/src/deapi_sdk/types/chat.py +++ b/src/deapi_sdk/types/chat.py @@ -128,7 +128,7 @@ class ChatCompletionChunkChoice(_Model): class ChatCompletionChunk(_Model): """One streamed chunk (``stream=True``). - With ``stream_options={"include_usage": True}`` the last chunk has empty ``choices`` and + With ``stream_options={"include_usage": True}`` (the SDK default) the last chunk has empty ``choices`` and carries ``usage`` (including ``cost``). """ diff --git a/tests/test_chat.py b/tests/test_chat.py index 022cff6..c23910e 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -219,7 +219,9 @@ def test_stream(self, chat_client: DeapiClient) -> None: assert isinstance(stream, ChatCompletionStream) chunks = list(stream) - assert json.loads(route.calls.last.request.content)["stream"] is True + body = json.loads(route.calls.last.request.content) + assert body["stream"] is True + assert body["stream_options"] == {"include_usage": True} assert len(chunks) == 4 assert chunks[0].choices[0].delta.reasoning_content == "Thinking" assert "".join(c.choices[0].delta.content or "" for c in chunks if c.choices) == "Hello!" @@ -229,6 +231,28 @@ def test_stream(self, chat_client: DeapiClient) -> None: assert stream.cost == 0.0000123 assert stream.response.is_closed + @respx.mock + def test_include_usage_is_the_default(self, chat_client: DeapiClient) -> None: + route = respx.post(CHAT_URL).mock(return_value=httpx.Response(200, content=STREAM_BODY)) + messages = [{"role": "user", "content": "x"}] + + list(chat_client.chat.completions.create(model="m", messages=messages, stream=True)) + assert json.loads(route.calls.last.request.content)["stream_options"] == {"include_usage": True} + + list(chat_client.chat.completions.create( + model="m", messages=messages, stream=True, stream_options={"include_usage": False}, + )) + assert json.loads(route.calls.last.request.content)["stream_options"] == {"include_usage": False} + + chat_client.chat.completions.create(model="m", messages=messages, stream=True, stream_options=None).close() + assert json.loads(route.calls.last.request.content)["stream_options"] == {"include_usage": True} + + @respx.mock + def test_no_stream_options_without_stream(self, chat_client: DeapiClient) -> None: + route = respx.post(CHAT_URL).mock(return_value=httpx.Response(200, json=COMPLETION)) + chat_client.chat.completions.create(model="m", messages=[{"role": "user", "content": "x"}]) + assert "stream_options" not in json.loads(route.calls.last.request.content) + @respx.mock def test_stream_without_done_and_multiline_data(self, chat_client: DeapiClient) -> None: payload = json.dumps(_chunk("a"), indent=1) # spans several lines From 8bd153e31a35d73ba65d03bb8bd90eeffd3920dd Mon Sep 17 00:00:00 2001 From: Dawid Wenderski Date: Sun, 29 Nov 2026 18:29:11 +0100 Subject: [PATCH 11/13] Add web search and contents, ModelRetiredError, and final job prices - client.web.search() / contents() (sync and async) with search_price() and contents_price(): synchronous calls whose results come back in the response as WebResults (request_id, cost, results of WebPage). Text, excerpts and summary options take True, a max_length / query, or the API's object; for search they are sent as "include". Web search is in limited availability: a 404 is raised as WebSearchUnavailableError (a NotFoundError). Like other POSTs, a web call is retried after a 429 (a refused call is not charged) and never resent after a timeout or a 5xx. - A 410 whose code is model_retired (or whose body has retired_at) raises ModelRetiredError with the API's message, retired_at and replacement; any other 410 stays a DeapiError. Not retried. - JobResult.price_amount / price_is_estimated read the job's charge from price. Text-to-music is billed by the length actually generated, so compose_price() is documented as a quote for the requested duration. - Webhooks: a refund is booked before job.failed is sent, so refunded reports it; docs and the WebhookEventData docstring say so. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 15 ++ README.md | 50 ++++- docs/api-reference.md | 79 ++++++- src/deapi_sdk/__init__.py | 13 ++ src/deapi_sdk/_client.py | 11 + src/deapi_sdk/_constants.py | 5 + src/deapi_sdk/_exceptions.py | 33 +++ src/deapi_sdk/resources/__init__.py | 3 + src/deapi_sdk/resources/audio.py | 12 +- src/deapi_sdk/resources/web.py | 336 ++++++++++++++++++++++++++++ src/deapi_sdk/types/__init__.py | 4 + src/deapi_sdk/types/common.py | 25 +++ src/deapi_sdk/types/web.py | 52 +++++ src/deapi_sdk/webhook.py | 7 +- tests/test_prod_compat.py | 116 ++++++++++ tests/test_web.py | 269 ++++++++++++++++++++++ 16 files changed, 1019 insertions(+), 11 deletions(-) create mode 100644 src/deapi_sdk/resources/web.py create mode 100644 src/deapi_sdk/types/web.py create mode 100644 tests/test_prod_compat.py create mode 100644 tests/test_web.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 0807523..5951e4b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,21 @@ Versions follow [Semantic Versioning](https://semver.org/) (pre-1.0: minor versi - Errors in the OpenAI shape (`{"error": {...}}`) map to the SDK's exceptions; a 400 is a `ValidationError` and a 429 `insufficient_quota` an `InsufficientBalanceError` (not retried). - Example `examples/chat.py`. +- `client.web.search()` and `client.web.contents()` (sync and async clients), with `search_price()` + and `contents_price()`: web search and page contents returned in the response as `WebResults` + (`request_id`, `cost`, `results` of `WebPage`). Web search and contents are in limited availability; accounts without access get a 404, + raised as `WebSearchUnavailableError` (a `NotFoundError`). Like other POSTs, a web call is + retried after a 429 and never resent after a timeout or a 5xx. +- `ModelRetiredError` (HTTP 410 `model_retired`): a request named a retired model. Keeps the API's + message and exposes `retired_at` and `replacement`. Any other 410 stays a `DeapiError`. +- `JobResult.price_amount` and `JobResult.price_is_estimated`: the charge of a job, read from `price`. + +### Changed + +- Text-to-music is billed by the length actually generated: `compose_price()` is documented as a + quote for the requested duration; the finished job carries the final charge. +- Webhooks: a refund is now booked before `job.failed` is sent, so its `refunded` reports it; the + docs and `WebhookEventData` docstring say so. ## [0.6.1] - 2026-11-19 diff --git a/README.md b/README.md index 9fa42df..eed3717 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ Generate images, videos, audio, transcriptions, embeddings, and more — all thr - **Audio** — text-to-speech (with voice cloning), text-to-music (with a style reference) - **Transcription** — URLs and file uploads, plain-text or structured JSON transcripts; fast transcription of short audio clips (no job to poll) - **Chat (LLMs)** — OpenAI-compatible chat completions with streaming, reasoning and per-request cost +- **Web search and contents** — ranked results or page text, excerpts and summaries, in the response - **Embeddings, OCR, prompt enhancement** - **Account and keys** — balance, usage, payments, API-key management (ADMIN keys) - **Sync + Async** — both `DeapiClient` and `AsyncDeapiClient` @@ -232,6 +233,10 @@ job = client.audio.compose( ) ``` +Text-to-music is billed by the length actually generated: `compose_price()` quotes the requested +`duration`, and a song that ends early is charged less (never more). The final charge is on the +finished job: `job.wait().price_amount`. + ### Transcription ```python @@ -353,6 +358,38 @@ job = client.embeddings.create( job = client.ocr.extract(image=Path("scan.png"), model="LightOnOcr_3_4B_Q8", return_result_in_response=True) ``` +### Web Search and Contents + +Search the web, or read known pages, and get the results in the response: no job, no polling. +Web search and contents are in limited availability; accounts without access get a 404 (raised as `WebSearchUnavailableError`, a `NotFoundError`). + +```python +results = client.web.search( + query="FLUX.2 image model release", + mode="balanced", # or "quick" (faster, cheaper; no summary / freshness_hours) + limit=5, + only_domains=["bfl.ai"], # also skip_domains, published_after/before, country, goal + text=2000, # clean page text, up to 2000 characters (True = API default) + excerpts=True, # most relevant passages + summary="What is new?", # AI summary per result, focused on a question +) +print(results.cost) # USD charged for this call +for page in results.results: + print(page.url, page.title, page.published_at, page.summary) + +pages = client.web.contents(urls=["https://deapi.ai", "https://deapi.ai/missing"], text=True) +for page in pages.results: + print(page.url, page.status, (page.text or "")[:80]) # pages that are not "ok" are not charged + +quote = client.web.search_price(query="FLUX.2", mode="quick") # free +quote = client.web.contents_price(urls=["https://deapi.ai"], text=True) +``` + +`contents()` needs at least one of `text`, `excerpts` or `summary` (each is billed per page read). +A call that fails is not charged. Like other POSTs, a web call is retried after a 429 (a refused +call is not charged) and never resent after a timeout or a 5xx. See the +[web search docs](https://docs.deapi.ai/api/v2/web/search.md) for limits and pricing. + ### Prompt Enhancement Prompt methods return results immediately (no job polling): @@ -378,6 +415,9 @@ not part of the quote. ```python price = client.images.generate_price(prompt="a cat in space", model="Flux1schnell", width=1024, height=1024) print(f"Cost: ${price.price}") + +result = job.wait() +print(result.price_amount, result.price_is_estimated) # what the finished job was charged ``` ### Account, Keys and Balance @@ -532,6 +572,8 @@ DeapiError │ ├── InsufficientPermissionsError 403 insufficient_permissions (API key on an ADMIN endpoint) │ └── AccountSuspendedError 403 no code ├── NotFoundError 404 +│ └── WebSearchUnavailableError 404 from client.web: web search is not available for this account +├── ModelRetiredError 410 model_retired (retired_at, replacement); other 410s: DeapiError ├── PayloadTooLargeError 413 ├── ValidationError 422 .errors = {"field": ["message", ...]} │ ├── InsufficientBalanceError 422 insufficient_balance: the ACCOUNT is out of credit @@ -576,6 +618,9 @@ Existing `except AccountSuspendedError` and `except ValidationError` handlers ke or a 422 on `model`). It is also a `NotFoundError` or a `ValidationError`, so those handlers still catch it. +A request that names a retired model gets `ModelRetiredError` (HTTP 410) before any job is created: +`message` is the API's notice, `replacement` the model to use instead (when there is one). + **Retries** (up to `max_retries`): - `GET` requests are retried on 429, 5xx and network errors. @@ -639,8 +684,9 @@ async def handle_webhook(request: Request): `PROCESSING_FAILED`), `retryable` and `refunded`. Failed jobs are reliably announced only by webhook (and the job status endpoint), not over the real-time WebSocket. - `job.completed` and `job.failed` carry `price` (`JobPrice`: `amount`, `is_estimated`). On completion it - may still be an estimate; for a failed job's final amount and refund state read - `client.jobs.status(request_id)`. + may still be an estimate. +- A refund is booked before `job.failed` is sent, so its `refunded` reports it (`refunded=False` can also + mean the job was never charged). `client.jobs.status(request_id)` remains the authoritative record. ## Upgrading to 0.5.0 diff --git a/docs/api-reference.md b/docs/api-reference.md index d6f1bc9..61b88d9 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -14,6 +14,7 @@ Install: `pip install deapi-sdk` (`pip install deapi` is an unrelated package). - [Resource: video](#resource-video) - [Resource: transcription](#resource-transcription) - [Resource: chat](#resource-chat) +- [Resource: web](#resource-web) - [Resource: embeddings](#resource-embeddings) - [Resource: ocr](#resource-ocr) - [Resource: prompts](#resource-prompts) @@ -63,7 +64,7 @@ account and key-management endpoints. | `client.websocket_config()` | `WebSocketConfig` | Realtime WebSocket parameters of the account (`GET /websocket`, any key) | | `client.close()` | `None` | Close the HTTP connection | -**Resources:** `images`, `audio`, `video`, `transcription`, `chat`, `embeddings`, `ocr`, `prompts`, +**Resources:** `images`, `audio`, `video`, `transcription`, `chat`, `web`, `embeddings`, `ocr`, `prompts`, `models`, `jobs`, `account` and `keys`. ```python @@ -228,7 +229,9 @@ job = client.audio.compose( ``` `compose_price()`: `model`, `duration`, and optionally `inference_steps`, `guidance_scale`, -`caption`, `lyrics`, `bpm`, `keyscale`, `timesignature`, `vocal_language`. +`caption`, `lyrics`, `bpm`, `keyscale`, `timesignature`, `vocal_language`. It quotes the requested +`duration`; the job is billed by the length actually generated, so a song that ends early costs less +than the quote (never more). Read the final charge from the finished job (`JobResult.price_amount`). --- @@ -547,6 +550,65 @@ The official `openai` package also works against `https://oai.deapi.ai/v1` with --- +## Resource: web + +Web search and page contents, returned in the response (no job, no polling). Web search and contents are in limited availability; accounts without access get a 404, +raised as `WebSearchUnavailableError` (a `NotFoundError`). + +```python +results = client.web.search( + *, + query: str, + goal: str | None = None, # what the results are for (ranking only) + mode: "quick" | "balanced" | None = None, # API default "balanced"; quick: no summary / freshness_hours + limit: int | None = None, # API default 10 + only_domains: Sequence[str] | None = None, + skip_domains: Sequence[str] | None = None, + published_after: str | date | datetime | None = None, + published_before: str | date | datetime | None = None, + country: str | None = None, # ISO 3166-1 alpha-2; a ranking preference + text: bool | int | dict | None = None, # True, a max_length, or {"max_length": N} + excerpts: bool | str | dict | None = None, # True, a query, or {"query": "..."} + summary: bool | str | dict | None = None, # True, a query, or {"query": "..."} (balanced only) + freshness_hours: int | None = None, # re-fetch copies older than this; 0 = live +) -> WebResults + +results = client.web.contents( + *, + urls: Sequence[str], # http(s), no duplicates + text=None, excerpts=None, summary=None, # at least one (ValueError otherwise); same forms as above + freshness_hours: int | None = None, +) -> WebResults + +client.web.search_price(...same as search...) -> PriceResult # free +client.web.contents_price(...same as contents...) -> PriceResult # assumes every page can be read +``` + +For `search()`, `text` / `excerpts` / `summary` / `freshness_hours` are sent as the API's `include`. + +```python +class WebResults(BaseModel): # extra fields allowed + request_id: str # identifies the call (usage report, support) + cost: float # USD charged; 0 when not charged + results: list[WebPage] + +class WebPage(BaseModel): # fields a page does not provide are None + url: str + status: str | None # contents: ok | not_found | target_error | timeout | blocked + # | unsupported_url | unknown (not-ok pages are not charged) + title, published_at, author, image, favicon: str | None + text: str | None; excerpts: list[str] | None; summary: str | None + ok: bool # property: status is None or "ok" +``` + +A failed call is not charged. Retries follow the POST policy: a 429 is retried (a refused call is not +charged), a timeout or a 5xx is never resent. Errors: 404 `WebSearchUnavailableError`, 422 `ValidationError` (`code` +`content_rejected` for a query refused by the content policy) or `InsufficientBalanceError`, 429 +`RateLimitError` (`code` `concurrency_limited`: too many web calls in progress), 503 `ServerError` +(`code` `capacity` | `timeout` | `unavailable` | `upstream_error`). + +--- + ## Resource: embeddings ```python @@ -800,6 +862,8 @@ class JobResult(BaseModel): metadata: dict | None prompt_boosted: bool | None prompt_boost: PromptBoost | None + price_amount: float | None # property: price.amount (or a bare number); the final charge once done + price_is_estimated: bool | None # property: price.is_estimated class JobStatusEvent(BaseModel): # realtime status event request_id: str @@ -854,6 +918,8 @@ DeapiError # .message .status_code .body .code │ ├── InsufficientPermissionsError # 403 insufficient_permissions │ └── AccountSuspendedError # 403 without a code ├── NotFoundError # 404 +│ └── WebSearchUnavailableError # 404 from client.web (no access to web search) +├── ModelRetiredError # 410 model_retired; .retired_at .replacement (other 410s: DeapiError) ├── PayloadTooLargeError # 413 ├── ValidationError # 422 .errors │ ├── InsufficientBalanceError # 422 insufficient_balance - the ACCOUNT is out of credit @@ -878,6 +944,10 @@ Specific attributes: class ValidationError(DeapiError): errors: dict[str, list[str]] # {"field": ["message", ...]} +class ModelRetiredError(DeapiError): + retired_at: str | None # ISO date + replacement: str | None # model slug to use instead, when there is one + class KeyLimitExceededError(PaymentRequiredError): limit: float | None; used: float | None; remaining: float | None resets_at: str | None # ISO datetime or None @@ -971,12 +1041,13 @@ class WebhookEventData(BaseModel): # unknown extra fields are kept (model_ex completed_at: str | None # job.completed result_url: str | None # job.completed processing_time_ms: int | None # job.completed - price: JobPrice | None # job.completed, job.failed (on failure: read jobs.status for the final amount) + price: JobPrice | None # job.completed, job.failed (on failure: the charge before the refund) failed_at: str | None # job.failed error_code: str | None # job.failed: WORKER_TIMEOUT | WORKER_ERROR | PROCESSING_ERROR error_reason: str | None # job.failed: open list, e.g. SOURCE_PRIVATE, TIMEOUT retryable: bool | None # job.failed: resubmitting the same request could succeed - refunded: bool | None # job.failed: the upfront charge was returned + refunded: bool | None # job.failed: the charge was returned (booked before the webhook is sent; + # False can also mean it was never charged). jobs.status is authoritative. ``` `construct_event()` rejects bad signatures and timestamps outside `tolerance`, but an identical diff --git a/src/deapi_sdk/__init__.py b/src/deapi_sdk/__init__.py index 0a0a69a..1af3eff 100644 --- a/src/deapi_sdk/__init__.py +++ b/src/deapi_sdk/__init__.py @@ -19,6 +19,7 @@ IpNotAllowedError, JobTimeoutError, KeyLimitExceededError, + ModelRetiredError, NetworkError, NotFoundError, PayloadTooLargeError, @@ -29,6 +30,7 @@ ServerError, SyncTranscriptionUnavailableError, ValidationError, + WebSearchUnavailableError, ) from deapi_sdk._polling import AsyncJob, AsyncJobs, Job, Jobs from deapi_sdk._realtime import AsyncRealtime, Realtime @@ -63,6 +65,7 @@ ) from deapi_sdk.types.transcription import SyncTranscriptionResult from deapi_sdk.types.video import VideoDescription, VideoEvent, parse_video_description +from deapi_sdk.types.web import WebPage, WebResults from deapi_sdk.types.websocket import WebSocketConfig, WebSocketConnection from deapi_sdk.webhook import ( InvalidSignatureError, @@ -87,6 +90,7 @@ def _attach_resources_sync(client: DeapiClient) -> None: Prompts, Transcription, Video, + Web, ) client.images = Images(client._http_client) client.models = Models(client._http_client) @@ -94,6 +98,7 @@ def _attach_resources_sync(client: DeapiClient) -> None: client.chat = Chat(client._http_client) client.transcription = Transcription(client._http_client) client.video = Video(client._http_client) + client.web = Web(client._http_client) client.embeddings = Embeddings(client._http_client) client.prompts = Prompts(client._http_client) client.ocr = OCR(client._http_client) @@ -115,6 +120,7 @@ def _attach_resources_async(client: AsyncDeapiClient) -> None: AsyncPrompts, AsyncTranscription, AsyncVideo, + AsyncWeb, ) client.images = AsyncImages(client._http_client) client.models = AsyncModels(client._http_client) @@ -122,6 +128,7 @@ def _attach_resources_async(client: AsyncDeapiClient) -> None: client.chat = AsyncChat(client._http_client) client.transcription = AsyncTranscription(client._http_client) client.video = AsyncVideo(client._http_client) + client.web = AsyncWeb(client._http_client) client.embeddings = AsyncEmbeddings(client._http_client) client.prompts = AsyncPrompts(client._http_client) client.ocr = AsyncOCR(client._http_client) @@ -160,6 +167,7 @@ class DeapiClient: chat: Any transcription: Any video: Any + web: Any embeddings: Any prompts: Any ocr: Any @@ -274,6 +282,7 @@ class AsyncDeapiClient: chat: Any transcription: Any video: Any + web: Any embeddings: Any prompts: Any ocr: Any @@ -411,6 +420,8 @@ async def __aexit__(self, *args: Any) -> None: "TranscriptWord", "VideoDescription", "VideoEvent", + "WebPage", + "WebResults", "parse_transcript", "parse_video_description", "transcript_output_format", @@ -425,6 +436,7 @@ async def __aexit__(self, *args: Any) -> None: "IpNotAllowedError", "JobTimeoutError", "KeyLimitExceededError", + "ModelRetiredError", "PayloadTooLargeError", "PaymentRequiredError", "PermissionDeniedError", @@ -434,6 +446,7 @@ async def __aexit__(self, *args: Any) -> None: "ServerError", "SyncTranscriptionUnavailableError", "ValidationError", + "WebSearchUnavailableError", # Webhook "InvalidSignatureError", "WebhookEvent", diff --git a/src/deapi_sdk/_client.py b/src/deapi_sdk/_client.py index 002e822..a78339c 100644 --- a/src/deapi_sdk/_client.py +++ b/src/deapi_sdk/_client.py @@ -21,6 +21,7 @@ InsufficientPermissionsError, IpNotAllowedError, KeyLimitExceededError, + ModelRetiredError, NetworkError, NotFoundError, PayloadTooLargeError, @@ -165,6 +166,16 @@ def _raise_for_status(self, response: httpx.Response) -> None: if status == 404: raise NotFoundError(message, **kwargs) + if status == 410 and (code == "model_retired" or "retired_at" in body): + retired_at = body.get("retired_at") + replacement = body.get("replacement") + raise ModelRetiredError( + message, + **kwargs, + retired_at=retired_at if isinstance(retired_at, str) else None, + replacement=replacement if isinstance(replacement, str) else None, + ) + if status == 413: raise PayloadTooLargeError(message, **kwargs) diff --git a/src/deapi_sdk/_constants.py b/src/deapi_sdk/_constants.py index 9593c4d..597b803 100644 --- a/src/deapi_sdk/_constants.py +++ b/src/deapi_sdk/_constants.py @@ -43,6 +43,11 @@ # Image-to-text (OCR) "img2txt": "images/ocr", "img2txt_price": "images/ocr/price", + # Web search and contents (synchronous; bare responses, no `data` wrapper) + "web_search": "web/search", + "web_search_price": "web/search/price", + "web_contents": "web/contents", + "web_contents_price": "web/contents/price", # Prompts (one prompt booster endpoint, selected by `type`) "prompts_enhance": "prompts/enhancements", "prompts_enhance_price": "prompts/enhancements/price", diff --git a/src/deapi_sdk/_exceptions.py b/src/deapi_sdk/_exceptions.py index 775d695..3ccf8bb 100644 --- a/src/deapi_sdk/_exceptions.py +++ b/src/deapi_sdk/_exceptions.py @@ -81,6 +81,39 @@ class NotFoundError(DeapiError): """404 — Resource not found.""" +class WebSearchUnavailableError(NotFoundError): + """404 from a web search or web contents endpoint: web search is not available for this account. + + Web search and contents are in limited availability; accounts without access get a 404. + """ + + +class ModelRetiredError(DeapiError): + """410 ``model_retired`` — the requested model has been retired. + + Raised for a 410 whose ``code`` is ``model_retired`` (or whose body has ``retired_at``); any + other 410 stays a plain ``DeapiError``. + + ``message`` is the API's notice (it names the replacement when there is one); + ``retired_at`` (ISO date) and ``replacement`` (model slug) are taken from the response + when present. Nothing was charged and no job was created. + """ + + def __init__( + self, + message: str, + *, + status_code: int | None = 410, + body: dict | None = None, # type: ignore[type-arg] + code: str | None = None, + retired_at: str | None = None, + replacement: str | None = None, + ) -> None: + super().__init__(message, status_code=status_code, body=body, code=code) + self.retired_at = retired_at + self.replacement = replacement + + class PayloadTooLargeError(DeapiError): """413 — Uploaded payload exceeds the size limit.""" diff --git a/src/deapi_sdk/resources/__init__.py b/src/deapi_sdk/resources/__init__.py index 2db802f..6fb0335 100644 --- a/src/deapi_sdk/resources/__init__.py +++ b/src/deapi_sdk/resources/__init__.py @@ -11,6 +11,7 @@ from deapi_sdk.resources.prompts import AsyncPrompts, Prompts from deapi_sdk.resources.transcription import AsyncTranscription, Transcription from deapi_sdk.resources.video import AsyncVideo, Video +from deapi_sdk.resources.web import AsyncWeb, Web __all__ = [ "OCR", @@ -26,6 +27,7 @@ "AsyncPrompts", "AsyncTranscription", "AsyncVideo", + "AsyncWeb", "Audio", "Chat", "Embeddings", @@ -35,4 +37,5 @@ "Prompts", "Transcription", "Video", + "Web", ] diff --git a/src/deapi_sdk/resources/audio.py b/src/deapi_sdk/resources/audio.py index 8ae62a3..cc60895 100644 --- a/src/deapi_sdk/resources/audio.py +++ b/src/deapi_sdk/resources/audio.py @@ -141,7 +141,11 @@ def compose_price( timesignature: int | None = None, vocal_language: str | None = None, ) -> PriceResult: - """Calculate price for music generation (only model, duration and steps affect the price). + """Estimate the price of music generation (only model, duration and steps affect the price). + + The quote is for the requested ``duration``. A model may end the song early; the job is then + charged for the length actually generated, so the final charge can be lower than the quote, + never higher. Read it from the finished job: ``job.wait().price_amount``. Unset ``inference_steps`` are taken from the model's ``info.defaults`` (one catalogue request per client, cached; disable with ``fill_model_defaults=False``). @@ -295,7 +299,11 @@ async def compose_price( timesignature: int | None = None, vocal_language: str | None = None, ) -> PriceResult: - """Calculate price for music generation (only model, duration and steps affect the price). + """Estimate the price of music generation (only model, duration and steps affect the price). + + The quote is for the requested ``duration``. A model may end the song early; the job is then + charged for the length actually generated, so the final charge can be lower than the quote, + never higher. Read it from the finished job: ``job.wait().price_amount``. Unset ``inference_steps`` are taken from the model's ``info.defaults`` (one catalogue request per client, cached; disable with ``fill_model_defaults=False``). diff --git a/src/deapi_sdk/resources/web.py b/src/deapi_sdk/resources/web.py new file mode 100644 index 0000000..62cde7d --- /dev/null +++ b/src/deapi_sdk/resources/web.py @@ -0,0 +1,336 @@ +"""Web search and web contents: synchronous, results in the response (no job, no polling). + +Web search and contents are in limited availability; accounts without access get a 404, +raised as ``WebSearchUnavailableError``. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from datetime import date, datetime +from typing import Any, TypeAlias + +from deapi_sdk._client import AsyncHTTPClient, SyncHTTPClient +from deapi_sdk._exceptions import NotFoundError, WebSearchUnavailableError +from deapi_sdk._payload import drop_none +from deapi_sdk.types.common import PriceResult +from deapi_sdk.types.web import WebResults, WebSearchMode + +# ``text``: True, a max_length in characters, or the API's object ({"max_length": N}). +TextOption: TypeAlias = bool | int | Mapping[str, Any] +# ``excerpts`` / ``summary``: True, a query to steer them, or the API's object ({"query": "..."}). +QueryOption: TypeAlias = bool | str | Mapping[str, Any] +DateInput: TypeAlias = str | date | datetime + + +def _text_option(value: TextOption | None) -> Any: + if value is None or isinstance(value, bool): + return value + if isinstance(value, int): + return {"max_length": value} + return dict(value) + + +def _query_option(value: QueryOption | None) -> Any: + if value is None or isinstance(value, bool): + return value + if isinstance(value, str): + return {"query": value} + return dict(value) + + +def _date(value: DateInput | None) -> str | None: + if value is None or isinstance(value, str): + return value + return value.isoformat() + + +def _content_options( + text: TextOption | None, + excerpts: QueryOption | None, + summary: QueryOption | None, + freshness_hours: int | None, +) -> dict[str, Any]: + return drop_none({ + "text": _text_option(text), + "excerpts": _query_option(excerpts), + "summary": _query_option(summary), + "freshness_hours": freshness_hours, + }) + + +def _search_body( + *, + query: str, + goal: str | None, + mode: WebSearchMode | str | None, + limit: int | None, + only_domains: Sequence[str] | None, + skip_domains: Sequence[str] | None, + published_after: DateInput | None, + published_before: DateInput | None, + country: str | None, + text: TextOption | None, + excerpts: QueryOption | None, + summary: QueryOption | None, + freshness_hours: int | None, +) -> dict[str, Any]: + body = drop_none({ + "query": query, + "goal": goal, + "mode": mode, + "limit": limit, + "only_domains": list(only_domains) if only_domains is not None else None, + "skip_domains": list(skip_domains) if skip_domains is not None else None, + "published_after": _date(published_after), + "published_before": _date(published_before), + "country": country, + }) + include = _content_options(text, excerpts, summary, freshness_hours) + if include: + body["include"] = include + return body + + +def _contents_body( + *, + urls: Sequence[str], + text: TextOption | None, + excerpts: QueryOption | None, + summary: QueryOption | None, + freshness_hours: int | None, +) -> dict[str, Any]: + if isinstance(urls, str): + raise TypeError("'urls' must be a list of URLs, not a single string.") + options = _content_options(text, excerpts, summary, freshness_hours) + if not any(options.get(k) for k in ("text", "excerpts", "summary")): + raise ValueError("Request at least one of 'text', 'excerpts' or 'summary' (each is billed per page).") + return {"urls": list(urls), **options} + + +def _unavailable(exc: NotFoundError) -> WebSearchUnavailableError: + return WebSearchUnavailableError(exc.message, status_code=exc.status_code, body=exc.body, code=exc.code) + + +class Web: + """``client.web``: web search and page contents, returned in the response. + + Web search and contents are in limited availability; accounts without access get a 404, + raised as ``WebSearchUnavailableError`` (a ``NotFoundError``). A call that fails is not charged. + Like other POSTs, a call is retried after a 429 (a refused call is not charged) or when the + connection was never established, and never resent after a timeout or a 5xx. + """ + + def __init__(self, client: SyncHTTPClient) -> None: + self._client = client + + def _post(self, operation: str, body: dict[str, Any]) -> Any: + try: + return self._client.post(self._client._resolve_endpoint(operation), json=body) + except NotFoundError as exc: + raise _unavailable(exc) from exc + + def search( + self, + *, + query: str, + goal: str | None = None, + mode: WebSearchMode | str | None = None, + limit: int | None = None, + only_domains: Sequence[str] | None = None, + skip_domains: Sequence[str] | None = None, + published_after: DateInput | None = None, + published_before: DateInput | None = None, + country: str | None = None, + text: TextOption | None = None, + excerpts: QueryOption | None = None, + summary: QueryOption | None = None, + freshness_hours: int | None = None, + ) -> WebResults: + """Search the web (``POST /web/search``) and return ranked results with ``cost``. + + Args: + query: What to search for, in natural language. + goal: What the results are for; helps ranking, not searched for itself. + mode: ``"balanced"`` (API default) or ``"quick"`` (faster and cheaper; no ``summary`` + or ``freshness_hours``). + limit: Maximum number of results (API default 10). + only_domains / skip_domains: Bare hostnames to restrict to / exclude. + published_after / published_before: ISO 8601 string, ``date`` or ``datetime``. + country: ISO 3166-1 alpha-2 code; a ranking preference, not a filter. + text: Each page's clean text: ``True``, or a ``max_length`` in characters. + excerpts: The most relevant passages: ``True``, or a query to steer them. + summary: An AI-written summary per result: ``True``, or a query to focus it. + freshness_hours: Re-fetch a stored copy older than this many hours (``0`` = live). + + ``text`` / ``excerpts`` / ``summary`` / ``freshness_hours`` are sent as the API's ``include``. + Quote the same arguments with ``search_price()``. Never resent after a timeout or a 5xx. + """ + body = _search_body( + query=query, goal=goal, mode=mode, limit=limit, only_domains=only_domains, + skip_domains=skip_domains, published_after=published_after, published_before=published_before, + country=country, text=text, excerpts=excerpts, summary=summary, freshness_hours=freshness_hours, + ) + return WebResults.model_validate(self._post("web_search", body)) + + def search_price( + self, + *, + query: str, + goal: str | None = None, + mode: WebSearchMode | str | None = None, + limit: int | None = None, + only_domains: Sequence[str] | None = None, + skip_domains: Sequence[str] | None = None, + published_after: DateInput | None = None, + published_before: DateInput | None = None, + country: str | None = None, + text: TextOption | None = None, + excerpts: QueryOption | None = None, + summary: QueryOption | None = None, + freshness_hours: int | None = None, + ) -> PriceResult: + """Quote ``search()`` with the same arguments (free). The price depends on ``mode``, ``limit`` + and ``summary``.""" + body = _search_body( + query=query, goal=goal, mode=mode, limit=limit, only_domains=only_domains, + skip_domains=skip_domains, published_after=published_after, published_before=published_before, + country=country, text=text, excerpts=excerpts, summary=summary, freshness_hours=freshness_hours, + ) + resp = self._post("web_search_price", body) + return PriceResult.model_validate(resp.get("data", resp)) + + def contents( + self, + *, + urls: Sequence[str], + text: TextOption | None = None, + excerpts: QueryOption | None = None, + summary: QueryOption | None = None, + freshness_hours: int | None = None, + ) -> WebResults: + """Read known pages (``POST /web/contents``): text, excerpts and/or summary per URL. + + Results come back in the order of ``urls``, each with a ``status``; pages that are not + ``ok`` are not charged. Request at least one of ``text``, ``excerpts`` or ``summary`` + (``ValueError`` otherwise; each is billed per page read). + + Args: + urls: http(s) URLs, no duplicates. + text: Each page's clean text: ``True``, or a ``max_length`` in characters. + excerpts: The most relevant passages: ``True``, or a query to steer them. + summary: An AI-written summary: ``True``, or a query to focus it. + freshness_hours: Re-fetch a stored copy older than this many hours (``0`` = live). + + Quote it with ``contents_price()``. Never resent after a timeout or a 5xx. + """ + body = _contents_body(urls=urls, text=text, excerpts=excerpts, summary=summary, freshness_hours=freshness_hours) + return WebResults.model_validate(self._post("web_contents", body)) + + def contents_price( + self, + *, + urls: Sequence[str], + text: TextOption | None = None, + excerpts: QueryOption | None = None, + summary: QueryOption | None = None, + freshness_hours: int | None = None, + ) -> PriceResult: + """Quote ``contents()`` with the same arguments (free), assuming every page can be read. + + The actual ``cost`` can be lower (unread pages are not charged), never higher. + """ + body = _contents_body(urls=urls, text=text, excerpts=excerpts, summary=summary, freshness_hours=freshness_hours) + resp = self._post("web_contents_price", body) + return PriceResult.model_validate(resp.get("data", resp)) + + +class AsyncWeb: + """``client.web`` on ``AsyncDeapiClient``. See ``Web``.""" + + def __init__(self, client: AsyncHTTPClient) -> None: + self._client = client + + async def _post(self, operation: str, body: dict[str, Any]) -> Any: + try: + return await self._client.post(self._client._resolve_endpoint(operation), json=body) + except NotFoundError as exc: + raise _unavailable(exc) from exc + + async def search( + self, + *, + query: str, + goal: str | None = None, + mode: WebSearchMode | str | None = None, + limit: int | None = None, + only_domains: Sequence[str] | None = None, + skip_domains: Sequence[str] | None = None, + published_after: DateInput | None = None, + published_before: DateInput | None = None, + country: str | None = None, + text: TextOption | None = None, + excerpts: QueryOption | None = None, + summary: QueryOption | None = None, + freshness_hours: int | None = None, + ) -> WebResults: + """Search the web. See ``Web.search``.""" + body = _search_body( + query=query, goal=goal, mode=mode, limit=limit, only_domains=only_domains, + skip_domains=skip_domains, published_after=published_after, published_before=published_before, + country=country, text=text, excerpts=excerpts, summary=summary, freshness_hours=freshness_hours, + ) + return WebResults.model_validate(await self._post("web_search", body)) + + async def search_price( + self, + *, + query: str, + goal: str | None = None, + mode: WebSearchMode | str | None = None, + limit: int | None = None, + only_domains: Sequence[str] | None = None, + skip_domains: Sequence[str] | None = None, + published_after: DateInput | None = None, + published_before: DateInput | None = None, + country: str | None = None, + text: TextOption | None = None, + excerpts: QueryOption | None = None, + summary: QueryOption | None = None, + freshness_hours: int | None = None, + ) -> PriceResult: + """Quote ``search()``. See ``Web.search_price``.""" + body = _search_body( + query=query, goal=goal, mode=mode, limit=limit, only_domains=only_domains, + skip_domains=skip_domains, published_after=published_after, published_before=published_before, + country=country, text=text, excerpts=excerpts, summary=summary, freshness_hours=freshness_hours, + ) + resp = await self._post("web_search_price", body) + return PriceResult.model_validate(resp.get("data", resp)) + + async def contents( + self, + *, + urls: Sequence[str], + text: TextOption | None = None, + excerpts: QueryOption | None = None, + summary: QueryOption | None = None, + freshness_hours: int | None = None, + ) -> WebResults: + """Read known pages. See ``Web.contents``.""" + body = _contents_body(urls=urls, text=text, excerpts=excerpts, summary=summary, freshness_hours=freshness_hours) + return WebResults.model_validate(await self._post("web_contents", body)) + + async def contents_price( + self, + *, + urls: Sequence[str], + text: TextOption | None = None, + excerpts: QueryOption | None = None, + summary: QueryOption | None = None, + freshness_hours: int | None = None, + ) -> PriceResult: + """Quote ``contents()``. See ``Web.contents_price``.""" + body = _contents_body(urls=urls, text=text, excerpts=excerpts, summary=summary, freshness_hours=freshness_hours) + resp = await self._post("web_contents_price", body) + return PriceResult.model_validate(resp.get("data", resp)) diff --git a/src/deapi_sdk/types/__init__.py b/src/deapi_sdk/types/__init__.py index 170abfa..4186dc7 100644 --- a/src/deapi_sdk/types/__init__.py +++ b/src/deapi_sdk/types/__init__.py @@ -45,6 +45,7 @@ VideoEvent, parse_video_description, ) +from deapi_sdk.types.web import WebPage, WebResults, WebSearchMode from deapi_sdk.types.websocket import WebSocketConfig, WebSocketConnection __all__ = [ @@ -95,6 +96,9 @@ "UsageReport", "VideoDescription", "VideoEvent", + "WebPage", + "WebResults", + "WebSearchMode", "WebSocketConfig", "WebSocketConnection", "parse_video_description", diff --git a/src/deapi_sdk/types/common.py b/src/deapi_sdk/types/common.py index 8ddeba9..97708c8 100644 --- a/src/deapi_sdk/types/common.py +++ b/src/deapi_sdk/types/common.py @@ -44,6 +44,31 @@ class JobResult(BaseModel): model_config = {"extra": "allow"} + @property + def price_amount(self) -> float | None: + """The job's charge in USD (``price.amount``, or ``price`` when it is a bare number), else None. + + On a finished job this is the amount actually charged, e.g. for text-to-music the price of the + length that was generated, which can be lower than the quote. See ``price_is_estimated``. + """ + if isinstance(self.price, bool): + return None + if isinstance(self.price, (int, float)): + return float(self.price) + if isinstance(self.price, dict): + amount = self.price.get("amount") + if isinstance(amount, (int, float)) and not isinstance(amount, bool): + return float(amount) + return None + + @property + def price_is_estimated(self) -> bool | None: + """``price.is_estimated``: True while the charge has not settled yet; None when not reported.""" + if isinstance(self.price, dict): + value = self.price.get("is_estimated") + return value if isinstance(value, bool) else None + return None + class JobStatusEvent(BaseModel): """A real-time job status update delivered over WebSocket (``request.status.updated``). diff --git a/src/deapi_sdk/types/web.py b/src/deapi_sdk/types/web.py new file mode 100644 index 0000000..affe660 --- /dev/null +++ b/src/deapi_sdk/types/web.py @@ -0,0 +1,52 @@ +"""Web search and web contents results.""" + +from __future__ import annotations + +from typing import Literal, TypeAlias + +from pydantic import BaseModel, ConfigDict + +WebSearchMode: TypeAlias = Literal["quick", "balanced"] + + +class WebPage(BaseModel): + """One page of a web search or web contents call. + + Fields the page does not provide are left out by the API, so they are None here. + ``status`` is set on web contents results: ``ok`` (content returned), ``not_found``, + ``target_error``, ``timeout``, ``blocked``, ``unsupported_url`` or ``unknown``; a page that is + not ``ok`` carries only ``url`` and ``status`` and is not charged. ``text``, ``excerpts`` and + ``summary`` are present when requested. + """ + + model_config = ConfigDict(extra="allow") + + url: str + status: str | None = None + title: str | None = None + published_at: str | None = None + author: str | None = None + image: str | None = None + favicon: str | None = None + text: str | None = None + excerpts: list[str] | None = None + summary: str | None = None + + @property + def ok(self) -> bool: + """True unless the page has a ``status`` other than ``ok`` (search results have no status).""" + return self.status in (None, "ok") + + +class WebResults(BaseModel): + """Result of ``client.web.search()`` / ``client.web.contents()``: no job, no polling. + + ``cost`` is what the call was charged in USD (``0`` when it was not charged). ``request_id`` + identifies the call in your usage report and for support. + """ + + model_config = ConfigDict(extra="allow") + + request_id: str + cost: float + results: list[WebPage] = [] diff --git a/src/deapi_sdk/webhook.py b/src/deapi_sdk/webhook.py index d5a1367..561ce5f 100644 --- a/src/deapi_sdk/webhook.py +++ b/src/deapi_sdk/webhook.py @@ -27,8 +27,9 @@ class WebhookEventData(BaseModel): ``job.processing`` sets ``started_at``; ``job.completed`` sets ``completed_at``, ``result_url``, ``processing_time_ms`` and ``price``; ``job.failed`` sets ``failed_at``, ``price`` and the failure fields. On ``job.completed`` the price may still be an - estimate (``is_estimated``); for the final amount and refund state of a failed job, - read the job status endpoint (``client.jobs.status(request_id)``). + estimate (``is_estimated``). A refund is booked before ``job.failed`` is sent, so its + ``refunded`` reports it; ``refunded=False`` can also mean the job was never charged. The job + status endpoint (``client.jobs.status(request_id)``) remains the authoritative record. ``error_reason`` is an open list: treat a value you do not recognise as ``PROCESSING_FAILED``, and branch on ``retryable`` to decide whether to resubmit. @@ -48,7 +49,7 @@ class WebhookEventData(BaseModel): error_code: str | None = None # WORKER_TIMEOUT | WORKER_ERROR | PROCESSING_ERROR error_reason: str | None = None # e.g. SOURCE_PRIVATE, TIMEOUT, CAPACITY_UNAVAILABLE (open list) retryable: bool | None = None - refunded: bool | None = None + refunded: bool | None = None # job.failed: the refund is booked before the webhook is sent model_config = {"extra": "allow"} diff --git a/tests/test_prod_compat.py b/tests/test_prod_compat.py new file mode 100644 index 0000000..484fd60 --- /dev/null +++ b/tests/test_prod_compat.py @@ -0,0 +1,116 @@ +"""Retired models (410), the final job price, and the job.failed refund state.""" + +from __future__ import annotations + +import httpx +import pytest +import respx + +from deapi_sdk import DeapiClient, DeapiError, JobResult, ModelRetiredError +from tests.conftest import TEST_BASE_URL + +RETIRED = { + "message": "Model OldModel has been retired. Use NewModel instead.", + "code": "model_retired", + "retired_at": "2026-11-30", + "replacement": "NewModel", +} + + +class TestModelRetired: + @respx.mock + def test_410_on_a_job(self, client: DeapiClient) -> None: + route = respx.post(f"{TEST_BASE_URL}/api/v2/images/generations").mock( + return_value=httpx.Response(410, json=RETIRED), + ) + with pytest.raises(ModelRetiredError) as info: + client.images.generate(prompt="a cat", model="OldModel", width=512, height=512, steps=4, seed=1) + + err = info.value + assert isinstance(err, DeapiError) + assert err.status_code == 410 + assert err.code == "model_retired" + assert err.message == RETIRED["message"] + assert err.retired_at == "2026-11-30" + assert err.replacement == "NewModel" + assert route.call_count == 1 # not retried + + @respx.mock + def test_410_on_a_price_quote_without_replacement(self, client: DeapiClient) -> None: + body = {**RETIRED, "message": "Model OldModel has been retired.", "replacement": None} + respx.post(f"{TEST_BASE_URL}/api/v2/audio/music/price").mock(return_value=httpx.Response(410, json=body)) + with pytest.raises(ModelRetiredError) as info: + client.audio.compose_price(model="OldModel", duration=30, inference_steps=8) + assert info.value.replacement is None + assert info.value.message == "Model OldModel has been retired." + + @respx.mock + def test_410_with_retired_at_but_no_code(self, client: DeapiClient) -> None: + body = {"message": "Retired.", "retired_at": "2026-11-30"} + respx.post(f"{TEST_BASE_URL}/api/v2/audio/music/price").mock(return_value=httpx.Response(410, json=body)) + with pytest.raises(ModelRetiredError) as info: + client.audio.compose_price(model="OldModel", duration=30, inference_steps=8) + assert info.value.retired_at == "2026-11-30" + assert info.value.code is None + + @respx.mock + @pytest.mark.parametrize( + "response", + [httpx.Response(410, text="Gone"), httpx.Response(410, json={"message": "Gone", "code": "other"})], + ) + def test_other_410_stays_generic(self, client: DeapiClient, response: httpx.Response) -> None: + respx.get(f"{TEST_BASE_URL}/api/v2/account/balance").mock(return_value=response) + with pytest.raises(DeapiError) as info: + client.balance() + assert type(info.value) is DeapiError + assert info.value.status_code == 410 + assert info.value.message == "Gone" + + + @respx.mock + def test_410_from_the_openai_compatible_api(self) -> None: + # Retired chat models answer 410 in the OpenAI error shape, with the code inside "error". + url = "https://oai.test.deapi.ai/v1/chat/completions" + route = respx.post(url).mock(return_value=httpx.Response(410, json={"error": { + "message": "Model old-chat has been retired.", "type": "invalid_request_error", + "param": "model", "code": "model_retired", + }})) + client = DeapiClient(api_key="k", oai_base_url="https://oai.test.deapi.ai/v1") + with client, pytest.raises(ModelRetiredError) as info: + client.chat.completions.create(model="old-chat", messages=[{"role": "user", "content": "x"}]) + assert info.value.message == "Model old-chat has been retired." + assert info.value.code == "model_retired" + assert route.call_count == 1 + + +class TestJobPrice: + @pytest.mark.parametrize( + ("price", "amount", "estimated"), + [ + ({"amount": 0.0123, "is_estimated": False}, 0.0123, False), + ({"amount": 0.05, "is_estimated": True}, 0.05, True), + (0.02, 0.02, None), + (None, None, None), + ({"is_estimated": False}, None, False), + ], + ) + def test_price_helpers(self, price: object, amount: float | None, estimated: bool | None) -> None: + result = JobResult.model_validate({"status": "done", "price": price}) + assert result.price_amount == amount + assert result.price_is_estimated is estimated + + @respx.mock + def test_music_job_reports_the_charged_amount(self, client: DeapiClient) -> None: + # Quoted for 60 s; the song ended early, so the finished job carries the lower charge. + respx.post(f"{TEST_BASE_URL}/api/v2/audio/music/price").mock( + return_value=httpx.Response(200, json={"data": {"price": 0.06}}), + ) + respx.get(f"{TEST_BASE_URL}/api/v2/jobs/music-1").mock(return_value=httpx.Response(200, json={"data": { + "status": "done", "result_url": "https://cdn.example/song.mp3", + "price": {"amount": 0.041, "is_estimated": False}, + }})) + quote = client.audio.compose_price(model="SomeMusicModel", duration=60, inference_steps=8) + result = client.jobs.get("music-1").status() + assert quote.price == 0.06 + assert result.price_amount == 0.041 + assert result.price_is_estimated is False diff --git a/tests/test_web.py b/tests/test_web.py new file mode 100644 index 0000000..10ad722 --- /dev/null +++ b/tests/test_web.py @@ -0,0 +1,269 @@ +from __future__ import annotations + +import json +from datetime import UTC, date, datetime + +import httpx +import pytest +import respx + +from deapi_sdk import ( + AsyncDeapiClient, + DeapiClient, + InsufficientBalanceError, + NotFoundError, + RateLimitError, + ServerError, + ValidationError, + WebPage, + WebResults, + WebSearchUnavailableError, +) +from tests.conftest import TEST_BASE_URL + +SEARCH_URL = f"{TEST_BASE_URL}/api/v2/web/search" +SEARCH_PRICE_URL = f"{TEST_BASE_URL}/api/v2/web/search/price" +CONTENTS_URL = f"{TEST_BASE_URL}/api/v2/web/contents" +CONTENTS_PRICE_URL = f"{TEST_BASE_URL}/api/v2/web/contents/price" + +# Bare responses (no "data" wrapper), as the web endpoints return them. +SEARCH_RESPONSE = { + "request_id": "dc260284-883c-44be-b61b-ef82a3486a50", + "cost": 0.012, + "results": [ + { + "url": "https://example.com/flux-2", + "title": "FLUX.2", + "published_at": "2025-11-25T15:11:07+00:00", + "image": "https://example.com/og.png", + "text": "FLUX.2 ...", + "excerpts": ["FLUX.2 is designed for ..."], + "summary": "FLUX.2 introduces ...", + }, + {"url": "https://example.org/other", "title": "Other", "author": "Someone"}, + ], +} + +CONTENTS_RESPONSE = { + "request_id": "ddb2e452-de33-4eb3-9763-8d339794bc4a", + "cost": 0.0024, + "results": [ + {"url": "https://example.com", "status": "ok", "title": "Example", "text": "Hello", "summary": "A page"}, + {"url": "https://example.com/missing", "status": "not_found"}, + ], +} + + +class TestSearch: + @respx.mock + def test_search_minimal(self, client: DeapiClient) -> None: + route = respx.post(SEARCH_URL).mock(return_value=httpx.Response(200, json=SEARCH_RESPONSE)) + + results = client.web.search(query="FLUX.2 release") + + assert json.loads(route.calls.last.request.content) == {"query": "FLUX.2 release"} + assert isinstance(results, WebResults) + assert results.request_id == "dc260284-883c-44be-b61b-ef82a3486a50" + assert results.cost == 0.012 + first, second = results.results + assert isinstance(first, WebPage) + assert first.excerpts == ["FLUX.2 is designed for ..."] + assert first.summary == "FLUX.2 introduces ..." + assert first.status is None and first.ok + assert second.text is None and second.author == "Someone" + + @respx.mock + def test_search_all_options(self, client: DeapiClient) -> None: + route = respx.post(SEARCH_URL).mock(return_value=httpx.Response(200, json=SEARCH_RESPONSE)) + + client.web.search( + query="solid-state batteries", + goal="peer-reviewed sources", + mode="balanced", + limit=3, + only_domains=("arxiv.org",), + skip_domains=["example.com"], + published_after=date(2026, 1, 1), + published_before=datetime(2026, 6, 30, 12, 0, tzinfo=UTC), + country="PL", + text=2000, + excerpts=True, + summary="What is new?", + freshness_hours=24, + ) + + assert json.loads(route.calls.last.request.content) == { + "query": "solid-state batteries", + "goal": "peer-reviewed sources", + "mode": "balanced", + "limit": 3, + "only_domains": ["arxiv.org"], + "skip_domains": ["example.com"], + "published_after": "2026-01-01", + "published_before": "2026-06-30T12:00:00+00:00", + "country": "PL", + "include": { + "text": {"max_length": 2000}, + "excerpts": True, + "summary": {"query": "What is new?"}, + "freshness_hours": 24, + }, + } + + @respx.mock + def test_search_passes_api_objects_through(self, client: DeapiClient) -> None: + route = respx.post(SEARCH_URL).mock(return_value=httpx.Response(200, json=SEARCH_RESPONSE)) + client.web.search(query="q", mode="quick", text={"max_length": 5}, excerpts={"query": "x"}, summary=False) + assert json.loads(route.calls.last.request.content)["include"] == { + "text": {"max_length": 5}, "excerpts": {"query": "x"}, "summary": False, + } + + @respx.mock + def test_search_price(self, client: DeapiClient) -> None: + route = respx.post(SEARCH_PRICE_URL).mock(return_value=httpx.Response(200, json={"price": 0.0048})) + price = client.web.search_price(query="q", mode="quick", limit=10) + assert price.price == 0.0048 + assert json.loads(route.calls.last.request.content) == {"query": "q", "mode": "quick", "limit": 10} + + +class TestContents: + @respx.mock + def test_contents(self, client: DeapiClient) -> None: + route = respx.post(CONTENTS_URL).mock(return_value=httpx.Response(200, json=CONTENTS_RESPONSE)) + + results = client.web.contents( + urls=["https://example.com", "https://example.com/missing"], + text=2000, + summary="What does this company offer?", + freshness_hours=0, + ) + + assert json.loads(route.calls.last.request.content) == { + "urls": ["https://example.com", "https://example.com/missing"], + "text": {"max_length": 2000}, + "summary": {"query": "What does this company offer?"}, + "freshness_hours": 0, + } + assert results.cost == 0.0024 + ok, missing = results.results + assert ok.ok and ok.text == "Hello" + assert missing.status == "not_found" and not missing.ok and missing.text is None + + def test_contents_needs_a_content_type(self, client: DeapiClient) -> None: + with pytest.raises(ValueError, match="at least one of"): + client.web.contents(urls=["https://example.com"]) + with pytest.raises(ValueError, match="at least one of"): + client.web.contents(urls=["https://example.com"], text=False, freshness_hours=1) + with pytest.raises(TypeError, match="list of URLs"): + client.web.contents(urls="https://example.com", text=True) + + @respx.mock + def test_contents_price(self, client: DeapiClient) -> None: + route = respx.post(CONTENTS_PRICE_URL).mock(return_value=httpx.Response(200, json={"price": 0.0012})) + price = client.web.contents_price(urls=["https://example.com"], text=True) + assert price.price == 0.0012 + assert json.loads(route.calls.last.request.content) == {"urls": ["https://example.com"], "text": True} + + +class TestErrors: + @respx.mock + @pytest.mark.parametrize("url", [SEARCH_URL, SEARCH_PRICE_URL, CONTENTS_URL, CONTENTS_PRICE_URL]) + def test_404_is_unavailable(self, client: DeapiClient, url: str) -> None: + respx.post(url).mock(return_value=httpx.Response(404, json={"message": "Not Found"})) + with pytest.raises(WebSearchUnavailableError) as info: + if "search" in url: + (client.web.search_price if url.endswith("price") else client.web.search)(query="q") + else: + (client.web.contents_price if url.endswith("price") else client.web.contents)( + urls=["https://example.com"], text=True, + ) + assert isinstance(info.value, NotFoundError) + assert info.value.status_code == 404 + assert info.value.message == "Not Found" + + @respx.mock + def test_content_rejected_and_balance(self, client: DeapiClient) -> None: + respx.post(SEARCH_URL).mock(side_effect=[ + httpx.Response(422, json={"message": "Rejected by the content policy.", "code": "content_rejected"}), + httpx.Response(422, json={"message": "Not enough balance.", "code": "insufficient_balance"}), + ]) + with pytest.raises(ValidationError) as info: + client.web.search(query="q") + assert info.value.code == "content_rejected" + with pytest.raises(InsufficientBalanceError): + client.web.search(query="q") + + @respx.mock + def test_429_is_retried(self, monkeypatch: pytest.MonkeyPatch) -> None: + # A refused call is not charged, so a 429 is retried like on any other POST. + sleeps: list[float] = [] + monkeypatch.setattr("deapi_sdk._client.time.sleep", sleeps.append) + route = respx.post(SEARCH_URL).mock(side_effect=[ + httpx.Response(429, json={"message": "Too many web calls in progress.", "code": "concurrency_limited"}, + headers={"Retry-After": "2"}), + httpx.Response(200, json=SEARCH_RESPONSE), + ]) + with DeapiClient(api_key="k", base_url=TEST_BASE_URL) as client: + assert client.web.search(query="q").cost == 0.012 + assert route.call_count == 2 + assert sleeps == [2.0] + + @respx.mock + def test_429_error_after_retries(self) -> None: + respx.post(SEARCH_URL).mock(return_value=httpx.Response( + 429, json={"message": "Too many web calls in progress.", "code": "concurrency_limited"}, + headers={"Retry-After": "1"}, + )) + client = DeapiClient(api_key="k", base_url=TEST_BASE_URL, max_retries=0) + with client, pytest.raises(RateLimitError) as info: + client.web.search(query="q") + assert info.value.code == "concurrency_limited" + assert info.value.retry_after == 1.0 + + @respx.mock + def test_5xx_and_timeout_are_not_resent(self) -> None: + with DeapiClient(api_key="k", base_url=TEST_BASE_URL, max_retries=3) as client: + route = respx.post(CONTENTS_URL).mock(return_value=httpx.Response( + 503, json={"message": "The service is at capacity.", "code": "capacity"}, + )) + with pytest.raises(ServerError) as server_info: + client.web.contents(urls=["https://example.com"], text=True) + assert server_info.value.code == "capacity" + assert route.call_count == 1 + + route = respx.post(SEARCH_URL).mock(side_effect=httpx.ReadTimeout("slow")) + with pytest.raises(Exception, match="slow"): + client.web.search(query="q") + assert route.call_count == 1 + + @respx.mock + def test_price_quotes_keep_the_retry_policy(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr("deapi_sdk._client.time.sleep", lambda _s: None) + route = respx.post(SEARCH_PRICE_URL).mock(side_effect=[ + httpx.Response(429, json={"message": "slow down"}), + httpx.Response(200, json={"price": 0.0048}), + ]) + with DeapiClient(api_key="k", base_url=TEST_BASE_URL) as client: + assert client.web.search_price(query="q").price == 0.0048 + assert route.call_count == 2 + + +class TestAsyncWeb: + @respx.mock + async def test_async_search_and_contents(self, async_client: AsyncDeapiClient) -> None: + respx.post(SEARCH_URL).mock(return_value=httpx.Response(200, json=SEARCH_RESPONSE)) + respx.post(CONTENTS_URL).mock(return_value=httpx.Response(200, json=CONTENTS_RESPONSE)) + respx.post(SEARCH_PRICE_URL).mock(return_value=httpx.Response(200, json={"price": 0.0084})) + respx.post(CONTENTS_PRICE_URL).mock(return_value=httpx.Response(200, json={"price": 0.0036})) + + assert len((await async_client.web.search(query="q")).results) == 2 + assert (await async_client.web.contents(urls=["https://example.com"], excerpts=True)).cost == 0.0024 + assert (await async_client.web.search_price(query="q")).price == 0.0084 + assert (await async_client.web.contents_price(urls=["https://example.com"], text=True)).price == 0.0036 + + @respx.mock + async def test_async_unavailable(self, async_client: AsyncDeapiClient) -> None: + route = respx.post(SEARCH_URL).mock(return_value=httpx.Response(404)) + with pytest.raises(WebSearchUnavailableError): + await async_client.web.search(query="q") + assert route.call_count == 1 From 56a0aeb2de1dcf684965e7a841c611cb9e496d12 Mon Sep 17 00:00:00 2001 From: Dawid Wenderski Date: Sun, 29 Nov 2026 18:39:30 +0100 Subject: [PATCH 12/13] Add WebPage.reason for pages that could not be read The API adds "reason" (e.g. "fetch_failed") to some web contents results with status "unknown"; it is now a typed field instead of an extra. Co-Authored-By: Claude Opus 5.5 --- docs/api-reference.md | 1 + src/deapi_sdk/types/web.py | 1 + tests/test_web.py | 4 +++- 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/api-reference.md b/docs/api-reference.md index 61b88d9..cc8c9a7 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -596,6 +596,7 @@ class WebPage(BaseModel): # fields a page does not provide are None url: str status: str | None # contents: ok | not_found | target_error | timeout | blocked # | unsupported_url | unknown (not-ok pages are not charged) + reason: str | None # why a page could not be read, when given (e.g. "fetch_failed") title, published_at, author, image, favicon: str | None text: str | None; excerpts: list[str] | None; summary: str | None ok: bool # property: status is None or "ok" diff --git a/src/deapi_sdk/types/web.py b/src/deapi_sdk/types/web.py index affe660..4e6c5dd 100644 --- a/src/deapi_sdk/types/web.py +++ b/src/deapi_sdk/types/web.py @@ -23,6 +23,7 @@ class WebPage(BaseModel): url: str status: str | None = None + reason: str | None = None # why a page could not be read, when the API says (e.g. "fetch_failed") title: str | None = None published_at: str | None = None author: str | None = None diff --git a/tests/test_web.py b/tests/test_web.py index 10ad722..541ed4f 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -50,6 +50,7 @@ "results": [ {"url": "https://example.com", "status": "ok", "title": "Example", "text": "Hello", "summary": "A page"}, {"url": "https://example.com/missing", "status": "not_found"}, + {"url": "https://nonexistent.invalid/", "status": "unknown", "reason": "fetch_failed"}, ], } @@ -145,8 +146,9 @@ def test_contents(self, client: DeapiClient) -> None: "freshness_hours": 0, } assert results.cost == 0.0024 - ok, missing = results.results + ok, missing, unknown = results.results assert ok.ok and ok.text == "Hello" + assert unknown.status == "unknown" and unknown.reason == "fetch_failed" and not unknown.ok assert missing.status == "not_found" and not missing.ok and missing.text is None def test_contents_needs_a_content_type(self, client: DeapiClient) -> None: From df819373b8c3207f949c3ec07edb6e41455b3eb9 Mon Sep 17 00:00:00 2001 From: Dawid Wenderski Date: Mon, 30 Nov 2026 20:47:14 +0100 Subject: [PATCH 13/13] Release 0.7.0: fast transcription, chat, web search, prod compatibility Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- pyproject.toml | 2 +- src/deapi_sdk/_version.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fe1e59a..1c4717e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,7 @@ All notable changes to this project are documented in this file. Versions follow [Semantic Versioning](https://semver.org/) (pre-1.0: minor versions may contain breaking changes). -## Unreleased +## [0.7.0] - 2026-11-30 ### Added diff --git a/pyproject.toml b/pyproject.toml index 40c1519..87e39ed 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "deapi-sdk" -version = "0.6.1" +version = "0.7.0" description = "Official Python SDK for deAPI — distributed AI inference platform" readme = "README.md" license = "MIT" diff --git a/src/deapi_sdk/_version.py b/src/deapi_sdk/_version.py index 9e3ae3d..dd2d37b 100644 --- a/src/deapi_sdk/_version.py +++ b/src/deapi_sdk/_version.py @@ -1,3 +1,3 @@ from __future__ import annotations -__version__ = "0.6.1" +__version__ = "0.7.0"