🎤Micdrop

AssemblyAI Streaming Speech to Text in Node.js

@micdrop/assemblyai streams the voice of your users to AssemblyAI Universal-Streaming from a @micdrop/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

Terminal window
npm install @micdrop/server @micdrop/assemblyai ws

Create an API key in the AssemblyAI 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.

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:

import { Micdrop } from '@micdrop/web'
button.onclick = () => Micdrop.start({ url: 'ws://localhost:8081' })
Micdrop.on('StateChange', (state) => console.log(state.conversation))

Any agent and any text to speech fit in, and with AssemblyAISTT as the only component, the server transcribes the call without answering.

Options

OptionTypeDefaultDescription
apiKeystringapiKey or tokenYour AssemblyAI API key, sent in a header
tokenstring | () => string | PromiseapiKey or tokenA temporary token, or a function giving a fresh one for each connection
speechModelstring'assemblyai-stt-3-7-realtime-agent'Model to transcribe with
modestring'manual' with an -agent modelHow AssemblyAI ends turns: manual, min_latency, balanced or max_accuracy
minTurnSilencenumberSet by the modeSilence in ms before AssemblyAI checks whether the turn ended
maxTurnSilencenumberSet by the modeSilence in ms after which AssemblyAI ends the turn whatever it heard
vadThresholdnumber0.2Confidence needed to count a frame as speech, from 0 to 1
keytermsstring[]OptionalWords and names to recognize better, up to 100 of 50 characters each
promptstringOptionalWhat the conversation is about, up to 1750 characters
languageCodesstring[]DetectedLanguages to expect, such as ['en', 'fr']
region'us' | 'eu'NearestRegion that processes and keeps the audio
paramsRecord<string, ...>OptionalAny other query parameter of the endpoint, sent as is
onPartial(transcript: string) => voidOptionalReceives the transcript of the turn under way as it grows
transcriptionTimeoutnumber4000Milliseconds a turn waits for its transcript once it ended
connectionTimeoutnumber5000Milliseconds a connection attempt may take
retryDelaynumber1000Milliseconds between two connection attempts
maxRetrynumber3Failed 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 of the client or of the server and an optional turn detector. 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:

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:

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

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

EventPayloadDescription
TranscriptstringTranscription of one turn. The text is empty when nothing was recognized.
FailedBuffer[]Transcription gave up after its retries, with the audio chunks left pending.

See the STT interface 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 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.