> ## Documentation Index
> Fetch the complete documentation index at: https://assemblyai.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Achieve lowest latency

> Start the request before the speaker stops, so most of the utterance is uploaded by the time they finish.

The endpoint reads the body as it arrives, so a client that uploads during
the recording gets its transcript sooner: the connection, authentication, and
upload all overlap the recording instead of following it. On a long recording
the endpoint can also start transcribing early. Audio is split into speech
segments of up to about 32 seconds, and a segment is transcribed once two later
segments exist, so early transcription only begins on recordings longer than
roughly 90 seconds.

## Steps to the lowest latency

Do all four. Each one takes a different piece of time off what the user waits
for after they stop speaking.

1. **Pre-warm the connection when the user reaches for record.** Call
   `GET /warm` (or `warm()` in the SDKs) so the DNS, TCP and TLS setup happens
   while they get ready to speak, not after. Reuse the same HTTP client for the
   transcription request. See [Connection pre-warming](https://assemblyai.com/docs/dictation/connection-pre-warming.md).
2. **Upload while recording.** Send audio to `/v1/transcribe/live` as it's
   captured, so the upload is done by the time the user stops. The rest of this
   page shows how.
3. **Pick the rewrite mode for your latency budget.** `fast` (the default)
   returns the rewrite at the lowest latency. `smart` gives a more thorough
   cleanup and follows `llm_instruction` more reliably, at higher latency. See
   [Choosing a rewrite mode](https://assemblyai.com/docs/dictation/transcript-rewriting.md#choosing-a-rewrite-mode).
4. **Call the nearest region.** The global endpoint routes to the nearest
   region. Use a data-zone endpoint only when you need data residency. See
   [Cloud endpoints and data residency](https://assemblyai.com/docs/dictation/endpoints-and-data-zones.md).

## Rules for a chunked upload

Three rules apply to a chunked upload:

* The `config` part must arrive **before** the first audio byte.
* Don't let the connection go silent for long stretches mid-body — an
  abandoned upload is timed out rather than held open. For mute or
  push-to-talk, end the request when the user stops and start a new one when
  they resume, rather than pausing the stream.
* A chunked body can't be replayed. Keep the audio in memory if you want to
  retry a failed request.

Raw PCM is the easiest format to stream, since it needs no container header —
declare `sample_rate` and `channels` in `config` and send frames as they come
off the microphone.

## With the Python SDK

The Python SDK does the framing for you. `transcribe_live()` takes an iterator
of audio chunks, and `open_live()` takes audio pushed in from a callback — a
microphone library, a WebRTC track, a telephony media stream:

> [tab] Pull — an iterator of chunks
>
> ```python theme={null}
> import assemblyai as aai
>
> aai.settings.api_key = "<YOUR_API_KEY>"
>
> config = aai.DictationConfig(
>     sample_rate=16000,
>     channels=1,
>     rewrite_mode="smart",
>     llm_instruction="Remove filler words and tidy the punctuation.",
> )
>
> def record():
>     """Your microphone loop, yielding 16-bit PCM bytes."""
>     while recording:
>         yield stream.read(4096)
>
> result = aai.DictationTranscriber().transcribe_live(record(), config)
>
> print(result.text)
> print(result.llm_response)
> ```

> [tab] Push — audio from a callback
>
> ```python theme={null}
> import assemblyai as aai
> import sounddevice as sd
>
> aai.settings.api_key = "<YOUR_API_KEY>"
>
> config = aai.DictationConfig(sample_rate=16000, channels=1)
>
> with aai.DictationTranscriber() as transcriber:
>     with transcriber.open_live(config) as session:
>         stream = sd.RawInputStream(
>             samplerate=16000,
>             channels=1,
>             dtype="int16",
>             callback=lambda data, *_: session.write(bytes(data)),
>         )
>         with stream:
>             input("Dictating, press Enter to stop... ")
>
>     print(session.result().final_text)
> ```

`AsyncDictationTranscriber` is the asyncio counterpart, with the same two
methods. Call `transcriber.warm()` when you know audio is coming — as the user
reaches for the record button — to pay the DNS, TCP and TLS setup before the
first byte rather than in front of it.

## With the JavaScript SDK

The JavaScript SDK does the framing for you too. `transcribeLive()` takes a
stream or an async iterable of audio chunks, and `openLive()` takes audio pushed
in from a callback. Both examples record from the default microphone with
[SoX](https://sourceforge.net/projects/sox/), so install it first
(`brew install sox` or `sudo apt-get install sox`):

> [tab] Pull — an iterator of chunks
>
> ```javascript theme={null}
> import { spawn } from "node:child_process";
> import { AssemblyAI } from "assemblyai";
>
> const client = new AssemblyAI({ apiKey: "<YOUR_API_KEY>" });
>
> // SoX writes 16 kHz, 16-bit mono PCM from the default microphone to stdout.
> const microphone = spawn("sox", [
>   "--default-device", "--no-show-progress",
>   "--rate", "16000", "--channels", "1",
>   "--encoding", "signed-integer", "--bits", "16", "--type", "raw", "-",
> ]);
> microphone.on("error", () => console.error("Install SoX to record audio."));
>
> console.log("Dictating, press Enter to stop...");
> process.stdin.once("data", () => {
>   microphone.kill(); // ends the stream, which ends the upload
>   process.stdin.pause();
> });
>
> const result = await client.dictation.transcribeLive(microphone.stdout, {
>   sample_rate: 16000,
>   channels: 1,
>   rewrite_mode: "smart",
>   llm_instruction: "Remove filler words and tidy the punctuation.",
> });
>
> console.log(result.text);
> console.log(result.llm_response);
> ```

> [tab] Push — audio from a callback
>
> ```javascript theme={null}
> import { spawn } from "node:child_process";
> import { AssemblyAI } from "assemblyai";
>
> const client = new AssemblyAI({ apiKey: "<YOUR_API_KEY>" });
>
> const session = client.dictation.openLive({ sample_rate: 16000, channels: 1 });
>
> // Any callback source works the same way: a microphone library, a WebRTC
> // track, a telephony media stream.
> const microphone = spawn("sox", [
>   "--default-device", "--no-show-progress",
>   "--rate", "16000", "--channels", "1",
>   "--encoding", "signed-integer", "--bits", "16", "--type", "raw", "-",
> ]);
> microphone.on("error", () => console.error("Install SoX to record audio."));
> microphone.stdout.on("data", (chunk) => session.write(chunk));
>
> console.log("Dictating, press Enter to stop...");
> process.stdin.once("data", () => {
>   microphone.kill();
>   process.stdin.pause();
> });
>
> // Wait until recording stops: result() ends the audio, so a chunk written
> // after it is called is dropped.
> await new Promise((resolve) => microphone.on("close", resolve));
> const result = await session.result();
> console.log(result.final_text);
> ```

Call `client.dictation.warm()` when you know audio is coming to open the
connection before the first byte rather than in front of it.

## Without the SDK

Without the SDK, frame the multipart body yourself:

```python expandable theme={null}
import json
import requests

BOUNDARY = "----dictation-example"
CONFIG = {
    "sample_rate": 16000,
    "channels": 1,
    "rewrite_mode": "smart",
    "llm_instruction": "Remove filler words and tidy the punctuation.",
}

def multipart_body(frames):
    """Yield the config part, then each audio frame as it is captured."""
    yield (
        f"--{BOUNDARY}\r\n"
        'Content-Disposition: form-data; name="config"\r\n'
        "Content-Type: application/json\r\n\r\n"
        f"{json.dumps(CONFIG)}\r\n"
        f"--{BOUNDARY}\r\n"
        'Content-Disposition: form-data; name="audio"; filename="audio"\r\n'
        "Content-Type: audio/pcm\r\n\r\n"
    ).encode()
    for frame in frames:
        yield frame
    yield f"\r\n--{BOUNDARY}--\r\n".encode()

# `record()` is your microphone loop, yielding 16-bit PCM bytes.
response = requests.post(
    "https://dictation.assemblyai.com/v1/transcribe/live",
    headers={
        "Authorization": "<YOUR_API_KEY>",
        "Content-Type": f"multipart/form-data; boundary={BOUNDARY}",
    },
    data=multipart_body(record()),
    timeout=90,
)
response.raise_for_status()
result = response.json()

print(result["text"])
print(result["llm_response"])
```

Passing a generator to `data=` makes `requests` send the body with chunked
transfer encoding, which is what lets the upload start before the audio is
complete. A body with a `Content-Length` is also accepted, and still streams —
the server does not wait for the full body before it begins.

## Related pages

* [Quickstart](https://assemblyai.com/docs/dictation.md) — the single-call flow this builds on
* [Audio requirements](https://assemblyai.com/docs/dictation/audio-requirements.md) — why raw PCM is the easiest format to stream
* [Connection pre-warming](https://assemblyai.com/docs/dictation/connection-pre-warming.md) — take the handshake off the critical path too
* [Add context mid-dictation](https://assemblyai.com/docs/dictation/add-context-mid-dictation.md) — change the config after the user starts talking
