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