@livekit/agents-plugin-openai 0.0.0-next-20260624041820

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.
Files changed (179) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +18 -0
  3. package/dist/index.cjs +74 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.d.cts +9 -0
  6. package/dist/index.d.ts +9 -0
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.js +30 -0
  9. package/dist/index.js.map +1 -0
  10. package/dist/llm.cjs +382 -0
  11. package/dist/llm.cjs.map +1 -0
  12. package/dist/llm.d.cts +230 -0
  13. package/dist/llm.d.ts +230 -0
  14. package/dist/llm.d.ts.map +1 -0
  15. package/dist/llm.js +357 -0
  16. package/dist/llm.js.map +1 -0
  17. package/dist/llm.test.cjs +36 -0
  18. package/dist/llm.test.cjs.map +1 -0
  19. package/dist/llm.test.d.cts +2 -0
  20. package/dist/llm.test.d.ts +2 -0
  21. package/dist/llm.test.d.ts.map +1 -0
  22. package/dist/llm.test.js +35 -0
  23. package/dist/llm.test.js.map +1 -0
  24. package/dist/models.cjs +50 -0
  25. package/dist/models.cjs.map +1 -0
  26. package/dist/models.d.cts +26 -0
  27. package/dist/models.d.ts +26 -0
  28. package/dist/models.d.ts.map +1 -0
  29. package/dist/models.js +25 -0
  30. package/dist/models.js.map +1 -0
  31. package/dist/realtime/api_proto.cjs +41 -0
  32. package/dist/realtime/api_proto.cjs.map +1 -0
  33. package/dist/realtime/api_proto.d.cts +501 -0
  34. package/dist/realtime/api_proto.d.ts +501 -0
  35. package/dist/realtime/api_proto.d.ts.map +1 -0
  36. package/dist/realtime/api_proto.js +13 -0
  37. package/dist/realtime/api_proto.js.map +1 -0
  38. package/dist/realtime/index.cjs +25 -0
  39. package/dist/realtime/index.cjs.map +1 -0
  40. package/dist/realtime/index.d.cts +3 -0
  41. package/dist/realtime/index.d.ts +3 -0
  42. package/dist/realtime/index.d.ts.map +1 -0
  43. package/dist/realtime/index.js +3 -0
  44. package/dist/realtime/index.js.map +1 -0
  45. package/dist/realtime/realtime_model.cjs +1658 -0
  46. package/dist/realtime/realtime_model.cjs.map +1 -0
  47. package/dist/realtime/realtime_model.d.cts +202 -0
  48. package/dist/realtime/realtime_model.d.ts +202 -0
  49. package/dist/realtime/realtime_model.d.ts.map +1 -0
  50. package/dist/realtime/realtime_model.js +1637 -0
  51. package/dist/realtime/realtime_model.js.map +1 -0
  52. package/dist/realtime/realtime_model.test.cjs +596 -0
  53. package/dist/realtime/realtime_model.test.cjs.map +1 -0
  54. package/dist/realtime/realtime_model.test.d.cts +2 -0
  55. package/dist/realtime/realtime_model.test.d.ts +2 -0
  56. package/dist/realtime/realtime_model.test.d.ts.map +1 -0
  57. package/dist/realtime/realtime_model.test.js +600 -0
  58. package/dist/realtime/realtime_model.test.js.map +1 -0
  59. package/dist/responses/index.cjs +23 -0
  60. package/dist/responses/index.cjs.map +1 -0
  61. package/dist/responses/index.d.cts +2 -0
  62. package/dist/responses/index.d.ts +2 -0
  63. package/dist/responses/index.d.ts.map +1 -0
  64. package/dist/responses/index.js +2 -0
  65. package/dist/responses/index.js.map +1 -0
  66. package/dist/responses/llm.cjs +353 -0
  67. package/dist/responses/llm.cjs.map +1 -0
  68. package/dist/responses/llm.d.cts +52 -0
  69. package/dist/responses/llm.d.ts +52 -0
  70. package/dist/responses/llm.d.ts.map +1 -0
  71. package/dist/responses/llm.js +327 -0
  72. package/dist/responses/llm.js.map +1 -0
  73. package/dist/responses/llm.test.cjs +37 -0
  74. package/dist/responses/llm.test.cjs.map +1 -0
  75. package/dist/responses/llm.test.d.cts +2 -0
  76. package/dist/responses/llm.test.d.ts +2 -0
  77. package/dist/responses/llm.test.d.ts.map +1 -0
  78. package/dist/responses/llm.test.js +36 -0
  79. package/dist/responses/llm.test.js.map +1 -0
  80. package/dist/stt.cjs +627 -0
  81. package/dist/stt.cjs.map +1 -0
  82. package/dist/stt.d.cts +105 -0
  83. package/dist/stt.d.ts +105 -0
  84. package/dist/stt.d.ts.map +1 -0
  85. package/dist/stt.js +605 -0
  86. package/dist/stt.js.map +1 -0
  87. package/dist/stt.test.cjs +132 -0
  88. package/dist/stt.test.cjs.map +1 -0
  89. package/dist/stt.test.d.cts +2 -0
  90. package/dist/stt.test.d.ts +2 -0
  91. package/dist/stt.test.d.ts.map +1 -0
  92. package/dist/stt.test.js +131 -0
  93. package/dist/stt.test.js.map +1 -0
  94. package/dist/tool_utils.cjs +53 -0
  95. package/dist/tool_utils.cjs.map +1 -0
  96. package/dist/tool_utils.d.cts +4 -0
  97. package/dist/tool_utils.d.ts +4 -0
  98. package/dist/tool_utils.d.ts.map +1 -0
  99. package/dist/tool_utils.js +29 -0
  100. package/dist/tool_utils.js.map +1 -0
  101. package/dist/tool_utils.test.cjs +77 -0
  102. package/dist/tool_utils.test.cjs.map +1 -0
  103. package/dist/tool_utils.test.d.cts +2 -0
  104. package/dist/tool_utils.test.d.ts +2 -0
  105. package/dist/tool_utils.test.d.ts.map +1 -0
  106. package/dist/tool_utils.test.js +76 -0
  107. package/dist/tool_utils.test.js.map +1 -0
  108. package/dist/tools.cjs +117 -0
  109. package/dist/tools.cjs.map +1 -0
  110. package/dist/tools.d.cts +88 -0
  111. package/dist/tools.d.ts +88 -0
  112. package/dist/tools.d.ts.map +1 -0
  113. package/dist/tools.js +90 -0
  114. package/dist/tools.js.map +1 -0
  115. package/dist/tts.cjs +141 -0
  116. package/dist/tts.cjs.map +1 -0
  117. package/dist/tts.d.cts +42 -0
  118. package/dist/tts.d.ts +42 -0
  119. package/dist/tts.d.ts.map +1 -0
  120. package/dist/tts.js +116 -0
  121. package/dist/tts.js.map +1 -0
  122. package/dist/tts.test.cjs +17 -0
  123. package/dist/tts.test.cjs.map +1 -0
  124. package/dist/tts.test.d.cts +2 -0
  125. package/dist/tts.test.d.ts +2 -0
  126. package/dist/tts.test.d.ts.map +1 -0
  127. package/dist/tts.test.js +16 -0
  128. package/dist/tts.test.js.map +1 -0
  129. package/dist/ws/index.cjs +29 -0
  130. package/dist/ws/index.cjs.map +1 -0
  131. package/dist/ws/index.d.cts +3 -0
  132. package/dist/ws/index.d.ts +3 -0
  133. package/dist/ws/index.d.ts.map +1 -0
  134. package/dist/ws/index.js +5 -0
  135. package/dist/ws/index.js.map +1 -0
  136. package/dist/ws/llm.cjs +523 -0
  137. package/dist/ws/llm.cjs.map +1 -0
  138. package/dist/ws/llm.d.cts +96 -0
  139. package/dist/ws/llm.d.ts +96 -0
  140. package/dist/ws/llm.d.ts.map +1 -0
  141. package/dist/ws/llm.js +505 -0
  142. package/dist/ws/llm.js.map +1 -0
  143. package/dist/ws/llm.test.cjs +69 -0
  144. package/dist/ws/llm.test.cjs.map +1 -0
  145. package/dist/ws/llm.test.d.cts +2 -0
  146. package/dist/ws/llm.test.d.ts +2 -0
  147. package/dist/ws/llm.test.d.ts.map +1 -0
  148. package/dist/ws/llm.test.js +68 -0
  149. package/dist/ws/llm.test.js.map +1 -0
  150. package/dist/ws/types.cjs +129 -0
  151. package/dist/ws/types.cjs.map +1 -0
  152. package/dist/ws/types.d.cts +172 -0
  153. package/dist/ws/types.d.ts +172 -0
  154. package/dist/ws/types.d.ts.map +1 -0
  155. package/dist/ws/types.js +96 -0
  156. package/dist/ws/types.js.map +1 -0
  157. package/package.json +56 -0
  158. package/src/index.ts +25 -0
  159. package/src/llm.test.ts +38 -0
  160. package/src/llm.ts +553 -0
  161. package/src/models.ts +235 -0
  162. package/src/realtime/api_proto.ts +714 -0
  163. package/src/realtime/index.ts +5 -0
  164. package/src/realtime/realtime_model.test.ts +793 -0
  165. package/src/realtime/realtime_model.ts +2116 -0
  166. package/src/responses/index.ts +4 -0
  167. package/src/responses/llm.test.ts +39 -0
  168. package/src/responses/llm.ts +452 -0
  169. package/src/stt.test.ts +167 -0
  170. package/src/stt.ts +793 -0
  171. package/src/tool_utils.test.ts +84 -0
  172. package/src/tool_utils.ts +46 -0
  173. package/src/tools.ts +166 -0
  174. package/src/tts.test.ts +19 -0
  175. package/src/tts.ts +158 -0
  176. package/src/ws/index.ts +17 -0
  177. package/src/ws/llm.test.ts +83 -0
  178. package/src/ws/llm.ts +710 -0
  179. package/src/ws/types.ts +132 -0
package/src/ws/llm.ts ADDED
@@ -0,0 +1,710 @@
1
+ // SPDX-FileCopyrightText: 2025 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import type { APIConnectOptions } from '@livekit/agents';
5
+ import {
6
+ APIConnectionError,
7
+ APIStatusError,
8
+ APITimeoutError,
9
+ ConnectionPool,
10
+ DEFAULT_API_CONNECT_OPTIONS,
11
+ llm,
12
+ stream,
13
+ toError,
14
+ } from '@livekit/agents';
15
+ import type OpenAI from 'openai';
16
+ import { WebSocket } from 'ws';
17
+ import type { ChatModels, Reasoning } from '../models.js';
18
+ import { defaultReasoningEffort } from '../models.js';
19
+ import { toResponsesTools } from '../tool_utils.js';
20
+ import type {
21
+ WsOutputItemDoneEvent,
22
+ WsOutputTextDeltaEvent,
23
+ WsResponseCompletedEvent,
24
+ WsResponseCreateEvent,
25
+ WsResponseCreatedEvent,
26
+ WsResponseFailedEvent,
27
+ WsServerEvent,
28
+ } from './types.js';
29
+ import { wsServerEventSchema } from './types.js';
30
+
31
+ const OPENAI_RESPONSES_WS_URL = 'wss://api.openai.com/v1/responses';
32
+
33
+ // OpenAI enforces a 60-minute maximum duration on Responses WebSocket connections.
34
+ const WS_MAX_SESSION_DURATION = 3_600_000;
35
+
36
+ /**
37
+ * Build the Responses-API WebSocket URL.
38
+ *
39
+ * Includes the model on the upgrade URL so OpenAI-compatible gateways
40
+ * (which can only see the URL at the WebSocket upgrade, not the subsequent
41
+ * `response.create` frame) can route by model. Mirrors the existing
42
+ * convention in `realtime/realtime_model.ts` for the conversational
43
+ * Realtime API. OpenAI's native endpoint accepts and ignores the
44
+ * parameter, so this is a no-op for direct connections.
45
+ *
46
+ * The scheme of `baseURL` is respected: `http://` maps to `ws://`
47
+ * and `https://` maps to `wss://`.
48
+ *
49
+ * @internal
50
+ */
51
+ export function buildResponsesWsUrl(baseURL: string | undefined, model: string): string {
52
+ const base = baseURL
53
+ ? `${baseURL.replace(/^http(s?):/, 'ws$1:').replace(/\/+$/, '')}/responses`
54
+ : OPENAI_RESPONSES_WS_URL;
55
+ const url = new URL(base);
56
+ url.searchParams.set('model', model);
57
+ return url.toString();
58
+ }
59
+
60
+ // ============================================================================
61
+ // Internal: ResponsesWebSocket
62
+ //
63
+ // Wraps a single raw WebSocket connection. Maintains a FIFO queue of
64
+ // StreamChannels — one per outstanding response.create request — and
65
+ // dispatches every incoming server-event to the front of the queue.
66
+ // A response is terminated (and its channel closed) when the service sends
67
+ // response.completed, response.failed, or error.
68
+ //
69
+ // ============================================================================
70
+
71
+ export class ResponsesWebSocket {
72
+ #ws: WebSocket;
73
+ // FIFO queue: the front entry receives validated WsServerEvents for the in-flight response.
74
+ #outputQueue: stream.StreamChannel<WsServerEvent>[] = [];
75
+
76
+ constructor(ws: WebSocket) {
77
+ this.#ws = ws;
78
+
79
+ ws.on('message', (data: Buffer) => {
80
+ const current = this.#outputQueue[0];
81
+ if (!current) return;
82
+
83
+ let raw: unknown;
84
+ try {
85
+ raw = JSON.parse(data.toString());
86
+ } catch {
87
+ return;
88
+ }
89
+
90
+ // Validate and type-narrow with Zod at write time so readers always
91
+ // receive a fully-typed WsServerEvent.
92
+ const parsed = wsServerEventSchema.safeParse(raw);
93
+ if (!parsed.success) return;
94
+
95
+ const event = parsed.data;
96
+ void current.write(event);
97
+
98
+ // Close and dequeue on any terminal event.
99
+ if (
100
+ event.type === 'response.completed' ||
101
+ event.type === 'response.failed' ||
102
+ event.type === 'error'
103
+ ) {
104
+ void current.close();
105
+ this.#outputQueue.shift();
106
+ }
107
+ });
108
+
109
+ ws.on('close', () => {
110
+ // If the WebSocket closes while requests are still in flight, synthesise
111
+ // a typed error event so all readers can handle it cleanly.
112
+ for (const current of this.#outputQueue) {
113
+ if (!current.closed) {
114
+ const closeError: WsServerEvent = {
115
+ type: 'error',
116
+ error: {
117
+ code: 'websocket_closed',
118
+ message: 'OpenAI Responses WebSocket closed unexpectedly',
119
+ },
120
+ };
121
+ void current.write(closeError).finally(() => current.close());
122
+ }
123
+ }
124
+ this.#outputQueue = [];
125
+ });
126
+ }
127
+
128
+ /**
129
+ * Send a response.create event. Returns a typed `StreamChannel<WsServerEvent>`
130
+ * that yields validated server events until the response terminates.
131
+ */
132
+ sendRequest(payload: WsResponseCreateEvent): stream.StreamChannel<WsServerEvent> {
133
+ if (this.#ws.readyState !== WebSocket.OPEN) {
134
+ throw new APIConnectionError({
135
+ message: `OpenAI Responses WebSocket is not open (state ${getWebSocketStateLabel(this.#ws.readyState)})`,
136
+ options: { retryable: true },
137
+ });
138
+ }
139
+
140
+ const channel = stream.createStreamChannel<WsServerEvent>();
141
+ this.#outputQueue.push(channel);
142
+ this.#ws.send(JSON.stringify(payload));
143
+ return channel;
144
+ }
145
+
146
+ close(): void {
147
+ // Drain pending channels before closing the socket.
148
+ for (const ch of this.#outputQueue) {
149
+ void ch.close();
150
+ }
151
+ this.#outputQueue = [];
152
+ this.#ws.close();
153
+ }
154
+ }
155
+
156
+ // ============================================================================
157
+ // LLMOptions
158
+ // ============================================================================
159
+
160
+ export interface WSLLMOptions {
161
+ model: string | ChatModels;
162
+ apiKey?: string;
163
+ baseURL?: string;
164
+ temperature?: number;
165
+ parallelToolCalls?: boolean;
166
+ toolChoice?: llm.ToolChoice;
167
+ store?: boolean;
168
+ metadata?: Record<string, string>;
169
+ strictToolSchema?: boolean;
170
+ /** Specifies the processing tier (e.g. 'auto', 'default', 'priority', 'flex'). */
171
+ serviceTier?: string;
172
+ /** Upper bound for the number of tokens that can be generated for a response. */
173
+ maxOutputTokens?: number;
174
+ /** Configuration options for reasoning models. */
175
+ reasoning?: Reasoning | null;
176
+ }
177
+
178
+ const defaultLLMOptions: WSLLMOptions = {
179
+ model: 'gpt-4.1',
180
+ apiKey: process.env.OPENAI_API_KEY,
181
+ strictToolSchema: true,
182
+ };
183
+
184
+ // ============================================================================
185
+ // LLM
186
+ // ============================================================================
187
+
188
+ export class WSLLM extends llm.LLM {
189
+ #opts: WSLLMOptions;
190
+ #pool: ConnectionPool<ResponsesWebSocket>;
191
+ #prevResponseId = '';
192
+ #prevChatCtx: llm.ChatContext | null = null;
193
+ #pendingToolCalls = new Set<string>();
194
+
195
+ /**
196
+ * Create a new instance of the OpenAI Responses API WebSocket LLM.
197
+ *
198
+ * @remarks
199
+ * `apiKey` must be set to your OpenAI API key, either using the argument or
200
+ * by setting the `OPENAI_API_KEY` environment variable.
201
+ *
202
+ * A persistent WebSocket connection to `/v1/responses` is maintained and
203
+ * reused across turns, reducing per-turn continuation overhead for
204
+ * tool-call-heavy workflows.
205
+ */
206
+ constructor(opts: Partial<WSLLMOptions> = defaultLLMOptions) {
207
+ super();
208
+
209
+ this.#opts = { ...defaultLLMOptions, ...opts };
210
+ if (this.#opts.reasoning === undefined) {
211
+ const effort = defaultReasoningEffort(this.#opts.model);
212
+ if (effort !== undefined) {
213
+ this.#opts.reasoning = { effort };
214
+ }
215
+ }
216
+
217
+ if (!this.#opts.apiKey) {
218
+ throw new Error('OpenAI API key is required, whether as an argument or as $OPENAI_API_KEY');
219
+ }
220
+
221
+ this.#pool = new ConnectionPool<ResponsesWebSocket>({
222
+ maxSessionDuration: WS_MAX_SESSION_DURATION,
223
+ connectCb: async (timeoutMs: number) => {
224
+ const wsUrl = buildResponsesWsUrl(this.#opts.baseURL, String(this.#opts.model));
225
+ const ws = await connectWs(wsUrl, this.#opts.apiKey!, timeoutMs);
226
+ return new ResponsesWebSocket(ws);
227
+ },
228
+ closeCb: async (conn: ResponsesWebSocket) => {
229
+ conn.close();
230
+ },
231
+ });
232
+ }
233
+
234
+ label(): string {
235
+ return 'openai.ws.LLM';
236
+ }
237
+
238
+ get model(): string {
239
+ return this.#opts.model;
240
+ }
241
+
242
+ prewarm(): void {
243
+ this.#pool.prewarm();
244
+ }
245
+
246
+ async close(): Promise<void> {
247
+ await this.#pool.close();
248
+ }
249
+
250
+ override async aclose(): Promise<void> {
251
+ await this.close();
252
+ }
253
+
254
+ /** Called by LLMStream once response.created fires to atomically persist both the
255
+ * response ID and its corresponding chat context for the next turn's diff. */
256
+ _onResponseCreated(responseId: string, chatCtx: llm.ChatContext): void {
257
+ this.#prevResponseId = responseId;
258
+ this.#prevChatCtx = chatCtx;
259
+ }
260
+
261
+ _setPendingToolCalls(callIds: Set<string>): void {
262
+ this.#pendingToolCalls = callIds;
263
+ }
264
+
265
+ chat({
266
+ chatCtx,
267
+ toolCtx: toolCtxInput,
268
+ connOptions = DEFAULT_API_CONNECT_OPTIONS,
269
+ parallelToolCalls,
270
+ toolChoice,
271
+ extraKwargs,
272
+ }: {
273
+ chatCtx: llm.ChatContext;
274
+ toolCtx?: llm.ToolContextLike;
275
+ connOptions?: APIConnectOptions;
276
+ parallelToolCalls?: boolean;
277
+ toolChoice?: llm.ToolChoice;
278
+ extraKwargs?: Record<string, unknown>;
279
+ }): WSLLMStream {
280
+ const toolCtx = llm.toToolContext(toolCtxInput);
281
+ const modelOptions: Record<string, unknown> = { ...(extraKwargs ?? {}) };
282
+
283
+ parallelToolCalls =
284
+ parallelToolCalls !== undefined ? parallelToolCalls : this.#opts.parallelToolCalls;
285
+ if (
286
+ toolCtx &&
287
+ Object.keys(toolCtx.functionTools).length > 0 &&
288
+ parallelToolCalls !== undefined
289
+ ) {
290
+ modelOptions.parallel_tool_calls = parallelToolCalls;
291
+ }
292
+
293
+ toolChoice =
294
+ toolChoice !== undefined ? toolChoice : (this.#opts.toolChoice as llm.ToolChoice | undefined);
295
+ if (toolChoice) {
296
+ modelOptions.tool_choice = toolChoice;
297
+ }
298
+
299
+ if (this.#opts.temperature !== undefined) {
300
+ modelOptions.temperature = this.#opts.temperature;
301
+ }
302
+
303
+ if (this.#opts.store !== undefined) {
304
+ modelOptions.store = this.#opts.store;
305
+ }
306
+
307
+ if (this.#opts.metadata) {
308
+ modelOptions.metadata = this.#opts.metadata;
309
+ }
310
+
311
+ if (this.#opts.serviceTier) {
312
+ modelOptions.service_tier = this.#opts.serviceTier;
313
+ }
314
+
315
+ if (this.#opts.maxOutputTokens !== undefined) {
316
+ modelOptions.max_output_tokens = this.#opts.maxOutputTokens;
317
+ }
318
+
319
+ if (this.#opts.reasoning !== undefined) {
320
+ modelOptions.reasoning = this.#opts.reasoning;
321
+ }
322
+
323
+ let inputChatCtx = chatCtx;
324
+ let prevResponseId: string | undefined;
325
+ const canUseStoredResponse = modelOptions.store !== false;
326
+
327
+ if (canUseStoredResponse && this.#prevChatCtx && this.#prevResponseId) {
328
+ const diff = llm.computeChatCtxDiff(this.#prevChatCtx, chatCtx);
329
+ const lastPrevItemId = this.#prevChatCtx.items.at(-1)?.id ?? null;
330
+
331
+ if (
332
+ diff.toRemove.length === 0 &&
333
+ diff.toCreate.length > 0 &&
334
+ diff.toCreate[0]![0] === lastPrevItemId
335
+ ) {
336
+ // All new items are appended after the tail of the previous context —
337
+ // safe to send only the incremental input with previous_response_id,
338
+ // but only if all pending tool calls from the previous response have
339
+ // their corresponding function_call_output in the new items.
340
+ const newItemIds = new Set(diff.toCreate.map(([, id]) => id));
341
+ const newItems = chatCtx.items.filter((item: llm.ChatItem) => newItemIds.has(item.id));
342
+ const pendingToolCallsCompleted = this.#pendingToolCallsCompleted(newItems);
343
+ if (pendingToolCallsCompleted) {
344
+ inputChatCtx = new llm.ChatContext(newItems);
345
+ prevResponseId = this.#prevResponseId;
346
+ }
347
+ }
348
+ // Otherwise: items were removed or inserted mid-history — fall back to
349
+ // sending the full context with no previous_response_id.
350
+ }
351
+
352
+ return new WSLLMStream(this, {
353
+ pool: this.#pool,
354
+ model: this.#opts.model,
355
+ chatCtx: inputChatCtx,
356
+ fullChatCtx: chatCtx,
357
+ toolCtx,
358
+ connOptions,
359
+ modelOptions,
360
+ prevResponseId,
361
+ strictToolSchema: this.#opts.strictToolSchema ?? true,
362
+ });
363
+ }
364
+
365
+ #pendingToolCallsCompleted(items: llm.ChatItem[]): boolean {
366
+ if (this.#pendingToolCalls.size === 0) return true;
367
+ const completedCallIds = new Set(
368
+ items
369
+ .filter((item): item is llm.FunctionCallOutput => item.type === 'function_call_output')
370
+ .map((item) => item.callId),
371
+ );
372
+ return [...this.#pendingToolCalls].every((callId) => completedCallIds.has(callId));
373
+ }
374
+ }
375
+
376
+ // ============================================================================
377
+ // WsLLMStream
378
+ // ============================================================================
379
+
380
+ export class WSLLMStream extends llm.LLMStream {
381
+ #llm: WSLLM;
382
+ #pool: ConnectionPool<ResponsesWebSocket>;
383
+ #model: string | ChatModels;
384
+ #modelOptions: Record<string, unknown>;
385
+ #strictToolSchema: boolean;
386
+ #prevResponseId?: string;
387
+ /** Full chat context — used as fallback when previous_response_id is stale. */
388
+ #fullChatCtx: llm.ChatContext;
389
+ #responseId = '';
390
+ #pendingToolCalls = new Set<string>();
391
+
392
+ constructor(
393
+ llm: WSLLM,
394
+ {
395
+ pool,
396
+ model,
397
+ chatCtx,
398
+ fullChatCtx,
399
+ toolCtx,
400
+ connOptions,
401
+ modelOptions,
402
+ prevResponseId,
403
+ strictToolSchema,
404
+ }: {
405
+ pool: ConnectionPool<ResponsesWebSocket>;
406
+ model: string | ChatModels;
407
+ chatCtx: llm.ChatContext;
408
+ fullChatCtx: llm.ChatContext;
409
+ toolCtx?: llm.ToolContext;
410
+ connOptions: APIConnectOptions;
411
+ modelOptions: Record<string, unknown>;
412
+ prevResponseId?: string;
413
+ strictToolSchema: boolean;
414
+ },
415
+ ) {
416
+ super(llm, { chatCtx, toolCtx, connOptions });
417
+ this.#llm = llm;
418
+ this.#pool = pool;
419
+ this.#model = model;
420
+ this.#modelOptions = modelOptions;
421
+ this.#strictToolSchema = strictToolSchema;
422
+ this.#prevResponseId = prevResponseId;
423
+ this.#fullChatCtx = fullChatCtx;
424
+ }
425
+
426
+ protected async run(): Promise<void> {
427
+ let retryable = true;
428
+
429
+ try {
430
+ await this.#pool.withConnection(async (conn: ResponsesWebSocket) => {
431
+ const needsRetry = await this.#runWithConn(conn, this.chatCtx, this.#prevResponseId);
432
+
433
+ if (needsRetry) {
434
+ // previous_response_id was evicted from the server-side cache.
435
+ // Retry once on the same connection with the full context and no ID.
436
+ retryable = true;
437
+ await this.#runWithConn(conn, this.#fullChatCtx, undefined);
438
+ }
439
+ });
440
+ } catch (error) {
441
+ if (
442
+ error instanceof APIStatusError ||
443
+ error instanceof APITimeoutError ||
444
+ error instanceof APIConnectionError
445
+ ) {
446
+ throw error;
447
+ }
448
+ throw new APIConnectionError({
449
+ message: toError(error).message,
450
+ options: { retryable },
451
+ });
452
+ }
453
+ }
454
+
455
+ /**
456
+ * Execute a single response.create round-trip on the given connection.
457
+ * Returns `true` when the caller should retry with the full chat context
458
+ * (i.e. `previous_response_not_found`), `false` otherwise.
459
+ */
460
+ async #runWithConn(
461
+ conn: ResponsesWebSocket,
462
+ chatCtx: llm.ChatContext,
463
+ prevResponseId: string | undefined,
464
+ ): Promise<boolean> {
465
+ const messages = (await chatCtx.toProviderFormat(
466
+ 'openai.responses',
467
+ )) as OpenAI.Responses.ResponseInputItem[];
468
+
469
+ const tools = this.toolCtx ? toResponsesTools(this.toolCtx, this.#strictToolSchema) : undefined;
470
+
471
+ const requestOptions: Record<string, unknown> = { ...this.#modelOptions };
472
+ if (!tools) {
473
+ delete requestOptions.tool_choice;
474
+ }
475
+
476
+ const payload: WsResponseCreateEvent = {
477
+ type: 'response.create',
478
+ model: this.#model as string,
479
+ input: messages as unknown[],
480
+ tools: (tools ?? []) as unknown[],
481
+ ...(prevResponseId ? { previous_response_id: prevResponseId } : {}),
482
+ ...requestOptions,
483
+ };
484
+
485
+ let channel: stream.StreamChannel<WsServerEvent>;
486
+ try {
487
+ channel = conn.sendRequest(payload);
488
+ } catch (error) {
489
+ if (error instanceof APIConnectionError) {
490
+ conn.close();
491
+ this.#pool.invalidate();
492
+ }
493
+ throw error;
494
+ }
495
+ const reader = channel.stream().getReader();
496
+
497
+ // Events are already Zod-validated by ResponsesWebSocket before being
498
+ // written to the channel, so no re-parsing is needed here.
499
+ try {
500
+ while (true) {
501
+ const { done, value: event } = await reader.read();
502
+ if (done) break;
503
+
504
+ let chunk: llm.ChatChunk | undefined;
505
+
506
+ switch (event.type) {
507
+ case 'error': {
508
+ const retry = this.#handleError(event, conn);
509
+ if (retry) return true;
510
+ break;
511
+ }
512
+ case 'response.created':
513
+ this.#handleResponseCreated(event);
514
+ break;
515
+ case 'response.output_item.done':
516
+ chunk = this.#handleOutputItemDone(event);
517
+ break;
518
+ case 'response.output_text.delta':
519
+ chunk = this.#handleOutputTextDelta(event);
520
+ break;
521
+ case 'response.completed':
522
+ chunk = this.#handleResponseCompleted(event);
523
+ break;
524
+ case 'response.failed':
525
+ this.#handleResponseFailed(event);
526
+ break;
527
+ default:
528
+ break;
529
+ }
530
+
531
+ if (chunk) {
532
+ this.queue.put(chunk);
533
+ }
534
+ }
535
+ } finally {
536
+ reader.releaseLock();
537
+ }
538
+
539
+ return false;
540
+ }
541
+
542
+ /**
543
+ * Returns `true` when the caller should retry with full context
544
+ * (`previous_response_not_found`), throws for all other errors.
545
+ */
546
+ #handleError(event: WsServerEvent & { type: 'error' }, conn: ResponsesWebSocket): boolean {
547
+ const code = event.error?.code;
548
+
549
+ if (code === 'previous_response_not_found') {
550
+ // The server-side in-memory cache was evicted (e.g. after a failed turn
551
+ // or reconnect). Signal the caller to retry with the full context.
552
+ return true;
553
+ }
554
+
555
+ if (code === 'websocket_connection_limit_reached' || code === 'websocket_closed') {
556
+ // Transient connection issue (timeout, network drop, or 60-min limit).
557
+ // Evict this connection so the pool opens a fresh one on retry.
558
+ conn.close();
559
+ this.#pool.invalidate();
560
+ throw new APIConnectionError({
561
+ message: event.error?.message ?? `WebSocket closed (${code})`,
562
+ options: { retryable: true },
563
+ });
564
+ }
565
+
566
+ throw new APIStatusError({
567
+ message: event.error?.message ?? event.message ?? 'Unknown error from OpenAI Responses WS',
568
+ options: {
569
+ statusCode: event.status ?? -1,
570
+ retryable: false,
571
+ },
572
+ });
573
+ }
574
+
575
+ #handleResponseCreated(event: WsResponseCreatedEvent): void {
576
+ this.#responseId = event.response.id;
577
+ this.#llm._onResponseCreated(event.response.id, this.#fullChatCtx);
578
+ }
579
+
580
+ #handleOutputItemDone(event: WsOutputItemDoneEvent): llm.ChatChunk | undefined {
581
+ if (event.item.type === 'function_call') {
582
+ this.#pendingToolCalls.add(event.item.call_id);
583
+ return {
584
+ id: this.#responseId,
585
+ delta: {
586
+ role: 'assistant',
587
+ content: undefined,
588
+ toolCalls: [
589
+ llm.FunctionCall.create({
590
+ callId: event.item.call_id,
591
+ name: event.item.name,
592
+ args: event.item.arguments,
593
+ }),
594
+ ],
595
+ },
596
+ };
597
+ } else if (event.item.type === 'message' && event.item.phase !== undefined) {
598
+ return {
599
+ id: this.#responseId,
600
+ delta: {
601
+ role: 'assistant',
602
+ content: undefined,
603
+ extra: { openai: { phase: event.item.phase } },
604
+ },
605
+ };
606
+ }
607
+ return undefined;
608
+ }
609
+
610
+ #handleOutputTextDelta(event: WsOutputTextDeltaEvent): llm.ChatChunk {
611
+ return {
612
+ id: this.#responseId,
613
+ delta: {
614
+ role: 'assistant',
615
+ content: event.delta,
616
+ },
617
+ };
618
+ }
619
+
620
+ #handleResponseCompleted(event: WsResponseCompletedEvent): llm.ChatChunk | undefined {
621
+ this.#llm._setPendingToolCalls(this.#pendingToolCalls);
622
+
623
+ if (event.response.usage) {
624
+ return {
625
+ id: this.#responseId,
626
+ usage: {
627
+ completionTokens: event.response.usage.output_tokens,
628
+ promptTokens: event.response.usage.input_tokens,
629
+ promptCachedTokens: event.response.usage.input_tokens_details.cached_tokens,
630
+ totalTokens: event.response.usage.total_tokens,
631
+ serviceTier: event.response.service_tier ?? undefined,
632
+ },
633
+ };
634
+ }
635
+ return undefined;
636
+ }
637
+
638
+ #handleResponseFailed(event: WsResponseFailedEvent): void {
639
+ throw new APIStatusError({
640
+ message: event.response?.error?.message ?? 'Response failed',
641
+ options: { statusCode: -1, retryable: false },
642
+ });
643
+ }
644
+ }
645
+
646
+ // ============================================================================
647
+ // Internal helpers
648
+ // ============================================================================
649
+
650
+ async function connectWs(url: string, apiKey: string, timeoutMs: number): Promise<WebSocket> {
651
+ return new Promise<WebSocket>((resolve, reject) => {
652
+ const ws = new WebSocket(url, {
653
+ headers: { Authorization: `Bearer ${apiKey}` },
654
+ });
655
+
656
+ let settled = false;
657
+
658
+ const timer = setTimeout(() => {
659
+ settled = true;
660
+ ws.close();
661
+ reject(
662
+ new APIConnectionError({ message: 'Timeout connecting to OpenAI Responses WebSocket' }),
663
+ );
664
+ }, timeoutMs);
665
+
666
+ ws.once('open', () => {
667
+ if (settled) return;
668
+ settled = true;
669
+ clearTimeout(timer);
670
+ resolve(ws);
671
+ });
672
+
673
+ ws.once('error', (err) => {
674
+ if (settled) return;
675
+ settled = true;
676
+ clearTimeout(timer);
677
+ reject(
678
+ new APIConnectionError({
679
+ message: `Error connecting to OpenAI Responses WebSocket: ${err.message}`,
680
+ }),
681
+ );
682
+ });
683
+
684
+ ws.once('close', (code) => {
685
+ if (settled) return;
686
+ settled = true;
687
+ clearTimeout(timer);
688
+ reject(
689
+ new APIConnectionError({
690
+ message: `OpenAI Responses WebSocket closed unexpectedly during connect (code ${code})`,
691
+ }),
692
+ );
693
+ });
694
+ });
695
+ }
696
+
697
+ function getWebSocketStateLabel(readyState: number): string {
698
+ switch (readyState) {
699
+ case WebSocket.CONNECTING:
700
+ return 'CONNECTING';
701
+ case WebSocket.OPEN:
702
+ return 'OPEN';
703
+ case WebSocket.CLOSING:
704
+ return 'CLOSING';
705
+ case WebSocket.CLOSED:
706
+ return 'CLOSED';
707
+ default:
708
+ return `UNKNOWN:${readyState}`;
709
+ }
710
+ }