From 693508533e54d30c1366979046bfd48dcc68bfaa Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:09:16 -0800 Subject: [PATCH 1/3] docs(sdk): update JavaScript SDK pages for fish-audio 0.2.0 - SDK reference: install (Node.js 20+, ESM and CommonJS), default model s2.1-pro, Backends without casts, speechToText.convert({ model }), realtime speech to text (convertRealtime: options, events, control methods, RealtimeSTTError, stopping the audio source), multi-speaker TTS, opus_bitrate in bps, File reference audio, upgrade notes. - Cookbooks and migration pages: select transcribe-1-pro with model. - Migrate from S1: 0.1.0 defaults to s1; 0.2.0 defaults to s2.1-pro. - SDK quickstart, TTS page, changelog, llms.txt, fish-audio-sdk skill. - tests/js: fish-audio ^0.2.0. Co-Authored-By: Claude Fable 5.2 --- .mintlify/skills/fish-audio-sdk/SKILL.md | 37 ++- .../fish-audio-sdk/references/errors.md | 12 +- .../fish-audio-sdk/references/installation.md | 4 +- .../references/speech-to-text.md | 43 ++- .../references/text-to-speech.md | 46 ++- .../references/voice-cloning.md | 2 +- .../sdk/javascript/api-reference.mdx | 276 ++++++++++++++++-- developer-guide/getting-started/changelog.mdx | 10 + .../models-pricing/migrate-from-s1.mdx | 2 +- .../migrate-from-transcribe-1.mdx | 9 +- .../batch-transcribe-with-language-hint.mdx | 8 +- .../cookbook/transcribe-to-captions.mdx | 6 +- .../sdk-guide/cookbook/voice-agent-loop.mdx | 12 +- developer-guide/sdk-guide/quickstart.mdx | 6 +- features/text-to-speech.mdx | 2 +- llms.txt | 2 +- tests/js/package.json | 2 +- 17 files changed, 367 insertions(+), 112 deletions(-) diff --git a/.mintlify/skills/fish-audio-sdk/SKILL.md b/.mintlify/skills/fish-audio-sdk/SKILL.md index b8cc56b5..3c616dd4 100644 --- a/.mintlify/skills/fish-audio-sdk/SKILL.md +++ b/.mintlify/skills/fish-audio-sdk/SKILL.md @@ -1,6 +1,6 @@ --- name: fish-audio-sdk -description: Write code with the official Fish Audio SDKs, Python (`fishaudio`, PyPI `fish-audio-sdk`) and JavaScript/TypeScript (`fish-audio`). Use when the user wants text-to-speech, speech-to-text, voice cloning / voice-model management, or realtime WebSocket TTS through the installed SDK rather than raw HTTP. Covers install and auth, sync + async Python, the TypeScript client, exact method signatures and defaults, model selection (including the S2.1 typing caveat), the real exception types, and the Python↔JavaScript naming differences. For raw REST/WebSocket calls without an SDK (curl, unsupported languages, edge runtimes), use the `fish-audio-api` skill instead. +description: Write code with the official Fish Audio SDKs, Python (`fishaudio`, PyPI `fish-audio-sdk`) and JavaScript/TypeScript (`fish-audio`). Use when the user wants text-to-speech, speech-to-text (including realtime transcription in JavaScript), voice cloning / voice-model management, or realtime WebSocket TTS through the installed SDK rather than raw HTTP. Covers install and auth, sync + async Python, the TypeScript client, exact method signatures and defaults, model selection (including the S2.1 typing caveat), the real exception types, and the Python↔JavaScript naming differences. For raw REST/WebSocket calls without an SDK (curl, unsupported languages, edge runtimes), use the `fish-audio-api` skill instead. --- # Fish Audio SDK Skill @@ -8,7 +8,7 @@ description: Write code with the official Fish Audio SDKs, Python (`fishaudio`, Use this skill to generate correct, runnable code with the **official Fish Audio SDKs**: - **Python**: package `fish-audio-sdk` on PyPI, imported as `fishaudio`. (The same wheel still ships a separate legacy `fish_audio_sdk` package. Do **not** mix them; everything here is the modern `fishaudio` package.) -- **JavaScript / TypeScript**: package `fish-audio` on npm, imported as `FishAudioClient`. +- **JavaScript / TypeScript**: package `fish-audio` on npm (0.2.0), imported as `FishAudioClient`. Node.js 20+; `import` and `require` both work. If the user wants raw `curl` / HTTP / WebSocket without installing an SDK, use the **`fish-audio-api`** skill instead. @@ -18,8 +18,8 @@ If the user wants raw `curl` / HTTP / WebSocket without installing an SDK, use t - **Auth:** both SDKs read the API key from the `FISH_API_KEY` environment variable automatically. Get keys at `https://fish.audio/app/api-keys`. Never hardcode a key. - **Base URL:** `https://api.fish.audio` (override with `base_url=` in Python / `baseUrl:` in JS). -- **TTS models:** the API supports `s1` (deprecated), `s2-pro`, `s2.1-pro` (recommended for production), and `s2.1-pro-free` (free tier). Do not choose `s1` for new code: S1 is deprecated and will be retired on December 31, 2026. After that date, requests that specify `s1` are served by `s2.1-pro` (migration: `https://docs.fish.audio/developer-guide/models-pricing/migrate-from-s1`). However, the Python SDK types `model` as only `s1` and `s2-pro` (plus the deprecated `speech-1.x`), default `s2-pro`. The JS package on npm (`fish-audio` 0.1.0) types `backend` without `s2-pro` or `s2.1-pro` and defaults it to `"s1"` at runtime (its README says `"s2-pro"`), so in JS always pass `backend` explicitly. Both SDKs forward the model value without runtime validation, so `"s2.1-pro"` works over the wire. Static type checkers will flag it, so add `# type: ignore` (Python) / an `as` cast (TS), or use the `fish-audio-api` skill for raw calls. `speech-1.5` / `speech-1.6` are **deprecated**. In Python pass `model="s2-pro"` (keyword); in JS pass the **positional** `backend` argument. -- **ASR models:** use `transcribe-1-pro` (recommended: speaker turns, long recordings, emotion cues). Neither SDK has an ASR `model` argument: send the `model: transcribe-1-pro` HTTP header on every request (Python `RequestOptions(additional_headers=...)`, JS `requestOptions.headers`). A request without it is served and billed as `transcribe-1`, the model for short recordings. See [references/speech-to-text.md](references/speech-to-text.md). +- **TTS models:** the API supports `s1` (deprecated), `s2-pro`, `s2.1-pro` (recommended for production), and `s2.1-pro-free` (free tier). Do not choose `s1` for new code: S1 is deprecated and will be retired on December 31, 2026. After that date, requests that specify `s1` are served by `s2.1-pro` (migration: `https://docs.fish.audio/developer-guide/models-pricing/migrate-from-s1`). However, the Python SDK types `model` as only `s1` and `s2-pro` (plus the deprecated `speech-1.x`), default `s2-pro`; it forwards the value without runtime validation, so `"s2.1-pro"` works over the wire but type checkers flag it (add `# type: ignore`, or use the `fish-audio-api` skill for raw calls). The JS SDK (`fish-audio` 0.2.0) defaults to `"s2.1-pro"`, and its `Backends` type names `s2.1-pro`, `s2.1-pro-free`, `drama-3`, `s2-pro`, `s1` and accepts any other string, so no cast is needed. `fish-audio` 0.1.0 defaulted to the deprecated `"s1"`; if a project is on 0.1.0, upgrade it or pass the model explicitly. `speech-1.5` / `speech-1.6` are **deprecated**. In Python pass `model="s2-pro"` (keyword); in JS pass the **positional** `backend` argument. +- **ASR models:** use `transcribe-1-pro` (recommended: speaker turns, long recordings, emotion cues). It is selected by the `model` HTTP header: in JS pass `model: "transcribe-1-pro"` in the `convert()` request (`fish-audio` 0.2.0+), in Python send the header with `RequestOptions(additional_headers=...)`. A request without it is served and billed as `transcribe-1`, the model for short recordings. See [references/speech-to-text.md](references/speech-to-text.md). - **Audio formats:** `mp3` (default), `wav`, `pcm`, `opus`. - **Playback in examples:** `play()` shells out to a system audio tool: Python uses **ffmpeg/ffplay** (or `mpv`), JS uses **ffplay**. It is for local/desktop use; in a server, `save()` to a file or stream the bytes instead. See [references/installation.md](references/installation.md). @@ -63,32 +63,29 @@ const client = new FishAudioClient({ apiKey: process.env.FISH_API_KEY }); // convert() returns audio you can play or pipe to a file const audio = await client.textToSpeech.convert({ text: "Hello from Fish Audio!", -}); // npm 0.1.0 defaults to the deprecated "s1"; pass a model as shown below +}); // defaults to "s2.1-pro" (fish-audio 0.2.0+) await play(audio); // local playback (needs ffplay) ``` To pick a model in JS, pass `backend` as the **positional** argument (not a named option): ```ts -import type { Backends } from "fish-audio"; - -// The cast is needed because the npm 0.1.0 `Backends` type omits "s2.1-pro". const audio = await client.textToSpeech.convert( { text: "Hi" }, - "s2.1-pro" as Backends + "s2.1-pro-free" ); ``` ## Capabilities → references -| Task | Reference | -| ---------------------------------------------------------------- | ------------------------------------------------------------ | -| Install, auth, playback deps, verify a key | [references/installation.md](references/installation.md) | -| Text-to-Speech (convert, stream, formats, prosody, model select) | [references/text-to-speech.md](references/text-to-speech.md) | -| Voice cloning (instant references + persistent voice models) | [references/voice-cloning.md](references/voice-cloning.md) | -| Speech-to-Text (models, timestamps, fields the SDK drops) | [references/speech-to-text.md](references/speech-to-text.md) | -| Realtime WebSocket TTS (stream text → audio) | [references/websocket.md](references/websocket.md) | -| Errors, retries, and timeouts (the **real** exception types) | [references/errors.md](references/errors.md) | +| Task | Reference | +| ------------------------------------------------------------------------- | ------------------------------------------------------------ | +| Install, auth, playback deps, verify a key | [references/installation.md](references/installation.md) | +| Text-to-Speech (convert, stream, formats, prosody, model select) | [references/text-to-speech.md](references/text-to-speech.md) | +| Voice cloning (instant references + persistent voice models) | [references/voice-cloning.md](references/voice-cloning.md) | +| Speech-to-Text (models, timestamps, fields the SDK drops, realtime in JS) | [references/speech-to-text.md](references/speech-to-text.md) | +| Realtime WebSocket TTS (stream text → audio) | [references/websocket.md](references/websocket.md) | +| Errors, retries, and timeouts (the **real** exception types) | [references/errors.md](references/errors.md) | ## Python ↔ JavaScript name map @@ -101,6 +98,7 @@ The two SDKs do **not** use the same names. Use this map when porting code betwe | TTS HTTP stream | `client.tts.stream(...)` → `AudioStream` | (use `convert`; realtime streaming is `convertRealtime`) | | Realtime WebSocket | `client.tts.stream_websocket(text_stream)` | `client.textToSpeech.convertRealtime(request, textStream)` | | Speech-to-Text | `client.asr.transcribe(audio=...)` | `client.speechToText.convert({ audio })` | +| Realtime STT | see the Python SDK reference | `client.speechToText.convertRealtime(request, audio)` | | List voice models | `client.voices.list()` | `client.voices.search()` | | Get voice model | `client.voices.get(id)` | `client.voices.get(id)` | | Create voice (clone) | `client.voices.create(title=..., voices=[bytes])` | `client.voices.ivc.create({ title, voices: [File] })` | @@ -108,7 +106,7 @@ The two SDKs do **not** use the same names. Use this map when porting code betwe | Credit balance | `client.account.get_credits()` | `client.user.get_api_credit()` | | Subscription package | `client.account.get_package()` | `client.user.get_package()` | | Choose model | `model="s2-pro"` keyword arg | positional `backend` arg, e.g. `convert(req, "s2-pro")` | -| ASR model (header) | `RequestOptions(additional_headers=...)` | `convert(req, { headers: { model: "transcribe-1-pro" } })` | +| ASR model (header) | `RequestOptions(additional_headers=...)` | `convert({ audio, model: "transcribe-1-pro" })` | ## Decision shortcuts @@ -117,7 +115,8 @@ The two SDKs do **not** use the same names. Use this map when porting code betwe - **Clone a voice instantly from a clip** → pass `references=[ReferenceAudio(audio=..., text=...)]` (Python) / `references: [{ audio, text }]` (JS). See [voice-cloning](references/voice-cloning.md). - **Persistent custom voice to reuse** → create a voice model, then use its `id` as `reference_id`. - **Stream tokens from an LLM and play speech as it arrives** → `tts.stream_websocket` (Python) / `textToSpeech.convertRealtime` (JS). See [websocket](references/websocket.md). -- **Transcribe audio** → `asr.transcribe` (Python) / `speechToText.convert` (JS) with the `model: transcribe-1-pro` header (recommended; without it, the request runs on `transcribe-1`). Pro request fields, `speaker_turns`, `request_id`, and the language fields need raw HTTP in Python (`fish-audio-sdk` 1.3.0). See [speech-to-text](references/speech-to-text.md). +- **Transcribe audio** → `asr.transcribe` (Python) / `speechToText.convert` (JS) with `transcribe-1-pro` selected (recommended; without it, the request runs on `transcribe-1`). Pro request fields, `speaker_turns`, `request_id`, and the language fields need raw HTTP in Python (`fish-audio-sdk` 1.3.0). See [speech-to-text](references/speech-to-text.md). +- **Transcribe live audio turn by turn** → `speechToText.convertRealtime` (JS, Node.js only); see the realtime section of the speech-to-text reference. ## Gotchas (verified against the SDK source) diff --git a/.mintlify/skills/fish-audio-sdk/references/errors.md b/.mintlify/skills/fish-audio-sdk/references/errors.md index c788ff06..e2c3cf95 100644 --- a/.mintlify/skills/fish-audio-sdk/references/errors.md +++ b/.mintlify/skills/fish-audio-sdk/references/errors.md @@ -90,11 +90,13 @@ try { What the JS client actually throws: -| Error | When | -| ----------------------------------------------------- | -------------------------------------------------------------------------------------------- | -| `UnprocessableEntityError` (extends `FishAudioError`) | 422, the **only** typed HTTP subclass thrown; `.body` is `{ detail: [{ loc, msg, type }] }` | -| `FishAudioError` | every other non-2xx response; read `.statusCode`, `.body`, `.rawResponse` | -| `FishAudioTimeoutError` | request exceeded the timeout | +| Error | When | +| ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | +| `UnprocessableEntityError` (extends `FishAudioError`) | 422, the **only** typed HTTP subclass thrown; `.body` is `{ detail: [{ loc, msg, type }] }` | +| `FishAudioError` | every other non-2xx response; read `.statusCode`, `.body`, `.rawResponse` | +| `FishAudioTimeoutError` | request exceeded the timeout | +| `RealtimeSTTError` (extends `FishAudioError`) | realtime STT session failed or the connection was lost; read `.errorType`, `.statusCode`, `.closeCode`, `.requestId` | +| `UnauthorizedError` | realtime STT handshake refused with 401 (`speechToText.convertRealtime`) | > The package also exports `BadRequestError`, `UnauthorizedError`, `ForbiddenError`, `NotFoundError`, and `TooEarlyError`, but the current client throws a generic `FishAudioError` for those statuses. **Branch on `err.statusCode`** rather than relying on `instanceof NotFoundError`. diff --git a/.mintlify/skills/fish-audio-sdk/references/installation.md b/.mintlify/skills/fish-audio-sdk/references/installation.md index ff05bb46..5d9606ee 100644 --- a/.mintlify/skills/fish-audio-sdk/references/installation.md +++ b/.mintlify/skills/fish-audio-sdk/references/installation.md @@ -17,7 +17,9 @@ npm install fish-audio # or: pnpm add fish-audio / yarn add fish-audio ``` -- Requires Node.js 18+ (uses the global `fetch` / Web Streams). +- Requires Node.js 20+ (uses the global `fetch`, `File` and Web Streams). +- Ships ES module and CommonJS builds: `import { FishAudioClient } from "fish-audio"` and `const { FishAudioClient } = require("fish-audio")` both work (`require` needs `fish-audio` 0.2.0+). +- The WebSocket methods (`textToSpeech.convertRealtime`, `speechToText.convertRealtime`) are Node.js only. ## Authentication diff --git a/.mintlify/skills/fish-audio-sdk/references/speech-to-text.md b/.mintlify/skills/fish-audio-sdk/references/speech-to-text.md index ec675a9b..3fea2ed9 100644 --- a/.mintlify/skills/fish-audio-sdk/references/speech-to-text.md +++ b/.mintlify/skills/fish-audio-sdk/references/speech-to-text.md @@ -1,6 +1,6 @@ # Speech-to-Text (ASR) -Both SDKs wrap `POST /v1/asr`: one audio file per request, and the response arrives when the whole file has been transcribed. Use `transcribe-1-pro`, the recommended model. Neither SDK has a `model` argument for ASR, so select it with the `model` HTTP header on every request. Full guide: `https://docs.fish.audio/features/speech-to-text`. +Both SDKs wrap `POST /v1/asr`: one audio file per request, and the response arrives when the whole file has been transcribed. Use `transcribe-1-pro`, the recommended model, selected by the `model` HTTP header on every request. The JS SDK (`fish-audio` 0.2.0+) also streams live audio to `transcribe-stream-1`; see [JavaScript realtime](#javascript-realtime-speechtotextconvertrealtime). Full guide: `https://docs.fish.audio/features/speech-to-text`. ## Choose a model @@ -10,7 +10,7 @@ Both SDKs wrap `POST /v1/asr`: one audio file per request, and the response arri Select `transcribe-1-pro` with the `model` header: - Python: `request_options=RequestOptions(additional_headers={"model": "transcribe-1-pro"})`, with `from fishaudio.core import RequestOptions`. -- JavaScript: pass `{ headers: { model: "transcribe-1-pro" } }` as the second argument of `convert`. +- JavaScript: pass `model: "transcribe-1-pro"` in the `convert` request (`fish-audio` 0.2.0+; on 0.1.0, pass `{ headers: { model: "transcribe-1-pro" } }` as the second argument). - Write the value exactly, in lowercase. A missing or unrecognized value (for example `Transcribe-1-Pro` or `transcribe-1pro`) is served and billed as `transcribe-1`, and no error is returned. If you expected `transcribe-1-pro` but the transcript has no speaker markers and you did not send `diarize=false`, check the header. ## Python: `client.asr.transcribe` @@ -136,8 +136,9 @@ const result = await client.speechToText.convert( audio: new File([buf], "audio.wav"), language: "en", // optional hint; omit to auto-detect ignore_timestamps: false, // false → word-level segments (and speaker_turns on Pro) + model: "transcribe-1-pro", // sent as the model header }, - { headers: { model: "transcribe-1-pro" }, timeoutInSeconds: 900 } + { timeoutInSeconds: 900 } ); console.log(result.text); @@ -146,7 +147,7 @@ for (const seg of result.segments) { } ``` -`STTRequest` = `{ audio: File; language?: string; ignore_timestamps?: boolean }`, sent as multipart. JS uses `ignore_timestamps` (the inverse of Python's `include_timestamps`), and the server default is `true`, so you get no `segments` unless you pass `false`. +`STTRequest` = `{ audio: File; model?: string; language?: string; ignore_timestamps?: boolean }`, sent as multipart (`model` goes in the header and wins over a `model` header in `requestOptions`). JS uses `ignore_timestamps` (the inverse of Python's `include_timestamps`), and the server default is `true`, so you get no `segments` unless you pass `false`. In Node.js, the built-in `fetch` that the SDK uses stops waiting for response headers after 300 s, whatever `timeoutInSeconds` says (the call fails with `fetch failed`). For long Pro recordings, raise that limit once at startup with the `undici` package (`undici@7` runs on Node.js 20.18.1+; `undici@8` needs Node.js 22.19+ and fails at import on older versions): @@ -180,6 +181,40 @@ for (const turn of body.speaker_turns ?? []) { The JS SDK cannot send `tag_audio_events`, `diarize`, or the speaker counts; use `fetch` with `FormData` for those (see the `fish-audio-api` skill). +## JavaScript realtime: `speechToText.convertRealtime` + +`client.speechToText.convertRealtime(request, audioStream, requestOptions?)` (`fish-audio` 0.2.0+, **Node.js only**) streams live 16-bit little-endian mono PCM to `transcribe-stream-1` (Preview) over a WebSocket and returns a `RealtimeSTTStream` **synchronously** (no `await`). Iterate it with `for await`; events are narrowed by `type`, and their fields are the protocol's snake_case names. Guide: `https://docs.fish.audio/features/speech-to-text/realtime`. + +```ts +import { createReadStream } from "node:fs"; +import { FishAudioClient } from "fish-audio"; + +const client = new FishAudioClient(); + +// 16 kHz PCM, 40 ms (1280 bytes) per chunk. A microphone yields chunks as it captures them. +async function* audioChunks() { + yield* createReadStream("speech.pcm", { highWaterMark: 1280 }); +} + +const stream = client.speechToText.convertRealtime( + { sample_rate: 16000, drafts: true, diarize: false }, + audioChunks() +); +for await (const event of stream) { + if (event.type === "draft") + console.log("...", event.text); // not final + else if (event.type === "committed") console.log(event.text); // final text of the turn +} +``` + +- `request` (`{}` is valid): `sample_rate` (8000, 12000, 16000 default, 22050, 24000, 32000, 44100, 48000), `turn_detection` (`"auto"` default, `"vad"`, `"manual"`, or `{ mode, eager, silence_timeout_ms }`), `eager`, `drafts`, `diarize` (server default `true`: text starts with `<|speaker:0|>`), `terms`, `results`, `context`, `client_reference_id`, `model` (`transcribe-stream-1`). Top-level `eager`/`drafts`/`diarize`/`terms` win over the nested objects. +- `audioStream`: `Iterable` or `AsyncIterable` of `Buffer` / typed array / `ArrayBuffer` chunks (20–40 ms each). A control message object in it is sent at that position. The session ends with `session_done` once the source is exhausted. +- `requestOptions`: `abortSignal` (ends the session; the loop throws the signal's reason), `timeoutInSeconds` (opening the connection, default 30). +- Events: `session_started`, `speech_start`, `user_turn_taken`, `draft`, `eager_end_of_turn`, `turn_resumed`, `user_backchannel`, `committed` (`text`, `user_turn`, `reason`, `audio_start_ms`, `audio_end_ms`; exactly one per turn), `vad`, `eot_prob`, `configured`, `progress`, `error` (recoverable only), `session_done`. +- Control methods: `finalize()`, `agentSpeaking(boolean)`, `addContext(items, { resetHistory? })`, `configure(update)`, `keepalive()` (the SDK sends none; a session closes after 30 s without client messages), `send(message)`, `close()`. +- Errors thrown from the loop: `RealtimeSTTError` (session failed or connection lost; `errorType`, `statusCode`, `requestId`, `closeCode`, `recoverable`), `UnauthorizedError` / `FishAudioError` with `statusCode` (402, 429) when the handshake is refused, or the audio source's own error. +- Stopping: leaving the loop or `close()` closes the connection and calls `return()` on the source's iterator without awaiting it. An async generator blocked on a read is not interrupted by that, so race its read against an `AbortSignal`, release the device in its `finally`, and abort the signal in a `finally` around the loop. Full pattern: `https://docs.fish.audio/api-reference/sdk/javascript/api-reference#close-the-session-and-stop-the-audio-source`. + ## Limits and formats (both SDKs) - `transcribe-1-pro` accepts recordings up to 60 minutes (longer returns 400 `audio_too_long`). Send long recordings as compressed audio (MP3, Opus, or AAC); a request that is too large returns 413. Send a whole conversation as one file: speaker labels are consistent within one response, not across requests. diff --git a/.mintlify/skills/fish-audio-sdk/references/text-to-speech.md b/.mintlify/skills/fish-audio-sdk/references/text-to-speech.md index 88fea888..70ad2d83 100644 --- a/.mintlify/skills/fish-audio-sdk/references/text-to-speech.md +++ b/.mintlify/skills/fish-audio-sdk/references/text-to-speech.md @@ -28,17 +28,17 @@ audio = client.tts.convert(text="Speaking faster.", model="s2-pro", speed=1.5) All keyword-only: -| Param | Type | Default | Notes | -| ----------------- | ----------------------------------- | ------------- | ---------------------------------------------------------------- | -| `text` | `str` | — (required) | Text to synthesize. | -| `reference_id` | `str \| None` | `None` | Voice model id to speak with. | -| `references` | `list[ReferenceAudio] \| None` | `None` | Inline clone samples; see [voice-cloning.md](voice-cloning.md). | -| `format` | `"mp3" \| "wav" \| "pcm" \| "opus"` | `"mp3"` | Output format. | -| `latency` | `"normal" \| "balanced"` | `"balanced"` | `normal` = higher quality, `balanced` = faster. (No `"low"`.) | -| `speed` | `float` | — | Shortcut for prosody speed (0.5–2.0). | -| `config` | `TTSConfig` | `TTSConfig()` | Reusable bundle of the settings below. | +| Param | Type | Default | Notes | +| ----------------- | ----------------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `text` | `str` | — (required) | Text to synthesize. | +| `reference_id` | `str \| None` | `None` | Voice model id to speak with. | +| `references` | `list[ReferenceAudio] \| None` | `None` | Inline clone samples; see [voice-cloning.md](voice-cloning.md). | +| `format` | `"mp3" \| "wav" \| "pcm" \| "opus"` | `"mp3"` | Output format. | +| `latency` | `"normal" \| "balanced"` | `"balanced"` | `normal` = higher quality, `balanced` = faster. (No `"low"`.) | +| `speed` | `float` | — | Shortcut for prosody speed (0.5–2.0). | +| `config` | `TTSConfig` | `TTSConfig()` | Reusable bundle of the settings below. | | `model` | `"s2-pro" \| "s1"` | `"s2-pro"` | Synthesis model per current SDK typing. The API also accepts `"s2.1-pro"` / `"s2.1-pro-free"`, forwarded fine at runtime, but add `# type: ignore` for static checkers. `s1` is deprecated and will be retired on December 31, 2026; after that date, requests that specify `s1` are served by `s2.1-pro`. `speech-1.5` / `speech-1.6` are deprecated. | -| `request_options` | `RequestOptions \| None` | `None` | Per-request timeout / headers; see [errors.md](errors.md). | +| `request_options` | `RequestOptions \| None` | `None` | Per-request timeout / headers; see [errors.md](errors.md). | Direct params (`reference_id`, `format`, `latency`, `speed`) override the matching field on `config` when set. @@ -78,19 +78,18 @@ Async: every method mirrors onto `AsyncFishAudio`; `await client.tts.convert(... ## JavaScript: `client.textToSpeech` -`convert(request, backend?, requestOptions?)` resolves to a `ReadableStream` you can `play()` or pipe to a file. `backend` is the **second positional** argument, **not** a named option. Always pass it: the npm release (`fish-audio` 0.1.0) defaults it to the deprecated `"s1"` at runtime, although its README says `"s2-pro"`. +`convert(request, backend?, requestOptions?)` resolves to a `ReadableStream` you can `play()` or pipe to a file. `backend` is the **second positional** argument, **not** a named option. It defaults to `"s2.1-pro"` in `fish-audio` 0.2.0 (0.1.0 defaulted to the deprecated `"s1"`, so pass it explicitly if a project is still on 0.1.0). ```ts -import { FishAudioClient, play, type Backends } from "fish-audio"; -import { createWriteStream } from "node:fs"; -import { Readable } from "node:stream"; +import { FishAudioClient, play } from "fish-audio"; +import { writeFile } from "node:fs/promises"; const client = new FishAudioClient(); -// model only (the cast is needed: the npm 0.1.0 `Backends` type omits "s2.1-pro") +// model only const audio = await client.textToSpeech.convert( { text: "Hello, world!" }, - "s2.1-pro" as Backends + "s2.1-pro" ); await play(audio); @@ -100,21 +99,16 @@ const audio2 = await client.textToSpeech.convert( text: "Using a saved voice.", reference_id: "9a9cf47702da476aa4629e2506d4a857", }, - "s2.1-pro" as Backends // <-- positional backend, not { backend: "s2.1-pro" } + "s2.1-pro" // <-- positional backend, not { backend: "s2.1-pro" } ); -// pipe to a file instead of playing -await new Promise((resolve, reject) => - Readable.fromWeb(audio2) - .pipe(createWriteStream("out.mp3")) - .on("finish", resolve) - .on("error", reject) -); +// write to a file instead of playing (writeFile consumes the stream chunk by chunk) +await writeFile("out.mp3", audio2); ``` -`TTSRequest` (the first argument) fields: `text` (required), `reference_id?`, `references?`, `format?`, `latency?`, `prosody?: { speed?; volume? }`, `temperature?`, `top_p?`, `chunk_length?`, `mp3_bitrate?`, `opus_bitrate?`, `sample_rate?`, `normalize?`, plus the advanced generation knobs (`max_new_tokens`, `repetition_penalty`, etc.). Field names are `snake_case`, matching the API. +`TTSRequest` (the first argument) fields: `text` (required), `reference_id?` (a voice ID, or an array of IDs for multi-speaker text with `<|speaker:N|>` tags, S2 family only), `references?`, `format?`, `latency?` (`"low" | "normal" | "balanced"`), `prosody?: { speed?; volume?; normalize_loudness? }`, `temperature?`, `top_p?`, `chunk_length?`, `mp3_bitrate?`, `opus_bitrate?` (bits per second: `-1000 | 24000 | 32000 | 48000 | 64000`), `sample_rate?`, `normalize?`, plus the advanced generation knobs (`max_new_tokens`, `repetition_penalty`, `min_chunk_length`, `condition_on_previous_chunks`, `early_stop_threshold`, `features`). Field names are `snake_case`, matching the API. -> The npm 0.1.0 JS `Backends` type is `'speech-1.5' | 'speech-1.6' | 'agent-x0' | 's1' | 's1-mini'`; the API also accepts `s2-pro`, `s2.1-pro`, and `s2.1-pro-free`, so pass those with an `as Backends` cast. Prefer `s2.1-pro` for production. Do not choose `s1` or `s1-mini`. +> The JS `Backends` type (`fish-audio` 0.2.0) is `'s1' | 's2-pro' | 's2.1-pro' | 's2.1-pro-free' | 'drama-3'` plus any other string, so do not cast. Prefer `s2.1-pro` for production. Do not choose `s1`. Code written for 0.1.0 may still have `as Backends` casts; they are harmless but unnecessary. ## Model & expression notes diff --git a/.mintlify/skills/fish-audio-sdk/references/voice-cloning.md b/.mintlify/skills/fish-audio-sdk/references/voice-cloning.md index c21c195c..6f4fa9c9 100644 --- a/.mintlify/skills/fish-audio-sdk/references/voice-cloning.md +++ b/.mintlify/skills/fish-audio-sdk/references/voice-cloning.md @@ -47,7 +47,7 @@ const audio = await client.textToSpeech.convert({ await play(audio); ``` -In JS, `ReferenceAudio.audio` is a `File`. +In JS, `ReferenceAudio.audio` must be a `File` or `Blob`. In `fish-audio` 0.2.0 a `Buffer` or `Uint8Array` fails with `ref.audio.arrayBuffer is not a function`; wrap it in a `File` as above. ## 2. Persistent voice models diff --git a/api-reference/sdk/javascript/api-reference.mdx b/api-reference/sdk/javascript/api-reference.mdx index b603cd7c..fcdd8b20 100644 --- a/api-reference/sdk/javascript/api-reference.mdx +++ b/api-reference/sdk/javascript/api-reference.mdx @@ -1,29 +1,56 @@ --- title: "JavaScript SDK Reference" sidebarTitle: "Reference" -description: "Complete reference for Fish Audio JavaScript SDK" +description: "Complete reference for the Fish Audio JavaScript and TypeScript SDK (fish-audio on npm)" icon: "book" --- +This page describes `fish-audio` 0.2.0. Release notes are on [GitHub](https://github.com/fishaudio/fish-audio-typescript/releases/tag/v0.2.0). + +## Install + +```bash +npm install fish-audio +``` + +The SDK requires Node.js 20 or later. It ships ES module and CommonJS builds with type declarations for both, so `import` and `require` work: + + + +```typescript ES module +import { FishAudioClient } from "fish-audio"; +``` + +```javascript CommonJS +const { FishAudioClient } = require("fish-audio"); +``` + + + +The WebSocket methods, `textToSpeech.convertRealtime()` and `speechToText.convertRealtime()`, run in Node.js only: browsers cannot set the `Authorization` header on a WebSocket. + ## Client Import and initialize the client: ```typescript -import { FishAudioClient, type Backends } from "fish-audio"; +import { FishAudioClient } from "fish-audio"; + const fishAudio = new FishAudioClient({ apiKey: process.env.FISH_API_KEY }); ``` +Without `apiKey`, the client reads `FISH_API_KEY` from the environment. Pass `baseUrl` to send requests to another address, such as a proxy. + ## Text to Speech ### convert() Generate speech from text. ```typescript -const audio = await fishAudio.textToSpeech.convert({ text: "Hello" }, "s2.1-pro-free" as Backends); +const audio = await fishAudio.textToSpeech.convert({ text: "Hello" }, "s2.1-pro-free"); ``` -Parameters: `request` (TTSRequest), `model?` (Backends)
+Parameters: `request` (TTSRequest), `model?` (Backends, default `"s2.1-pro"`), `requestOptions?`
Returns: `Promise>` ### convertRealtime() @@ -31,11 +58,11 @@ Realtime streaming TTS over WebSocket. ```typescript async function* textStream() { yield "Hello, "; yield "world!"; } -const conn = await fishAudio.textToSpeech.convertRealtime({ text: "" }, textStream(), "s2.1-pro-free" as Backends); +const conn = await fishAudio.textToSpeech.convertRealtime({ text: "" }, textStream(), "s2.1-pro-free"); ``` -Parameters: `request` (TTSRequest with `text: ""`), `textStream` (`AsyncIterable`), `backend?` (Backends)
-Returns: `RealtimeConnection` (`EventEmitter`-like connection) emitting `RealtimeEvents` +Parameters: `request` (TTSRequest with `text: ""`), `textStream` (`Iterable` or `AsyncIterable`), `backend?` (Backends, default `"s2.1-pro"`)
+Returns: `Promise` (`EventEmitter`-like connection) emitting `RealtimeEvents` ## Speech to Text @@ -43,17 +70,174 @@ Returns: `RealtimeConnection` (`EventEmitter`-like connection) emitting `Realtim Transcribe audio to text. ```typescript -const res = await fishAudio.speechToText.convert( - { audio: myAudio }, - { headers: { model: "transcribe-1-pro" } } -); +const res = await fishAudio.speechToText.convert({ audio: myAudio, model: "transcribe-1-pro" }); console.log(res.text); ``` -Parameters: `request` (STTRequest), `requestOptions?` (for example `headers` and `timeoutInSeconds`)
+Parameters: `request` (STTRequest), `requestOptions?` (for example `timeoutInSeconds`)
Returns: `STTResponse` -Select the model with the `model` header in `requestOptions.headers`. Without it, the request is served and billed as `transcribe-1`. See [Speech to Text](/features/speech-to-text). +`model` is sent as the `model` header. Without it, the request is served and billed as `transcribe-1`. See [Speech to Text](/features/speech-to-text). + +### convertRealtime() +Transcribe live audio with `transcribe-stream-1` (Preview) over a WebSocket, turn by turn. Send 16-bit little-endian mono PCM in chunks of 20–40 ms as you capture it. The SDK opens the session, sends each chunk as the audio source yields it, and ends the session when the source is exhausted. It runs in Node.js only. + +```typescript +import { createReadStream } from "node:fs"; +import { FishAudioClient } from "fish-audio"; + +const fishAudio = new FishAudioClient(); + +// Raw 16-bit mono PCM at 16 kHz, 40 ms (1280 bytes) per chunk. +// From a file this sends faster than real time; a microphone yields chunks as it captures them. +async function* audioChunks() { + yield* createReadStream("speech.pcm", { highWaterMark: 1280 }); +} + +const stream = fishAudio.speechToText.convertRealtime( + { sample_rate: 16000, drafts: true, diarize: false }, + audioChunks(), +); + +for await (const event of stream) { + if (event.type === "draft") { + console.log("...", event.text); // live text of the open turn, not final + } else if (event.type === "committed") { + console.log(event.text); // final transcript of the turn + } +} +``` + +To make `speech.pcm` from a recording, run `ffmpeg -i input.mp3 -ac 1 -ar 16000 -f s16le speech.pcm`. + +Parameters: `request` (RealtimeSTTRequest, `{}` is valid), `audioStream` (`Iterable` or `AsyncIterable` of `Buffer`, typed array or `ArrayBuffer` chunks), `requestOptions?` (`abortSignal`, and `timeoutInSeconds` for opening the connection, default 30)
+Returns: `RealtimeSTTStream`, synchronously. Iterate it with `for await` to read events; the loop ends after `session_done`. + +`RealtimeSTTRequest` fields: + +| Field | Default | Meaning | +| --- | --- | --- | +| `sample_rate` | `16000` | Sample rate of your audio: 8000, 12000, 16000, 22050, 24000, 32000, 44100 or 48000 Hz. The server converts it. | +| `turn_detection` | `"auto"` | `"auto"`, `"vad"` or `"manual"`, or an object with `mode`, `eager` and `silence_timeout_ms`. | +| `eager` | `false` | Send `eager_end_of_turn` in `auto` mode, so a voice agent can prepare its reply early. | +| `drafts` | `false` | Send live `draft` events while a turn is open. | +| `diarize` | `true` | Speaker tags at the start of the text. `false` gives plain text. | +| `terms` | none | Names, products and jargon to recognize, up to 100 terms of up to 32 characters. | +| `results` | none | Every result setting of the protocol, such as `tag_audio_events` and `ignore_timestamps`. | +| `context` | none | `history` (earlier conversation) and `terms`. | +| `client_reference_id` | none | Your own ID for the session, recorded with it. | +| `model` | `"transcribe-stream-1"` | The realtime model. | + +A top-level field (`eager`, `drafts`, `diarize`, `terms`) wins over the same setting in `turn_detection`, `results` or `context`. By default each transcript starts with a speaker tag such as `<|speaker:0|>`; pass `diarize: false` for plain text. + +Events are narrowed by `type`. Their fields use the protocol's snake_case names, such as `turn_index` and `audio_end_ms`: + +| `type` | When | +| --- | --- | +| `session_started` | The session is ready. Carries `session_id` and `request_id`. | +| `speech_start` | A turn opened on voice activity. In `auto` mode it can be noise or another voice. | +| `user_turn_taken` | `auto` mode: the user is taking the turn. A speaking voice agent stops here. | +| `draft` | With `drafts: true`: the whole turn so far, not final. | +| `eager_end_of_turn` | With `eager: true`: the turn has probably ended. Its `text` is what `committed` will say unless `turn_resumed` follows. | +| `turn_resumed` | The speaker went on after `eager_end_of_turn`. | +| `user_backchannel` | `auto` mode, while your agent speaks: the user only acknowledged. | +| `committed` | The final transcript of the turn, with `text`, `user_turn`, `reason`, `audio_start_ms` and `audio_end_ms`. Every turn has exactly one. | +| `vad`, `eot_prob` | With `results.vad_events` or `results.eot_events`. | +| `configured` | The reply to `configure()`. | +| `progress` | Audio positions, every 5 seconds while you send nothing. | +| `error` | An error the session survives (`recoverable: true`). | +| `session_done` | The last event, after the audio source is exhausted. Carries `stats`. | + +See [Realtime Speech to Text](/features/speech-to-text/realtime) for how turns work and [the WebSocket reference](/api-reference/endpoint/websocket/asr-realtime) for every field. + +#### Control methods + +`RealtimeSTTStream` sends control messages while the session runs: + +```typescript +await stream.finalize(); // commit the open turn now (push-to-talk, with turn_detection: "manual") +await stream.agentSpeaking(true); // voice agents: your agent started speaking +await stream.addContext([{ role: "assistant", text: "Which day works for you?" }]); +await stream.configure({ turn_detection: { mode: "vad", silence_timeout_ms: 900 } }); +await stream.keepalive(); // a session closes after 30 seconds without any client message +await stream.close(); // end the session and close the connection +``` + +`send(message)` sends any control message, and a control message such as `{ type: "agent_speaking", speaking: true }` yielded by the audio source is sent at that position in the audio. The SDK does not send keepalives for you. + +#### Errors + +Errors are thrown from the `for await` loop: + +- `RealtimeSTTError` when the server ends the session or the connection is lost. It carries `errorType` (such as `unsupported_audio`; match on this field), `statusCode`, `requestId`, `closeCode` and `recoverable`. +- `UnauthorizedError`, or `FishAudioError` with a `statusCode` such as 402 or 429, when the connection is refused. +- The audio source's own error when the audio source throws. + +```typescript +import { FishAudioError, RealtimeSTTError } from "fish-audio"; + +try { + for await (const event of stream) { + if (event.type === "committed") console.log(event.text); + } +} catch (err) { + if (err instanceof RealtimeSTTError) { + console.error(err.errorType, err.statusCode, err.closeCode, err.requestId); + } else if (err instanceof FishAudioError) { + console.error("connection refused:", err.statusCode, err.body); + } else { + throw err; + } +} +``` + +#### Close the session and stop the audio source + +Leaving the loop early, or calling `stream.close()`, closes the connection. When the session ends for any reason, the stream calls `return()` on the audio source's iterator and does not wait for it, so `close()` never hangs on the source. + +An async generator that is suspended on a read cannot be interrupted this way: its `return()` only runs after that read settles. If your source can block, such as a microphone, give it an `AbortSignal` and abort it when you are done with the session: + +```typescript +async function* microphone(signal: AbortSignal) { + const recorder = openRecorder(); // your own capture code + try { + while (!signal.aborted) { + let stop!: () => void; + const aborted = new Promise((resolve) => { + stop = () => resolve(undefined); + }); + signal.addEventListener("abort", stop, { once: true }); + let chunk: Uint8Array | undefined; + try { + // read() resolves with the next 20–40 ms of PCM. + chunk = await Promise.race([recorder.read(), aborted]); + } finally { + signal.removeEventListener("abort", stop); + } + if (chunk === undefined) { + break; // aborted while waiting for audio + } + yield chunk; + } + } finally { + recorder.close(); // releases the device, and a read that is still pending + } +} + +const controller = new AbortController(); +const stream = fishAudio.speechToText.convertRealtime({ diarize: false }, microphone(controller.signal)); +try { + for await (const event of stream) { + if (event.type === "committed") console.log(event.text); + } +} finally { + controller.abort(); // stops the microphone, however the loop ended +} +``` + +Racing the read only stops the generator from waiting; `recorder.close()` in the `finally` block stops the capture, so release your device there. `controller.abort()` on its own ends the audio: the session then finishes with `session_done`, as it does when the source is exhausted. + +To end the session itself from outside the loop, pass `{ abortSignal }` as the third argument of `convertRealtime()`: when the signal aborts, the stream closes and throws the signal's reason. ## Voices @@ -81,7 +265,7 @@ Returns: `ModelEntity` Create a new voice model from audio samples. ```typescript -const res = await fishAudio.voices.ivc.create({ title, voices: [file], cover_image: file }); +const res = await fishAudio.voices.ivc.create({ title: "My voice", voices: [file], cover_image: image }); ``` Parameters: `request` (ModelCreateRequest)
@@ -136,49 +320,65 @@ Text-to-speech parameters. { text: "Hello", reference_id: "model_id", - references: [ { audio: File, text: "sample" } ], format: "mp3", prosody: { speed: 1.0, volume: 0 }, } ``` -Fields: `text`, `reference_id`, `references`, `format`, `mp3_bitrate`, `opus_bitrate`, `sample_rate`, `prosody`, `latency`, `chunk_length`, `normalize`, `temperature`, `top_p` +Fields: `text`, `reference_id`, `references`, `format`, `mp3_bitrate`, `opus_bitrate`, `sample_rate`, `prosody`, `latency`, `chunk_length`, `normalize`, `temperature`, `top_p`, `max_new_tokens`, `repetition_penalty`, `min_chunk_length`, `condition_on_previous_chunks`, `early_stop_threshold`, `features` + +- `opus_bitrate` is in bits per second: `-1000` (automatic), `24000`, `32000`, `48000` or `64000`. +- `latency` is `"low"`, `"normal"` or `"balanced"`. +- For multi-speaker dialogue (S2 family only), pass an array of voice IDs as `reference_id` and mark the turns in the text: + +```typescript +const audio = await fishAudio.textToSpeech.convert({ + text: "<|speaker:0|>Hello!<|speaker:1|>Hi there!", + reference_id: ["speaker-a-id", "speaker-b-id"], +}); +``` ### STTRequest Speech-to-text parameters. ```typescript -{ audio: File, language?: "en", ignore_timestamps?: boolean } +{ audio: File, model?: "transcribe-1-pro", language?: "en", ignore_timestamps?: boolean } ``` -Fields: `audio`, `language?`, `ignore_timestamps?` +Fields: `audio`, `model?`, `language?`, `ignore_timestamps?` ### ReferenceAudio -Reference audio for voice cloning. +Reference audio for zero-shot voice cloning. `audio` must be a `File` or `Blob`; wrap a `Buffer` in a `File`: ```typescript -{ audio: File, text: "spoken text" } +import { readFile } from "node:fs/promises"; +import type { ReferenceAudio } from "fish-audio"; + +const sample: ReferenceAudio = { + audio: new File([await readFile("reference.wav")], "reference.wav"), + text: "The words spoken in the clip.", +}; ``` -Fields: `audio`, `text` +Fields: `audio`, `text`. Pass a flat array as `references` for one speaker, or one array per speaker for multi-speaker dialogue. ### Prosody -Speed and volume control. +Speed and volume control (`ProsodyControl`). ```typescript { speed: 1.2, volume: 5 } ``` -Fields: `speed` (0.5–2.0), `volume` (-20 to 20) +Fields: `speed` (0.5–2.0), `volume` (-20 to 20), `normalize_loudness?` (S2 family only) ### Backends -The backend model to use. +The TTS model, sent as the `model` header. ```typescript -Backends = 's1' | 's2-pro'; +type Backends = "s1" | "s2-pro" | "s2.1-pro" | "s2.1-pro-free" | "drama-3" | (string & {}); ``` -The API also accepts `s2.1-pro` and `s2.1-pro-free`; the SDK's `Backends` type has not been updated yet, so pass them with a type assertion (for example `'s2.1-pro' as Backends`) or call the [REST API](/api-reference/endpoint/openapi-v1/text-to-speech) directly. +The default is `s2.1-pro`. Any other string is accepted, so a model released after this SDK version works without an update. `s1` is deprecated and retires on December 31, 2026; see [Migrate from S1](/developer-guide/models-pricing/migrate-from-s1). ## Response Classes @@ -199,7 +399,7 @@ Fields: `text` (string), `start` (number, seconds), `end` (number, seconds) ### ModelEntity Voice model information. -Fields: `_id`, `title`, `description`, `visibility`, `created_at`, `updated_at`, `tags` +Fields: `_id`, `title`, `description`, `state`, `visibility`, `created_at`, `updated_at`, `tags` ### ModelListResponse List response for voices. @@ -219,7 +419,7 @@ Fields: `user_id` (string), `type` (string), `total` (number), `balance` (number ## WebSocket Classes ### RealtimeEvents -Events emitted by `convertRealtime` connections. +Events emitted by `textToSpeech.convertRealtime()` connections. | Event | Meaning | |---------------|----------------------------------| @@ -228,6 +428,9 @@ Events emitted by `convertRealtime` connections. | `ERROR` | Error occurred | | `CLOSE` | Connection closed | +### RealtimeSTTStream +The session returned by `speechToText.convertRealtime()`: an async iterable of `RealtimeSTTEvent`, with the [control methods](#control-methods) above. + ## Event Classes ### StartEvent @@ -253,7 +456,22 @@ Fields: `event` ("stop") ## Exceptions ### FishAudioError -Generic error with status code, body, rawResponse. +Generic error with `statusCode`, `body`, `rawResponse`. ### FishAudioTimeoutError Connection timeout error. + +### RealtimeSTTError +A realtime speech-to-text session failed. Extends `FishAudioError` with `errorType`, `requestId`, `closeCode` and `recoverable`. + +## Upgrade notes + +Upgrading from 0.1.0 to 0.2.0: + +- **The default TTS model is now `s2.1-pro`**, for `textToSpeech.convert()` and `textToSpeech.convertRealtime()`. The published 0.1.0 package sent the deprecated `s1` when you passed no model. To use another model, pass it: `convert(request, "s2-pro")`. +- **`opus_bitrate` is in bits per second.** Code that passes `24`, `32`, `48` or `64` no longer compiles: multiply the value by 1000. +- **`ReferenceAudio.audio` must be a `File` or `Blob`.** A `Buffer` or `Uint8Array` passed with a type cast now fails with `ref.audio.arrayBuffer is not a function`. Wrap it: `new File([buffer], "sample.mp3")`. +- **Model names are no longer cast.** `Backends` names `s2.1-pro`, `s2.1-pro-free` and `drama-3` and accepts any other string, so remove `as Backends` casts. `speech-1.5`, `speech-1.6`, `agent-x0` and `s1-mini` no longer autocomplete. +- **Node.js 20 or later is required.** +- **`require("fish-audio")` works.** In 0.1.0 it threw `ReferenceError: exports is not defined in ES module scope`. +- **Select the speech-to-text model with `model`.** `convert({ audio, model: "transcribe-1-pro" })` replaces `{ headers: { model: "transcribe-1-pro" } }`, which still works. diff --git a/developer-guide/getting-started/changelog.mdx b/developer-guide/getting-started/changelog.mdx index 8d743d6f..b991f36f 100644 --- a/developer-guide/getting-started/changelog.mdx +++ b/developer-guide/getting-started/changelog.mdx @@ -4,6 +4,16 @@ description: "Complete release history and version updates for all Fish Audio pr icon: "clock-rotate-left" rss: true --- + + ## JavaScript SDK 0.2.0 + + `fish-audio` 0.2.0 on npm adds realtime speech to text with `transcribe-stream-1` (`speechToText.convertRealtime()`, Node.js only), a `model` option for `speechToText.convert()`, the `s2.1-pro`, `s2.1-pro-free` and `drama-3` models in the `Backends` type, multi-speaker text to speech, and more TTS request fields. `require("fish-audio")` works again. + + Upgrade notes: the default TTS model is now `s2.1-pro` (0.1.0 sent the deprecated `s1`), `opus_bitrate` is in bits per second, reference audio must be a `File` or `Blob`, and Node.js 20 or later is required. + + [JavaScript SDK reference](/api-reference/sdk/javascript/api-reference#upgrade-notes) | [Release notes](https://github.com/fishaudio/fish-audio-typescript/releases/tag/v0.2.0) + + ## Voice Agents React Native SDK and widget diff --git a/developer-guide/models-pricing/migrate-from-s1.mdx b/developer-guide/models-pricing/migrate-from-s1.mdx index 5db4fd9f..83daa910 100644 --- a/developer-guide/models-pricing/migrate-from-s1.mdx +++ b/developer-guide/models-pricing/migrate-from-s1.mdx @@ -33,7 +33,7 @@ The steps below cover each of these changes. In the API, you select the model with the `model` request header. Change `s1` to `s2.1-pro` wherever you set the model, including SDK and integration settings. -If you use the JavaScript SDK (`fish-audio` on npm) without passing a model, your requests use `s1`, because that is the SDK's default backend. Pass the model explicitly. +If you use the JavaScript SDK (`fish-audio` on npm) 0.1.0 without passing a model, your requests use `s1`, because that is its default backend. Upgrade to 0.2.0 or later, which defaults to `s2.1-pro`, or pass the model explicitly. This example also converts the emotion tags, as described in the next step: diff --git a/developer-guide/models-pricing/migrate-from-transcribe-1.mdx b/developer-guide/models-pricing/migrate-from-transcribe-1.mdx index ae2fad84..f0ac2d97 100644 --- a/developer-guide/models-pricing/migrate-from-transcribe-1.mdx +++ b/developer-guide/models-pricing/migrate-from-transcribe-1.mdx @@ -72,10 +72,11 @@ import { readFile } from "fs/promises"; const client = new FishAudioClient({ apiKey: process.env.FISH_API_KEY }); -const result = await client.speechToText.convert( - { audio: new File([await readFile("speech.wav")], "speech.wav") }, - { headers: { model: "transcribe-1-pro" } } -); +// model requires fish-audio 0.2.0 or later +const result = await client.speechToText.convert({ + audio: new File([await readFile("speech.wav")], "speech.wav"), + model: "transcribe-1-pro", +}); console.log(result.text); ``` diff --git a/developer-guide/sdk-guide/cookbook/batch-transcribe-with-language-hint.mdx b/developer-guide/sdk-guide/cookbook/batch-transcribe-with-language-hint.mdx index 8be23600..ee7567a2 100644 --- a/developer-guide/sdk-guide/cookbook/batch-transcribe-with-language-hint.mdx +++ b/developer-guide/sdk-guide/cookbook/batch-transcribe-with-language-hint.mdx @@ -129,17 +129,15 @@ const client = new FishAudioClient({ apiKey: process.env.FISH_API_KEY }); const paths = ["speech.wav"]; // add more file paths here const language = "en"; -const options = { - headers: { model: "transcribe-1-pro" }, - timeoutInSeconds: 900, // long recordings can take several minutes -}; +const options = { timeoutInSeconds: 900 }; // long recordings can take several minutes const results = []; for (const path of paths) { try { const audio = new File([await readFile(path)], path); const transcript = await client.speechToText.convert( - { audio, language }, + // model requires fish-audio 0.2.0 or later + { audio, language, model: "transcribe-1-pro" }, options ); results.push({ diff --git a/developer-guide/sdk-guide/cookbook/transcribe-to-captions.mdx b/developer-guide/sdk-guide/cookbook/transcribe-to-captions.mdx index 81e8fbcc..df7d1c82 100644 --- a/developer-guide/sdk-guide/cookbook/transcribe-to-captions.mdx +++ b/developer-guide/sdk-guide/cookbook/transcribe-to-captions.mdx @@ -185,11 +185,9 @@ const result = await client.speechToText.convert( { audio: new File([await readFile("speech.wav")], "speech.wav"), ignore_timestamps: false, + model: "transcribe-1-pro", // requires fish-audio 0.2.0 or later }, - { - headers: { model: "transcribe-1-pro" }, - timeoutInSeconds: 900, // long recordings can take several minutes - } + { timeoutInSeconds: 900 } // long recordings can take several minutes ); const cues = groupCues(result.segments); diff --git a/developer-guide/sdk-guide/cookbook/voice-agent-loop.mdx b/developer-guide/sdk-guide/cookbook/voice-agent-loop.mdx index 446ec21a..0f2e8974 100644 --- a/developer-guide/sdk-guide/cookbook/voice-agent-loop.mdx +++ b/developer-guide/sdk-guide/cookbook/voice-agent-loop.mdx @@ -108,13 +108,11 @@ function replyFromLlm(text) { } async function voiceAgentTurn(audioPath, outPath) { - const heard = await client.speechToText.convert( - { - audio: new File([await readFile(audioPath)], audioPath), - language: "en", - }, - { headers: { model: "transcribe-1-pro" } } - ); + const heard = await client.speechToText.convert({ + audio: new File([await readFile(audioPath)], audioPath), + language: "en", + model: "transcribe-1-pro", // requires fish-audio 0.2.0 or later + }); // Drop speaker markers such as <|speaker:0|>; keep cues such as [laughter]. const said = heard.text.replace(/\s*<\|speaker:\d+\|>\s*/g, " ").trim(); diff --git a/developer-guide/sdk-guide/quickstart.mdx b/developer-guide/sdk-guide/quickstart.mdx index dcb13697..929e4fdb 100644 --- a/developer-guide/sdk-guide/quickstart.mdx +++ b/developer-guide/sdk-guide/quickstart.mdx @@ -9,9 +9,9 @@ import Prerequisites from "/snippets/prerequisites.mdx"; The fastest path from zero to playable audio with the official Fish Audio SDKs. By the end you'll have a script that turns text into an MP3. - The Python SDK is the recommended starting point and is fully covered below. - The JavaScript SDK is in early release. See the [JavaScript SDK - guide](/api-reference/sdk/javascript/api-reference) for its current + The JavaScript SDK (`fish-audio` on npm) requires Node.js 20 or later and + works with both `import` and `require`. See the [JavaScript SDK + reference](/api-reference/sdk/javascript/api-reference) for its full surface. diff --git a/features/text-to-speech.mdx b/features/text-to-speech.mdx index ccf99b5a..b63e80e0 100644 --- a/features/text-to-speech.mdx +++ b/features/text-to-speech.mdx @@ -116,7 +116,7 @@ curl --request POST https://api.fish.audio/v1/tts \ - **`s2-pro`**: previous-generation S2 model with multi-speaker and natural-language expression control. - **`s1`**: previous generation, `(parenthesis)` emotion tags. S1 is deprecated and will be retired on December 31, 2026. After that date, requests that specify `s1` are served by `s2.1-pro`. See [Migrate from S1](/developer-guide/models-pricing/migrate-from-s1). -In the API, select with the `model` request header; requests without it use `s2.1-pro`. The Python SDK always sends a model and defaults to `model="s2-pro"`. See [Choosing a Model](/developer-guide/models-pricing/choosing-a-model). +In the API, select with the `model` request header; requests without it use `s2.1-pro`. The Python SDK always sends a model and defaults to `model="s2-pro"`. The JavaScript SDK defaults to `s2.1-pro` (`fish-audio` 0.2.0 and later). See [Choosing a Model](/developer-guide/models-pricing/choosing-a-model). ### Output formats diff --git a/llms.txt b/llms.txt index 2c231c54..06acba63 100644 --- a/llms.txt +++ b/llms.txt @@ -35,7 +35,7 @@ - [SDK Quickstart](https://docs.fish.audio/developer-guide/sdk-guide/quickstart.md): Install the Python SDK (pip install fish-audio-sdk) or the JavaScript SDK (npm install fish-audio), authenticate with the FISH_API_KEY environment variable, and generate your first audio. - [Python SDK Overview](https://docs.fish.audio/api-reference/sdk/python/overview.md): Official Python SDK overview and setup. - [Python Authentication](https://docs.fish.audio/developer-guide/sdk-guide/python/authentication.md): Configure API authentication for the Fish Audio Python SDK. -- [JavaScript SDK Reference](https://docs.fish.audio/api-reference/sdk/javascript/api-reference.md): Reference for the Fish Audio JavaScript SDK, covering client setup with an API key, text to speech, realtime streaming over WebSocket with convertRealtime(), speech to text, and voice model creation with voices.ivc.create(). +- [JavaScript SDK Reference](https://docs.fish.audio/api-reference/sdk/javascript/api-reference.md): Reference for the Fish Audio JavaScript SDK (fish-audio 0.2.0, Node.js 20+), covering client setup with an API key, text to speech, realtime TTS streaming over WebSocket, speech to text with model selection, realtime speech to text with speechToText.convertRealtime(), voice model creation with voices.ivc.create(), and upgrade notes from 0.1.0. - [Get Your API Key](https://docs.fish.audio/developer-guide/getting-started/api-key.md): Create a Fish Audio account, generate an API key, and make your first request. - [Instant Voice Cloning](https://docs.fish.audio/developer-guide/sdk-guide/cookbook/instant-voice-cloning.md): Clone a voice on the fly for a single request from a short reference clip and its transcript, with Python SDK and JavaScript SDK examples. - [Clone a Voice and Wait Until It Is Ready](https://docs.fish.audio/developer-guide/sdk-guide/cookbook/clone-and-wait-until-ready.md): Create a persistent voice from a reference clip, poll until training finishes, then synthesize with it, with Python SDK and JavaScript SDK examples. diff --git a/tests/js/package.json b/tests/js/package.json index 5e61e09f..bd27010b 100644 --- a/tests/js/package.json +++ b/tests/js/package.json @@ -8,7 +8,7 @@ "test": "node run.mjs" }, "dependencies": { - "fish-audio": "^0.1.0", + "fish-audio": "^0.2.0", "@msgpack/msgpack": "^3.0.0", "ws": "^8.18.0" } From 7f8a2bb07e58b02c8bcd14bd7a49192b757a27bb Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:53:19 -0800 Subject: [PATCH 2/3] docs(sdk): address review on the JavaScript SDK 0.2.0 pages - Errors: separate ordinary HTTP errors (only 422 is typed) from the realtime STT handshake, which throws BadRequestError, UnauthorizedError, ForbiddenError or NotFoundError for 400/401/403/404. - ReferenceAudio: the type is File; a Blob works at runtime but does not compile, so wrap it in a File. - Migrate from S1: link the 0.2.0 upgrade notes. Co-Authored-By: Claude Fable 5.2 --- .../fish-audio-sdk/references/errors.md | 26 ++++++++++++------- .../references/voice-cloning.md | 2 +- .../sdk/javascript/api-reference.mdx | 6 ++--- developer-guide/getting-started/changelog.mdx | 2 +- .../models-pricing/migrate-from-s1.mdx | 2 +- 5 files changed, 23 insertions(+), 15 deletions(-) diff --git a/.mintlify/skills/fish-audio-sdk/references/errors.md b/.mintlify/skills/fish-audio-sdk/references/errors.md index e2c3cf95..cd206401 100644 --- a/.mintlify/skills/fish-audio-sdk/references/errors.md +++ b/.mintlify/skills/fish-audio-sdk/references/errors.md @@ -88,17 +88,25 @@ try { } ``` -What the JS client actually throws: +What the JS client actually throws for ordinary HTTP requests (`convert`, `voices.*`, `user.*`, ...): -| Error | When | -| ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -| `UnprocessableEntityError` (extends `FishAudioError`) | 422, the **only** typed HTTP subclass thrown; `.body` is `{ detail: [{ loc, msg, type }] }` | -| `FishAudioError` | every other non-2xx response; read `.statusCode`, `.body`, `.rawResponse` | -| `FishAudioTimeoutError` | request exceeded the timeout | -| `RealtimeSTTError` (extends `FishAudioError`) | realtime STT session failed or the connection was lost; read `.errorType`, `.statusCode`, `.closeCode`, `.requestId` | -| `UnauthorizedError` | realtime STT handshake refused with 401 (`speechToText.convertRealtime`) | +| Error | When | +| ----------------------------------------------------- | ------------------------------------------------------------------------------------------- | +| `UnprocessableEntityError` (extends `FishAudioError`) | 422, the **only** typed HTTP subclass thrown; `.body` is `{ detail: [{ loc, msg, type }] }` | +| `FishAudioError` | every other non-2xx response; read `.statusCode`, `.body`, `.rawResponse` | +| `FishAudioTimeoutError` | request exceeded the timeout | -> The package also exports `BadRequestError`, `UnauthorizedError`, `ForbiddenError`, `NotFoundError`, and `TooEarlyError`, but the current client throws a generic `FishAudioError` for those statuses. **Branch on `err.statusCode`** rather than relying on `instanceof NotFoundError`. +> For HTTP requests, the package also exports `BadRequestError`, `UnauthorizedError`, `ForbiddenError`, `NotFoundError`, and `TooEarlyError`, but the client throws a generic `FishAudioError` for those statuses. **Branch on `err.statusCode`** rather than relying on `instanceof NotFoundError`. + +Realtime speech-to-text (`speechToText.convertRealtime`) throws from the `for await` loop: + +| Error | When | +| ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | +| `BadRequestError` / `UnauthorizedError` / `ForbiddenError` / `NotFoundError` | the WebSocket handshake was refused with 400 / 401 / 403 / 404 (an invalid API key gives `UnauthorizedError`) | +| `FishAudioError` | the handshake was refused with any other status, such as 402 or 429; read `.statusCode` and `.body` | +| `RealtimeSTTError` (extends `FishAudioError`) | the session failed or the connection was lost; read `.errorType`, `.statusCode`, `.closeCode`, `.requestId` | + +All of these extend `FishAudioError`, so `err.statusCode` works for each of them. ### Retries & timeouts (JavaScript) diff --git a/.mintlify/skills/fish-audio-sdk/references/voice-cloning.md b/.mintlify/skills/fish-audio-sdk/references/voice-cloning.md index 6f4fa9c9..cfb1e6d8 100644 --- a/.mintlify/skills/fish-audio-sdk/references/voice-cloning.md +++ b/.mintlify/skills/fish-audio-sdk/references/voice-cloning.md @@ -47,7 +47,7 @@ const audio = await client.textToSpeech.convert({ await play(audio); ``` -In JS, `ReferenceAudio.audio` must be a `File` or `Blob`. In `fish-audio` 0.2.0 a `Buffer` or `Uint8Array` fails with `ref.audio.arrayBuffer is not a function`; wrap it in a `File` as above. +In JS, `ReferenceAudio.audio` is typed as `File`. A `Blob` also works at runtime but does not compile in TypeScript, so wrap it: `new File([blob], "reference.wav")`. In `fish-audio` 0.2.0 a `Buffer` or `Uint8Array` fails with `ref.audio.arrayBuffer is not a function`; wrap it in a `File` as above. ## 2. Persistent voice models diff --git a/api-reference/sdk/javascript/api-reference.mdx b/api-reference/sdk/javascript/api-reference.mdx index fcdd8b20..64a05992 100644 --- a/api-reference/sdk/javascript/api-reference.mdx +++ b/api-reference/sdk/javascript/api-reference.mdx @@ -170,7 +170,7 @@ await stream.close(); // end the session and close the connection Errors are thrown from the `for await` loop: - `RealtimeSTTError` when the server ends the session or the connection is lost. It carries `errorType` (such as `unsupported_audio`; match on this field), `statusCode`, `requestId`, `closeCode` and `recoverable`. -- `UnauthorizedError`, or `FishAudioError` with a `statusCode` such as 402 or 429, when the connection is refused. +- When the connection is refused: `BadRequestError` (400), `UnauthorizedError` (401), `ForbiddenError` (403) or `NotFoundError` (404), and `FishAudioError` with a `statusCode` for any other status, such as 402 or 429. All of them extend `FishAudioError`, so `err.statusCode` works for each. - The audio source's own error when the audio source throws. ```typescript @@ -348,7 +348,7 @@ Speech-to-text parameters. Fields: `audio`, `model?`, `language?`, `ignore_timestamps?` ### ReferenceAudio -Reference audio for zero-shot voice cloning. `audio` must be a `File` or `Blob`; wrap a `Buffer` in a `File`: +Reference audio for zero-shot voice cloning. `audio` is typed as `File`. At runtime the SDK also accepts a `Blob`, but TypeScript rejects one, so wrap a `Blob` or a `Buffer` in a `File` (`new File([blob], "reference.wav")`): ```typescript import { readFile } from "node:fs/promises"; @@ -470,7 +470,7 @@ Upgrading from 0.1.0 to 0.2.0: - **The default TTS model is now `s2.1-pro`**, for `textToSpeech.convert()` and `textToSpeech.convertRealtime()`. The published 0.1.0 package sent the deprecated `s1` when you passed no model. To use another model, pass it: `convert(request, "s2-pro")`. - **`opus_bitrate` is in bits per second.** Code that passes `24`, `32`, `48` or `64` no longer compiles: multiply the value by 1000. -- **`ReferenceAudio.audio` must be a `File` or `Blob`.** A `Buffer` or `Uint8Array` passed with a type cast now fails with `ref.audio.arrayBuffer is not a function`. Wrap it: `new File([buffer], "sample.mp3")`. +- **`ReferenceAudio.audio` must be a `File`** (a `Blob` also works at runtime, but the TypeScript type is `File`). A `Buffer` or `Uint8Array` passed with a type cast now fails with `ref.audio.arrayBuffer is not a function`. Wrap it: `new File([buffer], "sample.mp3")`. - **Model names are no longer cast.** `Backends` names `s2.1-pro`, `s2.1-pro-free` and `drama-3` and accepts any other string, so remove `as Backends` casts. `speech-1.5`, `speech-1.6`, `agent-x0` and `s1-mini` no longer autocomplete. - **Node.js 20 or later is required.** - **`require("fish-audio")` works.** In 0.1.0 it threw `ReferenceError: exports is not defined in ES module scope`. diff --git a/developer-guide/getting-started/changelog.mdx b/developer-guide/getting-started/changelog.mdx index b991f36f..a24d589d 100644 --- a/developer-guide/getting-started/changelog.mdx +++ b/developer-guide/getting-started/changelog.mdx @@ -9,7 +9,7 @@ rss: true `fish-audio` 0.2.0 on npm adds realtime speech to text with `transcribe-stream-1` (`speechToText.convertRealtime()`, Node.js only), a `model` option for `speechToText.convert()`, the `s2.1-pro`, `s2.1-pro-free` and `drama-3` models in the `Backends` type, multi-speaker text to speech, and more TTS request fields. `require("fish-audio")` works again. - Upgrade notes: the default TTS model is now `s2.1-pro` (0.1.0 sent the deprecated `s1`), `opus_bitrate` is in bits per second, reference audio must be a `File` or `Blob`, and Node.js 20 or later is required. + Upgrade notes: the default TTS model is now `s2.1-pro` (0.1.0 sent the deprecated `s1`), `opus_bitrate` is in bits per second, reference audio must be a `File`, and Node.js 20 or later is required. [JavaScript SDK reference](/api-reference/sdk/javascript/api-reference#upgrade-notes) | [Release notes](https://github.com/fishaudio/fish-audio-typescript/releases/tag/v0.2.0) diff --git a/developer-guide/models-pricing/migrate-from-s1.mdx b/developer-guide/models-pricing/migrate-from-s1.mdx index 83daa910..8967e83c 100644 --- a/developer-guide/models-pricing/migrate-from-s1.mdx +++ b/developer-guide/models-pricing/migrate-from-s1.mdx @@ -33,7 +33,7 @@ The steps below cover each of these changes. In the API, you select the model with the `model` request header. Change `s1` to `s2.1-pro` wherever you set the model, including SDK and integration settings. -If you use the JavaScript SDK (`fish-audio` on npm) 0.1.0 without passing a model, your requests use `s1`, because that is its default backend. Upgrade to 0.2.0 or later, which defaults to `s2.1-pro`, or pass the model explicitly. +If you use the JavaScript SDK (`fish-audio` on npm) 0.1.0 without passing a model, your requests use `s1`, because that is its default backend. Upgrade to 0.2.0 or later, which defaults to `s2.1-pro` (check the [upgrade notes](/api-reference/sdk/javascript/api-reference#upgrade-notes) for other breaking changes first), or pass the model explicitly. This example also converts the emotion tags, as described in the next step: From 26fbcae0c15e49351b9c34da43591b2578396af5 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:12:13 -0800 Subject: [PATCH 3/3] docs(sdk): realtime error fields can be undefined; the model header also selects the STT model Co-Authored-By: Claude Fable 5.2 --- .mintlify/skills/fish-audio-sdk/references/errors.md | 12 ++++++------ api-reference/sdk/javascript/api-reference.mdx | 4 ++-- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.mintlify/skills/fish-audio-sdk/references/errors.md b/.mintlify/skills/fish-audio-sdk/references/errors.md index cd206401..5409897f 100644 --- a/.mintlify/skills/fish-audio-sdk/references/errors.md +++ b/.mintlify/skills/fish-audio-sdk/references/errors.md @@ -100,13 +100,13 @@ What the JS client actually throws for ordinary HTTP requests (`convert`, `voice Realtime speech-to-text (`speechToText.convertRealtime`) throws from the `for await` loop: -| Error | When | -| ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | -| `BadRequestError` / `UnauthorizedError` / `ForbiddenError` / `NotFoundError` | the WebSocket handshake was refused with 400 / 401 / 403 / 404 (an invalid API key gives `UnauthorizedError`) | -| `FishAudioError` | the handshake was refused with any other status, such as 402 or 429; read `.statusCode` and `.body` | -| `RealtimeSTTError` (extends `FishAudioError`) | the session failed or the connection was lost; read `.errorType`, `.statusCode`, `.closeCode`, `.requestId` | +| Error | When | +| ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | +| `BadRequestError` / `UnauthorizedError` / `ForbiddenError` / `NotFoundError` | the WebSocket handshake was refused with 400 / 401 / 403 / 404 (an invalid API key gives `UnauthorizedError`) | +| `FishAudioError` | the handshake was refused with any other status, such as 402 or 429; read `.statusCode` and `.body` | +| `RealtimeSTTError` (extends `FishAudioError`) | the session failed or the connection was lost; read `.errorType`, `.closeCode`, `.requestId`, and `.statusCode` when it is set | -All of these extend `FishAudioError`, so `err.statusCode` works for each of them. +All of these extend `FishAudioError`. `err.statusCode` is set when the handshake is refused. On a `RealtimeSTTError` it can be `undefined`: a lost connection has a `closeCode` but no HTTP status, so handle connection errors without relying on a status. ### Retries & timeouts (JavaScript) diff --git a/api-reference/sdk/javascript/api-reference.mdx b/api-reference/sdk/javascript/api-reference.mdx index 64a05992..67f8c018 100644 --- a/api-reference/sdk/javascript/api-reference.mdx +++ b/api-reference/sdk/javascript/api-reference.mdx @@ -77,7 +77,7 @@ console.log(res.text); Parameters: `request` (STTRequest), `requestOptions?` (for example `timeoutInSeconds`)
Returns: `STTResponse` -`model` is sent as the `model` header. Without it, the request is served and billed as `transcribe-1`. See [Speech to Text](/features/speech-to-text). +`model` is sent as the `model` header. Without it, and without a `model` header in `requestOptions.headers`, the request is served and billed as `transcribe-1`. See [Speech to Text](/features/speech-to-text). ### convertRealtime() Transcribe live audio with `transcribe-stream-1` (Preview) over a WebSocket, turn by turn. Send 16-bit little-endian mono PCM in chunks of 20–40 ms as you capture it. The SDK opens the session, sends each chunk as the audio source yields it, and ends the session when the source is exhausted. It runs in Node.js only. @@ -169,7 +169,7 @@ await stream.close(); // end the session and close the connection Errors are thrown from the `for await` loop: -- `RealtimeSTTError` when the server ends the session or the connection is lost. It carries `errorType` (such as `unsupported_audio`; match on this field), `statusCode`, `requestId`, `closeCode` and `recoverable`. +- `RealtimeSTTError` when the server ends the session or the connection is lost. It carries `errorType` (such as `unsupported_audio`; match on this field), `statusCode`, `requestId`, `closeCode` and `recoverable`. `statusCode` and `closeCode` are optional: a lost connection has no HTTP status, so they can be `undefined`. - When the connection is refused: `BadRequestError` (400), `UnauthorizedError` (401), `ForbiddenError` (403) or `NotFoundError` (404), and `FishAudioError` with a `statusCode` for any other status, such as 402 or 429. All of them extend `FishAudioError`, so `err.statusCode` works for each. - The audio source's own error when the audio source throws.