---
title: "AssemblyAI Streaming Speech to Text in Node.js | Micdrop"
description: "Transcribe a live call with AssemblyAI Universal-Streaming from your Node.js server in TypeScript. A complete voice agent example, turn detection modes, key terms and temporary tokens."
url: "https://micdrop.dev/docs/speech-to-text/assemblyai"
---

# AssemblyAI Streaming Speech to Text in Node.js

`@micdrop/assemblyai` streams the voice of your users to AssemblyAI Universal-Streaming from a [@micdrop/server](/docs/server) voice agent, in TypeScript. `AssemblyAISTT` speaks the v3 streaming API, uses the `assemblyai-stt-3-7-realtime-agent` model made for voice agents by default, and hands over one formatted transcript per turn of the user.

## Installation

```bash
npm install @micdrop/server @micdrop/assemblyai ws
```

Create an API key in the [AssemblyAI dashboard](https://www.assemblyai.com/dashboard) and set it as `ASSEMBLYAI_API_KEY`.

## A complete voice agent with AssemblyAI

This server answers every browser that connects on port 8081. AssemblyAI transcribes the user, an OpenAI model writes the answer and ElevenLabs speaks it.

```typescript
import { AssemblyAISTT } from '@micdrop/assemblyai'
import { ElevenLabsTTS } from '@micdrop/elevenlabs'
import { OpenaiAgent } from '@micdrop/openai'
import { MicdropServer } from '@micdrop/server'
import { WebSocketServer } from 'ws'

const wss = new WebSocketServer({ port: 8081 })

wss.on('connection', (socket) => {
  new MicdropServer(socket, {
    firstMessage: 'Hello, how can I help you today?',
    stt: new AssemblyAISTT({
      apiKey: process.env.ASSEMBLYAI_API_KEY || '',
      keyterms: ['Micdrop'],
    }),
    agent: new OpenaiAgent({
      apiKey: process.env.OPENAI_API_KEY || '',
      systemPrompt: 'You are a friendly assistant. Answer in one or two sentences.',
    }),
    tts: new ElevenLabsTTS({
      apiKey: process.env.ELEVENLABS_API_KEY || '',
      voiceId: process.env.ELEVENLABS_VOICE_ID || '',
    }),
  })
})
```

The browser starts the call with [`@micdrop/web`](/docs/client):

```typescript
import { Micdrop } from '@micdrop/web'

button.onclick = () => Micdrop.start({ url: 'ws://localhost:8081' })

Micdrop.on('StateChange', (state) => console.log(state.conversation))
```

Any [agent](/docs/agents) and any [text to speech](/docs/text-to-speech) fit in, and with `AssemblyAISTT` as the only component, the server [transcribes the call without answering](/docs/server/dictation).

## Options

Option

Type

Default

Description

`apiKey`

`string`

`apiKey` or `token`

Your AssemblyAI API key, sent in a header

`token`

`string | () => string | Promise`

`apiKey` or `token`

A temporary token, or a function giving a fresh one for each connection

`speechModel`

`string`

`'assemblyai-stt-3-7-realtime-agent'`

Model to transcribe with

`mode`

`string`

`'manual'` with an `-agent` model

How AssemblyAI ends turns: `manual`, `min_latency`, `balanced` or `max_accuracy`

`minTurnSilence`

`number`

Set by the mode

Silence in ms before AssemblyAI checks whether the turn ended

`maxTurnSilence`

`number`

Set by the mode

Silence in ms after which AssemblyAI ends the turn whatever it heard

`vadThreshold`

`number`

`0.2`

Confidence needed to count a frame as speech, from 0 to 1

`keyterms`

`string[]`

Optional

Words and names to recognize better, up to 100 of 50 characters each

`prompt`

`string`

Optional

What the conversation is about, up to 1750 characters

`languageCodes`

`string[]`

Detected

Languages to expect, such as `['en', 'fr']`

`region`

`'us' | 'eu'`

Nearest

Region that processes and keeps the audio

`params`

`Record<string, ...>`

Optional

Any other query parameter of the endpoint, sent as is

`onPartial`

`(transcript: string) => void`

Optional

Receives the transcript of the turn under way as it grows

`transcriptionTimeout`

`number`

`4000`

Milliseconds a turn waits for its transcript once it ended

`connectionTimeout`

`number`

`5000`

Milliseconds a connection attempt may take

`retryDelay`

`number`

`1000`

Milliseconds between two connection attempts

`maxRetry`

`number`

`3`

Failed attempts in a row before `Failed`

Out of range values throw when the instance is created: more than 100 key terms, a key term over 50 characters, a `vadThreshold` outside 0 to 1, or the `manual` mode with a model that does not end in `-agent`.

## How a turn ends

Micdrop detects the turns itself, with the [voice activity detection](/docs/client/vad) of the client or of the server and an optional [turn detector](/docs/client/turn-detection). `AssemblyAISTT` opens the session in the `manual` mode, so AssemblyAI never cuts a turn on its own, and sends `ForceEndpoint` when the stream of the turn ends. AssemblyAI answers with the final, formatted transcript of the turn, or an empty one when no word was spoken, and that answer is the `Transcript` event.

With `mode: 'balanced'` or another preset, AssemblyAI ends turns on silence too. The transcript of a Micdrop turn then joins every turn AssemblyAI heard in it, once they all ended. The `manual` mode exists for the `-agent` models only, so another model gets the default mode of AssemblyAI.

## Temporary tokens

A temporary token opens streaming sessions without the API key, for a server that should not hold it, such as an edge function. The API key stays where the tokens are made:

```typescript
import { AssemblyAISTT } from '@micdrop/assemblyai'

const token = await AssemblyAISTT.createToken({
  apiKey: process.env.ASSEMBLYAI_API_KEY || '',
  expiresInSeconds: 600,
})

const stt = new AssemblyAISTT({ token })
```

A token opens sessions until it expires, after 1 to 600 seconds, and the sessions it opened run on. A function given as `token` is called on every connection attempt, so a reconnection never meets an expired token:

```typescript
const stt = new AssemblyAISTT({
  token: () =>
    AssemblyAISTT.createToken({ apiKey: process.env.ASSEMBLYAI_API_KEY || '' }),
})
```

`maxSessionDurationSeconds` caps the length of the sessions a token opens, and `region` makes the token in the region the sessions connect to.

## Usage without MicdropServer

```typescript
import { AssemblyAISTT } from '@micdrop/assemblyai'
import { createReadStream } from 'fs'

const stt = new AssemblyAISTT({ apiKey: process.env.ASSEMBLYAI_API_KEY || '' })

stt.on('Transcript', (text) => console.log('Transcript:', text))
stt.on('Failed', (chunks) => console.error('Failed:', chunks.length, 'chunks'))

// Audio is raw PCM, 16 bits, 16 kHz, mono
stt.transcribe(createReadStream('speech.pcm'))
```

## Events

Event

Payload

Description

`Transcript`

`string`

Transcription of one turn. The text is empty when nothing was recognized.

`Failed`

`Buffer[]`

Transcription gave up after its retries, with the audio chunks left pending.

See the [STT interface](/docs/speech-to-text/custom) for the full contract.

## Connection and retries

The session opens with the instance, so the first turn does not wait for it, and the audio goes out in chunks of 50 ms, the size AssemblyAI recommends. AssemblyAI bills the duration of the session, which lasts as long as the call. On `destroy()`, the session ends with `Terminate`.

A session that drops in the middle of a turn opens again, and the audio of every turn still waiting for its transcript goes to the new one. After `maxRetry` failed attempts in a row, `Failed` hands that audio back, ready for a [`FallbackSTT`](/docs/speech-to-text/fallback) to transcribe it with another provider, and the next turn tries to connect again. A refused session, for a wrong key or a spent balance, fails its attempt with the reason AssemblyAI gave.

Prices, languages and latency of the streaming speech to text APIs are compared in the [ranking of speech to text APIs for voice agents](/blog/top-speech-to-text-apis-voice-agents).
