VoiceRouter

adapters/deepgram-adapter

Voice Router SDK - Deepgram Provider / adapters/deepgram-adapter

adapters/deepgram-adapter

Classes

DeepgramAdapter

Deepgram transcription provider adapter

Implements transcription for the Deepgram API with support for:

  • Synchronous pre-recorded transcription
  • Real-time streaming transcription (WebSocket)
  • Speaker diarization (identifying different speakers)
  • Multi-language detection and transcription
  • Summarization and sentiment analysis
  • Entity detection and intent recognition
  • Custom vocabulary (keywords)
  • Word-level timestamps with high precision
  • PII redaction

See

https://developers.deepgram.com/ Deepgram API Documentation

Examples

import { DeepgramAdapter } from '@meeting-baas/sdk';

const adapter = new DeepgramAdapter();
adapter.initialize({
  apiKey: process.env.DEEPGRAM_API_KEY
});

const result = await adapter.transcribe({
  type: 'url',
  url: 'https://example.com/audio.mp3'
}, {
  language: 'en',
  diarization: true
});

console.log(result.data.text);
console.log(result.data.speakers);
import { DeepgramAdapter, DeepgramRegion } from '@meeting-baas/sdk';

const adapter = new DeepgramAdapter();
adapter.initialize({
  apiKey: process.env.DEEPGRAM_API_KEY,
  region: DeepgramRegion.eu  // EU endpoint for data residency
});
const result = await adapter.transcribe(audio, {
  language: 'en',
  diarization: true,
  summarization: true,
  sentimentAnalysis: true,
  entityDetection: true,
  customVocabulary: ['TypeScript', 'JavaScript', 'API']
});

console.log('Summary:', result.data.summary);
console.log('Sentiment:', result.data.metadata?.sentiment);

Extends

Methods

buildStreamingUrl()

private buildStreamingUrl(options?): string

Build WebSocket URL with all streaming parameters

Parameters
ParameterType
options?StreamingOptions
Returns

string

buildTranscriptionParams()

private buildTranscriptionParams(options?): ListenV1MediaTranscribeParams

Build Deepgram transcription parameters from unified options

Parameters
ParameterType
options?TranscribeOptions
Returns

ListenV1MediaTranscribeParams

createErrorResponse()

protected createErrorResponse(error, statusCode?, code?): UnifiedTranscriptResponse

Helper method to create error responses with stack traces

Parameters
ParameterTypeDescription
errorunknownError object or unknown error
statusCode?numberOptional HTTP status code
code?ErrorCodeOptional error code (defaults to extracted or UNKNOWN_ERROR)
Returns

UnifiedTranscriptResponse

Inherited from

BaseAdapter.createErrorResponse

extractSpeakers()

private extractSpeakers(response): object[] | undefined

Extract speaker information from Deepgram response

Parameters
ParameterType
responseListenV1Response
Returns

object[] | undefined

extractSummary()

private extractSummary(alternative): string | undefined

Extract summary from Deepgram response

Parameters
ParameterType
alternativeListenV1ResponseResultsChannelsItemAlternativesItem
Returns

string | undefined

extractUtterances()

private extractUtterances(response): object[] | undefined

Extract utterances from Deepgram response

Parameters
ParameterType
responseListenV1Response
Returns

object[] | undefined

extractWords()

private extractWords(alternative): object[] | undefined

Extract word timestamps from Deepgram response

Parameters
ParameterType
alternativeListenV1ResponseResultsChannelsItemAlternativesItem
Returns

object[] | undefined

getAxiosConfig()

protected getAxiosConfig(authHeaderName, authHeaderValue?): object

Build axios config for generated API client functions

Parameters
ParameterTypeDefault valueDescription
authHeaderNamestring"Authorization"Header name for API key (e.g., "Authorization", "x-gladia-key")
authHeaderValue?(apiKey) => stringundefinedOptional function to format auth header value (defaults to raw API key)
Returns

object

Axios config object

baseURL

baseURL: string

headers

headers: Record<string, string>

timeout

timeout: number

Inherited from

BaseAdapter.getAxiosConfig

getRegion()

getRegion(): object

Get the current regional endpoints being used

Returns

object

Object with REST API and WebSocket URLs

api

api: string

websocket

websocket: string

getRegionalHost()

private getRegionalHost(region?): string

Get API host based on region

Parameters
ParameterTypeDescription
region?DeepgramRegionTypeRegional endpoint identifier
Returns

string

API host (without protocol or path)

getTranscript()

getTranscript(transcriptId): Promise<UnifiedTranscriptResponse<TranscriptionProvider>>

Get transcription result by ID

Retrieves a previous transcription from Deepgram's request history.

Unlike the list endpoint, getting a single request DOES include the full transcript response. Requires projectId to be set during initialization.

Parameters
ParameterTypeDescription
transcriptIdstringRequest ID from a previous transcription
Returns

Promise<UnifiedTranscriptResponse<TranscriptionProvider>>

Full transcript response including text, words, and metadata

Example
const adapter = new DeepgramAdapter()
adapter.initialize({
  apiKey: process.env.DEEPGRAM_API_KEY,
  projectId: process.env.DEEPGRAM_PROJECT_ID
})

const result = await adapter.getTranscript('abc123-request-id')
if (result.success) {
  console.log(result.data?.text)
  console.log(result.data?.words)
}
See

https://developers.deepgram.com/reference/get-request

Overrides

BaseAdapter.getTranscript

handleWebSocketMessage()

private handleWebSocketMessage(message, callbacks?): void

Handle all WebSocket message types from Deepgram streaming

Parameters
ParameterType
messageDeepgramRealtimeMessage
callbacks?StreamingCallbacks
Returns

void

initialize()

initialize(config): void

Initialize the adapter with configuration

Parameters
ParameterType
configDeepgramConfig
Returns

void

Overrides

BaseAdapter.initialize

listTranscripts()

listTranscripts(options?): Promise<{ transcripts: UnifiedTranscriptResponse<TranscriptionProvider>[]; hasMore?: boolean; total?: number; }>

List recent transcription requests from Deepgram's request history

Important: Deepgram processes synchronously and doesn't store transcript content. This method returns request metadata (IDs, timestamps, status) but NOT the actual transcript text. Use this for auditing, billing analysis, or request tracking.

Requires projectId to be set during initialization.

Parameters
ParameterTypeDescription
options?ListTranscriptsOptionsFiltering and pagination options
Returns

Promise<{ transcripts: UnifiedTranscriptResponse<TranscriptionProvider>[]; hasMore?: boolean; total?: number; }>

List of transcription request metadata

Example
const adapter = new DeepgramAdapter()
adapter.initialize({
  apiKey: process.env.DEEPGRAM_API_KEY,
  projectId: process.env.DEEPGRAM_PROJECT_ID
})

const { transcripts, hasMore } = await adapter.listTranscripts({
  limit: 50,
  status: 'succeeded'
})

transcripts.forEach(t => {
  console.log(t.data?.id, t.data?.metadata?.createdAt)
})
See

https://developers.deepgram.com/reference/get-all-requests

normalizeRequestItem()

private normalizeRequestItem(item): UnifiedTranscriptResponse

Normalize a Deepgram request history item to unified format

Parameters
ParameterType
itemProjectRequestResponse
Returns

UnifiedTranscriptResponse

normalizeResponse()

private normalizeResponse(response): UnifiedTranscriptResponse<"deepgram">

Normalize Deepgram response to unified format

Parameters
ParameterType
responseListenV1Response
Returns

UnifiedTranscriptResponse<"deepgram">

pollForCompletion()

protected pollForCompletion(transcriptId, options?): Promise<UnifiedTranscriptResponse<TranscriptionProvider>>

Generic polling helper for async transcription jobs

Polls getTranscript() until job completes or times out.

Parameters
ParameterTypeDescription
transcriptIdstringJob/transcript ID to poll
options?{ intervalMs?: number; maxAttempts?: number; }Polling configuration
options.intervalMs?number-
options.maxAttempts?number-
Returns

Promise<UnifiedTranscriptResponse<TranscriptionProvider>>

Final transcription result

Inherited from

BaseAdapter.pollForCompletion

setRegion()

setRegion(region): void

Change the regional endpoint dynamically

Useful for testing different regions or switching based on user location. Preserves all other configuration (apiKey, projectId, timeout, headers). Affects both REST API and WebSocket streaming endpoints.

Parameters
ParameterTypeDescription
regionDeepgramRegionTypeNew regional endpoint to use (global or eu)
Returns

void

Example
import { DeepgramRegion } from 'voice-router-dev/constants'

// Test global endpoint
adapter.setRegion(DeepgramRegion.global)
await adapter.transcribe(audio)

// Switch to EU for data residency testing
adapter.setRegion(DeepgramRegion.eu)
await adapter.transcribe(audio)
transcribe()

transcribe(audio, options?): Promise<UnifiedTranscriptResponse<TranscriptionProvider>>

Submit audio for transcription

Sends audio to Deepgram API for transcription. Deepgram processes synchronously and returns results immediately (no polling required).

Parameters
ParameterTypeDescription
audioAudioInputAudio input (URL or file buffer)
options?TranscribeOptionsTranscription options
Returns

Promise<UnifiedTranscriptResponse<TranscriptionProvider>>

Normalized transcription response

Examples
const result = await adapter.transcribe({
  type: 'url',
  url: 'https://example.com/meeting.mp3'
});
const result = await adapter.transcribe({
  type: 'url',
  url: 'https://example.com/meeting.mp3'
}, {
  language: 'en',
  diarization: true,
  summarization: true,
  sentimentAnalysis: true,
  entityDetection: true,
  customVocabulary: ['API', 'TypeScript', 'JavaScript']
});
Overrides

BaseAdapter.transcribe

transcribeStream()

transcribeStream(options?, callbacks?): Promise<StreamingSession>

Stream audio for real-time transcription

Creates a WebSocket connection to Deepgram for streaming transcription. Send audio chunks via session.sendAudio() and receive results via callbacks.

Supports all Deepgram streaming features:

  • Real-time transcription with interim/final results
  • Speech detection events (SpeechStarted, UtteranceEnd)
  • Speaker diarization
  • Language detection
  • Real-time sentiment, entity detection, topics, intents
  • Custom vocabulary (keywords, keyterms)
  • PII redaction
  • Filler words, numerals, measurements, paragraphs
  • Profanity filtering
  • Dictation mode
Parameters
ParameterTypeDescription
options?StreamingOptionsStreaming configuration options
callbacks?StreamingCallbacksEvent callbacks for transcription results
Returns

Promise<StreamingSession>

Promise that resolves with a StreamingSession

Examples
const session = await adapter.transcribeStream({
  encoding: 'linear16',
  sampleRate: 16000,
  channels: 1,
  language: 'en',
  diarization: true,
  interimResults: true
}, {
  onOpen: () => console.log('Connected'),
  onTranscript: (event) => {
    if (event.isFinal) {
      console.log('Final:', event.text);
    } else {
      console.log('Interim:', event.text);
    }
  },
  onError: (error) => console.error('Error:', error),
  onClose: () => console.log('Disconnected')
});

// Send audio chunks
const audioChunk = getAudioChunk();
await session.sendAudio({ data: audioChunk });

// Close when done
await session.close();
const session = await adapter.transcribeStream({
  encoding: 'linear16',
  sampleRate: 16000,
  language: 'en',
  model: 'nova-3',
  diarization: true,
  sentimentAnalysis: true,
  entityDetection: true,
  deepgramStreaming: {
    fillerWords: true,
    numerals: true,
    profanityFilter: true,
    topics: true,
    intents: true,
    customTopic: ['sales', 'support'],
    customIntent: ['purchase', 'complaint'],
    keyterm: ['TypeScript', 'JavaScript'],
    utteranceSplit: 800,
    punctuate: true,
    smartFormat: true
  }
}, {
  onTranscript: (e) => console.log('Transcript:', e.text),
  onSpeechStart: (e) => console.log('Speech started at:', e.timestamp),
  onSpeechEnd: (e) => console.log('Utterance ended'),
  onMetadata: (m) => console.log('Metadata:', m)
});
validateConfig()

protected validateConfig(): void

Helper method to validate configuration

Returns

void

Inherited from

BaseAdapter.validateConfig

Constructors

Constructor

new DeepgramAdapter(): DeepgramAdapter

Returns

DeepgramAdapter

Inherited from

BaseAdapter.constructor

Properties

baseUrl

protected baseUrl: string = "https://api.deepgram.com/v1"

Base URL for provider API (must be defined by subclass)

Overrides

BaseAdapter.baseUrl

capabilities

readonly capabilities: ProviderCapabilities

Provider capabilities

Overrides

BaseAdapter.capabilities

name

readonly name: "deepgram"

Provider name

Overrides

BaseAdapter.name

wsBaseUrl

private wsBaseUrl: string = "wss://api.deepgram.com/v1/listen"

client?

private optional client: AxiosInstance

config?

protected optional config: ProviderConfig

Inherited from

BaseAdapter.config

projectId?

private optional projectId: string

Functions

createDeepgramAdapter()

createDeepgramAdapter(config): DeepgramAdapter

Factory function to create a Deepgram adapter

Parameters

ParameterType
configDeepgramConfig

Returns

DeepgramAdapter

Examples

import { createDeepgramAdapter } from 'voice-router-dev'

const adapter = createDeepgramAdapter({
  apiKey: process.env.DEEPGRAM_API_KEY
})
import { createDeepgramAdapter, DeepgramRegion } from 'voice-router-dev'

const adapter = createDeepgramAdapter({
  apiKey: process.env.DEEPGRAM_API_KEY,
  region: DeepgramRegion.eu,
  projectId: process.env.DEEPGRAM_PROJECT_ID  // Optional, for listTranscripts
})

Interfaces

DeepgramConfig

Deepgram-specific configuration options

See

https://developers.deepgram.com/reference/custom-endpoints - Official custom endpoints documentation

Extends

Properties

apiKey

apiKey: string

API key for authentication

Inherited from

ProviderConfig.apiKey

baseUrl?

optional baseUrl: string

Base API URL (optional, uses provider default if not specified)

Inherited from

ProviderConfig.baseUrl

headers?

optional headers: Record<string, string>

Custom headers to include in requests

Inherited from

ProviderConfig.headers

options?

optional options: Record<string, unknown>

Additional provider-specific options

Inherited from

ProviderConfig.options

projectId?

optional projectId: string

Project ID for accessing request history via listTranscripts/getTranscript

region?

optional region: DeepgramRegionType

Regional endpoint for EU data residency

Available regions:

  • global - Global endpoint (default): api.deepgram.com
  • eu - European Union endpoint: api.eu.deepgram.com

The EU endpoint keeps all processing within the European Union.

For Dedicated endpoints ({SHORT_UID}.{REGION}.api.deepgram.com) or self-hosted deployments, use baseUrl instead.

See

https://developers.deepgram.com/reference/custom-endpoints

timeout?

optional timeout: number

Request timeout in milliseconds

Inherited from

ProviderConfig.timeout

On this page