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()
privatebuildStreamingUrl(options?):string
Build WebSocket URL with all streaming parameters
Parameters
| Parameter | Type |
|---|---|
options? | StreamingOptions |
Returns
string
buildTranscriptionParams()
privatebuildTranscriptionParams(options?):ListenV1MediaTranscribeParams
Build Deepgram transcription parameters from unified options
Parameters
| Parameter | Type |
|---|---|
options? | TranscribeOptions |
Returns
ListenV1MediaTranscribeParams
createErrorResponse()
protectedcreateErrorResponse(error,statusCode?,code?):UnifiedTranscriptResponse
Helper method to create error responses with stack traces
Parameters
| Parameter | Type | Description |
|---|---|---|
error | unknown | Error object or unknown error |
statusCode? | number | Optional HTTP status code |
code? | ErrorCode | Optional error code (defaults to extracted or UNKNOWN_ERROR) |
Returns
Inherited from
BaseAdapter.createErrorResponse
extractSpeakers()
privateextractSpeakers(response):object[] |undefined
Extract speaker information from Deepgram response
Parameters
| Parameter | Type |
|---|---|
response | ListenV1Response |
Returns
object[] | undefined
extractSummary()
privateextractSummary(alternative):string|undefined
Extract summary from Deepgram response
Parameters
| Parameter | Type |
|---|---|
alternative | ListenV1ResponseResultsChannelsItemAlternativesItem |
Returns
string | undefined
extractUtterances()
privateextractUtterances(response):object[] |undefined
Extract utterances from Deepgram response
Parameters
| Parameter | Type |
|---|---|
response | ListenV1Response |
Returns
object[] | undefined
extractWords()
privateextractWords(alternative):object[] |undefined
Extract word timestamps from Deepgram response
Parameters
| Parameter | Type |
|---|---|
alternative | ListenV1ResponseResultsChannelsItemAlternativesItem |
Returns
object[] | undefined
getAxiosConfig()
protectedgetAxiosConfig(authHeaderName,authHeaderValue?):object
Build axios config for generated API client functions
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
authHeaderName | string | "Authorization" | Header name for API key (e.g., "Authorization", "x-gladia-key") |
authHeaderValue? | (apiKey) => string | undefined | Optional 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
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()
privategetRegionalHost(region?):string
Get API host based on region
Parameters
| Parameter | Type | Description |
|---|---|---|
region? | DeepgramRegionType | Regional 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
| Parameter | Type | Description |
|---|---|---|
transcriptId | string | Request 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
handleWebSocketMessage()
privatehandleWebSocketMessage(message,callbacks?):void
Handle all WebSocket message types from Deepgram streaming
Parameters
| Parameter | Type |
|---|---|
message | DeepgramRealtimeMessage |
callbacks? | StreamingCallbacks |
Returns
void
initialize()
initialize(
config):void
Initialize the adapter with configuration
Parameters
| Parameter | Type |
|---|---|
config | DeepgramConfig |
Returns
void
Overrides
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
| Parameter | Type | Description |
|---|---|---|
options? | ListTranscriptsOptions | Filtering 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()
privatenormalizeRequestItem(item):UnifiedTranscriptResponse
Normalize a Deepgram request history item to unified format
Parameters
| Parameter | Type |
|---|---|
item | ProjectRequestResponse |
Returns
normalizeResponse()
privatenormalizeResponse(response):UnifiedTranscriptResponse<"deepgram">
Normalize Deepgram response to unified format
Parameters
| Parameter | Type |
|---|---|
response | ListenV1Response |
Returns
UnifiedTranscriptResponse<"deepgram">
pollForCompletion()
protectedpollForCompletion(transcriptId,options?):Promise<UnifiedTranscriptResponse<TranscriptionProvider>>
Generic polling helper for async transcription jobs
Polls getTranscript() until job completes or times out.
Parameters
| Parameter | Type | Description |
|---|---|---|
transcriptId | string | Job/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
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
| Parameter | Type | Description |
|---|---|---|
region | DeepgramRegionType | New 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
| Parameter | Type | Description |
|---|---|---|
audio | AudioInput | Audio input (URL or file buffer) |
options? | TranscribeOptions | Transcription 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
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
| Parameter | Type | Description |
|---|---|---|
options? | StreamingOptions | Streaming configuration options |
callbacks? | StreamingCallbacks | Event 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()
protectedvalidateConfig():void
Helper method to validate configuration
Returns
void
Inherited from
Constructors
Constructor
new DeepgramAdapter():
DeepgramAdapter
Returns
Inherited from
Properties
baseUrl
protectedbaseUrl:string="https://api.deepgram.com/v1"
Base URL for provider API (must be defined by subclass)
Overrides
capabilities
readonlycapabilities:ProviderCapabilities
Provider capabilities
Overrides
name
readonlyname:"deepgram"
Provider name
Overrides
wsBaseUrl
privatewsBaseUrl:string="wss://api.deepgram.com/v1/listen"
client?
privateoptionalclient:AxiosInstance
config?
protectedoptionalconfig:ProviderConfig
Inherited from
projectId?
privateoptionalprojectId:string
Functions
createDeepgramAdapter()
createDeepgramAdapter(
config):DeepgramAdapter
Factory function to create a Deepgram adapter
Parameters
| Parameter | Type |
|---|---|
config | DeepgramConfig |
Returns
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
baseUrl?
optionalbaseUrl:string
Base API URL (optional, uses provider default if not specified)
Inherited from
headers?
optionalheaders:Record<string,string>
Custom headers to include in requests
Inherited from
options?
optionaloptions:Record<string,unknown>
Additional provider-specific options
Inherited from
projectId?
optionalprojectId:string
Project ID for accessing request history via listTranscripts/getTranscript
region?
optionalregion:DeepgramRegionType
Regional endpoint for EU data residency
Available regions:
global- Global endpoint (default): api.deepgram.comeu- 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?
optionaltimeout:number
Request timeout in milliseconds