Deepgram Speech to Text in Node.js
@micdrop/deepgram streams the voice of your users to Deepgram from a
@micdrop/server voice agent, in TypeScript. It speaks the live
WebSocket API of Deepgram for two families of models:
DeepgramSTTruns Nova-3, Deepgram’s most accurate streaming model, in English and dozens of other languages, or inmultimode for a speaker who switches language mid sentence.DeepgramFluxSTTruns Flux, the conversational model built for voice agents, which follows each turn of the speaker.
Both keep one connection open for the whole call, send the audio as the user speaks, and hand over one transcript per turn, a few hundred milliseconds after the user stops. The same package also holds Aura-2 text to speech.
Installation
npm install @micdrop/server @micdrop/deepgram wsCreate an API key in the Deepgram console and
set it as DEEPGRAM_API_KEY.
A complete voice agent with Deepgram
This server answers every browser that connects on port 8081. Deepgram transcribes the user with Nova-3 and speaks the answer with an Aura-2 voice, and an OpenAI model writes it.
import { DeepgramSTT, DeepgramTTS } from '@micdrop/deepgram'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 DeepgramSTT({ apiKey: process.env.DEEPGRAM_API_KEY || '', model: 'nova-3', language: 'en', 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 DeepgramTTS({ apiKey: process.env.DEEPGRAM_API_KEY || '', voice: 'aura-2-thalia-en', }), })})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 fits in place of OpenAI, and with DeepgramSTT as the
only component, the server transcribes the call without answering.
Nova-3 with DeepgramSTT
import { DeepgramSTT } from '@micdrop/deepgram'
const stt = new DeepgramSTT({ apiKey: process.env.DEEPGRAM_API_KEY || '', model: 'nova-3', language: 'fr', keyterms: ['Micdrop', 'Lonestone'], numerals: true,})Options
| Option | Type | Default | Description |
|---|---|---|---|
apiKey | string | Required | Your Deepgram API key |
model | string | 'nova-3' | Model of the /v1/listen endpoint, such as nova-3, nova-3-medical or nova-2-phonecall |
language | string | 'en' | Language spoken, such as fr or en-US, or multi for Nova-3 multilingual |
keyterms | string[] | Optional | Words and names to recognize better. Nova-3 reads them as key terms, the older models as keywords |
smartFormat | boolean | true | Formats dates, numbers, amounts, emails and the like |
punctuate | boolean | true | Adds punctuation and capitals |
numerals | boolean | Optional | Writes numbers as digits |
fillerWords | boolean | Optional | Keeps the hesitations, such as “uh” and “um” |
profanityFilter | boolean | Optional | Masks profanity |
redact | string | string[] | Optional | Hides sensitive data, such as pci, ssn or numbers |
mipOptOut | boolean | Optional | Opts out of the Deepgram Model Improvement Program |
tag | string | string[] | Optional | Labels the requests in the Deepgram console |
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, from the interim results |
apiUrl | string | Deepgram | Address of a dedicated or self-hosted deployment, wss://api.deepgram.com by default |
transcriptionTimeout | number | 4000 | Milliseconds a turn waits for its last words 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 |
Languages and key terms
Nova-3 transcribes English and dozens of other languages, each set with
language. With language: 'multi', it follows a speaker who mixes its
languages in one sentence, and params: { language_hint: ['en', 'es'] }
narrows the languages it expects.
Key terms teach Nova-3 the names your users say: a product, a brand, a place,
a person. Each one is sent as a keyterm parameter, up to 500 tokens in all.
The models before Nova-3 receive them as keywords.
How a turn ends
Each stream given to transcribe() is one turn of the user and gets exactly
one Transcript event. When the stream ends, DeepgramSTT sends Finalize,
which makes Deepgram transcribe the audio it holds right away rather than wait
for a pause, and joins the final results of the turn. A final result that
reaches the end of the turn completes it too, since Deepgram has nothing left
to finalize then. With no word at all, the transcript is empty after
transcriptionTimeout.
Micdrop detects the turns itself, with the voice activity detection of the client or of the server and an optional turn detector, so the endpointing of Deepgram stays at its default. A turn held open through a hesitation goes on in the same stream.
Listing the models
const models = await DeepgramSTT.listModels({ apiKey: process.env.DEEPGRAM_API_KEY || '',})// [{ id: 'nova-3', languages: ['en', 'en-US', ...] }, ...]The list holds the models that transcribe in real time. It is fetched once and shared by every call of the process for a day.
Flux with DeepgramFluxSTT
Flux is the conversational model of Deepgram. It transcribes and follows the
turns of the speaker in the same pass, and DeepgramFluxSTT connects to it on
the /v2/listen endpoint.
import { DeepgramFluxSTT } from '@micdrop/deepgram'
const stt = new DeepgramFluxSTT({ apiKey: process.env.DEEPGRAM_API_KEY || '', model: 'flux-general-en', keyterms: ['Micdrop'],})flux-general-multi transcribes English, Spanish, French, German, Hindi,
Russian, Portuguese, Japanese, Italian and Dutch, and languageHints tells it
which ones to expect:
const stt = new DeepgramFluxSTT({ apiKey: process.env.DEEPGRAM_API_KEY || '', model: 'flux-general-multi', languageHints: ['fr', 'en'],})By default Micdrop decides when the turn ends and closes it with
ForceEndTurn, which Flux answers with the final transcript of the turn. A
lower eotThreshold lets Flux end turns on its own too, and the transcript of
a Micdrop turn then joins every turn Flux heard in it.
Options
| Option | Type | Default | Description |
|---|---|---|---|
apiKey | string | Required | Your Deepgram API key |
model | string | 'flux-general-en' | flux-general-en or flux-general-multi |
languageHints | string[] | Optional | Languages to expect, for flux-general-multi only |
keyterms | string[] | Optional | Words and names to recognize better, up to 100 |
eotThreshold | number | 1 | Confidence Flux needs to end a turn on its own, from 0.5 to 1. At 1, Micdrop decides |
eotTimeoutMs | number | 5000 | Silence after which Flux ends a turn whatever its confidence, from 500 to 60000 ms |
numerals | boolean | Optional | Writes numbers as digits |
profanityFilter | boolean | Optional | Masks profanity |
redact | string | Optional | numbers or aggressive_numbers |
mipOptOut | boolean | Optional | Opts out of the Deepgram Model Improvement Program |
tag | string | string[] | Optional | Labels the requests in the Deepgram console |
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, from the updates of Flux |
apiUrl | string | Deepgram | Address of a dedicated or self-hosted deployment |
transcriptionTimeout | number | 4000 | Milliseconds a turn waits for its last words 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, as does
languageHints with a model other than flux-general-multi.
Usage without MicdropServer
import { DeepgramSTT } from '@micdrop/deepgram'import { createReadStream } from 'fs'
const stt = new DeepgramSTT({ apiKey: process.env.DEEPGRAM_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, monostt.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 for the full contract.
Connection and retries
The connection opens with the instance, so the first turn does not wait for
it. The audio goes out in chunks of 50 ms for Nova-3 and 80 ms for Flux, the
sizes Deepgram recommends. Between two turns, DeepgramSTT sends a
KeepAlive every four seconds.
A connection 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 session. 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. Deepgram closes a connection left without
audio for a while: with no turn pending, it stays closed until the next turn
opens a new one.
On destroy(), the session ends with CloseStream.
Nova-3 or Flux
Nova-3 covers the most languages, the medical vocabulary and the formatting options, such as smart formatting and redaction. Flux is tuned for conversation and follows the turns of the speaker itself. Prices, languages and latency of the streaming speech to text APIs are compared in the ranking of speech to text APIs for voice agents.