🎤Micdrop

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:

  • DeepgramSTT runs Nova-3, Deepgram’s most accurate streaming model, in English and dozens of other languages, or in multi mode for a speaker who switches language mid sentence.
  • DeepgramFluxSTT runs 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

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

Create 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

OptionTypeDefaultDescription
apiKeystringRequiredYour Deepgram API key
modelstring'nova-3'Model of the /v1/listen endpoint, such as nova-3, nova-3-medical or nova-2-phonecall
languagestring'en'Language spoken, such as fr or en-US, or multi for Nova-3 multilingual
keytermsstring[]OptionalWords and names to recognize better. Nova-3 reads them as key terms, the older models as keywords
smartFormatbooleantrueFormats dates, numbers, amounts, emails and the like
punctuatebooleantrueAdds punctuation and capitals
numeralsbooleanOptionalWrites numbers as digits
fillerWordsbooleanOptionalKeeps the hesitations, such as “uh” and “um”
profanityFilterbooleanOptionalMasks profanity
redactstring | string[]OptionalHides sensitive data, such as pci, ssn or numbers
mipOptOutbooleanOptionalOpts out of the Deepgram Model Improvement Program
tagstring | string[]OptionalLabels the requests in the Deepgram console
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, from the interim results
apiUrlstringDeepgramAddress of a dedicated or self-hosted deployment, wss://api.deepgram.com by default
transcriptionTimeoutnumber4000Milliseconds a turn waits for its last words once it ended
connectionTimeoutnumber5000Milliseconds a connection attempt may take
retryDelaynumber1000Milliseconds between two connection attempts
maxRetrynumber3Failed 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

OptionTypeDefaultDescription
apiKeystringRequiredYour Deepgram API key
modelstring'flux-general-en'flux-general-en or flux-general-multi
languageHintsstring[]OptionalLanguages to expect, for flux-general-multi only
keytermsstring[]OptionalWords and names to recognize better, up to 100
eotThresholdnumber1Confidence Flux needs to end a turn on its own, from 0.5 to 1. At 1, Micdrop decides
eotTimeoutMsnumber5000Silence after which Flux ends a turn whatever its confidence, from 500 to 60000 ms
numeralsbooleanOptionalWrites numbers as digits
profanityFilterbooleanOptionalMasks profanity
redactstringOptionalnumbers or aggressive_numbers
mipOptOutbooleanOptionalOpts out of the Deepgram Model Improvement Program
tagstring | string[]OptionalLabels the requests in the Deepgram console
paramsRecord<string, ...>OptionalAny other query parameter of the endpoint, sent as is
onPartial(transcript: string) => voidOptionalReceives the transcript of the turn under way, from the updates of Flux
apiUrlstringDeepgramAddress of a dedicated or self-hosted deployment
transcriptionTimeoutnumber4000Milliseconds a turn waits for its last words 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, 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, 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 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.