The open-source AI receptionist for businesses. Answers every call, books the appointment and hands over to a person when needed. You own the code and the data.
TypeScript ai-receptionistanswering-serviceappointment-bookinglivekitlocal-firstmcpopen-sourceself-hostedsiptelephonytypescriptvoice-agentvoice-ai
// One pace for every voice (Tim, 2026-11-28). ElevenLabs voices speak at very different paces at the same speed: the
// same German sentence took 6.3 s with Susi and 11.4 s with "Mia Swiss" (Voice Library). The talking speed an owner
// sets (80-120 %) was relative to each voice's own pace, so 110 % of a slow voice stayed slow. Now 100 % is the pace
// of the language's default voice (languageDefaultVoices; Jessica for English) for every voice: each voice's pace is
// measured once (a short sample with ElevenLabs' character timings, at speed 1), kept on disk next to the stored
// greetings, and the speed sent to ElevenLabs is the owner's percentage times reference pace / voice pace, within
// ElevenLabs' range (0.7-1.2). A voice not measured yet keeps the owner's percentage as before.
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { defaultVoiceFor, type Language, providerLanguageCode } from '@linedesk/actions'
import { GREETING_CACHE_DIR } from './greeting-cache.ts'
/** ElevenLabs' speed range (voice_settings.speed), in percent. */
export const PACE_SPEED_MIN_PCT = 70
export const PACE_SPEED_MAX_PCT = 120
/** How long a call waits for a voice's first measurement before it starts without it. */
export const PACE_WAIT_MS = 1500
/** The sentence a pace is measured with: about 110 characters, a typical reply. English for languages without one. */
const SAMPLES: Partial<Record<Language, string>> & { en: string } = {
en: "Hello, this is Maya. I'm calling to confirm your appointment on Monday at nine. Does that still work for you?",
de: 'Guten Tag, hier ist Maya. Ich rufe an, um Ihren Termin am Montag um neun Uhr zu bestätigen. Passt Ihnen das noch?',
fr: 'Bonjour, ici Maya. Je vous appelle pour confirmer votre rendez-vous lundi à neuf heures. Est-ce que cela vous convient toujours ?',
es: 'Hola, soy Maya. Le llamo para confirmar su cita del lunes a las nueve. ¿Le sigue viniendo bien?',
}
type Pace = { cps: number; at: string }
const FILE = join(GREETING_CACHE_DIR, 'voice-paces.json')
let paces: Record<string, Pace> | null = null
const pending = new Map<string, Promise<number | null>>()
const keyOf = (voiceId: string, language: Language) => `elevenlabs|${voiceId}|${language}`
function load(): Record<string, Pace> {
if (paces) return paces
try {
paces = JSON.parse(readFileSync(FILE, 'utf8')) as Record<string, Pace>
} catch {
paces = {}
}
return paces
}
function save() {
try {
mkdirSync(dirname(FILE), { recursive: true })
writeFileSync(FILE, JSON.stringify(load()))
} catch (e) {
console.warn(`voice paces not stored: ${e instanceof Error ? e.message : String(e)}`)
}
}
/** The measured pace (characters a second at speed 1) of a voice in a language, or undefined. */
export const knownPace = (voiceId: string | undefined, language: Language): number | undefined =>
voiceId ? load()[keyOf(voiceId, language)]?.cps : undefined
/** Characters a second of one sample, from ElevenLabs' character timings (start of the first to end of the last). */
export async function measurePace(
{ apiKey, voiceId, model, language }: { apiKey: string; voiceId: string; model?: string; language: Language },
doFetch: typeof fetch = fetch,
): Promise<number | null> {
const text = SAMPLES[language] ?? SAMPLES.en
const res = await doFetch(
`https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(voiceId)}/with-timestamps`,
{
method: 'POST',
headers: { 'xi-api-key': apiKey, 'content-type': 'application/json' },
body: JSON.stringify({
text,
...(model ? { model_id: model } : {}),
...(language !== 'en' && SAMPLES[language]
? { language_code: providerLanguageCode(language, 'elevenlabs') }
: {}),
voice_settings: { speed: 1 },
}),
signal: AbortSignal.timeout(10_000),
},
)
if (!res.ok) return null
const body = (await res.json()) as {
alignment?: {
characters?: string[]
character_start_times_seconds?: number[]
character_end_times_seconds?: number[]
}
}
return paceOfAlignment(body.alignment)
}
/** Characters a second of an alignment; null when it is too short to tell. */
export function paceOfAlignment(
a:
| { characters?: string[]; character_start_times_seconds?: number[]; character_end_times_seconds?: number[] }
| undefined,
): number | null {
const chars = a?.characters?.length ?? 0
const start = a?.character_start_times_seconds?.[0]
const end = a?.character_end_times_seconds?.at(-1)
if (chars < 20 || start === undefined || end === undefined || end - start < 1) return null
return chars / (end - start)
}
/** Measures a voice once (and keeps it); its pace, or null when it could not be measured. */
export function ensurePace(args: {
apiKey: string
voiceId: string
model?: string
language: Language
}): Promise<number | null> {
const key = keyOf(args.voiceId, args.language)
const known = load()[key]
if (known) return Promise.resolve(known.cps)
const running = pending.get(key)
if (running) return running
const measuring = measurePace(args)
.then(cps => {
if (cps) {
load()[key] = { cps, at: new Date().toISOString() }
save()
}
return cps
})
.catch(e => {
console.warn(`voice pace of ${args.voiceId} not measured: ${e instanceof Error ? e.message : String(e)}`)
return null
})
.finally(() => pending.delete(key))
pending.set(key, measuring)
return measuring
}
/** Measures the voice and its language's reference voice (the default one), for one call or the greeting prewarm. */
export function ensurePaces(args: { apiKey: string; voiceId?: string; model?: string; language: Language }) {
const reference = defaultVoiceFor('elevenlabs', args.language)
const ids = [...new Set([args.voiceId, reference].filter((id): id is string => !!id))]
return Promise.all(ids.map(voiceId => ensurePace({ ...args, voiceId })))
}
/**
* The speed to send for `speedPct` so the voice speaks at that percentage of the reference pace: unchanged until both
* paces are known, within ElevenLabs' range, rounded to whole percent.
*/
export function uniformSpeedPct(
speedPct: number,
voicePace: number | undefined,
referencePace: number | undefined,
): number {
if (!voicePace || !referencePace) return speedPct
const pct = Math.round((speedPct * referencePace) / voicePace)
return Math.min(PACE_SPEED_MAX_PCT, Math.max(PACE_SPEED_MIN_PCT, pct))
}
/** The corrected speed of an ElevenLabs voice in a language (uniformSpeedPct with the kept paces). */
export const paceCorrectedPct = (speedPct: number, voiceId: string | undefined, language: Language): number =>
uniformSpeedPct(speedPct, knownPace(voiceId, language), knownPace(defaultVoiceFor('elevenlabs', language), language))