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

# Real-time speech-to-text

> Stream Hebrew or English audio over one WebSocket and receive word tokens as they are recognized

## Overview

You stream audio in and receive word tokens back as they are recognized. Each word arrives first as provisional, then as final.

Try it

Free trial key, your voice

API key

Choose file

The box uses the public free trial key. Press Record and speak Hebrew or English. The browser streams your microphone to the socket and words appear while you talk. You can also choose an audio file.

One WebSocket is one audio stream, one conversation. Open a new socket for each new stream.

## Connection

| | |
| - | - |
| URL | `wss://wsgw.deepdub.ai/transcribe-websocket` |
| Auth | `Authorization: Bearer YOUR_API_KEY` on the handshake. A browser sends the same key as `?x-api-key=YOUR_API_KEY` on that URL. |
| Model | `stt-egf` |

Keys use the same `dd-...` format as the rest of the API. See [Authentication](https://docs.deepdub.ai/authentication.md) for how to get one. The Try it box is filled with the public free trial key. Keep your own key in a secrets manager or in `DEEPDUB_API_KEY`.

## Start message

The first frame is a text frame of JSON. Send it before any audio.

```json theme={null}
{
  "model": "stt-egf",
  "audio_format": "pcm_s16le",
  "sample_rate": 16000,
  "num_channels": 1,
  "language_hints": ["he"],
  "enable_endpoint_detection": false,
  "context": {"terms": ["Deepdub", "insurance"], "text": ""},
  "enable_agent_text_input": false,
  "client_reference_id": "my-call-123"
}
```

**model** `string` *required*

Speech-to-text model. Use `stt-egf`.

**audio\_format** `string` *required*

Raw formats `pcm_s16le`, `pcm_f32le`, `pcm_mulaw`, and `pcm_alaw` also require `sample_rate` and `num_channels`. Container formats are `auto`, `wav`, `ogg`, `flac`, `mp3`, `webm`, `aac`, `m4a`, `amr`, and `mp4`. Raw 16 kHz mono `pcm_s16le` is the lowest-latency choice.

**sample\_rate** `integer`

Sample rate in Hz for a raw format. The example uses `16000`.

**num\_channels** `integer`

Channel count for a raw format. Use `1` for mono.

**language\_hints** `string[]`

`["he"]` or `["en"]` locks that language. Both, or omitting the field, turns on automatic detection per utterance. Hebrew and English can switch within one session in automatic mode.

**language\_hints\_strict** `boolean`

Restrict automatic detection to the languages in `language_hints`.

**enable\_endpoint\_detection** `boolean` (default: false)

When `true`, the server sends a final `<end>` token when the speaker finishes a turn.

**max\_endpoint\_delay\_ms** `integer`

How long a pause must last before a turn ends, from `500` to `3000`. Used with endpoint detection.

**context.terms** `string[]`

Words to boost: names, products, rare words. Up to 200 words.

**context.text** `string`

Earlier conversation as plain text. Used as history for recognition.

**context.prev** `string`

Earlier conversation as plain text, same role as `context.text`.

**enable\_agent\_text\_input** `boolean` (default: false)

Set `true` when you will send what your voice agent is saying. See [Agent text](#agent-text).

**client\_reference\_id** `string`

Your own id. It is echoed in Deepdub logs.

> [!WARNING]
>
> `translation` and `enable_speaker_diarization` are rejected.

## Audio

Send audio as binary frames, at real-time pace, in chunks of about 100 ms. That is 3,200 bytes of 16 kHz `pcm_s16le` mono. An empty binary frame is a valid empty chunk.

End the audio with an empty text frame, `""`. The server flushes the last words, sends a final message with `"finished": true`, and closes the socket with code 1000.

## Control messages

After the start message, further text frames are JSON.

**type** `string`

`keepalive` keeps the stream open while you have no audio to send. `finalize` finalizes everything recognized so far and leaves the stream open. `agent_text` sends what your agent is saying.

### Agent text

Requires `enable_agent_text_input: true`. Send the agent's speech in small pieces, each just before it is played to the user, and end each agent turn with `end_of_segment`:

```json theme={null}
{"type": "agent_text", "text": "Which branch: Dizengoff or "}
{"type": "agent_text", "text": "Ibn Gabirol?", "end_of_segment": true}
```

Send the text exactly as spoken, spaces included. Each message can be at most 2,000 characters. The text becomes history for the user's next reply. Vocabulary boosting stays on `context.terms`. Agent text is omitted from the transcript. If the user interrupts the agent, send `end_of_segment: true` immediately and stop sending the rest of that reply.

## Tokens

Each server message is JSON:

```json theme={null}
{
  "tokens": [
    {
      "text": " שלום",
      "start_ms": 1200,
      "end_ms": 1480,
      "confidence": 0.97,
      "is_final": true,
      "language": "he"
    }
  ],
  "final_audio_proc_ms": 1600,
  "total_audio_proc_ms": 2400
}
```

**tokens** `object[]`

Words or word pieces recognized so far in this message.

**tokens.text** `string`

The word, with its leading space when the server sends one. Build the transcript by concatenating `text` exactly as sent. Do not add or remove spaces.

**tokens.start\_ms** `integer`

Start time of the token in the audio, in milliseconds.

**tokens.end\_ms** `integer`

End time of the token in the audio, in milliseconds.

**tokens.confidence** `number`

Recognition confidence for this token.

**tokens.is\_final** `boolean`

`false` tokens are provisional and are replaced by later messages. `true` tokens never change. Keep the finals, and redraw the provisional tokens from the latest message.

**tokens.language** `string`

Language of this token, `he` or `en`.

**final\_audio\_proc\_ms** `integer`

Milliseconds of audio included in the latest final tokens.

**total\_audio\_proc\_ms** `integer`

Milliseconds of audio processed so far.

**finished** `boolean`

`true` on the last message, which has an empty `tokens` array. The socket then closes.

`<end>` is sent only when endpoint detection is on. It marks the end of a speaker turn. Skip it when building text.

## Errors

An error is a JSON message, and then the socket closes.

```json theme={null}
{"error_code": 400, "error_type": "...", "error_message": "..."}
```

| Code | When |
| - | - |
| 400 | The start message or a later frame is invalid. |
| 401 | The API key is missing or invalid. |
| 503 | `error_type` is `no_capacity` and the close code is 1013. Every server is busy. Retry after a short backoff. |

## Code example

The file is 16 kHz mono 16-bit WAV. Audio is sent in 100 ms chunks at real-time pace. The returned string is the concatenation of final tokens.

```python theme={null}
import asyncio
import json
import os
import wave

import websockets  # pip install "websockets>=14"

URL = "wss://wsgw.deepdub.ai/transcribe-websocket"

async def transcribe(path: str, lang: str = "he") -> str:
    with wave.open(path) as w:
        sample_rate = w.getframerate()
        pcm = w.readframes(w.getnframes())

    finals = []
    headers = {"Authorization": f"Bearer {os.environ['DEEPDUB_API_KEY']}"}
    async with websockets.connect(URL, additional_headers=headers, max_size=None) as ws:
        await ws.send(json.dumps({
            "model": "stt-egf",
            "audio_format": "pcm_s16le",
            "sample_rate": sample_rate,
            "num_channels": 1,
            "language_hints": [lang],
        }))

        async def receive():
            async for msg in ws:
                data = json.loads(msg)
                if data.get("error_code"):
                    raise RuntimeError(data)
                finals.extend(
                    token["text"]
                    for token in data.get("tokens", [])
                    if token["is_final"] and token["text"] != "<end>"
                )
                if data.get("finished"):
                    return

        receive_task = asyncio.create_task(receive())
        chunk = sample_rate * 2 // 10  # 100 ms of 16-bit mono
        for i in range(0, len(pcm), chunk):
            await ws.send(pcm[i:i + chunk])
            await asyncio.sleep(0.1)
        await ws.send("")  # end of audio
        await receive_task

    return "".join(finals).strip()

print(asyncio.run(transcribe("sample.wav")))
```

## Limits

Final words arrive about 0.1 s after the speaker stops (median). Provisional words stream while they talk.

A session can run for up to 5 hours. Send `{"type": "keepalive"}` during a long silence in which you send no audio.

Each message, in either direction, is limited to 1 MiB.


## AsyncAPI

````yaml api-reference/stt/asyncapi.json transcribe
id: transcribe
title: Transcribe
description: >-
  One WebSocket is one audio stream. The first frame is the start message. Audio
  follows as binary frames.
servers:
  - id: production
    protocol: wss
    host: wsgw.deepdub.ai
    bindings: []
    variables: []
address: /transcribe-websocket
parameters: []
bindings: []
operations:
  - &ref_2
    id: sendStart
    title: Start transcription
    description: >-
      Send this JSON text frame first. Then send audio as binary frames of about
      100 ms at real-time pace. End the audio with an empty text frame.
    type: send
    messages:
      - &ref_4
        id: start
        contentType: application/json
        payload:
          - name: Start message
            type: object
            properties:
              - name: model
                type: string
                description: Speech-to-text model.
                enumValues:
                  - stt-egf
                required: true
              - name: audio_format
                type: string
                description: >-
                  Raw formats pcm_s16le, pcm_f32le, pcm_mulaw, and pcm_alaw need
                  sample_rate and num_channels. Containers include wav, ogg,
                  flac, mp3, webm, aac, m4a, amr, and mp4.
                enumValues:
                  - pcm_s16le
                  - pcm_f32le
                  - pcm_mulaw
                  - pcm_alaw
                  - auto
                  - wav
                  - ogg
                  - flac
                  - mp3
                  - webm
                  - aac
                  - m4a
                  - amr
                  - mp4
                required: true
              - name: sample_rate
                type: integer
                description: Sample rate in Hz for a raw format.
                required: true
              - name: num_channels
                type: integer
                description: Channel count for a raw format. Use 1 for mono.
                required: true
              - name: language_hints
                type: array
                description: >-
                  ["he"] or ["en"] locks that language. Both, or omitting the
                  field, detects the language per utterance.
                required: false
                properties:
                  - name: item
                    type: string
                    enumValues:
                      - he
                      - en
                    required: false
              - name: language_hints_strict
                type: boolean
                description: Restrict detection to the hinted languages.
                required: false
              - name: enable_endpoint_detection
                type: boolean
                description: Send a final <end> token when the speaker finishes a turn.
                required: false
              - name: max_endpoint_delay_ms
                type: integer
                description: Pause length before a turn ends, from 500 to 3000.
                required: false
              - name: context
                type: object
                required: false
                properties:
                  - name: terms
                    type: array
                    description: Words to boost. Up to 200.
                    required: false
                    properties:
                      - name: item
                        type: string
                        required: false
                  - name: text
                    type: string
                    description: Earlier conversation, used as history.
                    required: false
                  - name: prev
                    type: string
                    description: Earlier conversation, same role as text.
                    required: false
              - name: enable_agent_text_input
                type: boolean
                description: Allow agent_text control messages on this socket.
                required: false
              - name: client_reference_id
                type: string
                description: Your own id, echoed in Deepdub logs.
                required: false
        headers: []
        jsonPayloadSchema:
          type: object
          required:
            - model
            - audio_format
            - sample_rate
            - num_channels
          properties:
            model:
              type: string
              description: Speech-to-text model.
              enum:
                - stt-egf
              x-parser-schema-id: <anonymous-schema-2>
            audio_format:
              type: string
              description: >-
                Raw formats pcm_s16le, pcm_f32le, pcm_mulaw, and pcm_alaw need
                sample_rate and num_channels. Containers include wav, ogg, flac,
                mp3, webm, aac, m4a, amr, and mp4.
              enum:
                - pcm_s16le
                - pcm_f32le
                - pcm_mulaw
                - pcm_alaw
                - auto
                - wav
                - ogg
                - flac
                - mp3
                - webm
                - aac
                - m4a
                - amr
                - mp4
              x-parser-schema-id: <anonymous-schema-3>
            sample_rate:
              type: integer
              description: Sample rate in Hz for a raw format.
              x-parser-schema-id: <anonymous-schema-4>
            num_channels:
              type: integer
              description: Channel count for a raw format. Use 1 for mono.
              x-parser-schema-id: <anonymous-schema-5>
            language_hints:
              type: array
              description: >-
                ["he"] or ["en"] locks that language. Both, or omitting the
                field, detects the language per utterance.
              items:
                type: string
                enum:
                  - he
                  - en
                x-parser-schema-id: <anonymous-schema-7>
              x-parser-schema-id: <anonymous-schema-6>
            language_hints_strict:
              type: boolean
              description: Restrict detection to the hinted languages.
              x-parser-schema-id: <anonymous-schema-8>
            enable_endpoint_detection:
              type: boolean
              description: Send a final <end> token when the speaker finishes a turn.
              x-parser-schema-id: <anonymous-schema-9>
            max_endpoint_delay_ms:
              type: integer
              description: Pause length before a turn ends, from 500 to 3000.
              minimum: 500
              maximum: 3000
              x-parser-schema-id: <anonymous-schema-10>
            context:
              type: object
              properties:
                terms:
                  type: array
                  description: Words to boost. Up to 200.
                  items:
                    type: string
                    x-parser-schema-id: <anonymous-schema-13>
                  x-parser-schema-id: <anonymous-schema-12>
                text:
                  type: string
                  description: Earlier conversation, used as history.
                  x-parser-schema-id: <anonymous-schema-14>
                prev:
                  type: string
                  description: Earlier conversation, same role as text.
                  x-parser-schema-id: <anonymous-schema-15>
              x-parser-schema-id: <anonymous-schema-11>
            enable_agent_text_input:
              type: boolean
              description: Allow agent_text control messages on this socket.
              x-parser-schema-id: <anonymous-schema-16>
            client_reference_id:
              type: string
              description: Your own id, echoed in Deepdub logs.
              x-parser-schema-id: <anonymous-schema-17>
          x-parser-schema-id: <anonymous-schema-1>
        title: Start message
        example: |-
          {
            "model": "stt-egf",
            "audio_format": "pcm_s16le",
            "sample_rate": 16000,
            "num_channels": 1,
            "language_hints": [
              "he"
            ],
            "enable_endpoint_detection": false,
            "context": {
              "terms": [
                "Deepdub",
                "insurance"
              ],
              "text": ""
            },
            "enable_agent_text_input": false,
            "client_reference_id": "my-call-123"
          }
        bindings: []
        extensions:
          - id: x-parser-unique-object-id
            value: start
    bindings: []
    extensions: &ref_0
      - id: x-parser-unique-object-id
        value: transcribe
  - &ref_1
    id: receiveTokens
    title: Word tokens
    description: >-
      Words arrive as provisional tokens, then as final tokens. The last message
      has finished set to true, and the socket closes.
    type: receive
    messages:
      - &ref_3
        id: tokens
        contentType: application/json
        payload:
          - name: Word tokens
            type: object
            properties:
              - name: tokens
                type: array
                required: false
                properties:
                  - name: text
                    type: string
                    description: Word text, spaces included. Concatenate exactly.
                    required: false
                  - name: start_ms
                    type: integer
                    required: false
                  - name: end_ms
                    type: integer
                    required: false
                  - name: confidence
                    type: number
                    required: false
                  - name: is_final
                    type: boolean
                    description: >-
                      Final tokens never change. Provisional tokens are replaced
                      by a later message.
                    required: false
                  - name: language
                    type: string
                    enumValues:
                      - he
                      - en
                    required: false
              - name: final_audio_proc_ms
                type: integer
                required: false
              - name: total_audio_proc_ms
                type: integer
                required: false
              - name: finished
                type: boolean
                description: True on the last message. The socket then closes.
                required: false
              - name: error_code
                type: integer
                required: false
              - name: error_type
                type: string
                required: false
              - name: error_message
                type: string
                required: false
        headers: []
        jsonPayloadSchema:
          type: object
          properties:
            tokens:
              type: array
              items:
                type: object
                properties:
                  text:
                    type: string
                    description: Word text, spaces included. Concatenate exactly.
                    x-parser-schema-id: <anonymous-schema-21>
                  start_ms:
                    type: integer
                    x-parser-schema-id: <anonymous-schema-22>
                  end_ms:
                    type: integer
                    x-parser-schema-id: <anonymous-schema-23>
                  confidence:
                    type: number
                    x-parser-schema-id: <anonymous-schema-24>
                  is_final:
                    type: boolean
                    description: >-
                      Final tokens never change. Provisional tokens are replaced
                      by a later message.
                    x-parser-schema-id: <anonymous-schema-25>
                  language:
                    type: string
                    enum:
                      - he
                      - en
                    x-parser-schema-id: <anonymous-schema-26>
                x-parser-schema-id: <anonymous-schema-20>
              x-parser-schema-id: <anonymous-schema-19>
            final_audio_proc_ms:
              type: integer
              x-parser-schema-id: <anonymous-schema-27>
            total_audio_proc_ms:
              type: integer
              x-parser-schema-id: <anonymous-schema-28>
            finished:
              type: boolean
              description: True on the last message. The socket then closes.
              x-parser-schema-id: <anonymous-schema-29>
            error_code:
              type: integer
              x-parser-schema-id: <anonymous-schema-30>
            error_type:
              type: string
              x-parser-schema-id: <anonymous-schema-31>
            error_message:
              type: string
              x-parser-schema-id: <anonymous-schema-32>
          x-parser-schema-id: <anonymous-schema-18>
        title: Word tokens
        example: |-
          {
            "tokens": [
              {
                "text": " hello",
                "start_ms": 1200,
                "end_ms": 1480,
                "confidence": 0.97,
                "is_final": true,
                "language": "en"
              }
            ],
            "final_audio_proc_ms": 1600,
            "total_audio_proc_ms": 2400
          }
        bindings: []
        extensions:
          - id: x-parser-unique-object-id
            value: tokens
    bindings: []
    extensions: *ref_0
sendOperations:
  - *ref_1
receiveOperations:
  - *ref_2
sendMessages:
  - *ref_3
receiveMessages:
  - *ref_4
extensions:
  - id: x-parser-unique-object-id
    value: transcribe
securitySchemes:
  - id: bearerAuth
    name: bearerAuth
    type: http
    description: >-
      Deepdub API key. Send it as Authorization: Bearer on the WebSocket
      handshake.
    scheme: bearer
    extensions: []

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.