From e89366b9435edd714d6a2fb515a7475e4f7b818f Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:01:00 -0800 Subject: [PATCH 1/6] docs(stt): use the Python SDK for realtime speech to text and model selection fish-audio-python adds client.asr.stream_websocket() for realtime speech to text and a model argument on asr.transcribe() (fishaudio/fish-audio-python#170). Realtime: the feature page's quick start and the "Transcribe a live audio stream" recipe now use the SDK (sync and async), say that transcripts carry speaker tags by default and how diarize=False turns them off, and list the session options. The WebSocket and MessagePack clients stay under "Without the SDK", for JavaScript (the TypeScript SDK does not support the endpoint yet) and other languages. Model selection: Python examples pass model="transcribe-1-pro" instead of RequestOptions(additional_headers={"model": ...}); examples that set a timeout keep RequestOptions for it. JavaScript examples are unchanged. Each page notes that the new arguments require fish-audio-sdk 1.5.0 or later. The cookbook specs follow the recipe's new block order and cover the two SDK scripts. Co-Authored-By: Claude Fable 5.2 --- .../endpoint/openapi-v1/speech-to-text.mdx | 7 +- .../migrate-from-transcribe-1.mdx | 9 +- .../batch-transcribe-with-language-hint.mdx | 22 +- .../cookbook/realtime-transcription.mdx | 277 ++++++++++++++---- .../cookbook/transcribe-to-captions.mdx | 16 +- .../sdk-guide/cookbook/voice-agent-loop.mdx | 19 +- features/speech-to-text.mdx | 49 ++-- features/speech-to-text/realtime.mdx | 42 ++- tests/cookbooks/requirements.txt | 2 +- tests/cookbooks/specs.py | 35 ++- 10 files changed, 350 insertions(+), 128 deletions(-) diff --git a/api-reference/endpoint/openapi-v1/speech-to-text.mdx b/api-reference/endpoint/openapi-v1/speech-to-text.mdx index b1fa93f8..8a265717 100644 --- a/api-reference/endpoint/openapi-v1/speech-to-text.mdx +++ b/api-reference/endpoint/openapi-v1/speech-to-text.mdx @@ -97,9 +97,10 @@ A field that is not returned is absent from the JSON, never `null`. Do not depen Both SDKs select `transcribe-1-pro` through the `model` header. In Python, - pass - `request_options=RequestOptions(additional_headers={"model": "transcribe-1-pro"})` - to `asr.transcribe()`. In JavaScript, pass + pass `model="transcribe-1-pro"` to `asr.transcribe()` (`fish-audio-sdk` 1.5.0 + or later; on earlier versions, pass + `request_options=RequestOptions(additional_headers={"model": "transcribe-1-pro"})`). + In JavaScript, pass `{ headers: { model: "transcribe-1-pro" } }` as the second argument to `speechToText.convert()`. The Python SDK currently returns only `text`, `duration`, and `segments`, and neither SDK can send `tag_audio_events`, diff --git a/developer-guide/models-pricing/migrate-from-transcribe-1.mdx b/developer-guide/models-pricing/migrate-from-transcribe-1.mdx index ae2fad84..36838459 100644 --- a/developer-guide/models-pricing/migrate-from-transcribe-1.mdx +++ b/developer-guide/models-pricing/migrate-from-transcribe-1.mdx @@ -51,17 +51,12 @@ curl --request POST https://api.fish.audio/v1/asr \ ```python Python from fishaudio import FishAudio -from fishaudio.core import RequestOptions client = FishAudio() # reads FISH_API_KEY with open("speech.wav", "rb") as f: - result = client.asr.transcribe( - audio=f.read(), - request_options=RequestOptions( - additional_headers={"model": "transcribe-1-pro"} - ), - ) + # model sends the header; it requires fish-audio-sdk 1.5.0 or later + result = client.asr.transcribe(audio=f.read(), model="transcribe-1-pro") print(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..27b4a5d2 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 @@ -12,13 +12,18 @@ import Prerequisites from "/snippets/prerequisites.mdx"; ## Recipe -This recipe uses `transcribe-1-pro`, which handles recordings up to 60 minutes long. Every tab selects it with the `model` request header; without that header, the request is served and billed as `transcribe-1`. +This recipe uses `transcribe-1-pro`, which handles recordings up to 60 minutes long. Every tab selects it with the `model` request header, which the Python SDK sends for its `model` argument; without that header, the request is served and billed as `transcribe-1`. Read each file's bytes from disk and pass them to [`asr.transcribe()`](/api-reference/sdk/python/resources#transcribe) with `language` set to a lowercase ISO 639-1 code such as `en`, `zh`, or `ja`. Other forms, such as `en-US` or `English`, may be rejected with 400. Pass `language` when you know the source language. Detection still runs, and the hint does not force the transcript into that language; the hint is reported as `language_code` when the language cannot be determined. See [Language](/features/speech-to-text#language) for details. Collect one result row per file as you go. If a file cannot be read, its request fails with a network error such as a timeout, or the API returns an error for it, record the error in that file's row and move on to the next file. -Install the Python SDK first: `pip install fish-audio-sdk`. +Install the Python SDK first: `pip install --upgrade fish-audio-sdk`. + + + The `model` argument of `asr.transcribe()` requires `fish-audio-sdk` 1.5.0 or + later. + @@ -32,10 +37,7 @@ client = FishAudio() paths = ["speech.wav"] # add more file paths here language = "en" -options = RequestOptions( - timeout=900, # long recordings can take several minutes - additional_headers={"model": "transcribe-1-pro"}, -) +options = RequestOptions(timeout=900) # long recordings can take several minutes results = [] for path in paths: @@ -44,6 +46,7 @@ for path in paths: audio = f.read() transcript = client.asr.transcribe( audio=audio, + model="transcribe-1-pro", language=language, include_timestamps=False, request_options=options, @@ -81,10 +84,8 @@ async def main(): async with AsyncFishAudio() as client: paths = ["speech.wav"] # add more file paths here language = "en" - options = RequestOptions( - timeout=900, # long recordings can take several minutes - additional_headers={"model": "transcribe-1-pro"}, - ) + # long recordings can take several minutes + options = RequestOptions(timeout=900) results = [] for path in paths: @@ -93,6 +94,7 @@ async def main(): audio = f.read() transcript = await client.asr.transcribe( audio=audio, + model="transcribe-1-pro", language=language, include_timestamps=False, request_options=options, diff --git a/developer-guide/sdk-guide/cookbook/realtime-transcription.mdx b/developer-guide/sdk-guide/cookbook/realtime-transcription.mdx index 01a3f63a..951462e8 100644 --- a/developer-guide/sdk-guide/cookbook/realtime-transcription.mdx +++ b/developer-guide/sdk-guide/cookbook/realtime-transcription.mdx @@ -13,7 +13,222 @@ import Prerequisites from "/snippets/prerequisites.mdx"; -The SDKs do not wrap the realtime speech-to-text endpoint yet, so this recipe speaks the WebSocket protocol directly. Install a WebSocket client and a MessagePack library: +Install the Python SDK: + +```bash +pip install --upgrade fish-audio-sdk +``` + + + `client.asr.stream_websocket()` requires `fish-audio-sdk` 1.5.0 or later. The + TypeScript SDK does not support realtime speech to text yet: in JavaScript, + [connect to the WebSocket directly](#without-the-sdk). + + +You also need a 16-bit PCM mono WAV file, at 8000, 12000, 16000, 22050, 24000, 32000, 44100 or 48000 Hz. To convert a recording, run `ffmpeg -i input.mp3 -ac 1 -ar 16000 -c:a pcm_s16le speech.wav`. + +## Recipe + +`client.asr.stream_websocket()` takes an iterator of audio chunks and returns the events the server sends. The script streams the file in 40 ms chunks at real-time speed, as a live microphone would, and prints every event until the session ends. The SDK opens the session, sends each chunk as it is yielded, and ends the session when the iterator is exhausted. + + + +```python Python +"""Stream a WAV file to Fish Audio realtime speech-to-text and print the events. + + pip install --upgrade fish-audio-sdk + export FISH_API_KEY=... + python transcribe_file.py speech.wav + +The WAV must be 16-bit PCM, mono, at 8000, 12000, 16000, 22050, 24000, 32000, 44100 or 48000 Hz. +""" +import sys +import time +import wave + +from fishaudio import FishAudio + +CHUNK_MS = 40 # ms of audio per chunk; 20-40 ms suits live audio + + +def microphone(wav, rate): + """Yield the audio in real time, as a live microphone would.""" + start = time.monotonic() + sent_ms = 0 + while chunk := wav.readframes(rate * CHUNK_MS // 1000): + yield chunk + sent_ms += CHUNK_MS + time.sleep(max(0.0, start + sent_ms / 1000 - time.monotonic())) + + +def show(event): + t = event.type + if t == "session_started": + print(f"session {event.session_id} (request {event.request_id})") + elif t == "draft": + print(f" draft #{event.turn_index}: {event.text}") + elif t == "eager_end_of_turn": + print(f" eager #{event.turn_index}: {event.text}") + elif t == "committed": + who = "user " if event.user_turn else "other" + print(f"committed #{event.turn_index} [{who}] {event.audio_start_ms}-{event.audio_end_ms} ms " + f"({event.reason}, {event.language_code or '?'}): {event.text}") + elif t == "error": # recoverable: the session continues + print(f"error {event.error_type} ({event.code}): {event.message} [request {event.request_id}]") + elif t == "session_done": + print(f"done: {event.stats.audio_ms} ms of audio, {event.stats.turns} turns") + else: # speech_start, user_turn_taken, turn_resumed, ... + print(f" {t} #{getattr(event, 'turn_index', '')}") + + +def main(path): + wav = wave.open(path, "rb") + if wav.getsampwidth() != 2 or wav.getnchannels() != 1: + sys.exit("need a 16-bit mono WAV") + rate = wav.getframerate() + + client = FishAudio() # reads FISH_API_KEY + for event in client.asr.stream_websocket( + microphone(wav, rate), sample_rate=rate, eager=True, drafts=True + ): + show(event) + + +if __name__ == "__main__": + main(sys.argv[1]) +``` + +```python Python (async) +"""The same script with AsyncFishAudio: pass an async iterator, read with async for.""" +import asyncio +import sys +import wave + +from fishaudio import AsyncFishAudio + +CHUNK_MS = 40 # ms of audio per chunk; 20-40 ms suits live audio + + +async def microphone(wav, rate): + """Yield the audio in real time, as a live microphone would.""" + loop = asyncio.get_running_loop() + start = loop.time() + sent_ms = 0 + while chunk := wav.readframes(rate * CHUNK_MS // 1000): + yield chunk + sent_ms += CHUNK_MS + await asyncio.sleep(max(0.0, start + sent_ms / 1000 - loop.time())) + + +async def main(path): + wav = wave.open(path, "rb") + if wav.getsampwidth() != 2 or wav.getnchannels() != 1: + sys.exit("need a 16-bit mono WAV") + rate = wav.getframerate() + + client = AsyncFishAudio() # reads FISH_API_KEY + async for event in client.asr.stream_websocket( + microphone(wav, rate), sample_rate=rate, eager=True, drafts=True + ): + if event.type == "draft": + print(f" draft #{event.turn_index}: {event.text}") + elif event.type == "committed": + print(f"committed #{event.turn_index}: {event.text}") + elif event.type == "session_done": + print(f"done: {event.stats.audio_ms} ms of audio, {event.stats.turns} turns") + await client.close() + + +if __name__ == "__main__": + asyncio.run(main(sys.argv[1])) +``` + + + +Run it with your API key in `FISH_API_KEY`: + +```bash +python transcribe_file.py speech.wav +``` + +For a 15-second customer-support clip, the output looks like this (`...` marks drafts left out): + +```text +session s_ab12cd34 (request 0b6f4c1e-7d2a-4e8b-9f3c-5a1d2e3f4b6c) + speech_start #0 + draft #0: <|speaker:0|> Can you... + draft #0: <|speaker:0|> Can you tell + user_turn_taken #0 + draft #0: <|speaker:0|> Can you tell me what... + ... + draft #0: <|speaker:0|> Can you tell me what time the pharmacy on Main Street closes tonight? + eager #0: <|speaker:0|> Can you tell me what time the pharmacy on Main Street closes tonight? +committed #0 [user ] 2768-8000 ms (eot, en): <|speaker:0|> Can you tell me what time the pharmacy on Main Street closes tonight? + speech_start #1 + draft #1: <|speaker:0|> Uh-huh. + user_turn_taken #1 + eager #1: <|speaker:0|> Uh-huh. +committed #1 [user ] 9840-11840 ms (eot, ?): <|speaker:0|> Uh-huh. + speech_start #2 + draft #2: <|speaker:0|> I'd like + user_turn_taken #2 + ... + draft #2: <|speaker:0|> I'd like to change my deli- +committed #2 [user ] 13168-14992 ms (audio_done, en): <|speaker:0|> I'd like to change my delivery +done: 15000 ms of audio, 3 turns +``` + +The clip ends mid-sentence, so the last turn is committed by `audio_done`. Drafts can hold partial words, such as `deli-`; the committed text is final. + +## Read the events + +Each event is an object with a `type` and the fields of the server message as attributes; a field the server left out is `None`. + +- **`speech_start`** opens a turn when voice activity begins. In the default `auto` mode, noise and other voices open turns too. +- **`draft`** is the whole turn so far, and replaces the previous draft. Drafts come only with `drafts=True` (`results.drafts: true` in the protocol); use them for live captions. +- **`user_turn_taken`** says the server judged that the user is taking their turn, rather than noise or someone else nearby. +- **`eager_end_of_turn`** comes with `eager=True` (`turn_detection.eager: true`) when the turn has probably ended. Its text equals the final transcript unless `turn_resumed` follows, so an agent can start its reply early. +- **`committed`** is the final transcript of the turn. `user_turn: false` marks a non-user turn, such as background noise or a short acknowledgement while your agent is speaking. Speaker tags such as `<|speaker:0|>` are stable within the session; strip them and trim the text, or pass `diarize=False` (`results.diarize: false`). Text can also contain [sound tags](/api-reference/endpoint/websocket/asr-realtime#sound-tags) such as `[laughter]`; strip them too, or turn them off with `results.tag_audio_events: false`. `language_code` is missing when the text is too short to tell, as for "Uh-huh." above. +- **`session_done`** is the last event. The SDK sends `audio_done` when your iterator is exhausted; the server answers with `session_done` and closes the connection with code 1000. + +The SDK skips message types it does not know; if you read the protocol yourself, ignore message types and fields you do not know, because new ones can be added. Every message is described in the [WebSocket reference](/api-reference/endpoint/websocket/asr-realtime#server-messages). + + + The script streams the file at real-time speed so that the events arrive as + they would for live audio. To transcribe a recording you already have, use + [`POST /v1/asr`](/features/speech-to-text) instead; it is simpler and returns + the whole transcript at once. + + +## Choose what you receive + +The keyword arguments of `stream_websocket()` set the session's options: + +| Argument | Default | What it does | +| ---------------- | -------- | ------------------------------------------------------------------------------------------------ | +| `sample_rate` | `16000` | The sample rate of your audio, in Hz. The server converts it, so do not resample. | +| `drafts` | off | `True` sends live `draft` events while a turn is open. | +| `eager` | off | `True` sends `eager_end_of_turn` as soon as a turn has probably ended. | +| `diarize` | on | `False` removes speaker tags from the text. | +| `turn_detection` | `"auto"` | `"vad"` ends a turn after a fixed silence; `"manual"` ends it when you call `finalize()`. | +| `terms` | none | Names, products and jargon to recognize, for example `["Main Street"]`. | +| `config` | | An `ASRRealtimeConfig` with every other option, such as word timestamps, sound tags and history. | + +By default, each transcript starts with a speaker tag, as in the output above. For plain text, pass `diarize=False`: + +```python +for event in client.asr.stream_websocket(audio_chunks, sample_rate=16000, diarize=False): + if event.type == "committed": + print(event.text) # Can you tell me what time the pharmacy on Main Street closes tonight? +``` + +The object that `stream_websocket()` returns also sends messages during the session: `finalize()` commits the current turn (push-to-talk), and `agent_speaking()`, `add_context()` and `configure()` are for [voice agents](/developer-guide/sdk-guide/cookbook/realtime-voice-agent). To stop before the audio ends, leave the loop, or use the stream in a `with` block; the SDK closes the connection. + +An error that ends the session raises `ASRRealtimeError` (from `fishaudio`), with the server's `error_type` and the WebSocket `close_code`. A refused connection raises `APIError`, such as `AuthenticationError` for an invalid API key. + +## Without the SDK + +In JavaScript, in other languages, or to control the connection yourself, speak the WebSocket protocol directly: connect to `wss://api.fish.audio/v1/asr/realtime`, send a `config` message, wait for `session_started`, then send `audio` messages and finish with `audio_done`. Every message is a MessagePack map in a binary frame. Install a WebSocket client and a MessagePack library: @@ -27,15 +242,11 @@ npm install ws @msgpack/msgpack -You also need a 16-bit PCM mono WAV file, at 8000, 12000, 16000, 22050, 24000, 32000, 44100 or 48000 Hz. To convert a recording, run `ffmpeg -i input.mp3 -ac 1 -ar 16000 -c:a pcm_s16le speech.wav`. - -## Recipe - -The script connects to `wss://api.fish.audio/v1/asr/realtime`, sends a `config` message, waits for `session_started`, and then streams the file in 40 ms messages at real-time speed, as a live microphone would. It prints every message the server sends until the session ends. +These scripts do the same as the recipe above, and also print the close code when the session ends (`closed: 1000 done`): -```python Python +```python Python (websockets) """Stream a WAV file to Fish Audio realtime speech-to-text and print the events. pip install "websockets>=14" msgpack @@ -125,7 +336,7 @@ if __name__ == "__main__": asyncio.run(main(sys.argv[1])) ``` -```javascript JavaScript +```javascript JavaScript (ws) // npm install ws @msgpack/msgpack // FISH_API_KEY=... node transcribe_file.mjs speech.wav import { readFileSync } from "node:fs"; @@ -240,7 +451,7 @@ The audio goes in `data` as the raw PCM bytes, which must travel as MessagePack The server closes a session after 30 seconds without any client message, but a WebSocket ping counts as one, and Python's `websockets` sends a ping every 20 seconds by default, so the session stays open even if your audio stops; see [Capture audio well](/developer-guide/sdk-guide/cookbook/realtime-voice-agent#capture-audio-well) for a live source that can stall. -Run it with your API key in `FISH_API_KEY`: +Run them with your API key in `FISH_API_KEY`: ```bash python transcribe_file.py speech.wav @@ -248,54 +459,6 @@ python transcribe_file.py speech.wav node transcribe_file.mjs speech.wav ``` -For a 15-second customer-support clip, the output looks like this (`...` marks drafts left out): - -```text -session s_ab12cd34 (request 0b6f4c1e-7d2a-4e8b-9f3c-5a1d2e3f4b6c) - speech_start #0 - draft #0: <|speaker:0|> Can you... - draft #0: <|speaker:0|> Can you tell - user_turn_taken #0 - draft #0: <|speaker:0|> Can you tell me what... - ... - draft #0: <|speaker:0|> Can you tell me what time the pharmacy on Main Street closes tonight? - eager #0: <|speaker:0|> Can you tell me what time the pharmacy on Main Street closes tonight? -committed #0 [user ] 2768-8000 ms (eot, en): <|speaker:0|> Can you tell me what time the pharmacy on Main Street closes tonight? - speech_start #1 - draft #1: <|speaker:0|> Uh-huh. - user_turn_taken #1 - eager #1: <|speaker:0|> Uh-huh. -committed #1 [user ] 9840-11840 ms (eot, ?): <|speaker:0|> Uh-huh. - speech_start #2 - draft #2: <|speaker:0|> I'd like - user_turn_taken #2 - ... - draft #2: <|speaker:0|> I'd like to change my deli- -committed #2 [user ] 13168-14992 ms (audio_done, en): <|speaker:0|> I'd like to change my delivery -done: 15000 ms of audio, 3 turns -closed: 1000 done -``` - -The clip ends mid-sentence, so the last turn is committed by `audio_done`. Drafts can hold partial words, such as `deli-`; the committed text is final. - -## Read the events - -- **`speech_start`** opens a turn when voice activity begins. In the default `auto` mode, noise and other voices open turns too. -- **`draft`** is the whole turn so far, and replaces the previous draft. Drafts come only with `results.drafts: true`; use them for live captions. -- **`user_turn_taken`** says the server judged that the user is taking their turn, rather than noise or someone else nearby. -- **`eager_end_of_turn`** comes with `turn_detection.eager: true` when the turn has probably ended. Its text equals the final transcript unless `turn_resumed` follows, so an agent can start its reply early. -- **`committed`** is the final transcript of the turn. `user_turn: false` marks a non-user turn, such as background noise or a short acknowledgement while your agent is speaking. Speaker tags such as `<|speaker:0|>` are stable within the session; strip them and trim the text, or send `results.diarize: false`. Text can also contain [sound tags](/api-reference/endpoint/websocket/asr-realtime#sound-tags) such as `[laughter]`; strip them too, or send `results.tag_audio_events: false`. `language_code` is omitted when the text is too short to tell, as for "Uh-huh." above. -- **`session_done`** follows `audio_done`, and the server then closes the connection with code 1000. - -Ignore message types and fields you do not know: new ones can be added. Every message is described in the [WebSocket reference](/api-reference/endpoint/websocket/asr-realtime#server-messages). - - - The script streams the file at real-time speed so that the events arrive as - they would for live audio. To transcribe a recording you already have, use - [`POST /v1/asr`](/features/speech-to-text) instead; it is simpler and returns - the whole transcript at once. - - ## Capture from a browser microphone The API key travels in a request header, and browsers cannot set headers on a WebSocket. Never put your API key in a web page: run a small relay on your server that adds the `Authorization` header and passes MessagePack frames through unchanged. The page then speaks the same protocol as the scripts above. diff --git a/developer-guide/sdk-guide/cookbook/transcribe-to-captions.mdx b/developer-guide/sdk-guide/cookbook/transcribe-to-captions.mdx index 81e8fbcc..dccf6ba7 100644 --- a/developer-guide/sdk-guide/cookbook/transcribe-to-captions.mdx +++ b/developer-guide/sdk-guide/cookbook/transcribe-to-captions.mdx @@ -12,13 +12,18 @@ import Prerequisites from "/snippets/prerequisites.mdx"; ## Recipe -This recipe uses `transcribe-1-pro`, which handles recordings up to 60 minutes long. Both tabs select it with the `model` request header; without that header, the request is served and billed as `transcribe-1`. +This recipe uses `transcribe-1-pro`, which handles recordings up to 60 minutes long. Both tabs select it with the `model` request header, which the Python SDK sends for its `model` argument; without that header, the request is served and billed as `transcribe-1`. Call [`asr.transcribe()`](/api-reference/sdk/python/resources#transcribe) with `include_timestamps=True` (in JavaScript, `ignore_timestamps: false`) to get timed segments ([`ASRSegment`](/api-reference/sdk/python/types#asrsegment-objects)). Segments are word-level (one character, or a few, in Chinese and Japanese) and carry no punctuation, so group consecutive segments into caption-sized cues before you format them. Segment `start` / `end` are in **seconds**; SRT wants `HH:MM:SS,mmm` (comma), WebVTT wants `HH:MM:SS.mmm` (dot). The recipe starts a new cue after a pause longer than 0.6 seconds, or when the cue would grow past 42 characters or 6 seconds. It joins words with a space, except between Chinese or Japanese characters, which are written without spaces. A segment can have `start` equal to `end`, so a cue with no duration gets a short one that ends no later than the next cue starts. Every cue therefore ends after it starts, as SRT and WebVTT players expect. -Install the Python SDK first: `pip install fish-audio-sdk`. +Install the Python SDK first: `pip install --upgrade fish-audio-sdk`. + + + The `model` argument of `asr.transcribe()` requires `fish-audio-sdk` 1.5.0 or + later. + @@ -87,11 +92,10 @@ def format_timestamp(ms: int, separator: str) -> str: with open("speech.wav", "rb") as f: result = client.asr.transcribe( audio=f.read(), + model="transcribe-1-pro", include_timestamps=True, - request_options=RequestOptions( - timeout=900, # long recordings can take several minutes - additional_headers={"model": "transcribe-1-pro"}, - ), + # long recordings can take several minutes + request_options=RequestOptions(timeout=900), ) cues = group_cues(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..8d31a84e 100644 --- a/developer-guide/sdk-guide/cookbook/voice-agent-loop.mdx +++ b/developer-guide/sdk-guide/cookbook/voice-agent-loop.mdx @@ -14,9 +14,14 @@ import Prerequisites from "/snippets/prerequisites.mdx"; A voice agent is three stages chained together: [`asr.transcribe()`](/api-reference/sdk/python/resources#transcribe) turns the caller's audio into text, your own LLM turns that text into a reply, and [`tts.stream()`](/api-reference/sdk/python/resources#stream) turns the reply back into speech. The transcript and the reply are just strings, so the only Fish Audio-specific parts are the first and last calls. Streaming the reply lets you start writing (or forwarding) audio before the whole sentence is synthesized. -The recipe transcribes with `transcribe-1-pro`. Every tab selects it with the `model` request header; without that header, the request is served and billed as `transcribe-1`. +The recipe transcribes with `transcribe-1-pro`. Every tab selects it with the `model` request header, which the Python SDK sends for its `model` argument; without that header, the request is served and billed as `transcribe-1`. -Install the Python SDK first: `pip install fish-audio-sdk`. +Install the Python SDK first: `pip install --upgrade fish-audio-sdk`. + + + The `model` argument of `asr.transcribe()` requires `fish-audio-sdk` 1.5.0 or + later. + @@ -24,7 +29,6 @@ Install the Python SDK first: `pip install fish-audio-sdk`. import re from fishaudio import FishAudio -from fishaudio.core import RequestOptions from fishaudio.utils import save client = FishAudio() @@ -39,10 +43,8 @@ def voice_agent_turn(audio_path: str, out_path: str) -> str: with open(audio_path, "rb") as f: heard = client.asr.transcribe( audio=f.read(), + model="transcribe-1-pro", include_timestamps=False, - request_options=RequestOptions( - additional_headers={"model": "transcribe-1-pro"} - ), ) # Drop speaker markers such as <|speaker:0|>; keep cues such as [laughter]. @@ -62,7 +64,6 @@ import asyncio import re from fishaudio import AsyncFishAudio -from fishaudio.core import RequestOptions from fishaudio.utils import save def reply_from_llm(text: str) -> str: @@ -75,10 +76,8 @@ async def main(): with open("speech.wav", "rb") as f: heard = await client.asr.transcribe( audio=f.read(), + model="transcribe-1-pro", include_timestamps=False, - request_options=RequestOptions( - additional_headers={"model": "transcribe-1-pro"} - ), ) # Drop speaker markers such as <|speaker:0|>; keep cues such as [laughter]. diff --git a/features/speech-to-text.mdx b/features/speech-to-text.mdx index 96dfd19f..32569722 100644 --- a/features/speech-to-text.mdx +++ b/features/speech-to-text.mdx @@ -93,11 +93,10 @@ client = FishAudio() # reads FISH_API_KEY with open("speech.wav", "rb") as f: result = client.asr.transcribe( audio=f.read(), + model="transcribe-1-pro", include_timestamps=True, - request_options=RequestOptions( - timeout=900, # long recordings can take several minutes - additional_headers={"model": "transcribe-1-pro"}, - ), + # long recordings can take several minutes + request_options=RequestOptions(timeout=900), ) print(result.text) @@ -140,10 +139,12 @@ The response contains `text`, `duration` (seconds), `segments`, and `request_id` The Python SDK currently returns only `text`, `duration`, and `segments`. To read the other fields, call the API directly (see [Direct API](#direct-api-messagepack)). - The Python SDK selects Pro through `RequestOptions.additional_headers`; - `asr.transcribe()` has no `model` argument, and it cannot send the - `transcribe-1-pro` fields such as `diarize`. The JavaScript example calls the - REST API directly so the header is explicit. For multipart uploads, let your + In the Python SDK, `model="transcribe-1-pro"` sends the `model` header. The + argument requires `fish-audio-sdk` 1.5.0 or later; on earlier versions, pass + `request_options=RequestOptions(additional_headers={"model": "transcribe-1-pro"})` + instead. `asr.transcribe()` cannot send the `transcribe-1-pro` fields such as + `diarize`. The JavaScript example calls the REST API directly so the header is + explicit. For multipart uploads, let your HTTP client set `Content-Type` and its boundary. @@ -160,10 +161,8 @@ Each segment is `{ "text", "start", "end" }`, with times in **seconds**. Segment ```python Python result = client.asr.transcribe( audio=audio_bytes, + model="transcribe-1-pro", include_timestamps=True, - request_options=RequestOptions( - additional_headers={"model": "transcribe-1-pro"} - ), ) print(f"{result.duration:.1f}s total") @@ -371,14 +370,12 @@ If the language cannot be determined (for example, very short audio), `language_ ```python Python -pro = RequestOptions(additional_headers={"model": "transcribe-1-pro"}) - # Auto-detect -result = client.asr.transcribe(audio=audio_bytes, request_options=pro) +result = client.asr.transcribe(audio=audio_bytes, model="transcribe-1-pro") # Provide a language hint result = client.asr.transcribe( - audio=audio_bytes, language="zh", request_options=pro + audio=audio_bytes, language="zh", model="transcribe-1-pro" ) ``` @@ -494,12 +491,7 @@ import json from fishaudio.exceptions import APIError try: - result = client.asr.transcribe( - audio=audio_bytes, - request_options=RequestOptions( - additional_headers={"model": "transcribe-1-pro"} - ), - ) + result = client.asr.transcribe(audio=audio_bytes, model="transcribe-1-pro") except APIError as e: try: error = json.loads(e.body or "{}") @@ -525,10 +517,8 @@ async def main(): with open("speech.wav", "rb") as f: result = await client.asr.transcribe( audio=f.read(), - request_options=RequestOptions( - timeout=900, - additional_headers={"model": "transcribe-1-pro"}, - ), + model="transcribe-1-pro", + request_options=RequestOptions(timeout=900), ) print(result.text) @@ -544,12 +534,13 @@ from fishaudio.core import RequestOptions async def transcribe_all(paths): client = AsyncFishAudio() - pro = RequestOptions( - timeout=900, additional_headers={"model": "transcribe-1-pro"} - ) + options = RequestOptions(timeout=900) clips = [open(p, "rb").read() for p in paths] return await asyncio.gather(*[ - client.asr.transcribe(audio=clip, request_options=pro) for clip in clips + client.asr.transcribe( + audio=clip, model="transcribe-1-pro", request_options=options + ) + for clip in clips ]) for result in asyncio.run(transcribe_all(["speech.wav"])): diff --git a/features/speech-to-text/realtime.mdx b/features/speech-to-text/realtime.mdx index 30ce5966..0f83f50a 100644 --- a/features/speech-to-text/realtime.mdx +++ b/features/speech-to-text/realtime.mdx @@ -76,7 +76,43 @@ The realtime endpoints of the [compatible APIs](/developer-guide/compat/capabili ## Quick start -The SDKs do not wrap this endpoint; you connect with any WebSocket client and exchange MessagePack messages. +With the Python SDK, pass an iterator of audio chunks to `client.asr.stream_websocket()` and read the events it returns. Install it with `pip install --upgrade fish-audio-sdk` and set `FISH_API_KEY` in your environment. + +```python +import wave + +from fishaudio import FishAudio + +client = FishAudio() # reads FISH_API_KEY + + +def audio_chunks(): + # From a microphone, yield each chunk as you capture it. + with wave.open("speech.wav", "rb") as wav: # 16-bit mono PCM, 16 kHz + while chunk := wav.readframes(640): # 40 ms + yield chunk + + +for event in client.asr.stream_websocket( + audio_chunks(), sample_rate=16000, drafts=True, diarize=False +): + if event.type == "draft": # live text of the open turn, not final + print("...", event.text) + elif event.type == "committed": # final transcript of the turn + print(event.text) +``` + +Transcripts start with a speaker tag such as `<|speaker:0|>` by default; `diarize=False` gives plain text. With `AsyncFishAudio`, pass an async iterator and read the events with `async for`. + + + `client.asr.stream_websocket()` requires `fish-audio-sdk` 1.5.0 or later. The + TypeScript SDK does not support realtime speech to text yet; use the WebSocket + protocol below. + + +### Without the SDK + +In JavaScript and other languages, connect with any WebSocket client and exchange MessagePack messages. The Python SDK does these steps for you. @@ -110,7 +146,7 @@ The SDKs do not wrap this endpoint; you connect with any WebSocket client and ex } ``` -[Transcribe a live audio stream](/developer-guide/sdk-guide/cookbook/realtime-transcription) has complete, tested clients in Python and Node.js, and a browser microphone page with a server relay. +[Transcribe a live audio stream](/developer-guide/sdk-guide/cookbook/realtime-transcription) has a complete, tested recipe with the Python SDK, WebSocket clients in Python and Node.js, and a browser microphone page with a server relay. ## How a session works @@ -198,7 +234,7 @@ Send 16-bit little-endian PCM, mono, at 8000, 12000, 16000, 22050, 24000, 32000, ### Speakers -Transcripts contain speaker tags such as `<|speaker:0|>`, stable within a session. Strip them, or send `results.diarize: false` for plain text. Whitespace right after a tag can vary, so trim the text after you strip the tags. Transcripts can also contain sound tags such as `[laughter]` or `[pause]`. Strip them too, or send `results.tag_audio_events: false` to remove them; see [Sound tags](/api-reference/endpoint/websocket/asr-realtime#sound-tags). +Transcripts contain speaker tags such as `<|speaker:0|>`, stable within a session. Strip them, or send `results.diarize: false` (`diarize=False` in the Python SDK) for plain text. Whitespace right after a tag can vary, so trim the text after you strip the tags. Transcripts can also contain sound tags such as `[laughter]` or `[pause]`. Strip them too, or send `results.tag_audio_events: false` to remove them; see [Sound tags](/api-reference/endpoint/websocket/asr-realtime#sound-tags). ### Keys and browsers diff --git a/tests/cookbooks/requirements.txt b/tests/cookbooks/requirements.txt index 8c9c7f96..49c01c3e 100644 --- a/tests/cookbooks/requirements.txt +++ b/tests/cookbooks/requirements.txt @@ -1,4 +1,4 @@ -fish-audio-sdk>=1.3.0 +fish-audio-sdk>=1.5.0 httpx>=0.28 python-dotenv>=1.0 pytest>=8.0 diff --git a/tests/cookbooks/specs.py b/tests/cookbooks/specs.py index 1c15d741..a2530274 100644 --- a/tests/cookbooks/specs.py +++ b/tests/cookbooks/specs.py @@ -28,6 +28,24 @@ def print(*args, **kwargs): raise """ +# The same for a recipe that uses the SDK's client.asr.stream_websocket(). +SDK_REALTIME_RUN = """ +import builtins +import pytest +from fishaudio import APIError +_lines = [] +def print(*args, **kwargs): + _lines.append(" ".join(str(a) for a in args)) + builtins.print(*args, **kwargs) +def _run(recipe): + try: + recipe() + except APIError as e: + if e.status == 403: + pytest.skip("realtime speech to text is not enabled for this key's team") + raise +""" + SPECS = [ { "slug": "streaming-to-file", @@ -67,7 +85,7 @@ def print(*args, **kwargs): ], }, # ---- recipes authored by the cookbook workflow (one live-tested primary block each) ---- - # The speech-to-text recipes select transcribe-1-pro with the `model` header. + # The speech-to-text recipes select transcribe-1-pro with the SDK's `model` argument. { "slug": "transcribe-to-captions", "path": f"{COOKBOOK}/transcribe-to-captions.mdx", @@ -150,7 +168,20 @@ def print(*args, **kwargs): "slug": "realtime-transcription", "path": f"{COOKBOOK}/realtime-transcription.mdx", "cases": [ - {"name": "stream a wav file", "block": 0, "postamble": REALTIME_RUN + """ + {"name": "stream a wav file (sdk, sync)", "block": 0, "postamble": SDK_REALTIME_RUN + """ +_run(lambda: main("speech.wav")) +assert any(line.startswith("session ") for line in _lines), _lines +assert any(line.startswith(" draft ") for line in _lines), _lines +assert any(line.startswith("committed") for line in _lines), _lines +assert any(line.startswith("done: ") for line in _lines), _lines +"""}, + {"name": "stream a wav file (sdk, async)", "block": 1, "postamble": SDK_REALTIME_RUN + """ +import asyncio +_run(lambda: asyncio.run(main("speech.wav"))) +assert any(line.startswith("committed") for line in _lines), _lines +assert any(line.startswith("done: ") for line in _lines), _lines +"""}, + {"name": "stream a wav file (websocket)", "block": 3, "postamble": REALTIME_RUN + """ assert any(line.startswith("session ") for line in _lines), _lines assert any(line.startswith("committed") for line in _lines), _lines assert any(line.startswith("done: ") for line in _lines), _lines From 1130236b22ee86d71cf3388758906bfa5eec857c Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:01:12 -0800 Subject: [PATCH 2/6] docs(stt): describe reading and closing a realtime stream as released in 1.5.0 fish-audio-sdk 1.5.0 is on PyPI. Two behaviours it shipped with were not on the page: closing cuts the connection after half a second when the server has stopped reading, and a second concurrent read of the async stream raises RuntimeError while a cancelled read loses no event. Co-Authored-By: Claude Fable 5.2 --- developer-guide/sdk-guide/cookbook/realtime-transcription.mdx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/developer-guide/sdk-guide/cookbook/realtime-transcription.mdx b/developer-guide/sdk-guide/cookbook/realtime-transcription.mdx index 951462e8..ca41e724 100644 --- a/developer-guide/sdk-guide/cookbook/realtime-transcription.mdx +++ b/developer-guide/sdk-guide/cookbook/realtime-transcription.mdx @@ -222,7 +222,9 @@ for event in client.asr.stream_websocket(audio_chunks, sample_rate=16000, diariz print(event.text) # Can you tell me what time the pharmacy on Main Street closes tonight? ``` -The object that `stream_websocket()` returns also sends messages during the session: `finalize()` commits the current turn (push-to-talk), and `agent_speaking()`, `add_context()` and `configure()` are for [voice agents](/developer-guide/sdk-guide/cookbook/realtime-voice-agent). To stop before the audio ends, leave the loop, or use the stream in a `with` block; the SDK closes the connection. +The object that `stream_websocket()` returns also sends messages during the session: `finalize()` commits the current turn (push-to-talk), and `agent_speaking()`, `add_context()` and `configure()` are for [voice agents](/developer-guide/sdk-guide/cookbook/realtime-voice-agent). To stop before the audio ends, leave the loop, or use the stream in a `with` block; the SDK closes the connection. If the server has stopped reading, closing does not wait for it: after half a second the SDK cuts the connection. + +Read the events from one place at a time. With `AsyncFishAudio`, a second read started while another is waiting raises `RuntimeError`; a read cancelled by a timeout, such as `asyncio.wait_for()`, loses no event, so read again. An error that ends the session raises `ASRRealtimeError` (from `fishaudio`), with the server's `error_type` and the WebSocket `close_code`. A refused connection raises `APIError`, such as `AuthenticationError` for an invalid API key. From 1f1c00d8e985b09c5cd508dd8c1e1f8776134a77 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:24:55 -0800 Subject: [PATCH 3/6] docs(stt): add the TypeScript SDK to the realtime speech to text pages fish-audio 0.2.0 has client.speechToText.convertRealtime() and a model field on speechToText.convert(), so the pages no longer say that the TypeScript SDK lacks realtime speech to text. - Realtime feature page: TypeScript tab in the quick start. - Realtime transcription recipe: TypeScript tab for the script, the install and run commands and the diarize example; options, control methods, closing and errors name both SDKs. - Speech to text API reference: select the model with the model field. Co-Authored-By: Claude Fable 5.2 --- .../endpoint/openapi-v1/speech-to-text.mdx | 7 +- .../cookbook/realtime-transcription.mdx | 176 +++++++++++++++--- features/speech-to-text/realtime.mdx | 50 ++++- 3 files changed, 196 insertions(+), 37 deletions(-) diff --git a/api-reference/endpoint/openapi-v1/speech-to-text.mdx b/api-reference/endpoint/openapi-v1/speech-to-text.mdx index 8a265717..7ded939e 100644 --- a/api-reference/endpoint/openapi-v1/speech-to-text.mdx +++ b/api-reference/endpoint/openapi-v1/speech-to-text.mdx @@ -100,9 +100,10 @@ A field that is not returned is absent from the JSON, never `null`. Do not depen pass `model="transcribe-1-pro"` to `asr.transcribe()` (`fish-audio-sdk` 1.5.0 or later; on earlier versions, pass `request_options=RequestOptions(additional_headers={"model": "transcribe-1-pro"})`). - In JavaScript, pass - `{ headers: { model: "transcribe-1-pro" } }` as the second argument to - `speechToText.convert()`. The Python SDK currently returns only `text`, + In JavaScript, pass `model: "transcribe-1-pro"` in the request to + `speechToText.convert()` (`fish-audio` 0.2.0 or later; on 0.1.0, pass + `{ headers: { model: "transcribe-1-pro" } }` as the second argument). The + Python SDK currently returns only `text`, `duration`, and `segments`, and neither SDK can send `tag_audio_events`, `diarize`, or the speaker-count hints. To use them, call the API directly, as in the examples above. The JavaScript SDK returns the whole response body, diff --git a/developer-guide/sdk-guide/cookbook/realtime-transcription.mdx b/developer-guide/sdk-guide/cookbook/realtime-transcription.mdx index ca41e724..2065228e 100644 --- a/developer-guide/sdk-guide/cookbook/realtime-transcription.mdx +++ b/developer-guide/sdk-guide/cookbook/realtime-transcription.mdx @@ -13,23 +13,32 @@ import Prerequisites from "/snippets/prerequisites.mdx"; -Install the Python SDK: +Install the Python or TypeScript SDK: -```bash + + +```bash Python pip install --upgrade fish-audio-sdk ``` +```bash TypeScript +npm install fish-audio +``` + + + - `client.asr.stream_websocket()` requires `fish-audio-sdk` 1.5.0 or later. The - TypeScript SDK does not support realtime speech to text yet: in JavaScript, - [connect to the WebSocket directly](#without-the-sdk). + `client.asr.stream_websocket()` requires `fish-audio-sdk` 1.5.0 or later, and + `client.speechToText.convertRealtime()` requires `fish-audio` 0.2.0 or later + (Node.js only). In browsers or other languages, [connect to the WebSocket + directly](#without-the-sdk). You also need a 16-bit PCM mono WAV file, at 8000, 12000, 16000, 22050, 24000, 32000, 44100 or 48000 Hz. To convert a recording, run `ffmpeg -i input.mp3 -ac 1 -ar 16000 -c:a pcm_s16le speech.wav`. ## Recipe -`client.asr.stream_websocket()` takes an iterator of audio chunks and returns the events the server sends. The script streams the file in 40 ms chunks at real-time speed, as a live microphone would, and prints every event until the session ends. The SDK opens the session, sends each chunk as it is yielded, and ends the session when the iterator is exhausted. +`client.asr.stream_websocket()` in Python and `client.speechToText.convertRealtime()` in TypeScript take an iterator of audio chunks and return the events the server sends. The script streams the file in 40 ms chunks at real-time speed, as a live microphone would, and prints every event until the session ends. The SDK opens the session, sends each chunk as it is yielded, and ends the session when the iterator is exhausted. @@ -143,14 +152,117 @@ if __name__ == "__main__": asyncio.run(main(sys.argv[1])) ``` +```typescript TypeScript +// npm install fish-audio +// FISH_API_KEY=... node transcribe_file.ts speech.wav (Node.js 22.18+ runs TypeScript directly) +import { readFileSync } from "node:fs"; +import { setTimeout as sleep } from "node:timers/promises"; +import { + FishAudioClient, + type RealtimeSTTEvent, + type RealtimeSTTSampleRate, +} from "fish-audio"; + +const CHUNK_MS = 40; // ms of audio per chunk; 20-40 ms suits live audio + +// Read a 16-bit mono PCM WAV file: its sample rate and its samples. +function readWav(path: string) { + const buf = readFileSync(path); + let rate = 0, + channels = 0, + bits = 0; + let data: Buffer | undefined; + for (let pos = 12; pos + 8 <= buf.length; ) { + const id = buf.toString("ascii", pos, pos + 4); + const size = buf.readUInt32LE(pos + 4); + if (id === "fmt ") { + channels = buf.readUInt16LE(pos + 10); + rate = buf.readUInt32LE(pos + 12); + bits = buf.readUInt16LE(pos + 22); + } else if (id === "data") { + data = buf.subarray(pos + 8, pos + 8 + size); + } + pos += 8 + size + (size % 2); + } + if (bits !== 16 || channels !== 1 || !data) + throw new Error("need a 16-bit mono WAV"); + return { rate, data }; +} + +// Yield the audio in real time, as a live microphone would. +async function* microphone(data: Buffer, rate: number) { + const bytesPerChunk = ((rate * CHUNK_MS) / 1000) * 2; + const start = Date.now(); + for (let i = 0; i < data.length; i += bytesPerChunk) { + yield data.subarray(i, i + bytesPerChunk); + const sentMs = (i / bytesPerChunk + 1) * CHUNK_MS; + await sleep(Math.max(0, start + sentMs - Date.now())); + } +} + +function show(event: RealtimeSTTEvent) { + switch (event.type) { + case "session_started": + console.log(`session ${event.session_id} (request ${event.request_id})`); + break; + case "draft": + console.log(` draft #${event.turn_index}: ${event.text}`); + break; + case "eager_end_of_turn": + console.log(` eager #${event.turn_index}: ${event.text}`); + break; + case "committed": { + const who = event.user_turn ? "user " : "other"; + console.log( + `committed #${event.turn_index} [${who}] ${event.audio_start_ms}-${event.audio_end_ms} ms ` + + `(${event.reason}, ${event.language_code ?? "?"}): ${event.text}` + ); + break; + } + case "error": // recoverable: the session continues + console.log( + `error ${event.error_type} (${event.code}): ${event.message} [request ${event.request_id}]` + ); + break; + case "session_done": + console.log( + `done: ${event.stats.audio_ms} ms of audio, ${event.stats.turns} turns` + ); + break; + default: // speech_start, user_turn_taken, turn_resumed, ... + console.log( + ` ${event.type} #${"turn_index" in event ? event.turn_index : ""}` + ); + } +} + +const { rate, data } = readWav(process.argv[2]); +const client = new FishAudioClient(); // reads FISH_API_KEY +const stream = client.speechToText.convertRealtime( + { sample_rate: rate as RealtimeSTTSampleRate, eager: true, drafts: true }, + microphone(data, rate) +); +for await (const event of stream) show(event); +``` + Run it with your API key in `FISH_API_KEY`: -```bash + + +```bash Python python transcribe_file.py speech.wav ``` +```bash TypeScript +node transcribe_file.ts speech.wav +``` + + + +Node.js 22.18 or later runs TypeScript files directly; on an earlier version, compile the script with `tsc` first. + For a 15-second customer-support clip, the output looks like this (`...` marks drafts left out): ```text @@ -182,7 +294,7 @@ The clip ends mid-sentence, so the last turn is committed by `audio_done`. Draft ## Read the events -Each event is an object with a `type` and the fields of the server message as attributes; a field the server left out is `None`. +Each event is an object with a `type` and the fields of the server message as attributes; a field the server left out is `None` in Python and `undefined` in TypeScript. The options have the same names in both SDKs: `drafts=True` in Python is `drafts: true` in TypeScript. - **`speech_start`** opens a turn when voice activity begins. In the default `auto` mode, noise and other voices open turns too. - **`draft`** is the whole turn so far, and replaces the previous draft. Drafts come only with `drafts=True` (`results.drafts: true` in the protocol); use them for live captions. @@ -191,7 +303,7 @@ Each event is an object with a `type` and the fields of the server message as at - **`committed`** is the final transcript of the turn. `user_turn: false` marks a non-user turn, such as background noise or a short acknowledgement while your agent is speaking. Speaker tags such as `<|speaker:0|>` are stable within the session; strip them and trim the text, or pass `diarize=False` (`results.diarize: false`). Text can also contain [sound tags](/api-reference/endpoint/websocket/asr-realtime#sound-tags) such as `[laughter]`; strip them too, or turn them off with `results.tag_audio_events: false`. `language_code` is missing when the text is too short to tell, as for "Uh-huh." above. - **`session_done`** is the last event. The SDK sends `audio_done` when your iterator is exhausted; the server answers with `session_done` and closes the connection with code 1000. -The SDK skips message types it does not know; if you read the protocol yourself, ignore message types and fields you do not know, because new ones can be added. Every message is described in the [WebSocket reference](/api-reference/endpoint/websocket/asr-realtime#server-messages). +The SDKs skip message types they do not know; if you read the protocol yourself, ignore message types and fields you do not know, because new ones can be added. Every message is described in the [WebSocket reference](/api-reference/endpoint/websocket/asr-realtime#server-messages). The script streams the file at real-time speed so that the events arrive as @@ -202,35 +314,49 @@ The SDK skips message types it does not know; if you read the protocol yourself, ## Choose what you receive -The keyword arguments of `stream_websocket()` set the session's options: +The keyword arguments of `stream_websocket()`, and the fields of the first argument of `convertRealtime()`, set the session's options: + +| Argument | Default | What it does | +| ---------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `sample_rate` | `16000` | The sample rate of your audio, in Hz. The server converts it, so do not resample. | +| `drafts` | off | Turn on to receive live `draft` events while a turn is open. | +| `eager` | off | Turn on to receive `eager_end_of_turn` as soon as a turn has probably ended. | +| `diarize` | on | Turn off to remove speaker tags from the text. | +| `turn_detection` | `"auto"` | `"vad"` ends a turn after a fixed silence; `"manual"` ends it when you call `finalize()`. | +| `terms` | none | Names, products and jargon to recognize, for example `["Main Street"]`. | +| `config` | | Python only: an `ASRRealtimeConfig` with every other option, such as word timestamps, sound tags and history. In TypeScript, pass `results` and `context` next to the fields above. | -| Argument | Default | What it does | -| ---------------- | -------- | ------------------------------------------------------------------------------------------------ | -| `sample_rate` | `16000` | The sample rate of your audio, in Hz. The server converts it, so do not resample. | -| `drafts` | off | `True` sends live `draft` events while a turn is open. | -| `eager` | off | `True` sends `eager_end_of_turn` as soon as a turn has probably ended. | -| `diarize` | on | `False` removes speaker tags from the text. | -| `turn_detection` | `"auto"` | `"vad"` ends a turn after a fixed silence; `"manual"` ends it when you call `finalize()`. | -| `terms` | none | Names, products and jargon to recognize, for example `["Main Street"]`. | -| `config` | | An `ASRRealtimeConfig` with every other option, such as word timestamps, sound tags and history. | +By default, each transcript starts with a speaker tag, as in the output above. For plain text, turn `diarize` off: -By default, each transcript starts with a speaker tag, as in the output above. For plain text, pass `diarize=False`: + -```python +```python Python for event in client.asr.stream_websocket(audio_chunks, sample_rate=16000, diarize=False): if event.type == "committed": print(event.text) # Can you tell me what time the pharmacy on Main Street closes tonight? ``` -The object that `stream_websocket()` returns also sends messages during the session: `finalize()` commits the current turn (push-to-talk), and `agent_speaking()`, `add_context()` and `configure()` are for [voice agents](/developer-guide/sdk-guide/cookbook/realtime-voice-agent). To stop before the audio ends, leave the loop, or use the stream in a `with` block; the SDK closes the connection. If the server has stopped reading, closing does not wait for it: after half a second the SDK cuts the connection. +```typescript TypeScript +const stream = client.speechToText.convertRealtime( + { sample_rate: 16000, diarize: false }, + audioChunks +); +for await (const event of stream) { + if (event.type === "committed") console.log(event.text); +} +``` + + + +The stream that both calls return also sends messages during the session: `finalize()` commits the current turn (push-to-talk), and `agent_speaking()`, `add_context()` and `configure()` are for [voice agents](/developer-guide/sdk-guide/cookbook/realtime-voice-agent); in TypeScript they are `agentSpeaking()`, `addContext()` and `configure()`. To stop before the audio ends, leave the loop; the SDK closes the connection. You can also use the stream in a `with` block in Python, or call `close()` in TypeScript. If the server has stopped reading, the Python SDK does not wait for it when closing: after half a second it cuts the connection. -Read the events from one place at a time. With `AsyncFishAudio`, a second read started while another is waiting raises `RuntimeError`; a read cancelled by a timeout, such as `asyncio.wait_for()`, loses no event, so read again. +Read the events from one place at a time. In Python with `AsyncFishAudio`, a second read started while another is waiting raises `RuntimeError`; a read cancelled by a timeout, such as `asyncio.wait_for()`, loses no event, so read again. -An error that ends the session raises `ASRRealtimeError` (from `fishaudio`), with the server's `error_type` and the WebSocket `close_code`. A refused connection raises `APIError`, such as `AuthenticationError` for an invalid API key. +An error that ends the session raises `ASRRealtimeError` (from `fishaudio`), with the server's `error_type` and the WebSocket `close_code`. A refused connection raises `APIError`, such as `AuthenticationError` for an invalid API key. In TypeScript, the stream throws `RealtimeSTTError` (from `fish-audio`), with `errorType` and `closeCode`, and a refused connection throws an API error such as `UnauthorizedError`. ## Without the SDK -In JavaScript, in other languages, or to control the connection yourself, speak the WebSocket protocol directly: connect to `wss://api.fish.audio/v1/asr/realtime`, send a `config` message, wait for `session_started`, then send `audio` messages and finish with `audio_done`. Every message is a MessagePack map in a binary frame. Install a WebSocket client and a MessagePack library: +In other languages, or to control the connection yourself, speak the WebSocket protocol directly: connect to `wss://api.fish.audio/v1/asr/realtime`, send a `config` message, wait for `session_started`, then send `audio` messages and finish with `audio_done`. Every message is a MessagePack map in a binary frame. Install a WebSocket client and a MessagePack library: diff --git a/features/speech-to-text/realtime.mdx b/features/speech-to-text/realtime.mdx index 0f83f50a..5b2fb705 100644 --- a/features/speech-to-text/realtime.mdx +++ b/features/speech-to-text/realtime.mdx @@ -76,9 +76,11 @@ The realtime endpoints of the [compatible APIs](/developer-guide/compat/capabili ## Quick start -With the Python SDK, pass an iterator of audio chunks to `client.asr.stream_websocket()` and read the events it returns. Install it with `pip install --upgrade fish-audio-sdk` and set `FISH_API_KEY` in your environment. +With the Python or TypeScript SDK, pass an iterator of audio chunks and read the events it returns. Install it with `pip install --upgrade fish-audio-sdk` or `npm install fish-audio` and set `FISH_API_KEY` in your environment. -```python + + +```python Python import wave from fishaudio import FishAudio @@ -102,17 +104,47 @@ for event in client.asr.stream_websocket( print(event.text) ``` -Transcripts start with a speaker tag such as `<|speaker:0|>` by default; `diarize=False` gives plain text. With `AsyncFishAudio`, pass an async iterator and read the events with `async for`. +```typescript TypeScript +import { createReadStream } from "node:fs"; +import { FishAudioClient } from "fish-audio"; + +const client = new FishAudioClient(); // reads FISH_API_KEY + +// Raw 16-bit mono PCM at 16 kHz, 40 ms (1280 bytes) per chunk. +// From a microphone, yield each chunk as you capture it. +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); // live text of the open turn, not final + } else if (event.type === "committed") { + console.log(event.text); // final transcript of the turn + } +} +``` + + + +The Python example reads a WAV file and the TypeScript example reads raw PCM; to make `speech.pcm`, run `ffmpeg -i input.mp3 -ac 1 -ar 16000 -f s16le speech.pcm`. Transcripts start with a speaker tag such as `<|speaker:0|>` by default; `diarize=False` (`diarize: false` in TypeScript) gives plain text. With `AsyncFishAudio`, pass an async iterator and read the events with `async for`. - `client.asr.stream_websocket()` requires `fish-audio-sdk` 1.5.0 or later. The - TypeScript SDK does not support realtime speech to text yet; use the WebSocket - protocol below. + `client.asr.stream_websocket()` requires `fish-audio-sdk` 1.5.0 or later. + `client.speechToText.convertRealtime()` requires `fish-audio` 0.2.0 or later + and runs in Node.js only; see the [JavaScript SDK + reference](/api-reference/sdk/javascript/api-reference) for control methods, + errors and stopping a microphone source. ### Without the SDK -In JavaScript and other languages, connect with any WebSocket client and exchange MessagePack messages. The Python SDK does these steps for you. +In other languages and in browsers, connect with any WebSocket client and exchange MessagePack messages. The SDKs do these steps for you. @@ -146,7 +178,7 @@ In JavaScript and other languages, connect with any WebSocket client and exchang } ``` -[Transcribe a live audio stream](/developer-guide/sdk-guide/cookbook/realtime-transcription) has a complete, tested recipe with the Python SDK, WebSocket clients in Python and Node.js, and a browser microphone page with a server relay. +[Transcribe a live audio stream](/developer-guide/sdk-guide/cookbook/realtime-transcription) has a complete, tested recipe with the Python and TypeScript SDKs, WebSocket clients in Python and Node.js, and a browser microphone page with a server relay. ## How a session works @@ -234,7 +266,7 @@ Send 16-bit little-endian PCM, mono, at 8000, 12000, 16000, 22050, 24000, 32000, ### Speakers -Transcripts contain speaker tags such as `<|speaker:0|>`, stable within a session. Strip them, or send `results.diarize: false` (`diarize=False` in the Python SDK) for plain text. Whitespace right after a tag can vary, so trim the text after you strip the tags. Transcripts can also contain sound tags such as `[laughter]` or `[pause]`. Strip them too, or send `results.tag_audio_events: false` to remove them; see [Sound tags](/api-reference/endpoint/websocket/asr-realtime#sound-tags). +Transcripts contain speaker tags such as `<|speaker:0|>`, stable within a session. Strip them, or send `results.diarize: false` (`diarize=False` in the Python SDK, `diarize: false` in the TypeScript SDK) for plain text. Whitespace right after a tag can vary, so trim the text after you strip the tags. Transcripts can also contain sound tags such as `[laughter]` or `[pause]`. Strip them too, or send `results.tag_audio_events: false` to remove them; see [Sound tags](/api-reference/endpoint/websocket/asr-realtime#sound-tags). ### Keys and browsers From 850dccb713561d64e07b8698cf5f42efb361db02 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:53:01 -0800 Subject: [PATCH 4/6] docs(stt): point the realtime quick start note to the recipe for control methods and errors The JavaScript SDK reference on this branch does not document realtime speech to text yet, so the note promised content the link did not have. The recipe in this branch covers the control methods and errors of both SDKs. Co-Authored-By: Claude Fable 5.2 --- features/speech-to-text/realtime.mdx | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/features/speech-to-text/realtime.mdx b/features/speech-to-text/realtime.mdx index 5b2fb705..767dcea8 100644 --- a/features/speech-to-text/realtime.mdx +++ b/features/speech-to-text/realtime.mdx @@ -137,9 +137,10 @@ The Python example reads a WAV file and the TypeScript example reads raw PCM; to `client.asr.stream_websocket()` requires `fish-audio-sdk` 1.5.0 or later. `client.speechToText.convertRealtime()` requires `fish-audio` 0.2.0 or later - and runs in Node.js only; see the [JavaScript SDK - reference](/api-reference/sdk/javascript/api-reference) for control methods, - errors and stopping a microphone source. + and runs in Node.js only. For the control methods and errors of both SDKs, see + [Choose what you + receive](/developer-guide/sdk-guide/cookbook/realtime-transcription#choose-what-you-receive) + in the recipe. ### Without the SDK From 4a8310b415791c9111c9c591207c5ef9ede29b1a Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:42:45 -0800 Subject: [PATCH 5/6] docs(stt): say how to stop a realtime session early in Python Leaving the loop closes the session only when nothing else holds the stream. With the stream in a variable, as it is when you call its control methods, the Python SDK keeps the session open and keeps sending audio, so the recipe now tells readers to use a with block or call close(). Checked on fish-audio-sdk 1.6.0. The cookbook test no longer requires a draft event: drafts are best effort, so a successful session can have none. --- developer-guide/sdk-guide/cookbook/realtime-transcription.mdx | 2 +- tests/cookbooks/specs.py | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/developer-guide/sdk-guide/cookbook/realtime-transcription.mdx b/developer-guide/sdk-guide/cookbook/realtime-transcription.mdx index dbbabe81..44ef75cb 100644 --- a/developer-guide/sdk-guide/cookbook/realtime-transcription.mdx +++ b/developer-guide/sdk-guide/cookbook/realtime-transcription.mdx @@ -348,7 +348,7 @@ for await (const event of stream) { -The stream that both calls return also sends messages during the session: `finalize()` commits the current turn (push-to-talk), and `agent_speaking()`, `add_context()` and `configure()` are for [voice agents](/developer-guide/sdk-guide/cookbook/realtime-voice-agent); in TypeScript they are `agentSpeaking()`, `addContext()` and `configure()`. To stop before the audio ends, leave the loop; the SDK closes the connection. You can also use the stream in a `with` block in Python, or call `close()` in TypeScript. If the server has stopped reading, the Python SDK does not wait for it when closing: after half a second it cuts the connection. +The stream that both calls return also sends messages during the session: `finalize()` commits the current turn (push-to-talk), and `agent_speaking()`, `add_context()` and `configure()` are for [voice agents](/developer-guide/sdk-guide/cookbook/realtime-voice-agent); in TypeScript they are `agentSpeaking()`, `addContext()` and `configure()`. To stop before the audio ends in Python, use the stream in a `with` block (`async with` with `AsyncFishAudio`), or call `close()` (`await stream.aclose()`). Leaving the loop is not enough while you still hold the stream in a variable: the session stays open and the SDK keeps sending your audio. In TypeScript, leave the loop or call `close()`. If the server has stopped reading, the Python SDK does not wait for it when closing: after half a second it cuts the connection. Read the events from one place at a time. In Python with `AsyncFishAudio`, a second read started while another is waiting raises `RuntimeError`; a read cancelled by a timeout, such as `asyncio.wait_for()`, loses no event, so read again. diff --git a/tests/cookbooks/specs.py b/tests/cookbooks/specs.py index 5cc1d6a9..aca1d913 100644 --- a/tests/cookbooks/specs.py +++ b/tests/cookbooks/specs.py @@ -192,7 +192,6 @@ def _run(recipe): {"name": "stream a wav file (sdk, sync)", "block": 0, "postamble": SDK_REALTIME_RUN + """ _run(lambda: main("speech.wav")) assert any(line.startswith("session ") for line in _lines), _lines -assert any(line.startswith(" draft ") for line in _lines), _lines assert any(line.startswith("committed") for line in _lines), _lines assert any(line.startswith("done: ") for line in _lines), _lines """}, From fb47da29bf187ee1dafbb76c42330397257351cc Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:03:58 -0800 Subject: [PATCH 6/6] docs(stt): fix the install line, close_code and event defaults on the realtime pages - the STT page's install line upgrades to fish-audio-sdk 1.5.0 or later - close_code can be None in Python when the server's error ended the session - committed events fill user_turn (both SDKs) and reason/degraded (Python) - the sample output matches the live marker spacing - the realtime page no longer calls the TypeScript recipe tested - the TypeScript script runs as .mts in a CommonJS project --- .../cookbook/realtime-transcription.mdx | 30 +++++++++---------- features/speech-to-text.mdx | 2 +- features/speech-to-text/realtime.mdx | 2 +- 3 files changed, 17 insertions(+), 17 deletions(-) diff --git a/developer-guide/sdk-guide/cookbook/realtime-transcription.mdx b/developer-guide/sdk-guide/cookbook/realtime-transcription.mdx index 44ef75cb..c83b838d 100644 --- a/developer-guide/sdk-guide/cookbook/realtime-transcription.mdx +++ b/developer-guide/sdk-guide/cookbook/realtime-transcription.mdx @@ -261,32 +261,32 @@ node transcribe_file.ts speech.wav -Node.js 22.18 or later runs TypeScript files directly; on an earlier version, compile the script with `tsc` first. +Node.js 22.18 or later runs TypeScript files directly; on an earlier version, compile the script with `tsc` first. The script uses `import`: inside a project whose `package.json` sets `"type": "commonjs"`, name it `transcribe_file.mts`. For a 15-second customer-support clip, the output looks like this (`...` marks drafts left out): ```text session s_ab12cd34 (request 0b6f4c1e-7d2a-4e8b-9f3c-5a1d2e3f4b6c) speech_start #0 - draft #0: <|speaker:0|> Can you... - draft #0: <|speaker:0|> Can you tell + draft #0: <|speaker:0|>Can you... + draft #0: <|speaker:0|>Can you tell user_turn_taken #0 - draft #0: <|speaker:0|> Can you tell me what... + draft #0: <|speaker:0|>Can you tell me what... ... - draft #0: <|speaker:0|> Can you tell me what time the pharmacy on Main Street closes tonight? - eager #0: <|speaker:0|> Can you tell me what time the pharmacy on Main Street closes tonight? -committed #0 [user ] 2768-8000 ms (eot, en): <|speaker:0|> Can you tell me what time the pharmacy on Main Street closes tonight? + draft #0: <|speaker:0|>Can you tell me what time the pharmacy on Main Street closes tonight? + eager #0: <|speaker:0|>Can you tell me what time the pharmacy on Main Street closes tonight? +committed #0 [user ] 2768-8000 ms (eot, en): <|speaker:0|>Can you tell me what time the pharmacy on Main Street closes tonight? speech_start #1 - draft #1: <|speaker:0|> Uh-huh. + draft #1: <|speaker:0|>Uh-huh. user_turn_taken #1 - eager #1: <|speaker:0|> Uh-huh. -committed #1 [user ] 9840-11840 ms (eot, ?): <|speaker:0|> Uh-huh. + eager #1: <|speaker:0|>Uh-huh. +committed #1 [user ] 9840-11840 ms (eot, ?): <|speaker:0|>Uh-huh. speech_start #2 - draft #2: <|speaker:0|> I'd like + draft #2: <|speaker:0|>I'd like user_turn_taken #2 ... - draft #2: <|speaker:0|> I'd like to change my deli- -committed #2 [user ] 13168-14992 ms (audio_done, en): <|speaker:0|> I'd like to change my delivery + draft #2: <|speaker:0|>I'd like to change my deli- +committed #2 [user ] 13168-14992 ms (audio_done, en): <|speaker:0|>I'd like to change my delivery done: 15000 ms of audio, 3 turns ``` @@ -294,7 +294,7 @@ The clip ends mid-sentence, so the last turn is committed by `audio_done`. Draft ## Read the events -Each event is an object with a `type` and the fields of the server message as attributes; a field the server left out is `None` in Python and `undefined` in TypeScript. The options have the same names in both SDKs: `drafts=True` in Python is `drafts: true` in TypeScript. +Each event is an object with a `type` and the fields of the server message as attributes; a field the server left out is `None` in Python and `undefined` in TypeScript. The exceptions are on `committed`: a missing `user_turn` is `True` in both SDKs, and Python also fills a missing `reason` with `"eot"` and `degraded` with `False`. The options have the same names in both SDKs: `drafts=True` in Python is `drafts: true` in TypeScript. - **`speech_start`** opens a turn when voice activity begins. In the default `auto` mode, noise and other voices open turns too. - **`draft`** is the whole turn so far, and replaces the previous draft. Drafts come only with `drafts=True` (`results.drafts: true` in the protocol); use them for live captions. @@ -352,7 +352,7 @@ The stream that both calls return also sends messages during the session: `final Read the events from one place at a time. In Python with `AsyncFishAudio`, a second read started while another is waiting raises `RuntimeError`; a read cancelled by a timeout, such as `asyncio.wait_for()`, loses no event, so read again. -An error that ends the session raises `ASRRealtimeError` (from `fishaudio`), with the server's `error_type` and the WebSocket `close_code`. A refused connection raises `APIError`, such as `AuthenticationError` for an invalid API key. In TypeScript, the stream throws `RealtimeSTTError` (from `fish-audio`), with `errorType` and `closeCode`, and a refused connection throws an API error such as `UnauthorizedError`. +An error that ends the session raises `ASRRealtimeError` (from `fishaudio`), with the server's `error_type` and the WebSocket `close_code`. `close_code` can be `None` when the server's error message ended the session before the connection closed. A refused connection raises `APIError`, such as `AuthenticationError` for an invalid API key. In TypeScript, the stream throws `RealtimeSTTError` (from `fish-audio`), with `errorType` and `closeCode`, and a refused connection throws an API error such as `UnauthorizedError`. ## Without the SDK diff --git a/features/speech-to-text.mdx b/features/speech-to-text.mdx index eb726a45..92fb447f 100644 --- a/features/speech-to-text.mdx +++ b/features/speech-to-text.mdx @@ -80,7 +80,7 @@ Create an [API key](/developer-guide/getting-started/api-key) and set `FISH_API_ Every example on this page selects `transcribe-1-pro`. The examples below also request timestamps. -Install the Python SDK first: `pip install fish-audio-sdk`. +Install the Python SDK first: `pip install --upgrade "fish-audio-sdk>=1.5.0"`. diff --git a/features/speech-to-text/realtime.mdx b/features/speech-to-text/realtime.mdx index f421c28d..9fc6010d 100644 --- a/features/speech-to-text/realtime.mdx +++ b/features/speech-to-text/realtime.mdx @@ -179,7 +179,7 @@ In other languages and in browsers, connect with any WebSocket client and exchan } ``` -[Transcribe a live audio stream](/developer-guide/sdk-guide/cookbook/realtime-transcription) has a complete, tested recipe with the Python and TypeScript SDKs, WebSocket clients in Python and Node.js, and a browser microphone page with a server relay. +[Transcribe a live audio stream](/developer-guide/sdk-guide/cookbook/realtime-transcription) has a complete recipe with the Python and TypeScript SDKs, WebSocket clients in Python and Node.js, and a browser microphone page with a server relay. ## How a session works