@yaks/speech 0.0.0-stage → 0.2.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/openai.ts ADDED
@@ -0,0 +1,714 @@
1
+ // OpenAI: gpt-transcribe hears a recording and a call's turns,
2
+ // gpt-4o-mini-tts speaks, gpt-realtime-2.1 hears and speaks in one stream,
3
+ // answering as it goes, and gpt-live-1.1 hears and speaks at once, taking its
4
+ // own turns. Its TTS speaks 24 kHz PCM, made μ-law for a call here; the
5
+ // talking models take and speak a telephone's μ-law themselves. Prices are
6
+ // its list, 2026-11-05. Its transcription tells no speakers apart: only
7
+ // gpt-4o-transcribe-diarize does, deprecated and never on a stream.
8
+ // https://developers.openai.com/api/docs/pricing
9
+ // https://developers.openai.com/api/docs/guides/speech-to-text
10
+ // https://developers.openai.com/api/docs/guides/realtime-conversations
11
+ // https://developers.openai.com/api/reference/resources/realtime/server-events
12
+ // https://developers.openai.com/api/reference/resources/live/primary-websocket
13
+ import { listPrice, weigh } from '@yaks/model'
14
+ import {
15
+ audioForm,
16
+ type Cue,
17
+ type Provider,
18
+ type Raw,
19
+ type Said,
20
+ type Setup,
21
+ type Voice,
22
+ } from './mod.js'
23
+ import { base64, mulawed, unbase64 } from './audio.js'
24
+
25
+ // The realtime model's voices; its TTS model speaks in the same ones.
26
+ let VOICES: Voice[] = [
27
+ { id: 'cedar', name: 'Cedar', about: 'masculine, natural, calm, composed' },
28
+ { id: 'marin', name: 'Marin', about: 'feminine, natural, clear, warm' },
29
+ { id: 'alloy', name: 'Alloy', about: 'neutral, even, clear' },
30
+ { id: 'ash', name: 'Ash', about: 'masculine, soft, measured' },
31
+ { id: 'ballad', name: 'Ballad', about: 'masculine, warm, lyrical' },
32
+ { id: 'coral', name: 'Coral', about: 'feminine, warm, friendly' },
33
+ { id: 'echo', name: 'Echo', about: 'masculine, resonant, steady' },
34
+ { id: 'sage', name: 'Sage', about: 'feminine, calm, thoughtful' },
35
+ { id: 'shimmer', name: 'Shimmer', about: 'feminine, bright, energetic' },
36
+ { id: 'verse', name: 'Verse', about: 'masculine, expressive, dynamic' },
37
+ ]
38
+
39
+ // Audio on the realtime stream: a call's μ-law, or 24 kHz PCM.
40
+ let wire = (format: Raw) =>
41
+ format.encoding == 'mulaw'
42
+ ? { type: 'audio/pcmu' }
43
+ : { type: 'audio/pcm', rate: format.rate }
44
+
45
+ // What a response cost, from its input, cached input and output tokens.
46
+ type Tokens = { audio_tokens?: number; text_tokens?: number }
47
+ type Usage = {
48
+ input_token_details?: Tokens & { cached_tokens_details?: Tokens }
49
+ output_token_details?: Tokens
50
+ }
51
+ let PRICES = {
52
+ 'gpt-realtime-2.1-mini': {
53
+ audioIn: 10,
54
+ audioCached: 0.3,
55
+ audioOut: 20,
56
+ textIn: 0.6,
57
+ textCached: 0.06,
58
+ textOut: 2.4,
59
+ },
60
+ 'gpt-realtime-2.1': {
61
+ audioIn: 32,
62
+ audioCached: 0.4,
63
+ audioOut: 64,
64
+ textIn: 4,
65
+ textCached: 0.4,
66
+ textOut: 24,
67
+ },
68
+ }
69
+ let TRANSCRIBE_MINUTE = 0.017
70
+
71
+ // GPT-6 Luna is the current low-cost model. Saved Sol selections use 6.2.
72
+ let BACKENDS = ['gpt-6-luna', 'gpt-6.2-sol', 'gpt-6-sol']
73
+ export let openaiLiveBackend = (model: string) =>
74
+ model == 'gpt-6-sol' ? 'gpt-6.2-sol' : model
75
+
76
+ type Used = {
77
+ input_tokens?: number
78
+ output_tokens?: number
79
+ input_tokens_details?: {
80
+ cached_tokens?: number
81
+ cache_write_tokens?: number
82
+ }
83
+ }
84
+ let backendCost = (model: string, u: Used = {}) =>
85
+ weigh(listPrice(model) ?? listPrice('gpt-6.2-sol')!, {
86
+ input_tokens: u.input_tokens,
87
+ output_tokens: u.output_tokens,
88
+ cached_tokens: u.input_tokens_details?.cached_tokens,
89
+ cache_write_tokens: u.input_tokens_details?.cache_write_tokens,
90
+ })
91
+ let priceOf = (model: string) =>
92
+ Object.entries(PRICES).find(([name]) =>
93
+ model == name || model.startsWith(name + '-')
94
+ )?.[1]
95
+
96
+ let inputCost = (tokens = 0, hit = 0, input: number, cached: number) => {
97
+ let reused = Math.min(hit, tokens)
98
+ return (tokens - reused) * input + reused * cached
99
+ }
100
+
101
+ let costOf = (model: string, usage: Usage = {}, named = '') => {
102
+ let p = priceOf(named) ?? priceOf(model) ?? PRICES['gpt-realtime-2.1']
103
+ let i = usage.input_token_details ?? {}, o = usage.output_token_details ?? {}
104
+ let reused = i.cached_tokens_details ?? {}
105
+ return (inputCost(
106
+ i.audio_tokens,
107
+ reused.audio_tokens,
108
+ p.audioIn,
109
+ p.audioCached,
110
+ ) +
111
+ inputCost(i.text_tokens, reused.text_tokens, p.textIn, p.textCached) +
112
+ (o.audio_tokens ?? 0) * p.audioOut +
113
+ (o.text_tokens ?? 0) * p.textOut) / 1e6
114
+ }
115
+
116
+ type Event = {
117
+ type?: string
118
+ delta?: string
119
+ transcript?: string
120
+ call_id?: string
121
+ name?: string
122
+ arguments?: string
123
+ item_id?: string
124
+ item?: { id?: string; phase?: string }
125
+ response?: { usage?: Usage }
126
+ usage?: { type?: string; seconds?: number }
127
+ error?: { message?: string; code?: string }
128
+ }
129
+
130
+ let parsed = (data: unknown): Event => {
131
+ try {
132
+ return JSON.parse(String(data))
133
+ } catch {
134
+ return {}
135
+ }
136
+ }
137
+
138
+ /**
139
+ * What one message from a realtime transcription stream means.
140
+ *
141
+ * ```ts
142
+ * import { equal } from '@yaks/testing'
143
+ * import { OPENAI } from '@yaks/speech'
144
+ * let read = OPENAI.turns[0].reader()
145
+ * equal(read('{"type":"input_audio_buffer.speech_started"}'), { start: true })
146
+ * equal(
147
+ * read(JSON.stringify({
148
+ * type: 'conversation.item.input_audio_transcription.completed',
149
+ * transcript: ' Book it ',
150
+ * })),
151
+ * { ended: [{ speaker: 0, text: 'Book it' }] },
152
+ * )
153
+ * ```
154
+ */
155
+ let listening = () => {
156
+ let partials = new Map<string, string>()
157
+ return (data: unknown): Cue => {
158
+ let e = parsed(data)
159
+ let key = e.item_id ?? ''
160
+ if (e.type == 'input_audio_buffer.speech_started') return { start: true }
161
+ if (
162
+ e.type == 'conversation.item.input_audio_transcription.delta' && e.delta
163
+ ) {
164
+ let text = (partials.get(key) ?? '') + e.delta
165
+ partials.set(key, text)
166
+ return { hearing: { text, ...key ? { key } : {} } }
167
+ }
168
+ if (
169
+ e.type == 'conversation.item.input_audio_transcription.completed' ||
170
+ e.type == 'conversation.item.input_audio_transcription.failed'
171
+ ) {
172
+ partials.delete(key)
173
+ return {
174
+ ended: [{
175
+ speaker: 0,
176
+ text: e.transcript?.trim() ?? '',
177
+ ...key ? { key } : {},
178
+ }],
179
+ }
180
+ }
181
+ if (e.type == 'error') return { error: String(e.error?.message) }
182
+ return {}
183
+ }
184
+ }
185
+
186
+ // The quickest turns: a speaker's turn ends after this much silence.
187
+ let TURN = {
188
+ type: 'server_vad',
189
+ threshold: 0.5,
190
+ prefix_padding_ms: 300,
191
+ silence_duration_ms: 300,
192
+ }
193
+
194
+ export let OPENAI: Provider = {
195
+ name: 'openai',
196
+ title: 'OpenAI',
197
+ api: 'https://api.openai.com',
198
+ live: 'wss://api.openai.com',
199
+ authorization: (key) => `Bearer ${key}`,
200
+ protocols: (key) => ['realtime', `openai-insecure-api-key.${key}`],
201
+ hear: {
202
+ model: 'gpt-transcribe',
203
+ perMinute: 0.0045,
204
+ speakers: false,
205
+ // Its transcriptions' limit, a file sent in a form.
206
+ bytes: 25 * 1024 ** 2,
207
+ request: (audio, type, model) => ({
208
+ path: '/v1/audio/transcriptions',
209
+ init: audioForm({ model }, audio, type),
210
+ }),
211
+ read: (said) => {
212
+ let { text, usage } = said as {
213
+ text?: string
214
+ usage?: { seconds?: number }
215
+ }
216
+ return { text: text ?? '', seconds: usage?.seconds }
217
+ },
218
+ },
219
+ turns: [{
220
+ // gpt-live-transcribe takes no turn detection, refusing the session, so
221
+ // it cannot say when a caller's turn ends.
222
+ model: 'gpt-transcribe',
223
+ perMinute: 0.0045,
224
+ speakers: false,
225
+ path: () => '/v1/realtime?intent=transcription',
226
+ opening: (format, model) => [JSON.stringify({
227
+ type: 'session.update',
228
+ session: {
229
+ type: 'transcription',
230
+ audio: {
231
+ input: {
232
+ format: wire(format),
233
+ transcription: { model, language: 'en' },
234
+ turn_detection: TURN,
235
+ },
236
+ },
237
+ },
238
+ })],
239
+ audio: (bytes) =>
240
+ JSON.stringify({
241
+ type: 'input_audio_buffer.append',
242
+ audio: base64(bytes),
243
+ }),
244
+ reader: listening,
245
+ }],
246
+ speak: {
247
+ voice: 'cedar',
248
+ voices: [
249
+ ...VOICES,
250
+ { id: 'fable', name: 'Fable', about: 'masculine, British, expressive' },
251
+ { id: 'nova', name: 'Nova', about: 'feminine, bright, friendly' },
252
+ { id: 'onyx', name: 'Onyx', about: 'masculine, deep, authoritative' },
253
+ ],
254
+ // $12 a million audio tokens, 1,200 a minute, and about a thousand
255
+ // characters said a minute.
256
+ speeds: { min: 0.25, max: 4 },
257
+ // Deprecated, shut down 2027-01-06; its successor, gpt-realtime-2.1-mini,
258
+ // speaks only through the Realtime API, never /v1/audio/speech.
259
+ // https://developers.openai.com/api/docs/deprecations
260
+ models: [{ model: 'gpt-4o-mini-tts', perThousand: 0.015 }],
261
+ request: (text, voice, format, speed, model) => ({
262
+ path: '/v1/audio/speech',
263
+ init: {
264
+ method: 'POST',
265
+ headers: { 'content-type': 'application/json' },
266
+ body: JSON.stringify({
267
+ model,
268
+ voice,
269
+ input: text,
270
+ response_format: format.encoding == 'mp3' ? 'mp3' : 'pcm',
271
+ stream_format: 'audio',
272
+ ...speed == 1 ? {} : { speed },
273
+ }),
274
+ },
275
+ }),
276
+ // Its raw samples are 24 kHz PCM: a call's μ-law is made from them.
277
+ audio: (format) =>
278
+ format.encoding == 'mulaw' ? mulawed(24000, format.rate) : undefined,
279
+ },
280
+ talk: [{
281
+ models: ['gpt-realtime-2.1-mini', 'gpt-realtime-2.1'],
282
+ voice: 'cedar',
283
+ voices: VOICES,
284
+ speeds: { min: 0.25, max: 1.5 },
285
+ path: (model) => `/v1/realtime?model=${encodeURIComponent(model)}`,
286
+ opening: (setup) => [JSON.stringify({
287
+ type: 'session.update',
288
+ session: session(setup),
289
+ })],
290
+ audio: (bytes) =>
291
+ JSON.stringify({
292
+ type: 'input_audio_buffer.append',
293
+ audio: base64(bytes),
294
+ }),
295
+ read: (data, model) => {
296
+ let e = parsed(data)
297
+ let said: Said[] = []
298
+ switch (e.type) {
299
+ case 'input_audio_buffer.speech_started':
300
+ said.push({ start: true })
301
+ break
302
+ case 'input_audio_buffer.speech_stopped':
303
+ said.push({ stopped: true })
304
+ break
305
+ case 'conversation.item.input_audio_transcription.completed': {
306
+ said.push({ heard: e.transcript?.trim() ?? '', key: e.item_id })
307
+ let seconds = e.usage?.seconds
308
+ if (e.usage?.type == 'duration' && seconds && seconds > 0) {
309
+ said.push({ spent: seconds / 60 * TRANSCRIBE_MINUTE })
310
+ }
311
+ break
312
+ }
313
+ // Words not heard are none.
314
+ case 'conversation.item.input_audio_transcription.failed':
315
+ said.push({ heard: '', key: e.item_id })
316
+ break
317
+ case 'conversation.item.input_audio_transcription.delta':
318
+ if (e.delta) said.push({ hearing: e.delta, key: e.item_id })
319
+ break
320
+ // What a response says before its answer is an item of its own.
321
+ case 'response.output_item.added':
322
+ if (e.item?.phase == 'commentary' && e.item.id) {
323
+ said.push({ aside: e.item.id })
324
+ }
325
+ break
326
+ case 'response.output_audio.delta':
327
+ if (e.delta) said.push({ audio: unbase64(e.delta), of: e.item_id })
328
+ break
329
+ case 'response.output_audio_transcript.done':
330
+ if (e.transcript?.trim()) {
331
+ said.push({ said: e.transcript.trim(), of: e.item_id })
332
+ }
333
+ break
334
+ case 'response.function_call_arguments.done':
335
+ said.push({
336
+ call: {
337
+ id: e.call_id ?? '',
338
+ name: e.name ?? '',
339
+ args: e.arguments ?? '{}',
340
+ },
341
+ })
342
+ break
343
+ case 'output_audio_buffer.started':
344
+ said.push({ plays: true })
345
+ break
346
+ case 'response.created':
347
+ said.push({ begun: true })
348
+ break
349
+ case 'response.done': {
350
+ let usage = e.response?.usage
351
+ if (usage) said.push({ spent: costOf(model, usage, modelOf(e)) })
352
+ said.push({ done: true })
353
+ break
354
+ }
355
+ case 'error':
356
+ // A stop that came as the response finished has nothing to stop,
357
+ // and a turn ended as the model heard it end has nothing to end.
358
+ if (
359
+ e.error?.code == 'response_cancel_not_active' ||
360
+ e.error?.code == 'input_audio_buffer_commit_empty'
361
+ ) break
362
+ said.push(
363
+ e.error?.code == 'conversation_already_has_active_response'
364
+ ? { busy: true }
365
+ : { error: String(e.error?.message) },
366
+ )
367
+ }
368
+ return said
369
+ },
370
+ answer: (call, output) => [
371
+ JSON.stringify({
372
+ type: 'conversation.item.create',
373
+ item: { type: 'function_call_output', call_id: call, output },
374
+ }),
375
+ ],
376
+ // Asked to say a message with its tools at hand, it sometimes asked to
377
+ // listen instead and said nothing.
378
+ respond: ({ text, tools, call, instructions } = {}) =>
379
+ JSON.stringify({
380
+ type: 'response.create',
381
+ ...text == undefined && !tools ? {} : {
382
+ response: {
383
+ ...instructions && { instructions },
384
+ ...text == undefined ? {} : {
385
+ instructions:
386
+ `Say only the message below, without reading its source label aloud:\n${text}`,
387
+ tool_choice: 'none',
388
+ },
389
+ ...tools &&
390
+ { tools: tools.map((t) => ({ type: 'function', ...t })) },
391
+ ...call && { tool_choice: 'required' },
392
+ },
393
+ },
394
+ }),
395
+ cancel: JSON.stringify({ type: 'response.cancel' }),
396
+ tell: (text) => [
397
+ JSON.stringify({
398
+ type: 'conversation.item.create',
399
+ item: {
400
+ type: 'message',
401
+ role: 'system',
402
+ content: [{ type: 'input_text', text }],
403
+ },
404
+ }),
405
+ ],
406
+ commit: JSON.stringify({ type: 'input_audio_buffer.commit' }),
407
+ // A call sent to the project over SIP rings its webhook; once accepted
408
+ // with the session, a stream joins it by its id. The line plays the
409
+ // model's audio, and is told to stop.
410
+ // https://developers.openai.com/api/docs/guides/voice-sip
411
+ calls: {
412
+ rang: (event) => {
413
+ let e = event as {
414
+ type?: string
415
+ data?: {
416
+ call_id?: string
417
+ sip_headers?: { name?: string; value?: string }[]
418
+ }
419
+ }
420
+ if (e?.type != 'realtime.call.incoming' || !e.data?.call_id) return
421
+ return {
422
+ id: e.data.call_id,
423
+ headers: Object.fromEntries(
424
+ (e.data.sip_headers ?? []).map((h) => [
425
+ String(h.name).toLowerCase(),
426
+ String(h.value ?? ''),
427
+ ]),
428
+ ),
429
+ }
430
+ },
431
+ accept: (call, setup) =>
432
+ posted(
433
+ `/v1/realtime/calls/${encodeURIComponent(call)}/accept`,
434
+ session(setup),
435
+ ),
436
+ reject: (call) =>
437
+ posted(`/v1/realtime/calls/${encodeURIComponent(call)}/reject`, {
438
+ status_code: 486,
439
+ }),
440
+ hangup: (call) =>
441
+ posted(`/v1/realtime/calls/${encodeURIComponent(call)}/hangup`),
442
+ join: (call) => `/v1/realtime?call_id=${encodeURIComponent(call)}`,
443
+ hush: JSON.stringify({ type: 'output_audio_buffer.clear' }),
444
+ },
445
+ }, {
446
+ // GPT-Live: hears and speaks at once and takes its own turns, and hands
447
+ // what needs tools to the client, whoever runs the call (`delegated`),
448
+ // whose answer it says in its own words. It has no speeds.
449
+ models: ['gpt-live-1.1', 'gpt-live-1'],
450
+ duplex: true,
451
+ perMinute: 0.05,
452
+ voice: 'cedar',
453
+ voices: VOICES,
454
+ speeds: { min: 1, max: 1 },
455
+ path: () => '/v1/live/sessions',
456
+ opening: (setup) => [JSON.stringify({
457
+ type: 'session.start',
458
+ session: {
459
+ model: setup.model,
460
+ instructions: setup.instructions,
461
+ // Its first words are asked for from the start, and again once the
462
+ // session started (`opens`), as OpenAI has a greeting asked for.
463
+ // https://developers.openai.com/api/docs/guides/live-conversations#greet-before-the-caller-speaks
464
+ ...setup.opens
465
+ ? {
466
+ input: [{
467
+ type: 'message',
468
+ role: 'developer',
469
+ content: [{ type: 'input_text', text: greet(setup.opens) }],
470
+ }],
471
+ }
472
+ : {},
473
+ audio: {
474
+ ...setup.format ? { format: wired(setup.format) } : {},
475
+ output: { voice: setup.voice },
476
+ },
477
+ delegation: setup.backend
478
+ ? {
479
+ type: 'responses',
480
+ responses: {
481
+ model: openaiLiveBackend(setup.backend.model),
482
+ instructions: setup.backend.instructions,
483
+ tools: [
484
+ ...setup.backend.tools.map((t) => ({
485
+ type: 'function',
486
+ ...t,
487
+ strict: false,
488
+ })),
489
+ ...setup.backend.webSearch == false
490
+ ? []
491
+ : [{ type: 'web_search' }],
492
+ ],
493
+ tool_choice: 'auto',
494
+ // One call at a time, each answered before the next.
495
+ parallel_tool_calls: false,
496
+ reasoning: { effort: 'low' },
497
+ },
498
+ }
499
+ : { type: 'client' },
500
+ },
501
+ })],
502
+ audio: (bytes) =>
503
+ JSON.stringify({
504
+ type: 'session.input_audio.append',
505
+ audio: base64(bytes),
506
+ }),
507
+ read: (data, _, backend) => {
508
+ let e = parsed(data) as Event & {
509
+ delegation?: { id?: string; target?: string }
510
+ event?: {
511
+ type?: string
512
+ item?: {
513
+ type?: string
514
+ call_id?: string
515
+ name?: string
516
+ arguments?: string
517
+ }
518
+ response?: { model?: string; usage?: Used }
519
+ }
520
+ }
521
+ switch (e.type) {
522
+ case 'session.started':
523
+ return [{ ready: true }]
524
+ case 'session.input_transcript.delta':
525
+ return e.delta ? [{ hearing: e.delta }] : []
526
+ case 'session.output_transcript.delta':
527
+ return e.delta ? [{ saying: e.delta }] : []
528
+ case 'session.output_audio.delta':
529
+ return e.delta ? [{ audio: unbase64(e.delta) }] : []
530
+ // Work its backend does is no one's here but its tools'.
531
+ case 'session.delegation.created':
532
+ return e.delegation?.id && e.delegation.target != 'responses'
533
+ ? [{ delegated: e.delegation.id }]
534
+ : []
535
+ // What the backend does, each of its events wrapped in one of these.
536
+ case 'response.event': {
537
+ let n = e.event ?? {}
538
+ if (
539
+ n.type == 'response.output_item.done' &&
540
+ n.item?.type == 'function_call'
541
+ ) {
542
+ return [{
543
+ call: {
544
+ id: n.item.call_id ?? '',
545
+ name: n.item.name ?? '',
546
+ args: n.item.arguments ?? '{}',
547
+ },
548
+ }]
549
+ }
550
+ if (n.type == 'response.completed' && backend) {
551
+ return [{
552
+ spent: backendCost(
553
+ n.response?.model ?? openaiLiveBackend(backend),
554
+ n.response?.usage,
555
+ ),
556
+ }]
557
+ }
558
+ return []
559
+ }
560
+ case 'error':
561
+ return [{ error: String(e.error?.message) }]
562
+ }
563
+ return []
564
+ },
565
+ // What it is asked to say, and a delegation's answer, it says in its
566
+ // own words, as they come. Instructions appended stand for the rest of
567
+ // the session, so asking it that way to say a line now has it say the
568
+ // line again later, and only that.
569
+ answer: (id, output) => appended('commentary', output, id),
570
+ backends: BACKENDS,
571
+ result: (call, output) => [
572
+ JSON.stringify({
573
+ type: 'response.item.create',
574
+ item: { type: 'function_call_output', call_id: call, output },
575
+ }),
576
+ JSON.stringify({ type: 'response.create' }),
577
+ ],
578
+ say: (text) => appended('commentary', text),
579
+ opens: (text) => appended('commentary', greet(text)),
580
+ tell: (text) => appended('thinking', text),
581
+ }],
582
+ }
583
+
584
+ // What GPT-Live is asked for as its stream opens.
585
+ let greet = (text: string) =>
586
+ `Say exactly this to the caller now, word for word: "${text}" Then pause and listen.`
587
+
588
+ let posted = (path: string, body?: object) => ({
589
+ path,
590
+ init: {
591
+ method: 'POST',
592
+ ...body
593
+ ? {
594
+ headers: { 'content-type': 'application/json' },
595
+ body: JSON.stringify(body),
596
+ }
597
+ : {},
598
+ },
599
+ })
600
+
601
+ // A realtime session as a stream is set up with, or a call accepted with,
602
+ // which says its own audio format.
603
+ let session = (setup: Setup) => ({
604
+ type: 'realtime',
605
+ model: setup.model,
606
+ instructions: setup.instructions,
607
+ output_modalities: ['audio'],
608
+ // The least thought before the first word.
609
+ reasoning: { effort: 'minimal' },
610
+ audio: {
611
+ input: {
612
+ ...setup.format ? { format: wire(setup.format) } : {},
613
+ // The names it is called by, which a transcript would mishear.
614
+ transcription: {
615
+ model: 'gpt-live-transcribe',
616
+ language: 'en',
617
+ ...setup.words?.length && { prompt: setup.words.join(', ') },
618
+ },
619
+ // A phone held to the ear. The model says when the caller is done, in
620
+ // about a second when it is sure; unsure, it waits up to 4 s at medium
621
+ // eagerness, and mod.ts `talk` ends the turn sooner and answers it.
622
+ // High eagerness ends a turn at a thinking pause.
623
+ noise_reduction: { type: 'near_field' },
624
+ turn_detection: {
625
+ type: 'semantic_vad',
626
+ eagerness: 'medium',
627
+ create_response: false,
628
+ // The caller talking stops the model only once their words say
629
+ // something (mod.ts `talk`), not at the first sound.
630
+ interrupt_response: false,
631
+ },
632
+ },
633
+ output: {
634
+ ...setup.format ? { format: wire(setup.format) } : {},
635
+ voice: setup.voice,
636
+ ...setup.speed == 1 ? {} : { speed: setup.speed },
637
+ },
638
+ },
639
+ tools: setup.tools.map((t) => ({ type: 'function', ...t })),
640
+ tool_choice: 'auto',
641
+ })
642
+
643
+ // GPT-Live's audio: a call's μ-law, or 16-bit PCM at 16 or 24 kHz.
644
+ let wired = (format: Raw) =>
645
+ format.encoding == 'mulaw'
646
+ ? { type: 'audio/pcmu', rate: 8000 }
647
+ : { type: 'audio/pcm', rate: format.rate }
648
+
649
+ // The most GPT-Live takes in one append is 500 tokens, and a token is at
650
+ // least a byte, so a part of at most this many UTF-8 bytes always fits.
651
+ let APPENDED = 500
652
+
653
+ /**
654
+ * `text` appended to what GPT-Live knows, as `kind` (`instructions` it
655
+ * follows, `thinking` it knows without saying, `commentary` it says), about a
656
+ * delegation or the whole session, in parts each of at most `APPENDED`
657
+ * UTF-8 bytes, split between paragraphs, else lines, else words.
658
+ *
659
+ * ```ts
660
+ * import { equal } from '@yaks/testing'
661
+ * import { OPENAI } from '@yaks/speech'
662
+ * let live = OPENAI.talk!.find((t) => t.duplex)!
663
+ * equal(live.tell('A.').map((m) => JSON.parse(m)), [{
664
+ * type: 'session.thinking.append',
665
+ * delegation_id: null,
666
+ * content: 'A.',
667
+ * }])
668
+ * let long = ['a'.repeat(400), 'b'.repeat(400)].join('\n\n')
669
+ * equal(live.tell(long).map((m) => JSON.parse(m).content.length), [400, 400])
670
+ * let wide = '界'.repeat(400)
671
+ * equal(live.tell(wide).map((m) => JSON.parse(m).content.length), [166, 166, 68])
672
+ * ```
673
+ */
674
+ let appended = (kind: string, text: string, id: string | null = null) =>
675
+ parts(text, APPENDED).map((content) =>
676
+ JSON.stringify({
677
+ type: `session.${kind}.append`,
678
+ delegation_id: id,
679
+ content,
680
+ })
681
+ )
682
+
683
+ let utf8 = new TextEncoder()
684
+
685
+ // `text` in parts of at most `most` UTF-8 bytes, split at the widest break
686
+ // that fits.
687
+ let parts = (text: string, most: number): string[] => {
688
+ let fit = fitting(text, most)
689
+ if (fit == text.length) return [text]
690
+ for (let gap of ['\n\n', '\n', ' ']) {
691
+ let at = text.lastIndexOf(gap, fit)
692
+ if (at > 0) {
693
+ return [text.slice(0, at), ...parts(text.slice(at + gap.length), most)]
694
+ }
695
+ }
696
+ return [text.slice(0, fit), ...parts(text.slice(fit), most)]
697
+ }
698
+
699
+ // How many of `text`'s UTF-16 units fit in `most` UTF-8 bytes, never
700
+ // splitting a character.
701
+ let fitting = (text: string, most: number) => {
702
+ let bytes = 0, at = 0
703
+ for (let c of text) {
704
+ bytes += utf8.encode(c).length
705
+ if (bytes > most) break
706
+ at += c.length
707
+ }
708
+ return at
709
+ }
710
+
711
+ // The model a `response.done` was answered by, where it says: it reports
712
+ // none, so the session's own model prices it.
713
+ let modelOf = (e: Event) =>
714
+ String((e.response as { model?: string } | undefined)?.model ?? '')