@livekit/agents-plugin-openai 1.9.4 → 1.10.0

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.
@@ -7,6 +7,9 @@ import type OpenAI from 'openai';
7
7
  import { OpenAITool } from '../tools.js';
8
8
 
9
9
  export {
10
+ type DecisionEventEnvelope,
11
+ type DecisionsOptions,
12
+ type DecisionsTrigger,
10
13
  type GPTLiveDelegation,
11
14
  type GPTLiveModelOptions,
12
15
  GPTLiveSession,
package/src/tts.ts CHANGED
@@ -6,8 +6,8 @@ import type { AudioFrame } from '@livekit/rtc-node';
6
6
  import { OpenAI } from 'openai';
7
7
  import type { TTSModels, TTSVoices } from './models.js';
8
8
 
9
- const OPENAI_TTS_SAMPLE_RATE = 24000;
10
9
  const OPENAI_TTS_CHANNELS = 1;
10
+ const OPENAI_TTS_SAMPLE_RATE = 24000;
11
11
 
12
12
  export interface TTSOptions {
13
13
  model: TTSModels | string;
@@ -17,6 +17,11 @@ export interface TTSOptions {
17
17
  baseURL?: string;
18
18
  client?: OpenAI;
19
19
  apiKey?: string;
20
+ /**
21
+ * Sample rate of the provider's PCM output, in Hz. Defaults to 24000.
22
+ * Must be an integer of at least 10. The audio is not resampled.
23
+ */
24
+ sampleRate?: number;
20
25
  }
21
26
 
22
27
  const defaultTTSOptions: TTSOptions = {
@@ -24,6 +29,7 @@ const defaultTTSOptions: TTSOptions = {
24
29
  model: 'tts-1',
25
30
  voice: 'alloy',
26
31
  speed: 1,
32
+ sampleRate: OPENAI_TTS_SAMPLE_RATE,
27
33
  };
28
34
 
29
35
  export class TTS extends tts.TTS {
@@ -53,9 +59,15 @@ export class TTS extends tts.TTS {
53
59
  * `OPENAI_API_KEY` environment variable.
54
60
  */
55
61
  constructor(opts: Partial<TTSOptions> = defaultTTSOptions) {
56
- super(OPENAI_TTS_SAMPLE_RATE, OPENAI_TTS_CHANNELS, { streaming: false });
62
+ const sampleRate = opts.sampleRate ?? OPENAI_TTS_SAMPLE_RATE;
63
+ if (!Number.isInteger(sampleRate) || sampleRate < 10) {
64
+ throw new Error(
65
+ `OpenAI TTS sampleRate must be an integer of at least 10 Hz, got ${String(opts.sampleRate)}`,
66
+ );
67
+ }
68
+ super(sampleRate, OPENAI_TTS_CHANNELS, { streaming: false });
57
69
 
58
- this.#opts = { ...defaultTTSOptions, ...opts };
70
+ this.#opts = { ...defaultTTSOptions, ...opts, sampleRate };
59
71
  if (this.#opts.apiKey === undefined && !this.#opts.client) {
60
72
  throw new Error('OpenAI API key is required, whether as an argument or as $OPENAI_API_KEY');
61
73
  }
@@ -112,6 +124,7 @@ export class TTS extends tts.TTS {
112
124
  export class ChunkedStream extends tts.ChunkedStream {
113
125
  label = 'openai.ChunkedStream';
114
126
  private stream: Promise<any>;
127
+ private sampleRate: number;
115
128
 
116
129
  // set Promise<T> to any because OpenAI returns an annoying Response type
117
130
  constructor(
@@ -123,14 +136,15 @@ export class ChunkedStream extends tts.ChunkedStream {
123
136
  ) {
124
137
  super(text, tts, connOptions, abortSignal);
125
138
  this.stream = stream;
139
+ this.sampleRate = tts.sampleRate;
126
140
  }
127
141
 
128
142
  protected async run() {
129
143
  try {
130
144
  const buffer = await this.stream.then((r) => r.arrayBuffer());
131
145
  const requestId = shortuuid();
132
- const audioByteStream = new AudioByteStream(OPENAI_TTS_SAMPLE_RATE, OPENAI_TTS_CHANNELS);
133
- const frames = audioByteStream.write(buffer);
146
+ const audioByteStream = new AudioByteStream(this.sampleRate, OPENAI_TTS_CHANNELS);
147
+ const frames = [...audioByteStream.write(buffer), ...audioByteStream.flush()];
134
148
 
135
149
  let lastFrame: AudioFrame | undefined;
136
150
  const sendLastFrame = (segmentId: string, final: boolean) => {
@@ -0,0 +1,88 @@
1
+ // SPDX-FileCopyrightText: 2026 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import { initializeLogger } from '@livekit/agents';
5
+ import { OpenAI } from 'openai';
6
+ import { beforeAll, describe, expect, it } from 'vitest';
7
+ import { ChunkedStream, TTS } from './tts.js';
8
+
9
+ beforeAll(() => {
10
+ initializeLogger({ pretty: false, level: 'silent' });
11
+ });
12
+
13
+ async function collectAudio(stream: ChunkedStream) {
14
+ const audio = [];
15
+ for await (const chunk of stream) {
16
+ audio.push(chunk);
17
+ }
18
+ return audio;
19
+ }
20
+
21
+ describe('OpenAI TTS sample rates', () => {
22
+ it.each([-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.5, NaN, Infinity])(
23
+ 'rejects sampleRate %s before synthesis',
24
+ (sampleRate) => {
25
+ expect(() => new TTS({ apiKey: 'test-key', sampleRate })).toThrow(
26
+ 'sampleRate must be an integer of at least 10 Hz',
27
+ );
28
+ },
29
+ );
30
+
31
+ it.each([
32
+ { name: 'omitted', opts: {}, expectedRate: 24000 },
33
+ { name: 'undefined', opts: { sampleRate: undefined }, expectedRate: 24000 },
34
+ { name: 'minimum', opts: { sampleRate: 10 }, expectedRate: 10 },
35
+ { name: '44.1 kHz', opts: { sampleRate: 44100 }, expectedRate: 44100 },
36
+ ])('preserves PCM and frame metadata for $name sampleRate', async ({ opts, expectedRate }) => {
37
+ const samples = Int16Array.from(
38
+ { length: Math.floor(expectedRate / 10) + 1 },
39
+ (_, i) => i % 32768,
40
+ );
41
+ const client = new OpenAI({
42
+ apiKey: 'test-key',
43
+ fetch: async () => new Response(samples.buffer),
44
+ });
45
+ const tts = new TTS({ ...opts, client });
46
+ const audio = await collectAudio(tts.synthesize('hello'));
47
+
48
+ expect(tts.sampleRate).toBe(expectedRate);
49
+ expect(audio.map(({ frame }) => frame.sampleRate)).toEqual([expectedRate, expectedRate]);
50
+ expect(audio.map(({ frame }) => frame.channels)).toEqual([1, 1]);
51
+ expect(audio.flatMap(({ frame }) => [...frame.data])).toEqual([...samples]);
52
+ expect(audio.map(({ final }) => final)).toEqual([false, true]);
53
+ await tts.close();
54
+ });
55
+
56
+ it('supports the three-argument ChunkedStream constructor', async () => {
57
+ const tts = new TTS({ apiKey: 'test-key' });
58
+ const samples = new Int16Array(2400);
59
+ const stream = new ChunkedStream(tts, 'hello', Promise.resolve(new Response(samples.buffer)));
60
+ const audio = await collectAudio(stream);
61
+
62
+ expect(audio).toHaveLength(1);
63
+ expect(audio[0]?.frame.sampleRate).toBe(24000);
64
+ expect(audio[0]?.frame.samplesPerChannel).toBe(samples.length);
65
+ await tts.close();
66
+ });
67
+
68
+ it('preserves connection options and abort signal positions in ChunkedStream', async () => {
69
+ const tts = new TTS({ apiKey: 'test-key', sampleRate: 44100 });
70
+ const samples = new Int16Array(4410);
71
+ const abortController = new AbortController();
72
+ const stream = new ChunkedStream(
73
+ tts,
74
+ 'hello',
75
+ Promise.resolve(new Response(samples.buffer)),
76
+ { maxRetry: 0, retryIntervalMs: 0, timeoutMs: 1000 },
77
+ abortController.signal,
78
+ );
79
+ const audio = await collectAudio(stream);
80
+
81
+ expect(audio).toHaveLength(1);
82
+ expect(audio[0]?.frame.sampleRate).toBe(44100);
83
+ expect(stream.abortSignal.aborted).toBe(false);
84
+ abortController.abort();
85
+ expect(stream.abortSignal.aborted).toBe(true);
86
+ await tts.close();
87
+ });
88
+ });