On this page

Write a provider

Adapt any speech service to the VoiceAI SDK session API with defineProvider, and test it with the conformance suite.

A provider is a factory that returns an object describing what it can do and how to do it. The SDK handles sessions, keys, events, await using, and errors; your adapter only talks to the service.

The shape of a provider

TypeScript
import { defineProvider } from "voiceai-sdk/provider";

export const acme = defineProvider((options: { apiKey?: string } = {}) => ({
  name: "acme",
  capabilities: { streamingStt: true, streamingTts: false, speechToSpeech: false, wordTimings: true, diarization: false, interruptions: false, voices: false },
  async transcribe(audio, ctx) {
    const res = await fetch("https://api.acme.example/v1/transcribe", {
      method: "POST",
      headers: { authorization: `Bearer ${options.apiKey ?? process.env.ACME_API_KEY}` },
      body: audio,
      signal: ctx.signal,
    });
    const body = await res.json();
    return { ok: body.text.length > 0, text: body.text, words: body.words, language: body.language, durationMs: body.duration_ms };
  },
}));

Methods you can implement

MethodNeeded for
transcribe(audio, ctx)session.transcribe
listen(stream, ctx)session.listen and converse
speak(text, ctx)session.speak and say
listVoices()listVoices
close()Releasing sockets when the session closes

Leave out the methods the service can't do. Calling them on a session fails with unsupported.

Map errors

Throw VoiceError with the closest code, so callers can handle every provider the same way.

TypeScript
import { VoiceError } from "voiceai-sdk";

if (res.status === 401) throw new VoiceError("auth", { provider: "acme" });
if (res.status === 429) throw new VoiceError("rate_limited", { provider: "acme" });

Run the conformance suite

The suite runs the same checks the built-in adapters pass, against your factory.

TypeScript
import { conformance } from "voiceai-sdk/provider/testing";
import { acme } from "./acme";

conformance(acme(), { audio: "./fixtures" });

Next steps

Esc

Loading…

↑↓ navigate openCtrl J preview