openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
213 lines (212 loc) • 8.15 kB
JavaScript
import { normalizeResolvedSecretInputString } from "openclaw/plugin-sdk/secret-input";
import { asOptionalRecord, normalizeOptionalString, parseBooleanValue, parseFiniteNumber } from "openclaw/plugin-sdk/string-coerce-runtime";
//#region extensions/deepgram/audio.ts
const DEFAULT_DEEPGRAM_AUDIO_BASE_URL = "https://api.deepgram.com/v1";
const DEFAULT_DEEPGRAM_AUDIO_MODEL = "nova-3";
//#endregion
//#region extensions/deepgram/realtime-transcription-provider-factory.ts
const DEEPGRAM_REALTIME_DEFAULT_SAMPLE_RATE = 8e3;
const DEEPGRAM_REALTIME_DEFAULT_ENCODING = "mulaw";
const DEEPGRAM_REALTIME_DEFAULT_ENDPOINTING_MS = 800;
const DEEPGRAM_REALTIME_CLOSE_TIMEOUT_MS = 5e3;
const DEEPGRAM_REALTIME_MAX_RETAINED_TRANSCRIPT_BYTES = 262144;
const DEEPGRAM_REALTIME_FINALIZE_FALLBACK_MS = 4900;
function readNestedDeepgramConfig(e) {
const t = asOptionalRecord(e);
const n = asOptionalRecord(t?.providers);
return asOptionalRecord(n?.deepgram ?? t?.deepgram ?? t) ?? {};
}
function normalizeDeepgramEncoding(e) {
const t = normalizeOptionalString(e)?.toLowerCase();
if (!t) return;
if (t === "pcm" || t === "pcm_s16le" || t === "linear16") return "linear16";
if (t === "ulaw" || t === "g711_ulaw" || t === "g711-mulaw") return "mulaw";
if (t === "g711_alaw" || t === "g711-alaw") return "alaw";
if (t === "mulaw" || t === "alaw") return t;
throw new Error(`Invalid Deepgram realtime transcription encoding: ${t}`);
}
function normalizeDeepgramRealtimeBaseUrl(e) {
const t = normalizeOptionalString(e ?? process.env.DEEPGRAM_BASE_URL);
if (!t) return DEFAULT_DEEPGRAM_AUDIO_BASE_URL;
const n = URL.parse(t);
if (!n) throw new Error("Invalid Deepgram baseUrl: value is not a valid URL");
const { protocol: r } = n;
if (r !== "http:" && r !== "https:" && r !== "ws:" && r !== "wss:") throw new Error(`Invalid Deepgram baseUrl: unsupported scheme "${r}" (expected http, https, ws, or wss)`);
return t;
}
function normalizeProviderConfig(e) {
const t = readNestedDeepgramConfig(e);
return {
apiKey: normalizeResolvedSecretInputString({
value: t.apiKey,
path: "plugins.entries.voice-call.config.streaming.providers.deepgram.apiKey"
}),
baseUrl: normalizeOptionalString(t.baseUrl),
model: normalizeOptionalString(t.model ?? t.sttModel),
language: normalizeOptionalString(t.language),
sampleRate: parseFiniteNumber(t.sampleRate ?? t.sample_rate),
encoding: normalizeDeepgramEncoding(t.encoding),
interimResults: parseBooleanValue(t.interimResults ?? t.interim_results),
endpointingMs: parseFiniteNumber(t.endpointingMs ?? t.endpointing ?? t.silenceDurationMs)
};
}
function readErrorDetail(e) {
if (typeof e === "string") return e;
const t = asOptionalRecord(e);
const n = normalizeOptionalString(t?.message);
const r = normalizeOptionalString(t?.code);
return n ?? r ?? "Deepgram realtime transcription error";
}
function buildDeepgramRealtimeTranscriptionProvider({ createRealtimeTranscriptionWebSocketSession: e, isProviderAuthProfileConfiguredAsync: t, resolveProviderAuthProfileApiKey: n }) {
const isConfigured = ({ providerConfig: e }) => Boolean(normalizeProviderConfig(e).apiKey || process.env.DEEPGRAM_API_KEY);
return {
id: "deepgram",
label: "Deepgram Realtime Transcription",
aliases: ["deepgram-realtime", "nova-3-streaming"],
defaultModel: DEFAULT_DEEPGRAM_AUDIO_MODEL,
autoSelectOrder: 35,
resolveConfig: ({ rawConfig: e }) => normalizeProviderConfig(e),
isConfigured,
isConfiguredAsync: async (e) => isConfigured(e) || e.selectedExplicitly === true && await t({
provider: "deepgram",
cfg: e.cfg,
profileTypes: ["api_key"]
}),
createSession: (t) => {
const r = normalizeProviderConfig(t.providerConfig);
const i = r.apiKey || process.env.DEEPGRAM_API_KEY;
const a = {
...t,
baseUrl: normalizeDeepgramRealtimeBaseUrl(r.baseUrl),
model: r.model ?? "nova-3",
sampleRate: r.sampleRate ?? DEEPGRAM_REALTIME_DEFAULT_SAMPLE_RATE,
encoding: r.encoding ?? DEEPGRAM_REALTIME_DEFAULT_ENCODING,
interimResults: r.interimResults ?? true,
endpointingMs: r.endpointingMs ?? DEEPGRAM_REALTIME_DEFAULT_ENDPOINTING_MS,
language: r.language
};
let o = false;
let s = "";
let c = false;
let l;
let u = false;
const joinTranscript = (e, t) => (e && t ? `${e} ${t}` : e || t).replace(/\s+/g, " ").trim();
const clearTurn = () => {
clearTimeout(l);
l = void 0;
s = "";
o = false;
};
const updateTurn = (e, t, n) => {
if (Buffer.byteLength(e, "utf8") + Buffer.byteLength(t, "utf8") > DEEPGRAM_REALTIME_MAX_RETAINED_TRANSCRIPT_BYTES) {
clearTurn();
a.onError?.(/* @__PURE__ */ new Error(`Deepgram realtime retained transcript exceeded ${DEEPGRAM_REALTIME_MAX_RETAINED_TRANSCRIPT_BYTES} bytes`));
n.closeNow();
return false;
}
s = e;
return true;
};
const flushTurn = () => {
const e = s;
clearTurn();
if (e) a.onTranscript?.(e);
};
const handleEvent = (e, t) => {
switch (e.type) {
case "Results": {
if (c) return;
const n = normalizeOptionalString(e.channel?.alternatives?.[0]?.transcript);
if (n && !o) {
o = true;
a.onSpeechStart?.();
}
if (e.speech_final || e.from_finalize) {
const e = n ? joinTranscript(s, n) : s;
if (!updateTurn(e, "", t)) return;
flushTurn();
return;
}
if (!n) return;
const r = e.is_final ? joinTranscript(s, n) : s;
if (!updateTurn(r, e.is_final ? "" : n, t)) return;
a.onPartial?.(e.is_final ? r : joinTranscript(r, n));
return;
}
case "UtteranceEnd":
if ((e.last_word_end ?? -1) >= 0 && !c) flushTurn();
return;
case "SpeechStarted":
o = true;
a.onSpeechStart?.();
return;
case "Error":
case "error": a.onError?.(new Error(readErrorDetail(e.error ?? e.message)));
}
};
return e({
providerId: "deepgram",
callbacks: a,
url: () => {
const e = new URL(a.baseUrl);
if (e.protocol === "http:") e.protocol = "ws:";
else if (e.protocol === "https:") e.protocol = "wss:";
e.pathname = `${e.pathname.replace(/\/+$/, "")}/listen`;
e.searchParams.set("model", a.model);
e.searchParams.set("encoding", a.encoding);
e.searchParams.set("sample_rate", String(a.sampleRate));
e.searchParams.set("channels", "1");
e.searchParams.set("interim_results", String(a.interimResults));
e.searchParams.set("endpointing", String(a.endpointingMs));
if (a.interimResults && a.endpointingMs <= 5e3) e.searchParams.set("utterance_end_ms", String(Math.max(1e3, Math.ceil(a.endpointingMs))));
if (a.language) e.searchParams.set("language", a.language);
return e.toString();
},
headers: async () => {
const e = i || await n({
provider: "deepgram",
cfg: t.cfg,
profileTypes: ["api_key"]
});
if (!e) throw new Error("Deepgram API key missing");
return { Authorization: `Token ${e}` };
},
readyOnOpen: true,
closeTimeoutMs: DEEPGRAM_REALTIME_CLOSE_TIMEOUT_MS,
connectTimeoutMessage: "Deepgram realtime transcription connection timeout",
connectClosedBeforeReadyMessage: "Deepgram realtime transcription connection closed before ready",
reconnectLimitMessage: "Deepgram realtime transcription reconnect limit reached",
onOpen: () => {
if (u) flushTurn();
else {
u = true;
clearTurn();
}
c = false;
},
sendAudio: (e, t) => {
t.sendBinary(e);
},
onClose: (e) => {
if (s) l = setTimeout(() => {
c = true;
try {
flushTurn();
} catch (e) {
try {
a.onError?.(e instanceof Error ? e : new Error(String(e)));
} catch {}
}
}, DEEPGRAM_REALTIME_FINALIZE_FALLBACK_MS);
e.sendJson({ type: "Finalize" });
},
onMessage: handleEvent
});
}
};
}
//#endregion
//#region extensions/deepgram/capability-catalog.ts
var capability_catalog_default = ((e) => ({ realtimeTranscriptionProviders: [buildDeepgramRealtimeTranscriptionProvider(e)] }));
//#endregion
export { capability_catalog_default as default };