@eko-ai/eko 1.2.5 → 1.3.1

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/dist/index.cjs.js CHANGED
@@ -370,7 +370,7 @@ let Stream$1 = class Stream {
370
370
  let consumed = false;
371
371
  async function* iterLines() {
372
372
  const lineDecoder = new LineDecoder$1();
373
- const iter = readableStreamAsyncIterable$1(readableStream);
373
+ const iter = readableStreamAsyncIterable(readableStream);
374
374
  for await (const chunk of iter) {
375
375
  for (const line of lineDecoder.decode(chunk)) {
376
376
  yield line;
@@ -475,7 +475,7 @@ async function* _iterSSEMessages$1(response, controller) {
475
475
  }
476
476
  const sseDecoder = new SSEDecoder$1();
477
477
  const lineDecoder = new LineDecoder$1();
478
- const iter = readableStreamAsyncIterable$1(response.body);
478
+ const iter = readableStreamAsyncIterable(response.body);
479
479
  for await (const sseChunk of iterSSEChunks$1(iter)) {
480
480
  for (const line of lineDecoder.decode(sseChunk)) {
481
481
  const sse = sseDecoder.decode(line);
@@ -596,7 +596,7 @@ function partition$1(str, delimiter) {
596
596
  *
597
597
  * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490
598
598
  */
599
- function readableStreamAsyncIterable$1(stream) {
599
+ function readableStreamAsyncIterable(stream) {
600
600
  if (stream[Symbol.asyncIterator])
601
601
  return stream;
602
602
  const reader = stream.getReader();
@@ -722,13 +722,13 @@ const getStringFromMaybeBuffer$1 = (x) => {
722
722
  const isAsyncIterableIterator$1 = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function';
723
723
  const isMultipartBody$1 = (body) => body && typeof body === 'object' && body.body && body[Symbol.toStringTag] === 'MultipartBody';
724
724
 
725
- var __classPrivateFieldSet$5 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
725
+ var __classPrivateFieldSet$7 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
726
726
  if (kind === "m") throw new TypeError("Private method is not writable");
727
727
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
728
728
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
729
729
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
730
730
  };
731
- var __classPrivateFieldGet$6 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
731
+ var __classPrivateFieldGet$8 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
732
732
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
733
733
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
734
734
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
@@ -1160,7 +1160,7 @@ let APIClient$1 = class APIClient {
1160
1160
  let AbstractPage$1 = class AbstractPage {
1161
1161
  constructor(client, response, body, options) {
1162
1162
  _AbstractPage_client$1.set(this, void 0);
1163
- __classPrivateFieldSet$5(this, _AbstractPage_client$1, client, "f");
1163
+ __classPrivateFieldSet$7(this, _AbstractPage_client$1, client, "f");
1164
1164
  this.options = options;
1165
1165
  this.response = response;
1166
1166
  this.body = body;
@@ -1188,7 +1188,7 @@ let AbstractPage$1 = class AbstractPage {
1188
1188
  nextOptions.query = undefined;
1189
1189
  nextOptions.path = nextInfo.url.toString();
1190
1190
  }
1191
- return await __classPrivateFieldGet$6(this, _AbstractPage_client$1, "f").requestAPIList(this.constructor, nextOptions);
1191
+ return await __classPrivateFieldGet$8(this, _AbstractPage_client$1, "f").requestAPIList(this.constructor, nextOptions);
1192
1192
  }
1193
1193
  async *iterPages() {
1194
1194
  // eslint-disable-next-line @typescript-eslint/no-this-alias
@@ -1638,7 +1638,7 @@ class JSONLDecoder {
1638
1638
  controller.abort();
1639
1639
  throw new AnthropicError(`Attempted to iterate over a response with no body`);
1640
1640
  }
1641
- return new JSONLDecoder(readableStreamAsyncIterable$1(response.body), controller);
1641
+ return new JSONLDecoder(readableStreamAsyncIterable(response.body), controller);
1642
1642
  }
1643
1643
  }
1644
1644
 
@@ -1728,7 +1728,7 @@ class BetaMessageBatchesPage extends Page$1 {
1728
1728
  Batches$2.BetaMessageBatchesPage = BetaMessageBatchesPage;
1729
1729
 
1730
1730
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
1731
- let Messages$2 = class Messages extends APIResource$1 {
1731
+ let Messages$3 = class Messages extends APIResource$1 {
1732
1732
  constructor() {
1733
1733
  super(...arguments);
1734
1734
  this.batches = new Batches$2(this._client);
@@ -1764,20 +1764,20 @@ let Messages$2 = class Messages extends APIResource$1 {
1764
1764
  });
1765
1765
  }
1766
1766
  };
1767
- Messages$2.Batches = Batches$2;
1768
- Messages$2.BetaMessageBatchesPage = BetaMessageBatchesPage;
1767
+ Messages$3.Batches = Batches$2;
1768
+ Messages$3.BetaMessageBatchesPage = BetaMessageBatchesPage;
1769
1769
 
1770
1770
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
1771
1771
  let Beta$1 = class Beta extends APIResource$1 {
1772
1772
  constructor() {
1773
1773
  super(...arguments);
1774
1774
  this.models = new Models$2(this._client);
1775
- this.messages = new Messages$2(this._client);
1775
+ this.messages = new Messages$3(this._client);
1776
1776
  }
1777
1777
  };
1778
1778
  Beta$1.Models = Models$2;
1779
1779
  Beta$1.BetaModelInfosPage = BetaModelInfosPage;
1780
- Beta$1.Messages = Messages$2;
1780
+ Beta$1.Messages = Messages$3;
1781
1781
 
1782
1782
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
1783
1783
  let Completions$3 = class Completions extends APIResource$1 {
@@ -2072,13 +2072,13 @@ const tokenize = (input) => {
2072
2072
  return output;
2073
2073
  }, partialParse$1 = (input) => JSON.parse(generate(unstrip(strip(tokenize(input)))));
2074
2074
 
2075
- var __classPrivateFieldSet$4 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2075
+ var __classPrivateFieldSet$6 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2076
2076
  if (kind === "m") throw new TypeError("Private method is not writable");
2077
2077
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
2078
2078
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
2079
2079
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
2080
2080
  };
2081
- var __classPrivateFieldGet$5 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
2081
+ var __classPrivateFieldGet$7 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
2082
2082
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
2083
2083
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
2084
2084
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
@@ -2104,12 +2104,12 @@ class MessageStream {
2104
2104
  _MessageStream_aborted.set(this, false);
2105
2105
  _MessageStream_catchingPromiseCreated.set(this, false);
2106
2106
  _MessageStream_handleError.set(this, (error) => {
2107
- __classPrivateFieldSet$4(this, _MessageStream_errored, true, "f");
2107
+ __classPrivateFieldSet$6(this, _MessageStream_errored, true, "f");
2108
2108
  if (error instanceof Error && error.name === 'AbortError') {
2109
2109
  error = new APIUserAbortError$1();
2110
2110
  }
2111
2111
  if (error instanceof APIUserAbortError$1) {
2112
- __classPrivateFieldSet$4(this, _MessageStream_aborted, true, "f");
2112
+ __classPrivateFieldSet$6(this, _MessageStream_aborted, true, "f");
2113
2113
  return this._emit('abort', error);
2114
2114
  }
2115
2115
  if (error instanceof AnthropicError) {
@@ -2123,20 +2123,20 @@ class MessageStream {
2123
2123
  }
2124
2124
  return this._emit('error', new AnthropicError(String(error)));
2125
2125
  });
2126
- __classPrivateFieldSet$4(this, _MessageStream_connectedPromise, new Promise((resolve, reject) => {
2127
- __classPrivateFieldSet$4(this, _MessageStream_resolveConnectedPromise, resolve, "f");
2128
- __classPrivateFieldSet$4(this, _MessageStream_rejectConnectedPromise, reject, "f");
2126
+ __classPrivateFieldSet$6(this, _MessageStream_connectedPromise, new Promise((resolve, reject) => {
2127
+ __classPrivateFieldSet$6(this, _MessageStream_resolveConnectedPromise, resolve, "f");
2128
+ __classPrivateFieldSet$6(this, _MessageStream_rejectConnectedPromise, reject, "f");
2129
2129
  }), "f");
2130
- __classPrivateFieldSet$4(this, _MessageStream_endPromise, new Promise((resolve, reject) => {
2131
- __classPrivateFieldSet$4(this, _MessageStream_resolveEndPromise, resolve, "f");
2132
- __classPrivateFieldSet$4(this, _MessageStream_rejectEndPromise, reject, "f");
2130
+ __classPrivateFieldSet$6(this, _MessageStream_endPromise, new Promise((resolve, reject) => {
2131
+ __classPrivateFieldSet$6(this, _MessageStream_resolveEndPromise, resolve, "f");
2132
+ __classPrivateFieldSet$6(this, _MessageStream_rejectEndPromise, reject, "f");
2133
2133
  }), "f");
2134
2134
  // Don't let these promises cause unhandled rejection errors.
2135
2135
  // we will manually cause an unhandled rejection error later
2136
2136
  // if the user hasn't registered any error listener or called
2137
2137
  // any promise-returning method.
2138
- __classPrivateFieldGet$5(this, _MessageStream_connectedPromise, "f").catch(() => { });
2139
- __classPrivateFieldGet$5(this, _MessageStream_endPromise, "f").catch(() => { });
2138
+ __classPrivateFieldGet$7(this, _MessageStream_connectedPromise, "f").catch(() => { });
2139
+ __classPrivateFieldGet$7(this, _MessageStream_endPromise, "f").catch(() => { });
2140
2140
  }
2141
2141
  /**
2142
2142
  * Intended for use on the frontend, consuming a stream produced with
@@ -2162,7 +2162,7 @@ class MessageStream {
2162
2162
  executor().then(() => {
2163
2163
  this._emitFinal();
2164
2164
  this._emit('end');
2165
- }, __classPrivateFieldGet$5(this, _MessageStream_handleError, "f"));
2165
+ }, __classPrivateFieldGet$7(this, _MessageStream_handleError, "f"));
2166
2166
  }
2167
2167
  _addMessageParam(message) {
2168
2168
  this.messages.push(message);
@@ -2180,31 +2180,31 @@ class MessageStream {
2180
2180
  this.controller.abort();
2181
2181
  signal.addEventListener('abort', () => this.controller.abort());
2182
2182
  }
2183
- __classPrivateFieldGet$5(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this);
2183
+ __classPrivateFieldGet$7(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this);
2184
2184
  const stream = await messages.create({ ...params, stream: true }, { ...options, signal: this.controller.signal });
2185
2185
  this._connected();
2186
2186
  for await (const event of stream) {
2187
- __classPrivateFieldGet$5(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event);
2187
+ __classPrivateFieldGet$7(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event);
2188
2188
  }
2189
2189
  if (stream.controller.signal?.aborted) {
2190
2190
  throw new APIUserAbortError$1();
2191
2191
  }
2192
- __classPrivateFieldGet$5(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this);
2192
+ __classPrivateFieldGet$7(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this);
2193
2193
  }
2194
2194
  _connected() {
2195
2195
  if (this.ended)
2196
2196
  return;
2197
- __classPrivateFieldGet$5(this, _MessageStream_resolveConnectedPromise, "f").call(this);
2197
+ __classPrivateFieldGet$7(this, _MessageStream_resolveConnectedPromise, "f").call(this);
2198
2198
  this._emit('connect');
2199
2199
  }
2200
2200
  get ended() {
2201
- return __classPrivateFieldGet$5(this, _MessageStream_ended, "f");
2201
+ return __classPrivateFieldGet$7(this, _MessageStream_ended, "f");
2202
2202
  }
2203
2203
  get errored() {
2204
- return __classPrivateFieldGet$5(this, _MessageStream_errored, "f");
2204
+ return __classPrivateFieldGet$7(this, _MessageStream_errored, "f");
2205
2205
  }
2206
2206
  get aborted() {
2207
- return __classPrivateFieldGet$5(this, _MessageStream_aborted, "f");
2207
+ return __classPrivateFieldGet$7(this, _MessageStream_aborted, "f");
2208
2208
  }
2209
2209
  abort() {
2210
2210
  this.controller.abort();
@@ -2217,7 +2217,7 @@ class MessageStream {
2217
2217
  * @returns this MessageStream, so that calls can be chained
2218
2218
  */
2219
2219
  on(event, listener) {
2220
- const listeners = __classPrivateFieldGet$5(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet$5(this, _MessageStream_listeners, "f")[event] = []);
2220
+ const listeners = __classPrivateFieldGet$7(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet$7(this, _MessageStream_listeners, "f")[event] = []);
2221
2221
  listeners.push({ listener });
2222
2222
  return this;
2223
2223
  }
@@ -2229,7 +2229,7 @@ class MessageStream {
2229
2229
  * @returns this MessageStream, so that calls can be chained
2230
2230
  */
2231
2231
  off(event, listener) {
2232
- const listeners = __classPrivateFieldGet$5(this, _MessageStream_listeners, "f")[event];
2232
+ const listeners = __classPrivateFieldGet$7(this, _MessageStream_listeners, "f")[event];
2233
2233
  if (!listeners)
2234
2234
  return this;
2235
2235
  const index = listeners.findIndex((l) => l.listener === listener);
@@ -2243,7 +2243,7 @@ class MessageStream {
2243
2243
  * @returns this MessageStream, so that calls can be chained
2244
2244
  */
2245
2245
  once(event, listener) {
2246
- const listeners = __classPrivateFieldGet$5(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet$5(this, _MessageStream_listeners, "f")[event] = []);
2246
+ const listeners = __classPrivateFieldGet$7(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet$7(this, _MessageStream_listeners, "f")[event] = []);
2247
2247
  listeners.push({ listener, once: true });
2248
2248
  return this;
2249
2249
  }
@@ -2260,18 +2260,18 @@ class MessageStream {
2260
2260
  */
2261
2261
  emitted(event) {
2262
2262
  return new Promise((resolve, reject) => {
2263
- __classPrivateFieldSet$4(this, _MessageStream_catchingPromiseCreated, true, "f");
2263
+ __classPrivateFieldSet$6(this, _MessageStream_catchingPromiseCreated, true, "f");
2264
2264
  if (event !== 'error')
2265
2265
  this.once('error', reject);
2266
2266
  this.once(event, resolve);
2267
2267
  });
2268
2268
  }
2269
2269
  async done() {
2270
- __classPrivateFieldSet$4(this, _MessageStream_catchingPromiseCreated, true, "f");
2271
- await __classPrivateFieldGet$5(this, _MessageStream_endPromise, "f");
2270
+ __classPrivateFieldSet$6(this, _MessageStream_catchingPromiseCreated, true, "f");
2271
+ await __classPrivateFieldGet$7(this, _MessageStream_endPromise, "f");
2272
2272
  }
2273
2273
  get currentMessage() {
2274
- return __classPrivateFieldGet$5(this, _MessageStream_currentMessageSnapshot, "f");
2274
+ return __classPrivateFieldGet$7(this, _MessageStream_currentMessageSnapshot, "f");
2275
2275
  }
2276
2276
  /**
2277
2277
  * @returns a promise that resolves with the the final assistant Message response,
@@ -2279,7 +2279,7 @@ class MessageStream {
2279
2279
  */
2280
2280
  async finalMessage() {
2281
2281
  await this.done();
2282
- return __classPrivateFieldGet$5(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this);
2282
+ return __classPrivateFieldGet$7(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this);
2283
2283
  }
2284
2284
  /**
2285
2285
  * @returns a promise that resolves with the the final assistant Message's text response, concatenated
@@ -2288,35 +2288,35 @@ class MessageStream {
2288
2288
  */
2289
2289
  async finalText() {
2290
2290
  await this.done();
2291
- return __classPrivateFieldGet$5(this, _MessageStream_instances, "m", _MessageStream_getFinalText).call(this);
2291
+ return __classPrivateFieldGet$7(this, _MessageStream_instances, "m", _MessageStream_getFinalText).call(this);
2292
2292
  }
2293
2293
  _emit(event, ...args) {
2294
2294
  // make sure we don't emit any MessageStreamEvents after end
2295
- if (__classPrivateFieldGet$5(this, _MessageStream_ended, "f"))
2295
+ if (__classPrivateFieldGet$7(this, _MessageStream_ended, "f"))
2296
2296
  return;
2297
2297
  if (event === 'end') {
2298
- __classPrivateFieldSet$4(this, _MessageStream_ended, true, "f");
2299
- __classPrivateFieldGet$5(this, _MessageStream_resolveEndPromise, "f").call(this);
2298
+ __classPrivateFieldSet$6(this, _MessageStream_ended, true, "f");
2299
+ __classPrivateFieldGet$7(this, _MessageStream_resolveEndPromise, "f").call(this);
2300
2300
  }
2301
- const listeners = __classPrivateFieldGet$5(this, _MessageStream_listeners, "f")[event];
2301
+ const listeners = __classPrivateFieldGet$7(this, _MessageStream_listeners, "f")[event];
2302
2302
  if (listeners) {
2303
- __classPrivateFieldGet$5(this, _MessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once);
2303
+ __classPrivateFieldGet$7(this, _MessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once);
2304
2304
  listeners.forEach(({ listener }) => listener(...args));
2305
2305
  }
2306
2306
  if (event === 'abort') {
2307
2307
  const error = args[0];
2308
- if (!__classPrivateFieldGet$5(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
2308
+ if (!__classPrivateFieldGet$7(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
2309
2309
  Promise.reject(error);
2310
2310
  }
2311
- __classPrivateFieldGet$5(this, _MessageStream_rejectConnectedPromise, "f").call(this, error);
2312
- __classPrivateFieldGet$5(this, _MessageStream_rejectEndPromise, "f").call(this, error);
2311
+ __classPrivateFieldGet$7(this, _MessageStream_rejectConnectedPromise, "f").call(this, error);
2312
+ __classPrivateFieldGet$7(this, _MessageStream_rejectEndPromise, "f").call(this, error);
2313
2313
  this._emit('end');
2314
2314
  return;
2315
2315
  }
2316
2316
  if (event === 'error') {
2317
2317
  // NOTE: _emit('error', error) should only be called from #handleError().
2318
2318
  const error = args[0];
2319
- if (!__classPrivateFieldGet$5(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
2319
+ if (!__classPrivateFieldGet$7(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
2320
2320
  // Trigger an unhandled rejection if the user hasn't registered any error handlers.
2321
2321
  // If you are seeing stack traces here, make sure to handle errors via either:
2322
2322
  // - runner.on('error', () => ...)
@@ -2325,15 +2325,15 @@ class MessageStream {
2325
2325
  // - etc.
2326
2326
  Promise.reject(error);
2327
2327
  }
2328
- __classPrivateFieldGet$5(this, _MessageStream_rejectConnectedPromise, "f").call(this, error);
2329
- __classPrivateFieldGet$5(this, _MessageStream_rejectEndPromise, "f").call(this, error);
2328
+ __classPrivateFieldGet$7(this, _MessageStream_rejectConnectedPromise, "f").call(this, error);
2329
+ __classPrivateFieldGet$7(this, _MessageStream_rejectEndPromise, "f").call(this, error);
2330
2330
  this._emit('end');
2331
2331
  }
2332
2332
  }
2333
2333
  _emitFinal() {
2334
2334
  const finalMessage = this.receivedMessages.at(-1);
2335
2335
  if (finalMessage) {
2336
- this._emit('finalMessage', __classPrivateFieldGet$5(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this));
2336
+ this._emit('finalMessage', __classPrivateFieldGet$7(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this));
2337
2337
  }
2338
2338
  }
2339
2339
  async _fromReadableStream(readableStream, options) {
@@ -2343,16 +2343,16 @@ class MessageStream {
2343
2343
  this.controller.abort();
2344
2344
  signal.addEventListener('abort', () => this.controller.abort());
2345
2345
  }
2346
- __classPrivateFieldGet$5(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this);
2346
+ __classPrivateFieldGet$7(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this);
2347
2347
  this._connected();
2348
2348
  const stream = Stream$1.fromReadableStream(readableStream, this.controller);
2349
2349
  for await (const event of stream) {
2350
- __classPrivateFieldGet$5(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event);
2350
+ __classPrivateFieldGet$7(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event);
2351
2351
  }
2352
2352
  if (stream.controller.signal?.aborted) {
2353
2353
  throw new APIUserAbortError$1();
2354
2354
  }
2355
- __classPrivateFieldGet$5(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this);
2355
+ __classPrivateFieldGet$7(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this);
2356
2356
  }
2357
2357
  [(_MessageStream_currentMessageSnapshot = new WeakMap(), _MessageStream_connectedPromise = new WeakMap(), _MessageStream_resolveConnectedPromise = new WeakMap(), _MessageStream_rejectConnectedPromise = new WeakMap(), _MessageStream_endPromise = new WeakMap(), _MessageStream_resolveEndPromise = new WeakMap(), _MessageStream_rejectEndPromise = new WeakMap(), _MessageStream_listeners = new WeakMap(), _MessageStream_ended = new WeakMap(), _MessageStream_errored = new WeakMap(), _MessageStream_aborted = new WeakMap(), _MessageStream_catchingPromiseCreated = new WeakMap(), _MessageStream_handleError = new WeakMap(), _MessageStream_instances = new WeakSet(), _MessageStream_getFinalMessage = function _MessageStream_getFinalMessage() {
2358
2358
  if (this.receivedMessages.length === 0) {
@@ -2374,11 +2374,11 @@ class MessageStream {
2374
2374
  }, _MessageStream_beginRequest = function _MessageStream_beginRequest() {
2375
2375
  if (this.ended)
2376
2376
  return;
2377
- __classPrivateFieldSet$4(this, _MessageStream_currentMessageSnapshot, undefined, "f");
2377
+ __classPrivateFieldSet$6(this, _MessageStream_currentMessageSnapshot, undefined, "f");
2378
2378
  }, _MessageStream_addStreamEvent = function _MessageStream_addStreamEvent(event) {
2379
2379
  if (this.ended)
2380
2380
  return;
2381
- const messageSnapshot = __classPrivateFieldGet$5(this, _MessageStream_instances, "m", _MessageStream_accumulateMessage).call(this, event);
2381
+ const messageSnapshot = __classPrivateFieldGet$7(this, _MessageStream_instances, "m", _MessageStream_accumulateMessage).call(this, event);
2382
2382
  this._emit('streamEvent', event, messageSnapshot);
2383
2383
  switch (event.type) {
2384
2384
  case 'content_block_delta': {
@@ -2403,7 +2403,7 @@ class MessageStream {
2403
2403
  break;
2404
2404
  }
2405
2405
  case 'message_start': {
2406
- __classPrivateFieldSet$4(this, _MessageStream_currentMessageSnapshot, messageSnapshot, "f");
2406
+ __classPrivateFieldSet$6(this, _MessageStream_currentMessageSnapshot, messageSnapshot, "f");
2407
2407
  break;
2408
2408
  }
2409
2409
  }
@@ -2411,14 +2411,14 @@ class MessageStream {
2411
2411
  if (this.ended) {
2412
2412
  throw new AnthropicError(`stream has ended, this shouldn't happen`);
2413
2413
  }
2414
- const snapshot = __classPrivateFieldGet$5(this, _MessageStream_currentMessageSnapshot, "f");
2414
+ const snapshot = __classPrivateFieldGet$7(this, _MessageStream_currentMessageSnapshot, "f");
2415
2415
  if (!snapshot) {
2416
2416
  throw new AnthropicError(`request ended without sending any chunks`);
2417
2417
  }
2418
- __classPrivateFieldSet$4(this, _MessageStream_currentMessageSnapshot, undefined, "f");
2418
+ __classPrivateFieldSet$6(this, _MessageStream_currentMessageSnapshot, undefined, "f");
2419
2419
  return snapshot;
2420
2420
  }, _MessageStream_accumulateMessage = function _MessageStream_accumulateMessage(event) {
2421
- let snapshot = __classPrivateFieldGet$5(this, _MessageStream_currentMessageSnapshot, "f");
2421
+ let snapshot = __classPrivateFieldGet$7(this, _MessageStream_currentMessageSnapshot, "f");
2422
2422
  if (event.type === 'message_start') {
2423
2423
  if (snapshot) {
2424
2424
  throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`);
@@ -2522,7 +2522,7 @@ class MessageStream {
2522
2522
  }
2523
2523
 
2524
2524
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2525
- let Messages$1 = class Messages extends APIResource$1 {
2525
+ let Messages$2 = class Messages extends APIResource$1 {
2526
2526
  constructor() {
2527
2527
  super(...arguments);
2528
2528
  this.batches = new Batches$1(this._client);
@@ -2561,8 +2561,8 @@ const DEPRECATED_MODELS = {
2561
2561
  'claude-instant-1.1-100k': 'November 6th, 2024',
2562
2562
  'claude-instant-1.2': 'November 6th, 2024',
2563
2563
  };
2564
- Messages$1.Batches = Batches$1;
2565
- Messages$1.MessageBatchesPage = MessageBatchesPage;
2564
+ Messages$2.Batches = Batches$1;
2565
+ Messages$2.MessageBatchesPage = MessageBatchesPage;
2566
2566
 
2567
2567
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2568
2568
  let Models$1 = class Models extends APIResource$1 {
@@ -2624,7 +2624,7 @@ class Anthropic extends APIClient$1 {
2624
2624
  fetch: options.fetch,
2625
2625
  });
2626
2626
  this.completions = new Completions$3(this);
2627
- this.messages = new Messages$1(this);
2627
+ this.messages = new Messages$2(this);
2628
2628
  this.models = new Models$1(this);
2629
2629
  this.beta = new Beta$1(this);
2630
2630
  this._options = options;
@@ -2704,10 +2704,11 @@ Anthropic.UnprocessableEntityError = UnprocessableEntityError$1;
2704
2704
  Anthropic.toFile = toFile$1;
2705
2705
  Anthropic.fileFromPath = fileFromPath$1;
2706
2706
  Anthropic.Completions = Completions$3;
2707
- Anthropic.Messages = Messages$1;
2707
+ Anthropic.Messages = Messages$2;
2708
2708
  Anthropic.Models = Models$1;
2709
2709
  Anthropic.ModelInfosPage = ModelInfosPage;
2710
2710
  Anthropic.Beta = Beta$1;
2711
+ const { HUMAN_PROMPT, AI_PROMPT } = Anthropic;
2711
2712
 
2712
2713
  const prettyLogStyles = {
2713
2714
  reset: [0, 0],
@@ -3633,7 +3634,7 @@ function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, al
3633
3634
  let tmp_sc = sideChannel;
3634
3635
  let step = 0;
3635
3636
  let find_flag = false;
3636
- while ((tmp_sc = tmp_sc.get(sentinel)) !== void undefined && !find_flag) {
3637
+ while ((tmp_sc = tmp_sc.get(sentinel)) !== void 0 && !find_flag) {
3637
3638
  // Where object last appeared in the ref tree
3638
3639
  const pos = tmp_sc.get(object);
3639
3640
  step += 1;
@@ -3697,7 +3698,7 @@ function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, al
3697
3698
  // @ts-expect-error values only
3698
3699
  obj = maybe_map(obj, encoder);
3699
3700
  }
3700
- obj_keys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }];
3701
+ obj_keys = [{ value: obj.length > 0 ? obj.join(',') || null : void 0 }];
3701
3702
  }
3702
3703
  else if (is_array(filter)) {
3703
3704
  obj_keys = filter;
@@ -3853,7 +3854,7 @@ function stringify(object, opts = {}) {
3853
3854
  return joined.length > 0 ? prefix + joined : '';
3854
3855
  }
3855
3856
 
3856
- const VERSION = '4.77.0'; // x-release-please-version
3857
+ const VERSION = '4.87.3'; // x-release-please-version
3857
3858
 
3858
3859
  let auto = false;
3859
3860
  let kind = undefined;
@@ -4082,6 +4083,18 @@ class ContentFilterFinishReasonError extends OpenAIError {
4082
4083
  }
4083
4084
  }
4084
4085
 
4086
+ var __classPrivateFieldSet$5 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
4087
+ if (kind === "m") throw new TypeError("Private method is not writable");
4088
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4089
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
4090
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
4091
+ };
4092
+ var __classPrivateFieldGet$6 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
4093
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
4094
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
4095
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
4096
+ };
4097
+ var _LineDecoder_carriageReturnIndex;
4085
4098
  /**
4086
4099
  * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally
4087
4100
  * reading lines from text.
@@ -4090,39 +4103,42 @@ class ContentFilterFinishReasonError extends OpenAIError {
4090
4103
  */
4091
4104
  class LineDecoder {
4092
4105
  constructor() {
4093
- this.buffer = [];
4094
- this.trailingCR = false;
4106
+ _LineDecoder_carriageReturnIndex.set(this, void 0);
4107
+ this.buffer = new Uint8Array();
4108
+ __classPrivateFieldSet$5(this, _LineDecoder_carriageReturnIndex, null, "f");
4095
4109
  }
4096
4110
  decode(chunk) {
4097
- let text = this.decodeText(chunk);
4098
- if (this.trailingCR) {
4099
- text = '\r' + text;
4100
- this.trailingCR = false;
4101
- }
4102
- if (text.endsWith('\r')) {
4103
- this.trailingCR = true;
4104
- text = text.slice(0, -1);
4105
- }
4106
- if (!text) {
4107
- return [];
4108
- }
4109
- const trailingNewline = LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || '');
4110
- let lines = text.split(LineDecoder.NEWLINE_REGEXP);
4111
- // if there is a trailing new line then the last entry will be an empty
4112
- // string which we don't care about
4113
- if (trailingNewline) {
4114
- lines.pop();
4115
- }
4116
- if (lines.length === 1 && !trailingNewline) {
4117
- this.buffer.push(lines[0]);
4111
+ if (chunk == null) {
4118
4112
  return [];
4119
4113
  }
4120
- if (this.buffer.length > 0) {
4121
- lines = [this.buffer.join('') + lines[0], ...lines.slice(1)];
4122
- this.buffer = [];
4123
- }
4124
- if (!trailingNewline) {
4125
- this.buffer = [lines.pop() || ''];
4114
+ const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)
4115
+ : typeof chunk === 'string' ? new TextEncoder().encode(chunk)
4116
+ : chunk;
4117
+ let newData = new Uint8Array(this.buffer.length + binaryChunk.length);
4118
+ newData.set(this.buffer);
4119
+ newData.set(binaryChunk, this.buffer.length);
4120
+ this.buffer = newData;
4121
+ const lines = [];
4122
+ let patternIndex;
4123
+ while ((patternIndex = findNewlineIndex(this.buffer, __classPrivateFieldGet$6(this, _LineDecoder_carriageReturnIndex, "f"))) != null) {
4124
+ if (patternIndex.carriage && __classPrivateFieldGet$6(this, _LineDecoder_carriageReturnIndex, "f") == null) {
4125
+ // skip until we either get a corresponding `\n`, a new `\r` or nothing
4126
+ __classPrivateFieldSet$5(this, _LineDecoder_carriageReturnIndex, patternIndex.index, "f");
4127
+ continue;
4128
+ }
4129
+ // we got double \r or \rtext\n
4130
+ if (__classPrivateFieldGet$6(this, _LineDecoder_carriageReturnIndex, "f") != null &&
4131
+ (patternIndex.index !== __classPrivateFieldGet$6(this, _LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) {
4132
+ lines.push(this.decodeText(this.buffer.slice(0, __classPrivateFieldGet$6(this, _LineDecoder_carriageReturnIndex, "f") - 1)));
4133
+ this.buffer = this.buffer.slice(__classPrivateFieldGet$6(this, _LineDecoder_carriageReturnIndex, "f"));
4134
+ __classPrivateFieldSet$5(this, _LineDecoder_carriageReturnIndex, null, "f");
4135
+ continue;
4136
+ }
4137
+ const endIndex = __classPrivateFieldGet$6(this, _LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding;
4138
+ const line = this.decodeText(this.buffer.slice(0, endIndex));
4139
+ lines.push(line);
4140
+ this.buffer = this.buffer.slice(patternIndex.index);
4141
+ __classPrivateFieldSet$5(this, _LineDecoder_carriageReturnIndex, null, "f");
4126
4142
  }
4127
4143
  return lines;
4128
4144
  }
@@ -4152,18 +4168,99 @@ class LineDecoder {
4152
4168
  throw new OpenAIError(`Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`);
4153
4169
  }
4154
4170
  flush() {
4155
- if (!this.buffer.length && !this.trailingCR) {
4171
+ if (!this.buffer.length) {
4156
4172
  return [];
4157
4173
  }
4158
- const lines = [this.buffer.join('')];
4159
- this.buffer = [];
4160
- this.trailingCR = false;
4161
- return lines;
4174
+ return this.decode('\n');
4162
4175
  }
4163
4176
  }
4177
+ _LineDecoder_carriageReturnIndex = new WeakMap();
4164
4178
  // prettier-ignore
4165
4179
  LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r']);
4166
4180
  LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
4181
+ /**
4182
+ * This function searches the buffer for the end patterns, (\r or \n)
4183
+ * and returns an object with the index preceding the matched newline and the
4184
+ * index after the newline char. `null` is returned if no new line is found.
4185
+ *
4186
+ * ```ts
4187
+ * findNewLineIndex('abc\ndef') -> { preceding: 2, index: 3 }
4188
+ * ```
4189
+ */
4190
+ function findNewlineIndex(buffer, startIndex) {
4191
+ const newline = 0x0a; // \n
4192
+ const carriage = 0x0d; // \r
4193
+ for (let i = startIndex ?? 0; i < buffer.length; i++) {
4194
+ if (buffer[i] === newline) {
4195
+ return { preceding: i, index: i + 1, carriage: false };
4196
+ }
4197
+ if (buffer[i] === carriage) {
4198
+ return { preceding: i, index: i + 1, carriage: true };
4199
+ }
4200
+ }
4201
+ return null;
4202
+ }
4203
+ function findDoubleNewlineIndex(buffer) {
4204
+ // This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n)
4205
+ // and returns the index right after the first occurrence of any pattern,
4206
+ // or -1 if none of the patterns are found.
4207
+ const newline = 0x0a; // \n
4208
+ const carriage = 0x0d; // \r
4209
+ for (let i = 0; i < buffer.length - 1; i++) {
4210
+ if (buffer[i] === newline && buffer[i + 1] === newline) {
4211
+ // \n\n
4212
+ return i + 2;
4213
+ }
4214
+ if (buffer[i] === carriage && buffer[i + 1] === carriage) {
4215
+ // \r\r
4216
+ return i + 2;
4217
+ }
4218
+ if (buffer[i] === carriage &&
4219
+ buffer[i + 1] === newline &&
4220
+ i + 3 < buffer.length &&
4221
+ buffer[i + 2] === carriage &&
4222
+ buffer[i + 3] === newline) {
4223
+ // \r\n\r\n
4224
+ return i + 4;
4225
+ }
4226
+ }
4227
+ return -1;
4228
+ }
4229
+
4230
+ /**
4231
+ * Most browsers don't yet have async iterable support for ReadableStream,
4232
+ * and Node has a very different way of reading bytes from its "ReadableStream".
4233
+ *
4234
+ * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490
4235
+ */
4236
+ function ReadableStreamToAsyncIterable(stream) {
4237
+ if (stream[Symbol.asyncIterator])
4238
+ return stream;
4239
+ const reader = stream.getReader();
4240
+ return {
4241
+ async next() {
4242
+ try {
4243
+ const result = await reader.read();
4244
+ if (result?.done)
4245
+ reader.releaseLock(); // release lock when stream becomes closed
4246
+ return result;
4247
+ }
4248
+ catch (e) {
4249
+ reader.releaseLock(); // release lock when stream becomes errored
4250
+ throw e;
4251
+ }
4252
+ },
4253
+ async return() {
4254
+ const cancelPromise = reader.cancel();
4255
+ reader.releaseLock();
4256
+ await cancelPromise;
4257
+ return { done: true, value: undefined };
4258
+ },
4259
+ [Symbol.asyncIterator]() {
4260
+ return this;
4261
+ },
4262
+ };
4263
+ }
4167
4264
 
4168
4265
  class Stream {
4169
4266
  constructor(iterator, controller) {
@@ -4186,7 +4283,7 @@ class Stream {
4186
4283
  done = true;
4187
4284
  continue;
4188
4285
  }
4189
- if (sse.event === null) {
4286
+ if (sse.event === null || sse.event.startsWith('response.')) {
4190
4287
  let data;
4191
4288
  try {
4192
4289
  data = JSON.parse(sse.data);
@@ -4242,7 +4339,7 @@ class Stream {
4242
4339
  let consumed = false;
4243
4340
  async function* iterLines() {
4244
4341
  const lineDecoder = new LineDecoder();
4245
- const iter = readableStreamAsyncIterable(readableStream);
4342
+ const iter = ReadableStreamToAsyncIterable(readableStream);
4246
4343
  for await (const chunk of iter) {
4247
4344
  for (const line of lineDecoder.decode(chunk)) {
4248
4345
  yield line;
@@ -4347,7 +4444,7 @@ async function* _iterSSEMessages(response, controller) {
4347
4444
  }
4348
4445
  const sseDecoder = new SSEDecoder();
4349
4446
  const lineDecoder = new LineDecoder();
4350
- const iter = readableStreamAsyncIterable(response.body);
4447
+ const iter = ReadableStreamToAsyncIterable(response.body);
4351
4448
  for await (const sseChunk of iterSSEChunks(iter)) {
4352
4449
  for (const line of lineDecoder.decode(sseChunk)) {
4353
4450
  const sse = sseDecoder.decode(line);
@@ -4388,32 +4485,6 @@ async function* iterSSEChunks(iterator) {
4388
4485
  yield data;
4389
4486
  }
4390
4487
  }
4391
- function findDoubleNewlineIndex(buffer) {
4392
- // This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n)
4393
- // and returns the index right after the first occurrence of any pattern,
4394
- // or -1 if none of the patterns are found.
4395
- const newline = 0x0a; // \n
4396
- const carriage = 0x0d; // \r
4397
- for (let i = 0; i < buffer.length - 2; i++) {
4398
- if (buffer[i] === newline && buffer[i + 1] === newline) {
4399
- // \n\n
4400
- return i + 2;
4401
- }
4402
- if (buffer[i] === carriage && buffer[i + 1] === carriage) {
4403
- // \r\r
4404
- return i + 2;
4405
- }
4406
- if (buffer[i] === carriage &&
4407
- buffer[i + 1] === newline &&
4408
- i + 3 < buffer.length &&
4409
- buffer[i + 2] === carriage &&
4410
- buffer[i + 3] === newline) {
4411
- // \r\n\r\n
4412
- return i + 4;
4413
- }
4414
- }
4415
- return -1;
4416
- }
4417
4488
  class SSEDecoder {
4418
4489
  constructor() {
4419
4490
  this.event = null;
@@ -4462,40 +4533,6 @@ function partition(str, delimiter) {
4462
4533
  }
4463
4534
  return [str, '', ''];
4464
4535
  }
4465
- /**
4466
- * Most browsers don't yet have async iterable support for ReadableStream,
4467
- * and Node has a very different way of reading bytes from its "ReadableStream".
4468
- *
4469
- * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490
4470
- */
4471
- function readableStreamAsyncIterable(stream) {
4472
- if (stream[Symbol.asyncIterator])
4473
- return stream;
4474
- const reader = stream.getReader();
4475
- return {
4476
- async next() {
4477
- try {
4478
- const result = await reader.read();
4479
- if (result?.done)
4480
- reader.releaseLock(); // release lock when stream becomes closed
4481
- return result;
4482
- }
4483
- catch (e) {
4484
- reader.releaseLock(); // release lock when stream becomes errored
4485
- throw e;
4486
- }
4487
- },
4488
- async return() {
4489
- const cancelPromise = reader.cancel();
4490
- reader.releaseLock();
4491
- await cancelPromise;
4492
- return { done: true, value: undefined };
4493
- },
4494
- [Symbol.asyncIterator]() {
4495
- return this;
4496
- },
4497
- };
4498
- }
4499
4536
 
4500
4537
  const isResponseLike = (value) => value != null &&
4501
4538
  typeof value === 'object' &&
@@ -4630,13 +4667,13 @@ const addFormValue = async (form, key, value) => {
4630
4667
  }
4631
4668
  };
4632
4669
 
4633
- var __classPrivateFieldSet$3 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
4670
+ var __classPrivateFieldSet$4 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
4634
4671
  if (kind === "m") throw new TypeError("Private method is not writable");
4635
4672
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4636
4673
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
4637
4674
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
4638
4675
  };
4639
- var __classPrivateFieldGet$4 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
4676
+ var __classPrivateFieldGet$5 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
4640
4677
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
4641
4678
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
4642
4679
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
@@ -4661,7 +4698,8 @@ async function defaultParseResponse(props) {
4661
4698
  return response;
4662
4699
  }
4663
4700
  const contentType = response.headers.get('content-type');
4664
- const isJSON = contentType?.includes('application/json') || contentType?.includes('application/vnd.api+json');
4701
+ const mediaType = contentType?.split(';')[0]?.trim();
4702
+ const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json');
4665
4703
  if (isJSON) {
4666
4704
  const json = await response.json();
4667
4705
  debug('response', response.status, response.url, response.headers, json);
@@ -4831,6 +4869,7 @@ class APIClient {
4831
4869
  return null;
4832
4870
  }
4833
4871
  buildRequest(options, { retryCount = 0 } = {}) {
4872
+ options = { ...options };
4834
4873
  const { method, path, query, headers: headers = {} } = options;
4835
4874
  const body = ArrayBuffer.isView(options.body) || (options.__binaryRequest && typeof options.body === 'string') ?
4836
4875
  options.body
@@ -4841,9 +4880,9 @@ class APIClient {
4841
4880
  const url = this.buildURL(path, query);
4842
4881
  if ('timeout' in options)
4843
4882
  validatePositiveInteger('timeout', options.timeout);
4844
- const timeout = options.timeout ?? this.timeout;
4883
+ options.timeout = options.timeout ?? this.timeout;
4845
4884
  const httpAgent = options.httpAgent ?? this.httpAgent ?? getDefaultAgent(url);
4846
- const minAgentTimeout = timeout + 1000;
4885
+ const minAgentTimeout = options.timeout + 1000;
4847
4886
  if (typeof httpAgent?.options?.timeout === 'number' &&
4848
4887
  minAgentTimeout > (httpAgent.options.timeout ?? 0)) {
4849
4888
  // Allow any given request to bump our agent active socket timeout.
@@ -4867,7 +4906,7 @@ class APIClient {
4867
4906
  // not compatible with standard web types
4868
4907
  signal: options.signal ?? null,
4869
4908
  };
4870
- return { req, url, timeout };
4909
+ return { req, url, timeout: options.timeout };
4871
4910
  }
4872
4911
  buildHeaders({ options, headers, contentLength, retryCount, }) {
4873
4912
  const reqHeaders = {};
@@ -4881,13 +4920,18 @@ class APIClient {
4881
4920
  if (isMultipartBody(options.body) && kind !== 'node') {
4882
4921
  delete reqHeaders['content-type'];
4883
4922
  }
4884
- // Don't set the retry count header if it was already set or removed through default headers or by the
4885
- // caller. We check `defaultHeaders` and `headers`, which can contain nulls, instead of `reqHeaders` to
4886
- // account for the removal case.
4923
+ // Don't set theses headers if they were already set or removed through default headers or by the caller.
4924
+ // We check `defaultHeaders` and `headers`, which can contain nulls, instead of `reqHeaders` to account
4925
+ // for the removal case.
4887
4926
  if (getHeader(defaultHeaders, 'x-stainless-retry-count') === undefined &&
4888
4927
  getHeader(headers, 'x-stainless-retry-count') === undefined) {
4889
4928
  reqHeaders['x-stainless-retry-count'] = String(retryCount);
4890
4929
  }
4930
+ if (getHeader(defaultHeaders, 'x-stainless-timeout') === undefined &&
4931
+ getHeader(headers, 'x-stainless-timeout') === undefined &&
4932
+ options.timeout) {
4933
+ reqHeaders['x-stainless-timeout'] = String(options.timeout);
4934
+ }
4891
4935
  this.validateHeaders(reqHeaders, headers);
4892
4936
  return reqHeaders;
4893
4937
  }
@@ -4994,9 +5038,18 @@ class APIClient {
4994
5038
  if (signal)
4995
5039
  signal.addEventListener('abort', () => controller.abort());
4996
5040
  const timeout = setTimeout(() => controller.abort(), ms);
5041
+ const fetchOptions = {
5042
+ signal: controller.signal,
5043
+ ...options,
5044
+ };
5045
+ if (fetchOptions.method) {
5046
+ // Custom methods like 'patch' need to be uppercased
5047
+ // See https://github.com/nodejs/undici/issues/2294
5048
+ fetchOptions.method = fetchOptions.method.toUpperCase();
5049
+ }
4997
5050
  return (
4998
5051
  // use undefined this binding; fetch errors if bound to something else in browser/cloudflare
4999
- this.fetch.call(undefined, url, { signal: controller.signal, ...options }).finally(() => {
5052
+ this.fetch.call(undefined, url, fetchOptions).finally(() => {
5000
5053
  clearTimeout(timeout);
5001
5054
  }));
5002
5055
  }
@@ -5069,7 +5122,7 @@ class APIClient {
5069
5122
  class AbstractPage {
5070
5123
  constructor(client, response, body, options) {
5071
5124
  _AbstractPage_client.set(this, void 0);
5072
- __classPrivateFieldSet$3(this, _AbstractPage_client, client, "f");
5125
+ __classPrivateFieldSet$4(this, _AbstractPage_client, client, "f");
5073
5126
  this.options = options;
5074
5127
  this.response = response;
5075
5128
  this.body = body;
@@ -5097,7 +5150,7 @@ class AbstractPage {
5097
5150
  nextOptions.query = undefined;
5098
5151
  nextOptions.path = nextInfo.url.toString();
5099
5152
  }
5100
- return await __classPrivateFieldGet$4(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
5153
+ return await __classPrivateFieldGet$5(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
5101
5154
  }
5102
5155
  async *iterPages() {
5103
5156
  // eslint-disable-next-line @typescript-eslint/no-this-alias
@@ -5168,6 +5221,7 @@ const requestOptionsKeys = {
5168
5221
  httpAgent: true,
5169
5222
  signal: true,
5170
5223
  idempotencyKey: true,
5224
+ __metadata: true,
5171
5225
  __binaryRequest: true,
5172
5226
  __binaryResponse: true,
5173
5227
  __streamClass: true,
@@ -5391,9 +5445,36 @@ function applyHeadersMut(targetHeaders, newHeaders) {
5391
5445
  }
5392
5446
  }
5393
5447
  }
5448
+ const SENSITIVE_HEADERS = new Set(['authorization', 'api-key']);
5394
5449
  function debug(action, ...args) {
5395
5450
  if (typeof process !== 'undefined' && process?.env?.['DEBUG'] === 'true') {
5396
- console.log(`OpenAI:DEBUG:${action}`, ...args);
5451
+ const modifiedArgs = args.map((arg) => {
5452
+ if (!arg) {
5453
+ return arg;
5454
+ }
5455
+ // Check for sensitive headers in request body 'headers' object
5456
+ if (arg['headers']) {
5457
+ // clone so we don't mutate
5458
+ const modifiedArg = { ...arg, headers: { ...arg['headers'] } };
5459
+ for (const header in arg['headers']) {
5460
+ if (SENSITIVE_HEADERS.has(header.toLowerCase())) {
5461
+ modifiedArg['headers'][header] = 'REDACTED';
5462
+ }
5463
+ }
5464
+ return modifiedArg;
5465
+ }
5466
+ let modifiedArg = null;
5467
+ // Check for sensitive headers in headers object
5468
+ for (const header in arg) {
5469
+ if (SENSITIVE_HEADERS.has(header.toLowerCase())) {
5470
+ // avoid making a copy until we need to
5471
+ modifiedArg ?? (modifiedArg = { ...arg });
5472
+ modifiedArg[header] = 'REDACTED';
5473
+ }
5474
+ }
5475
+ return modifiedArg ?? arg;
5476
+ });
5477
+ console.log(`OpenAI:DEBUG:${action}`, ...modifiedArgs);
5397
5478
  }
5398
5479
  }
5399
5480
  /**
@@ -5477,10 +5558,17 @@ class CursorPage extends AbstractPage {
5477
5558
  constructor(client, response, body, options) {
5478
5559
  super(client, response, body, options);
5479
5560
  this.data = body.data || [];
5561
+ this.has_more = body.has_more || false;
5480
5562
  }
5481
5563
  getPaginatedItems() {
5482
5564
  return this.data ?? [];
5483
5565
  }
5566
+ hasNextPage() {
5567
+ if (this.has_more === false) {
5568
+ return false;
5569
+ }
5570
+ return super.hasNextPage();
5571
+ }
5484
5572
  // @deprecated Please use `nextPageInfo()` instead
5485
5573
  nextPageParams() {
5486
5574
  const info = this.nextPageInfo();
@@ -5513,12 +5601,60 @@ class APIResource {
5513
5601
  }
5514
5602
  }
5515
5603
 
5604
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
5605
+ let Messages$1 = class Messages extends APIResource {
5606
+ list(completionId, query = {}, options) {
5607
+ if (isRequestOptions(query)) {
5608
+ return this.list(completionId, {}, query);
5609
+ }
5610
+ return this._client.getAPIList(`/chat/completions/${completionId}/messages`, ChatCompletionStoreMessagesPage, { query, ...options });
5611
+ }
5612
+ };
5613
+
5516
5614
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
5517
5615
  let Completions$2 = class Completions extends APIResource {
5616
+ constructor() {
5617
+ super(...arguments);
5618
+ this.messages = new Messages$1(this._client);
5619
+ }
5518
5620
  create(body, options) {
5519
5621
  return this._client.post('/chat/completions', { body, ...options, stream: body.stream ?? false });
5520
5622
  }
5623
+ /**
5624
+ * Get a stored chat completion. Only Chat Completions that have been created with
5625
+ * the `store` parameter set to `true` will be returned.
5626
+ */
5627
+ retrieve(completionId, options) {
5628
+ return this._client.get(`/chat/completions/${completionId}`, options);
5629
+ }
5630
+ /**
5631
+ * Modify a stored chat completion. Only Chat Completions that have been created
5632
+ * with the `store` parameter set to `true` can be modified. Currently, the only
5633
+ * supported modification is to update the `metadata` field.
5634
+ */
5635
+ update(completionId, body, options) {
5636
+ return this._client.post(`/chat/completions/${completionId}`, { body, ...options });
5637
+ }
5638
+ list(query = {}, options) {
5639
+ if (isRequestOptions(query)) {
5640
+ return this.list({}, query);
5641
+ }
5642
+ return this._client.getAPIList('/chat/completions', ChatCompletionsPage, { query, ...options });
5643
+ }
5644
+ /**
5645
+ * Delete a stored chat completion. Only Chat Completions that have been created
5646
+ * with the `store` parameter set to `true` can be deleted.
5647
+ */
5648
+ del(completionId, options) {
5649
+ return this._client.delete(`/chat/completions/${completionId}`, options);
5650
+ }
5521
5651
  };
5652
+ class ChatCompletionsPage extends CursorPage {
5653
+ }
5654
+ class ChatCompletionStoreMessagesPage extends CursorPage {
5655
+ }
5656
+ Completions$2.ChatCompletionsPage = ChatCompletionsPage;
5657
+ Completions$2.Messages = Messages$1;
5522
5658
 
5523
5659
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
5524
5660
  let Chat$1 = class Chat extends APIResource {
@@ -5528,6 +5664,7 @@ let Chat$1 = class Chat extends APIResource {
5528
5664
  }
5529
5665
  };
5530
5666
  Chat$1.Completions = Completions$2;
5667
+ Chat$1.ChatCompletionsPage = ChatCompletionsPage;
5531
5668
 
5532
5669
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
5533
5670
  class Speech extends APIResource {
@@ -5535,21 +5672,26 @@ class Speech extends APIResource {
5535
5672
  * Generates audio from the input text.
5536
5673
  */
5537
5674
  create(body, options) {
5538
- return this._client.post('/audio/speech', { body, ...options, __binaryResponse: true });
5675
+ return this._client.post('/audio/speech', {
5676
+ body,
5677
+ ...options,
5678
+ headers: { Accept: 'application/octet-stream', ...options?.headers },
5679
+ __binaryResponse: true,
5680
+ });
5539
5681
  }
5540
5682
  }
5541
5683
 
5542
5684
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
5543
5685
  class Transcriptions extends APIResource {
5544
5686
  create(body, options) {
5545
- return this._client.post('/audio/transcriptions', multipartFormRequestOptions({ body, ...options }));
5687
+ return this._client.post('/audio/transcriptions', multipartFormRequestOptions({ body, ...options, __metadata: { model: body.model } }));
5546
5688
  }
5547
5689
  }
5548
5690
 
5549
5691
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
5550
5692
  class Translations extends APIResource {
5551
5693
  create(body, options) {
5552
- return this._client.post('/audio/translations', multipartFormRequestOptions({ body, ...options }));
5694
+ return this._client.post('/audio/translations', multipartFormRequestOptions({ body, ...options, __metadata: { model: body.model } }));
5553
5695
  }
5554
5696
  }
5555
5697
 
@@ -5668,13 +5810,13 @@ const isToolMessage = (message) => {
5668
5810
  return message?.role === 'tool';
5669
5811
  };
5670
5812
 
5671
- var __classPrivateFieldSet$2 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
5813
+ var __classPrivateFieldSet$3 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
5672
5814
  if (kind === "m") throw new TypeError("Private method is not writable");
5673
5815
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5674
5816
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5675
5817
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
5676
5818
  };
5677
- var __classPrivateFieldGet$3 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
5819
+ var __classPrivateFieldGet$4 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
5678
5820
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
5679
5821
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
5680
5822
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
@@ -5695,20 +5837,20 @@ class EventStream {
5695
5837
  _EventStream_errored.set(this, false);
5696
5838
  _EventStream_aborted.set(this, false);
5697
5839
  _EventStream_catchingPromiseCreated.set(this, false);
5698
- __classPrivateFieldSet$2(this, _EventStream_connectedPromise, new Promise((resolve, reject) => {
5699
- __classPrivateFieldSet$2(this, _EventStream_resolveConnectedPromise, resolve, "f");
5700
- __classPrivateFieldSet$2(this, _EventStream_rejectConnectedPromise, reject, "f");
5840
+ __classPrivateFieldSet$3(this, _EventStream_connectedPromise, new Promise((resolve, reject) => {
5841
+ __classPrivateFieldSet$3(this, _EventStream_resolveConnectedPromise, resolve, "f");
5842
+ __classPrivateFieldSet$3(this, _EventStream_rejectConnectedPromise, reject, "f");
5701
5843
  }), "f");
5702
- __classPrivateFieldSet$2(this, _EventStream_endPromise, new Promise((resolve, reject) => {
5703
- __classPrivateFieldSet$2(this, _EventStream_resolveEndPromise, resolve, "f");
5704
- __classPrivateFieldSet$2(this, _EventStream_rejectEndPromise, reject, "f");
5844
+ __classPrivateFieldSet$3(this, _EventStream_endPromise, new Promise((resolve, reject) => {
5845
+ __classPrivateFieldSet$3(this, _EventStream_resolveEndPromise, resolve, "f");
5846
+ __classPrivateFieldSet$3(this, _EventStream_rejectEndPromise, reject, "f");
5705
5847
  }), "f");
5706
5848
  // Don't let these promises cause unhandled rejection errors.
5707
5849
  // we will manually cause an unhandled rejection error later
5708
5850
  // if the user hasn't registered any error listener or called
5709
5851
  // any promise-returning method.
5710
- __classPrivateFieldGet$3(this, _EventStream_connectedPromise, "f").catch(() => { });
5711
- __classPrivateFieldGet$3(this, _EventStream_endPromise, "f").catch(() => { });
5852
+ __classPrivateFieldGet$4(this, _EventStream_connectedPromise, "f").catch(() => { });
5853
+ __classPrivateFieldGet$4(this, _EventStream_endPromise, "f").catch(() => { });
5712
5854
  }
5713
5855
  _run(executor) {
5714
5856
  // Unfortunately if we call `executor()` immediately we get runtime errors about
@@ -5717,23 +5859,23 @@ class EventStream {
5717
5859
  executor().then(() => {
5718
5860
  this._emitFinal();
5719
5861
  this._emit('end');
5720
- }, __classPrivateFieldGet$3(this, _EventStream_instances, "m", _EventStream_handleError).bind(this));
5862
+ }, __classPrivateFieldGet$4(this, _EventStream_instances, "m", _EventStream_handleError).bind(this));
5721
5863
  }, 0);
5722
5864
  }
5723
5865
  _connected() {
5724
5866
  if (this.ended)
5725
5867
  return;
5726
- __classPrivateFieldGet$3(this, _EventStream_resolveConnectedPromise, "f").call(this);
5868
+ __classPrivateFieldGet$4(this, _EventStream_resolveConnectedPromise, "f").call(this);
5727
5869
  this._emit('connect');
5728
5870
  }
5729
5871
  get ended() {
5730
- return __classPrivateFieldGet$3(this, _EventStream_ended, "f");
5872
+ return __classPrivateFieldGet$4(this, _EventStream_ended, "f");
5731
5873
  }
5732
5874
  get errored() {
5733
- return __classPrivateFieldGet$3(this, _EventStream_errored, "f");
5875
+ return __classPrivateFieldGet$4(this, _EventStream_errored, "f");
5734
5876
  }
5735
5877
  get aborted() {
5736
- return __classPrivateFieldGet$3(this, _EventStream_aborted, "f");
5878
+ return __classPrivateFieldGet$4(this, _EventStream_aborted, "f");
5737
5879
  }
5738
5880
  abort() {
5739
5881
  this.controller.abort();
@@ -5746,7 +5888,7 @@ class EventStream {
5746
5888
  * @returns this ChatCompletionStream, so that calls can be chained
5747
5889
  */
5748
5890
  on(event, listener) {
5749
- const listeners = __classPrivateFieldGet$3(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet$3(this, _EventStream_listeners, "f")[event] = []);
5891
+ const listeners = __classPrivateFieldGet$4(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet$4(this, _EventStream_listeners, "f")[event] = []);
5750
5892
  listeners.push({ listener });
5751
5893
  return this;
5752
5894
  }
@@ -5758,7 +5900,7 @@ class EventStream {
5758
5900
  * @returns this ChatCompletionStream, so that calls can be chained
5759
5901
  */
5760
5902
  off(event, listener) {
5761
- const listeners = __classPrivateFieldGet$3(this, _EventStream_listeners, "f")[event];
5903
+ const listeners = __classPrivateFieldGet$4(this, _EventStream_listeners, "f")[event];
5762
5904
  if (!listeners)
5763
5905
  return this;
5764
5906
  const index = listeners.findIndex((l) => l.listener === listener);
@@ -5772,7 +5914,7 @@ class EventStream {
5772
5914
  * @returns this ChatCompletionStream, so that calls can be chained
5773
5915
  */
5774
5916
  once(event, listener) {
5775
- const listeners = __classPrivateFieldGet$3(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet$3(this, _EventStream_listeners, "f")[event] = []);
5917
+ const listeners = __classPrivateFieldGet$4(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet$4(this, _EventStream_listeners, "f")[event] = []);
5776
5918
  listeners.push({ listener, once: true });
5777
5919
  return this;
5778
5920
  }
@@ -5789,44 +5931,44 @@ class EventStream {
5789
5931
  */
5790
5932
  emitted(event) {
5791
5933
  return new Promise((resolve, reject) => {
5792
- __classPrivateFieldSet$2(this, _EventStream_catchingPromiseCreated, true, "f");
5934
+ __classPrivateFieldSet$3(this, _EventStream_catchingPromiseCreated, true, "f");
5793
5935
  if (event !== 'error')
5794
5936
  this.once('error', reject);
5795
5937
  this.once(event, resolve);
5796
5938
  });
5797
5939
  }
5798
5940
  async done() {
5799
- __classPrivateFieldSet$2(this, _EventStream_catchingPromiseCreated, true, "f");
5800
- await __classPrivateFieldGet$3(this, _EventStream_endPromise, "f");
5941
+ __classPrivateFieldSet$3(this, _EventStream_catchingPromiseCreated, true, "f");
5942
+ await __classPrivateFieldGet$4(this, _EventStream_endPromise, "f");
5801
5943
  }
5802
5944
  _emit(event, ...args) {
5803
5945
  // make sure we don't emit any events after end
5804
- if (__classPrivateFieldGet$3(this, _EventStream_ended, "f")) {
5946
+ if (__classPrivateFieldGet$4(this, _EventStream_ended, "f")) {
5805
5947
  return;
5806
5948
  }
5807
5949
  if (event === 'end') {
5808
- __classPrivateFieldSet$2(this, _EventStream_ended, true, "f");
5809
- __classPrivateFieldGet$3(this, _EventStream_resolveEndPromise, "f").call(this);
5950
+ __classPrivateFieldSet$3(this, _EventStream_ended, true, "f");
5951
+ __classPrivateFieldGet$4(this, _EventStream_resolveEndPromise, "f").call(this);
5810
5952
  }
5811
- const listeners = __classPrivateFieldGet$3(this, _EventStream_listeners, "f")[event];
5953
+ const listeners = __classPrivateFieldGet$4(this, _EventStream_listeners, "f")[event];
5812
5954
  if (listeners) {
5813
- __classPrivateFieldGet$3(this, _EventStream_listeners, "f")[event] = listeners.filter((l) => !l.once);
5955
+ __classPrivateFieldGet$4(this, _EventStream_listeners, "f")[event] = listeners.filter((l) => !l.once);
5814
5956
  listeners.forEach(({ listener }) => listener(...args));
5815
5957
  }
5816
5958
  if (event === 'abort') {
5817
5959
  const error = args[0];
5818
- if (!__classPrivateFieldGet$3(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) {
5960
+ if (!__classPrivateFieldGet$4(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) {
5819
5961
  Promise.reject(error);
5820
5962
  }
5821
- __classPrivateFieldGet$3(this, _EventStream_rejectConnectedPromise, "f").call(this, error);
5822
- __classPrivateFieldGet$3(this, _EventStream_rejectEndPromise, "f").call(this, error);
5963
+ __classPrivateFieldGet$4(this, _EventStream_rejectConnectedPromise, "f").call(this, error);
5964
+ __classPrivateFieldGet$4(this, _EventStream_rejectEndPromise, "f").call(this, error);
5823
5965
  this._emit('end');
5824
5966
  return;
5825
5967
  }
5826
5968
  if (event === 'error') {
5827
5969
  // NOTE: _emit('error', error) should only be called from #handleError().
5828
5970
  const error = args[0];
5829
- if (!__classPrivateFieldGet$3(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) {
5971
+ if (!__classPrivateFieldGet$4(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) {
5830
5972
  // Trigger an unhandled rejection if the user hasn't registered any error handlers.
5831
5973
  // If you are seeing stack traces here, make sure to handle errors via either:
5832
5974
  // - runner.on('error', () => ...)
@@ -5835,20 +5977,20 @@ class EventStream {
5835
5977
  // - etc.
5836
5978
  Promise.reject(error);
5837
5979
  }
5838
- __classPrivateFieldGet$3(this, _EventStream_rejectConnectedPromise, "f").call(this, error);
5839
- __classPrivateFieldGet$3(this, _EventStream_rejectEndPromise, "f").call(this, error);
5980
+ __classPrivateFieldGet$4(this, _EventStream_rejectConnectedPromise, "f").call(this, error);
5981
+ __classPrivateFieldGet$4(this, _EventStream_rejectEndPromise, "f").call(this, error);
5840
5982
  this._emit('end');
5841
5983
  }
5842
5984
  }
5843
5985
  _emitFinal() { }
5844
5986
  }
5845
5987
  _EventStream_connectedPromise = new WeakMap(), _EventStream_resolveConnectedPromise = new WeakMap(), _EventStream_rejectConnectedPromise = new WeakMap(), _EventStream_endPromise = new WeakMap(), _EventStream_resolveEndPromise = new WeakMap(), _EventStream_rejectEndPromise = new WeakMap(), _EventStream_listeners = new WeakMap(), _EventStream_ended = new WeakMap(), _EventStream_errored = new WeakMap(), _EventStream_aborted = new WeakMap(), _EventStream_catchingPromiseCreated = new WeakMap(), _EventStream_instances = new WeakSet(), _EventStream_handleError = function _EventStream_handleError(error) {
5846
- __classPrivateFieldSet$2(this, _EventStream_errored, true, "f");
5988
+ __classPrivateFieldSet$3(this, _EventStream_errored, true, "f");
5847
5989
  if (error instanceof Error && error.name === 'AbortError') {
5848
5990
  error = new APIUserAbortError();
5849
5991
  }
5850
5992
  if (error instanceof APIUserAbortError) {
5851
- __classPrivateFieldSet$2(this, _EventStream_aborted, true, "f");
5993
+ __classPrivateFieldSet$3(this, _EventStream_aborted, true, "f");
5852
5994
  return this._emit('abort', error);
5853
5995
  }
5854
5996
  if (error instanceof OpenAIError) {
@@ -5866,16 +6008,24 @@ _EventStream_connectedPromise = new WeakMap(), _EventStream_resolveConnectedProm
5866
6008
  function isAutoParsableResponseFormat(response_format) {
5867
6009
  return response_format?.['$brand'] === 'auto-parseable-response-format';
5868
6010
  }
5869
- function isAutoParsableTool(tool) {
6011
+ function isAutoParsableTool$1(tool) {
5870
6012
  return tool?.['$brand'] === 'auto-parseable-tool';
5871
6013
  }
5872
6014
  function maybeParseChatCompletion(completion, params) {
5873
- if (!params || !hasAutoParseableInput(params)) {
6015
+ if (!params || !hasAutoParseableInput$1(params)) {
5874
6016
  return {
5875
6017
  ...completion,
5876
6018
  choices: completion.choices.map((choice) => ({
5877
6019
  ...choice,
5878
- message: { ...choice.message, parsed: null, tool_calls: choice.message.tool_calls ?? [] },
6020
+ message: {
6021
+ ...choice.message,
6022
+ parsed: null,
6023
+ ...(choice.message.tool_calls ?
6024
+ {
6025
+ tool_calls: choice.message.tool_calls,
6026
+ }
6027
+ : undefined),
6028
+ },
5879
6029
  })),
5880
6030
  };
5881
6031
  }
@@ -5893,7 +6043,11 @@ function parseChatCompletion(completion, params) {
5893
6043
  ...choice,
5894
6044
  message: {
5895
6045
  ...choice.message,
5896
- tool_calls: choice.message.tool_calls?.map((toolCall) => parseToolCall(params, toolCall)) ?? [],
6046
+ ...(choice.message.tool_calls ?
6047
+ {
6048
+ tool_calls: choice.message.tool_calls?.map((toolCall) => parseToolCall$1(params, toolCall)) ?? undefined,
6049
+ }
6050
+ : undefined),
5897
6051
  parsed: choice.message.content && !choice.message.refusal ?
5898
6052
  parseResponseFormat(params, choice.message.content)
5899
6053
  : null,
@@ -5915,13 +6069,13 @@ function parseResponseFormat(params, content) {
5915
6069
  }
5916
6070
  return null;
5917
6071
  }
5918
- function parseToolCall(params, toolCall) {
6072
+ function parseToolCall$1(params, toolCall) {
5919
6073
  const inputTool = params.tools?.find((inputTool) => inputTool.function?.name === toolCall.function.name);
5920
6074
  return {
5921
6075
  ...toolCall,
5922
6076
  function: {
5923
6077
  ...toolCall.function,
5924
- parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.function.arguments)
6078
+ parsed_arguments: isAutoParsableTool$1(inputTool) ? inputTool.$parseRaw(toolCall.function.arguments)
5925
6079
  : inputTool?.function.strict ? JSON.parse(toolCall.function.arguments)
5926
6080
  : null,
5927
6081
  },
@@ -5932,13 +6086,13 @@ function shouldParseToolCall(params, toolCall) {
5932
6086
  return false;
5933
6087
  }
5934
6088
  const inputTool = params.tools?.find((inputTool) => inputTool.function?.name === toolCall.function.name);
5935
- return isAutoParsableTool(inputTool) || inputTool?.function.strict || false;
6089
+ return isAutoParsableTool$1(inputTool) || inputTool?.function.strict || false;
5936
6090
  }
5937
- function hasAutoParseableInput(params) {
6091
+ function hasAutoParseableInput$1(params) {
5938
6092
  if (isAutoParsableResponseFormat(params.response_format)) {
5939
6093
  return true;
5940
6094
  }
5941
- return (params.tools?.some((t) => isAutoParsableTool(t) || (t.type === 'function' && t.function.strict === true)) ?? false);
6095
+ return (params.tools?.some((t) => isAutoParsableTool$1(t) || (t.type === 'function' && t.function.strict === true)) ?? false);
5942
6096
  }
5943
6097
  function validateInputTools(tools) {
5944
6098
  for (const tool of tools ?? []) {
@@ -5951,7 +6105,7 @@ function validateInputTools(tools) {
5951
6105
  }
5952
6106
  }
5953
6107
 
5954
- var __classPrivateFieldGet$2 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
6108
+ var __classPrivateFieldGet$3 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
5955
6109
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
5956
6110
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
5957
6111
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
@@ -6012,7 +6166,7 @@ class AbstractChatCompletionRunner extends EventStream {
6012
6166
  */
6013
6167
  async finalContent() {
6014
6168
  await this.done();
6015
- return __classPrivateFieldGet$2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this);
6169
+ return __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this);
6016
6170
  }
6017
6171
  /**
6018
6172
  * @returns a promise that resolves with the the final assistant ChatCompletionMessage response,
@@ -6020,7 +6174,7 @@ class AbstractChatCompletionRunner extends EventStream {
6020
6174
  */
6021
6175
  async finalMessage() {
6022
6176
  await this.done();
6023
- return __classPrivateFieldGet$2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this);
6177
+ return __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this);
6024
6178
  }
6025
6179
  /**
6026
6180
  * @returns a promise that resolves with the content of the final FunctionCall, or rejects
@@ -6028,15 +6182,15 @@ class AbstractChatCompletionRunner extends EventStream {
6028
6182
  */
6029
6183
  async finalFunctionCall() {
6030
6184
  await this.done();
6031
- return __classPrivateFieldGet$2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this);
6185
+ return __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this);
6032
6186
  }
6033
6187
  async finalFunctionCallResult() {
6034
6188
  await this.done();
6035
- return __classPrivateFieldGet$2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this);
6189
+ return __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this);
6036
6190
  }
6037
6191
  async totalUsage() {
6038
6192
  await this.done();
6039
- return __classPrivateFieldGet$2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this);
6193
+ return __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this);
6040
6194
  }
6041
6195
  allChatCompletions() {
6042
6196
  return [...this._chatCompletions];
@@ -6045,20 +6199,20 @@ class AbstractChatCompletionRunner extends EventStream {
6045
6199
  const completion = this._chatCompletions[this._chatCompletions.length - 1];
6046
6200
  if (completion)
6047
6201
  this._emit('finalChatCompletion', completion);
6048
- const finalMessage = __classPrivateFieldGet$2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this);
6202
+ const finalMessage = __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this);
6049
6203
  if (finalMessage)
6050
6204
  this._emit('finalMessage', finalMessage);
6051
- const finalContent = __classPrivateFieldGet$2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this);
6205
+ const finalContent = __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this);
6052
6206
  if (finalContent)
6053
6207
  this._emit('finalContent', finalContent);
6054
- const finalFunctionCall = __classPrivateFieldGet$2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this);
6208
+ const finalFunctionCall = __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this);
6055
6209
  if (finalFunctionCall)
6056
6210
  this._emit('finalFunctionCall', finalFunctionCall);
6057
- const finalFunctionCallResult = __classPrivateFieldGet$2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this);
6211
+ const finalFunctionCallResult = __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this);
6058
6212
  if (finalFunctionCallResult != null)
6059
6213
  this._emit('finalFunctionCallResult', finalFunctionCallResult);
6060
6214
  if (this._chatCompletions.some((c) => c.usage)) {
6061
- this._emit('totalUsage', __classPrivateFieldGet$2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this));
6215
+ this._emit('totalUsage', __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this));
6062
6216
  }
6063
6217
  }
6064
6218
  async _createChatCompletion(client, params, options) {
@@ -6068,7 +6222,7 @@ class AbstractChatCompletionRunner extends EventStream {
6068
6222
  this.controller.abort();
6069
6223
  signal.addEventListener('abort', () => this.controller.abort());
6070
6224
  }
6071
- __classPrivateFieldGet$2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params);
6225
+ __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params);
6072
6226
  const chatCompletion = await client.chat.completions.create({ ...params, stream: false }, { ...options, signal: this.controller.signal });
6073
6227
  this._connected();
6074
6228
  return this._addChatCompletion(parseChatCompletion(chatCompletion, params));
@@ -6137,7 +6291,7 @@ class AbstractChatCompletionRunner extends EventStream {
6137
6291
  }
6138
6292
  // @ts-expect-error it can't rule out `never` type.
6139
6293
  const rawContent = await fn.function(parsed, this);
6140
- const content = __classPrivateFieldGet$2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent);
6294
+ const content = __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent);
6141
6295
  this._addMessage({ role, name, content });
6142
6296
  if (singleFunctionToCall)
6143
6297
  return;
@@ -6150,7 +6304,7 @@ class AbstractChatCompletionRunner extends EventStream {
6150
6304
  const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {};
6151
6305
  // TODO(someday): clean this logic up
6152
6306
  const inputTools = params.tools.map((tool) => {
6153
- if (isAutoParsableTool(tool)) {
6307
+ if (isAutoParsableTool$1(tool)) {
6154
6308
  if (!tool.$callback) {
6155
6309
  throw new OpenAIError('Tool given to `.runTools()` that does not have an associated function');
6156
6310
  }
@@ -6233,7 +6387,7 @@ class AbstractChatCompletionRunner extends EventStream {
6233
6387
  }
6234
6388
  // @ts-expect-error it can't rule out `never` type.
6235
6389
  const rawContent = await fn.function(parsed, this);
6236
- const content = __classPrivateFieldGet$2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent);
6390
+ const content = __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent);
6237
6391
  this._addMessage({ role, tool_call_id, content });
6238
6392
  if (singleFunctionToCall) {
6239
6393
  return;
@@ -6244,7 +6398,7 @@ class AbstractChatCompletionRunner extends EventStream {
6244
6398
  }
6245
6399
  }
6246
6400
  _AbstractChatCompletionRunner_instances = new WeakSet(), _AbstractChatCompletionRunner_getFinalContent = function _AbstractChatCompletionRunner_getFinalContent() {
6247
- return __classPrivateFieldGet$2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null;
6401
+ return __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null;
6248
6402
  }, _AbstractChatCompletionRunner_getFinalMessage = function _AbstractChatCompletionRunner_getFinalMessage() {
6249
6403
  let i = this.messages.length;
6250
6404
  while (i-- > 0) {
@@ -6582,13 +6736,13 @@ const _parseJSON = (jsonString, allow) => {
6582
6736
  // using this function with malformed JSON is undefined behavior
6583
6737
  const partialParse = (input) => parseJSON(input, Allow.ALL ^ Allow.NUM);
6584
6738
 
6585
- var __classPrivateFieldSet$1 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
6739
+ var __classPrivateFieldSet$2 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
6586
6740
  if (kind === "m") throw new TypeError("Private method is not writable");
6587
6741
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
6588
6742
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6589
6743
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6590
6744
  };
6591
- var __classPrivateFieldGet$1 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
6745
+ var __classPrivateFieldGet$2 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
6592
6746
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
6593
6747
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
6594
6748
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
@@ -6601,11 +6755,11 @@ class ChatCompletionStream extends AbstractChatCompletionRunner {
6601
6755
  _ChatCompletionStream_params.set(this, void 0);
6602
6756
  _ChatCompletionStream_choiceEventStates.set(this, void 0);
6603
6757
  _ChatCompletionStream_currentChatCompletionSnapshot.set(this, void 0);
6604
- __classPrivateFieldSet$1(this, _ChatCompletionStream_params, params, "f");
6605
- __classPrivateFieldSet$1(this, _ChatCompletionStream_choiceEventStates, [], "f");
6758
+ __classPrivateFieldSet$2(this, _ChatCompletionStream_params, params, "f");
6759
+ __classPrivateFieldSet$2(this, _ChatCompletionStream_choiceEventStates, [], "f");
6606
6760
  }
6607
6761
  get currentChatCompletionSnapshot() {
6608
- return __classPrivateFieldGet$1(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
6762
+ return __classPrivateFieldGet$2(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
6609
6763
  }
6610
6764
  /**
6611
6765
  * Intended for use on the frontend, consuming a stream produced with
@@ -6632,16 +6786,16 @@ class ChatCompletionStream extends AbstractChatCompletionRunner {
6632
6786
  this.controller.abort();
6633
6787
  signal.addEventListener('abort', () => this.controller.abort());
6634
6788
  }
6635
- __classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
6789
+ __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
6636
6790
  const stream = await client.chat.completions.create({ ...params, stream: true }, { ...options, signal: this.controller.signal });
6637
6791
  this._connected();
6638
6792
  for await (const chunk of stream) {
6639
- __classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
6793
+ __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
6640
6794
  }
6641
6795
  if (stream.controller.signal?.aborted) {
6642
6796
  throw new APIUserAbortError();
6643
6797
  }
6644
- return this._addChatCompletion(__classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
6798
+ return this._addChatCompletion(__classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
6645
6799
  }
6646
6800
  async _fromReadableStream(readableStream, options) {
6647
6801
  const signal = options?.signal;
@@ -6650,29 +6804,29 @@ class ChatCompletionStream extends AbstractChatCompletionRunner {
6650
6804
  this.controller.abort();
6651
6805
  signal.addEventListener('abort', () => this.controller.abort());
6652
6806
  }
6653
- __classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
6807
+ __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
6654
6808
  this._connected();
6655
6809
  const stream = Stream.fromReadableStream(readableStream, this.controller);
6656
6810
  let chatId;
6657
6811
  for await (const chunk of stream) {
6658
6812
  if (chatId && chatId !== chunk.id) {
6659
6813
  // A new request has been made.
6660
- this._addChatCompletion(__classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
6814
+ this._addChatCompletion(__classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
6661
6815
  }
6662
- __classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
6816
+ __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
6663
6817
  chatId = chunk.id;
6664
6818
  }
6665
6819
  if (stream.controller.signal?.aborted) {
6666
6820
  throw new APIUserAbortError();
6667
6821
  }
6668
- return this._addChatCompletion(__classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
6822
+ return this._addChatCompletion(__classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
6669
6823
  }
6670
6824
  [(_ChatCompletionStream_params = new WeakMap(), _ChatCompletionStream_choiceEventStates = new WeakMap(), _ChatCompletionStream_currentChatCompletionSnapshot = new WeakMap(), _ChatCompletionStream_instances = new WeakSet(), _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest() {
6671
6825
  if (this.ended)
6672
6826
  return;
6673
- __classPrivateFieldSet$1(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f");
6827
+ __classPrivateFieldSet$2(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f");
6674
6828
  }, _ChatCompletionStream_getChoiceEventState = function _ChatCompletionStream_getChoiceEventState(choice) {
6675
- let state = __classPrivateFieldGet$1(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index];
6829
+ let state = __classPrivateFieldGet$2(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index];
6676
6830
  if (state) {
6677
6831
  return state;
6678
6832
  }
@@ -6684,12 +6838,12 @@ class ChatCompletionStream extends AbstractChatCompletionRunner {
6684
6838
  done_tool_calls: new Set(),
6685
6839
  current_tool_call_index: null,
6686
6840
  };
6687
- __classPrivateFieldGet$1(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index] = state;
6841
+ __classPrivateFieldGet$2(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index] = state;
6688
6842
  return state;
6689
6843
  }, _ChatCompletionStream_addChunk = function _ChatCompletionStream_addChunk(chunk) {
6690
6844
  if (this.ended)
6691
6845
  return;
6692
- const completion = __classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk);
6846
+ const completion = __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk);
6693
6847
  this._emit('chunk', chunk, completion);
6694
6848
  for (const choice of chunk.choices) {
6695
6849
  const choiceSnapshot = completion.choices[choice.index];
@@ -6723,19 +6877,19 @@ class ChatCompletionStream extends AbstractChatCompletionRunner {
6723
6877
  snapshot: choiceSnapshot.logprobs?.refusal ?? [],
6724
6878
  });
6725
6879
  }
6726
- const state = __classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
6880
+ const state = __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
6727
6881
  if (choiceSnapshot.finish_reason) {
6728
- __classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);
6882
+ __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);
6729
6883
  if (state.current_tool_call_index != null) {
6730
- __classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index);
6884
+ __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index);
6731
6885
  }
6732
6886
  }
6733
6887
  for (const toolCall of choice.delta.tool_calls ?? []) {
6734
6888
  if (state.current_tool_call_index !== toolCall.index) {
6735
- __classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);
6889
+ __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);
6736
6890
  // new tool call started, the previous one is done
6737
6891
  if (state.current_tool_call_index != null) {
6738
- __classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index);
6892
+ __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index);
6739
6893
  }
6740
6894
  }
6741
6895
  state.current_tool_call_index = toolCall.index;
@@ -6760,7 +6914,7 @@ class ChatCompletionStream extends AbstractChatCompletionRunner {
6760
6914
  }
6761
6915
  }
6762
6916
  }, _ChatCompletionStream_emitToolCallDoneEvent = function _ChatCompletionStream_emitToolCallDoneEvent(choiceSnapshot, toolCallIndex) {
6763
- const state = __classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
6917
+ const state = __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
6764
6918
  if (state.done_tool_calls.has(toolCallIndex)) {
6765
6919
  // we've already fired the done event
6766
6920
  return;
@@ -6773,12 +6927,12 @@ class ChatCompletionStream extends AbstractChatCompletionRunner {
6773
6927
  throw new Error('tool call snapshot missing `type`');
6774
6928
  }
6775
6929
  if (toolCallSnapshot.type === 'function') {
6776
- const inputTool = __classPrivateFieldGet$1(this, _ChatCompletionStream_params, "f")?.tools?.find((tool) => tool.type === 'function' && tool.function.name === toolCallSnapshot.function.name);
6930
+ const inputTool = __classPrivateFieldGet$2(this, _ChatCompletionStream_params, "f")?.tools?.find((tool) => tool.type === 'function' && tool.function.name === toolCallSnapshot.function.name);
6777
6931
  this._emit('tool_calls.function.arguments.done', {
6778
6932
  name: toolCallSnapshot.function.name,
6779
6933
  index: toolCallIndex,
6780
6934
  arguments: toolCallSnapshot.function.arguments,
6781
- parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCallSnapshot.function.arguments)
6935
+ parsed_arguments: isAutoParsableTool$1(inputTool) ? inputTool.$parseRaw(toolCallSnapshot.function.arguments)
6782
6936
  : inputTool?.function.strict ? JSON.parse(toolCallSnapshot.function.arguments)
6783
6937
  : null,
6784
6938
  });
@@ -6787,10 +6941,10 @@ class ChatCompletionStream extends AbstractChatCompletionRunner {
6787
6941
  assertNever(toolCallSnapshot.type);
6788
6942
  }
6789
6943
  }, _ChatCompletionStream_emitContentDoneEvents = function _ChatCompletionStream_emitContentDoneEvents(choiceSnapshot) {
6790
- const state = __classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
6944
+ const state = __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
6791
6945
  if (choiceSnapshot.message.content && !state.content_done) {
6792
6946
  state.content_done = true;
6793
- const responseFormat = __classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this);
6947
+ const responseFormat = __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this);
6794
6948
  this._emit('content.done', {
6795
6949
  content: choiceSnapshot.message.content,
6796
6950
  parsed: responseFormat ? responseFormat.$parseRaw(choiceSnapshot.message.content) : null,
@@ -6812,25 +6966,25 @@ class ChatCompletionStream extends AbstractChatCompletionRunner {
6812
6966
  if (this.ended) {
6813
6967
  throw new OpenAIError(`stream has ended, this shouldn't happen`);
6814
6968
  }
6815
- const snapshot = __classPrivateFieldGet$1(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
6969
+ const snapshot = __classPrivateFieldGet$2(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
6816
6970
  if (!snapshot) {
6817
6971
  throw new OpenAIError(`request ended without sending any chunks`);
6818
6972
  }
6819
- __classPrivateFieldSet$1(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f");
6820
- __classPrivateFieldSet$1(this, _ChatCompletionStream_choiceEventStates, [], "f");
6821
- return finalizeChatCompletion(snapshot, __classPrivateFieldGet$1(this, _ChatCompletionStream_params, "f"));
6973
+ __classPrivateFieldSet$2(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f");
6974
+ __classPrivateFieldSet$2(this, _ChatCompletionStream_choiceEventStates, [], "f");
6975
+ return finalizeChatCompletion(snapshot, __classPrivateFieldGet$2(this, _ChatCompletionStream_params, "f"));
6822
6976
  }, _ChatCompletionStream_getAutoParseableResponseFormat = function _ChatCompletionStream_getAutoParseableResponseFormat() {
6823
- const responseFormat = __classPrivateFieldGet$1(this, _ChatCompletionStream_params, "f")?.response_format;
6977
+ const responseFormat = __classPrivateFieldGet$2(this, _ChatCompletionStream_params, "f")?.response_format;
6824
6978
  if (isAutoParsableResponseFormat(responseFormat)) {
6825
6979
  return responseFormat;
6826
6980
  }
6827
6981
  return null;
6828
6982
  }, _ChatCompletionStream_accumulateChatCompletion = function _ChatCompletionStream_accumulateChatCompletion(chunk) {
6829
6983
  var _a, _b, _c, _d;
6830
- let snapshot = __classPrivateFieldGet$1(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
6984
+ let snapshot = __classPrivateFieldGet$2(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
6831
6985
  const { choices, ...rest } = chunk;
6832
6986
  if (!snapshot) {
6833
- snapshot = __classPrivateFieldSet$1(this, _ChatCompletionStream_currentChatCompletionSnapshot, {
6987
+ snapshot = __classPrivateFieldSet$2(this, _ChatCompletionStream_currentChatCompletionSnapshot, {
6834
6988
  ...rest,
6835
6989
  choices: [],
6836
6990
  }, "f");
@@ -6862,7 +7016,7 @@ class ChatCompletionStream extends AbstractChatCompletionRunner {
6862
7016
  }
6863
7017
  if (finish_reason) {
6864
7018
  choice.finish_reason = finish_reason;
6865
- if (__classPrivateFieldGet$1(this, _ChatCompletionStream_params, "f") && hasAutoParseableInput(__classPrivateFieldGet$1(this, _ChatCompletionStream_params, "f"))) {
7019
+ if (__classPrivateFieldGet$2(this, _ChatCompletionStream_params, "f") && hasAutoParseableInput$1(__classPrivateFieldGet$2(this, _ChatCompletionStream_params, "f"))) {
6866
7020
  if (finish_reason === 'length') {
6867
7021
  throw new LengthFinishReasonError();
6868
7022
  }
@@ -6896,7 +7050,7 @@ class ChatCompletionStream extends AbstractChatCompletionRunner {
6896
7050
  }
6897
7051
  if (content) {
6898
7052
  choice.message.content = (choice.message.content || '') + content;
6899
- if (!choice.message.refusal && __classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this)) {
7053
+ if (!choice.message.refusal && __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this)) {
6900
7054
  choice.message.parsed = partialParse(choice.message.content);
6901
7055
  }
6902
7056
  }
@@ -6916,7 +7070,7 @@ class ChatCompletionStream extends AbstractChatCompletionRunner {
6916
7070
  tool_call.function.name = fn.name;
6917
7071
  if (fn?.arguments) {
6918
7072
  tool_call.function.arguments += fn.arguments;
6919
- if (shouldParseToolCall(__classPrivateFieldGet$1(this, _ChatCompletionStream_params, "f"), tool_call)) {
7073
+ if (shouldParseToolCall(__classPrivateFieldGet$2(this, _ChatCompletionStream_params, "f"), tool_call)) {
6920
7074
  tool_call.function.parsed_arguments = partialParse(tool_call.function.arguments);
6921
7075
  }
6922
7076
  }
@@ -7140,12 +7294,41 @@ class Chat extends APIResource {
7140
7294
  Chat.Completions = Completions$1;
7141
7295
  })(Chat || (Chat = {}));
7142
7296
 
7143
- var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
7297
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
7298
+ class Sessions extends APIResource {
7299
+ /**
7300
+ * Create an ephemeral API token for use in client-side applications with the
7301
+ * Realtime API. Can be configured with the same session parameters as the
7302
+ * `session.update` client event.
7303
+ *
7304
+ * It responds with a session object, plus a `client_secret` key which contains a
7305
+ * usable ephemeral API token that can be used to authenticate browser clients for
7306
+ * the Realtime API.
7307
+ */
7308
+ create(body, options) {
7309
+ return this._client.post('/realtime/sessions', {
7310
+ body,
7311
+ ...options,
7312
+ headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
7313
+ });
7314
+ }
7315
+ }
7316
+
7317
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
7318
+ class Realtime extends APIResource {
7319
+ constructor() {
7320
+ super(...arguments);
7321
+ this.sessions = new Sessions(this._client);
7322
+ }
7323
+ }
7324
+ Realtime.Sessions = Sessions;
7325
+
7326
+ var __classPrivateFieldGet$1 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
7144
7327
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
7145
7328
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
7146
7329
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
7147
7330
  };
7148
- var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
7331
+ var __classPrivateFieldSet$1 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
7149
7332
  if (kind === "m") throw new TypeError("Private method is not writable");
7150
7333
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
7151
7334
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
@@ -7240,12 +7423,12 @@ class AssistantStream extends EventStream {
7240
7423
  this._connected();
7241
7424
  const stream = Stream.fromReadableStream(readableStream, this.controller);
7242
7425
  for await (const event of stream) {
7243
- __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
7426
+ __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
7244
7427
  }
7245
7428
  if (stream.controller.signal?.aborted) {
7246
7429
  throw new APIUserAbortError();
7247
7430
  }
7248
- return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
7431
+ return this._addRun(__classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
7249
7432
  }
7250
7433
  toReadableStream() {
7251
7434
  const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);
@@ -7273,12 +7456,12 @@ class AssistantStream extends EventStream {
7273
7456
  });
7274
7457
  this._connected();
7275
7458
  for await (const event of stream) {
7276
- __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
7459
+ __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
7277
7460
  }
7278
7461
  if (stream.controller.signal?.aborted) {
7279
7462
  throw new APIUserAbortError();
7280
7463
  }
7281
- return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
7464
+ return this._addRun(__classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
7282
7465
  }
7283
7466
  static createThreadAssistantStream(params, thread, options) {
7284
7467
  const runner = new AssistantStream();
@@ -7297,30 +7480,30 @@ class AssistantStream extends EventStream {
7297
7480
  return runner;
7298
7481
  }
7299
7482
  currentEvent() {
7300
- return __classPrivateFieldGet(this, _AssistantStream_currentEvent, "f");
7483
+ return __classPrivateFieldGet$1(this, _AssistantStream_currentEvent, "f");
7301
7484
  }
7302
7485
  currentRun() {
7303
- return __classPrivateFieldGet(this, _AssistantStream_currentRunSnapshot, "f");
7486
+ return __classPrivateFieldGet$1(this, _AssistantStream_currentRunSnapshot, "f");
7304
7487
  }
7305
7488
  currentMessageSnapshot() {
7306
- return __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f");
7489
+ return __classPrivateFieldGet$1(this, _AssistantStream_messageSnapshot, "f");
7307
7490
  }
7308
7491
  currentRunStepSnapshot() {
7309
- return __classPrivateFieldGet(this, _AssistantStream_currentRunStepSnapshot, "f");
7492
+ return __classPrivateFieldGet$1(this, _AssistantStream_currentRunStepSnapshot, "f");
7310
7493
  }
7311
7494
  async finalRunSteps() {
7312
7495
  await this.done();
7313
- return Object.values(__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f"));
7496
+ return Object.values(__classPrivateFieldGet$1(this, _AssistantStream_runStepSnapshots, "f"));
7314
7497
  }
7315
7498
  async finalMessages() {
7316
7499
  await this.done();
7317
- return Object.values(__classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f"));
7500
+ return Object.values(__classPrivateFieldGet$1(this, _AssistantStream_messageSnapshots, "f"));
7318
7501
  }
7319
7502
  async finalRun() {
7320
7503
  await this.done();
7321
- if (!__classPrivateFieldGet(this, _AssistantStream_finalRun, "f"))
7504
+ if (!__classPrivateFieldGet$1(this, _AssistantStream_finalRun, "f"))
7322
7505
  throw Error('Final run was not received.');
7323
- return __classPrivateFieldGet(this, _AssistantStream_finalRun, "f");
7506
+ return __classPrivateFieldGet$1(this, _AssistantStream_finalRun, "f");
7324
7507
  }
7325
7508
  async _createThreadAssistantStream(thread, params, options) {
7326
7509
  const signal = options?.signal;
@@ -7333,12 +7516,12 @@ class AssistantStream extends EventStream {
7333
7516
  const stream = await thread.createAndRun(body, { ...options, signal: this.controller.signal });
7334
7517
  this._connected();
7335
7518
  for await (const event of stream) {
7336
- __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
7519
+ __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
7337
7520
  }
7338
7521
  if (stream.controller.signal?.aborted) {
7339
7522
  throw new APIUserAbortError();
7340
7523
  }
7341
- return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
7524
+ return this._addRun(__classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
7342
7525
  }
7343
7526
  async _createAssistantStream(run, threadId, params, options) {
7344
7527
  const signal = options?.signal;
@@ -7351,12 +7534,12 @@ class AssistantStream extends EventStream {
7351
7534
  const stream = await run.create(threadId, body, { ...options, signal: this.controller.signal });
7352
7535
  this._connected();
7353
7536
  for await (const event of stream) {
7354
- __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
7537
+ __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
7355
7538
  }
7356
7539
  if (stream.controller.signal?.aborted) {
7357
7540
  throw new APIUserAbortError();
7358
7541
  }
7359
- return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
7542
+ return this._addRun(__classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
7360
7543
  }
7361
7544
  static accumulateDelta(acc, delta) {
7362
7545
  for (const [key, deltaValue] of Object.entries(delta)) {
@@ -7434,8 +7617,8 @@ class AssistantStream extends EventStream {
7434
7617
  _AssistantStream_addEvent = function _AssistantStream_addEvent(event) {
7435
7618
  if (this.ended)
7436
7619
  return;
7437
- __classPrivateFieldSet(this, _AssistantStream_currentEvent, event, "f");
7438
- __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleEvent).call(this, event);
7620
+ __classPrivateFieldSet$1(this, _AssistantStream_currentEvent, event, "f");
7621
+ __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_handleEvent).call(this, event);
7439
7622
  switch (event.event) {
7440
7623
  case 'thread.created':
7441
7624
  //No action on this event.
@@ -7445,11 +7628,12 @@ _AssistantStream_addEvent = function _AssistantStream_addEvent(event) {
7445
7628
  case 'thread.run.in_progress':
7446
7629
  case 'thread.run.requires_action':
7447
7630
  case 'thread.run.completed':
7631
+ case 'thread.run.incomplete':
7448
7632
  case 'thread.run.failed':
7449
7633
  case 'thread.run.cancelling':
7450
7634
  case 'thread.run.cancelled':
7451
7635
  case 'thread.run.expired':
7452
- __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRun).call(this, event);
7636
+ __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_handleRun).call(this, event);
7453
7637
  break;
7454
7638
  case 'thread.run.step.created':
7455
7639
  case 'thread.run.step.in_progress':
@@ -7458,14 +7642,14 @@ _AssistantStream_addEvent = function _AssistantStream_addEvent(event) {
7458
7642
  case 'thread.run.step.failed':
7459
7643
  case 'thread.run.step.cancelled':
7460
7644
  case 'thread.run.step.expired':
7461
- __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRunStep).call(this, event);
7645
+ __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_handleRunStep).call(this, event);
7462
7646
  break;
7463
7647
  case 'thread.message.created':
7464
7648
  case 'thread.message.in_progress':
7465
7649
  case 'thread.message.delta':
7466
7650
  case 'thread.message.completed':
7467
7651
  case 'thread.message.incomplete':
7468
- __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleMessage).call(this, event);
7652
+ __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_handleMessage).call(this, event);
7469
7653
  break;
7470
7654
  case 'error':
7471
7655
  //This is included for completeness, but errors are processed in the SSE event processing so this should not occur
@@ -7475,13 +7659,13 @@ _AssistantStream_addEvent = function _AssistantStream_addEvent(event) {
7475
7659
  if (this.ended) {
7476
7660
  throw new OpenAIError(`stream has ended, this shouldn't happen`);
7477
7661
  }
7478
- if (!__classPrivateFieldGet(this, _AssistantStream_finalRun, "f"))
7662
+ if (!__classPrivateFieldGet$1(this, _AssistantStream_finalRun, "f"))
7479
7663
  throw Error('Final run has not been received');
7480
- return __classPrivateFieldGet(this, _AssistantStream_finalRun, "f");
7664
+ return __classPrivateFieldGet$1(this, _AssistantStream_finalRun, "f");
7481
7665
  }, _AssistantStream_handleMessage = function _AssistantStream_handleMessage(event) {
7482
- const [accumulatedMessage, newContent] = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateMessage).call(this, event, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
7483
- __classPrivateFieldSet(this, _AssistantStream_messageSnapshot, accumulatedMessage, "f");
7484
- __classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f")[accumulatedMessage.id] = accumulatedMessage;
7666
+ const [accumulatedMessage, newContent] = __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_accumulateMessage).call(this, event, __classPrivateFieldGet$1(this, _AssistantStream_messageSnapshot, "f"));
7667
+ __classPrivateFieldSet$1(this, _AssistantStream_messageSnapshot, accumulatedMessage, "f");
7668
+ __classPrivateFieldGet$1(this, _AssistantStream_messageSnapshots, "f")[accumulatedMessage.id] = accumulatedMessage;
7485
7669
  for (const content of newContent) {
7486
7670
  const snapshotContent = accumulatedMessage.content[content.index];
7487
7671
  if (snapshotContent?.type == 'text') {
@@ -7509,48 +7693,48 @@ _AssistantStream_addEvent = function _AssistantStream_addEvent(event) {
7509
7693
  throw Error('The snapshot associated with this text delta is not text or missing');
7510
7694
  }
7511
7695
  }
7512
- if (content.index != __classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")) {
7696
+ if (content.index != __classPrivateFieldGet$1(this, _AssistantStream_currentContentIndex, "f")) {
7513
7697
  //See if we have in progress content
7514
- if (__classPrivateFieldGet(this, _AssistantStream_currentContent, "f")) {
7515
- switch (__classPrivateFieldGet(this, _AssistantStream_currentContent, "f").type) {
7698
+ if (__classPrivateFieldGet$1(this, _AssistantStream_currentContent, "f")) {
7699
+ switch (__classPrivateFieldGet$1(this, _AssistantStream_currentContent, "f").type) {
7516
7700
  case 'text':
7517
- this._emit('textDone', __classPrivateFieldGet(this, _AssistantStream_currentContent, "f").text, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
7701
+ this._emit('textDone', __classPrivateFieldGet$1(this, _AssistantStream_currentContent, "f").text, __classPrivateFieldGet$1(this, _AssistantStream_messageSnapshot, "f"));
7518
7702
  break;
7519
7703
  case 'image_file':
7520
- this._emit('imageFileDone', __classPrivateFieldGet(this, _AssistantStream_currentContent, "f").image_file, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
7704
+ this._emit('imageFileDone', __classPrivateFieldGet$1(this, _AssistantStream_currentContent, "f").image_file, __classPrivateFieldGet$1(this, _AssistantStream_messageSnapshot, "f"));
7521
7705
  break;
7522
7706
  }
7523
7707
  }
7524
- __classPrivateFieldSet(this, _AssistantStream_currentContentIndex, content.index, "f");
7708
+ __classPrivateFieldSet$1(this, _AssistantStream_currentContentIndex, content.index, "f");
7525
7709
  }
7526
- __classPrivateFieldSet(this, _AssistantStream_currentContent, accumulatedMessage.content[content.index], "f");
7710
+ __classPrivateFieldSet$1(this, _AssistantStream_currentContent, accumulatedMessage.content[content.index], "f");
7527
7711
  }
7528
7712
  }
7529
7713
  break;
7530
7714
  case 'thread.message.completed':
7531
7715
  case 'thread.message.incomplete':
7532
7716
  //We emit the latest content we were working on on completion (including incomplete)
7533
- if (__classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f") !== undefined) {
7534
- const currentContent = event.data.content[__classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")];
7717
+ if (__classPrivateFieldGet$1(this, _AssistantStream_currentContentIndex, "f") !== undefined) {
7718
+ const currentContent = event.data.content[__classPrivateFieldGet$1(this, _AssistantStream_currentContentIndex, "f")];
7535
7719
  if (currentContent) {
7536
7720
  switch (currentContent.type) {
7537
7721
  case 'image_file':
7538
- this._emit('imageFileDone', currentContent.image_file, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
7722
+ this._emit('imageFileDone', currentContent.image_file, __classPrivateFieldGet$1(this, _AssistantStream_messageSnapshot, "f"));
7539
7723
  break;
7540
7724
  case 'text':
7541
- this._emit('textDone', currentContent.text, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
7725
+ this._emit('textDone', currentContent.text, __classPrivateFieldGet$1(this, _AssistantStream_messageSnapshot, "f"));
7542
7726
  break;
7543
7727
  }
7544
7728
  }
7545
7729
  }
7546
- if (__classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")) {
7730
+ if (__classPrivateFieldGet$1(this, _AssistantStream_messageSnapshot, "f")) {
7547
7731
  this._emit('messageDone', event.data);
7548
7732
  }
7549
- __classPrivateFieldSet(this, _AssistantStream_messageSnapshot, undefined, "f");
7733
+ __classPrivateFieldSet$1(this, _AssistantStream_messageSnapshot, undefined, "f");
7550
7734
  }
7551
7735
  }, _AssistantStream_handleRunStep = function _AssistantStream_handleRunStep(event) {
7552
- const accumulatedRunStep = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateRunStep).call(this, event);
7553
- __classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, accumulatedRunStep, "f");
7736
+ const accumulatedRunStep = __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_accumulateRunStep).call(this, event);
7737
+ __classPrivateFieldSet$1(this, _AssistantStream_currentRunStepSnapshot, accumulatedRunStep, "f");
7554
7738
  switch (event.event) {
7555
7739
  case 'thread.run.step.created':
7556
7740
  this._emit('runStepCreated', event.data);
@@ -7562,17 +7746,17 @@ _AssistantStream_addEvent = function _AssistantStream_addEvent(event) {
7562
7746
  delta.step_details.tool_calls &&
7563
7747
  accumulatedRunStep.step_details.type == 'tool_calls') {
7564
7748
  for (const toolCall of delta.step_details.tool_calls) {
7565
- if (toolCall.index == __classPrivateFieldGet(this, _AssistantStream_currentToolCallIndex, "f")) {
7749
+ if (toolCall.index == __classPrivateFieldGet$1(this, _AssistantStream_currentToolCallIndex, "f")) {
7566
7750
  this._emit('toolCallDelta', toolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index]);
7567
7751
  }
7568
7752
  else {
7569
- if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) {
7570
- this._emit('toolCallDone', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f"));
7753
+ if (__classPrivateFieldGet$1(this, _AssistantStream_currentToolCall, "f")) {
7754
+ this._emit('toolCallDone', __classPrivateFieldGet$1(this, _AssistantStream_currentToolCall, "f"));
7571
7755
  }
7572
- __classPrivateFieldSet(this, _AssistantStream_currentToolCallIndex, toolCall.index, "f");
7573
- __classPrivateFieldSet(this, _AssistantStream_currentToolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index], "f");
7574
- if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f"))
7575
- this._emit('toolCallCreated', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f"));
7756
+ __classPrivateFieldSet$1(this, _AssistantStream_currentToolCallIndex, toolCall.index, "f");
7757
+ __classPrivateFieldSet$1(this, _AssistantStream_currentToolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index], "f");
7758
+ if (__classPrivateFieldGet$1(this, _AssistantStream_currentToolCall, "f"))
7759
+ this._emit('toolCallCreated', __classPrivateFieldGet$1(this, _AssistantStream_currentToolCall, "f"));
7576
7760
  }
7577
7761
  }
7578
7762
  }
@@ -7582,46 +7766,46 @@ _AssistantStream_addEvent = function _AssistantStream_addEvent(event) {
7582
7766
  case 'thread.run.step.failed':
7583
7767
  case 'thread.run.step.cancelled':
7584
7768
  case 'thread.run.step.expired':
7585
- __classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, undefined, "f");
7769
+ __classPrivateFieldSet$1(this, _AssistantStream_currentRunStepSnapshot, undefined, "f");
7586
7770
  const details = event.data.step_details;
7587
7771
  if (details.type == 'tool_calls') {
7588
- if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) {
7589
- this._emit('toolCallDone', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f"));
7590
- __classPrivateFieldSet(this, _AssistantStream_currentToolCall, undefined, "f");
7772
+ if (__classPrivateFieldGet$1(this, _AssistantStream_currentToolCall, "f")) {
7773
+ this._emit('toolCallDone', __classPrivateFieldGet$1(this, _AssistantStream_currentToolCall, "f"));
7774
+ __classPrivateFieldSet$1(this, _AssistantStream_currentToolCall, undefined, "f");
7591
7775
  }
7592
7776
  }
7593
7777
  this._emit('runStepDone', event.data, accumulatedRunStep);
7594
7778
  break;
7595
7779
  }
7596
7780
  }, _AssistantStream_handleEvent = function _AssistantStream_handleEvent(event) {
7597
- __classPrivateFieldGet(this, _AssistantStream_events, "f").push(event);
7781
+ __classPrivateFieldGet$1(this, _AssistantStream_events, "f").push(event);
7598
7782
  this._emit('event', event);
7599
7783
  }, _AssistantStream_accumulateRunStep = function _AssistantStream_accumulateRunStep(event) {
7600
7784
  switch (event.event) {
7601
7785
  case 'thread.run.step.created':
7602
- __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data;
7786
+ __classPrivateFieldGet$1(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data;
7603
7787
  return event.data;
7604
7788
  case 'thread.run.step.delta':
7605
- let snapshot = __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id];
7789
+ let snapshot = __classPrivateFieldGet$1(this, _AssistantStream_runStepSnapshots, "f")[event.data.id];
7606
7790
  if (!snapshot) {
7607
7791
  throw Error('Received a RunStepDelta before creation of a snapshot');
7608
7792
  }
7609
7793
  let data = event.data;
7610
7794
  if (data.delta) {
7611
7795
  const accumulated = AssistantStream.accumulateDelta(snapshot, data.delta);
7612
- __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = accumulated;
7796
+ __classPrivateFieldGet$1(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = accumulated;
7613
7797
  }
7614
- return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id];
7798
+ return __classPrivateFieldGet$1(this, _AssistantStream_runStepSnapshots, "f")[event.data.id];
7615
7799
  case 'thread.run.step.completed':
7616
7800
  case 'thread.run.step.failed':
7617
7801
  case 'thread.run.step.cancelled':
7618
7802
  case 'thread.run.step.expired':
7619
7803
  case 'thread.run.step.in_progress':
7620
- __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data;
7804
+ __classPrivateFieldGet$1(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data;
7621
7805
  break;
7622
7806
  }
7623
- if (__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id])
7624
- return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id];
7807
+ if (__classPrivateFieldGet$1(this, _AssistantStream_runStepSnapshots, "f")[event.data.id])
7808
+ return __classPrivateFieldGet$1(this, _AssistantStream_runStepSnapshots, "f")[event.data.id];
7625
7809
  throw new Error('No snapshot available');
7626
7810
  }, _AssistantStream_accumulateMessage = function _AssistantStream_accumulateMessage(event, snapshot) {
7627
7811
  let newContent = [];
@@ -7639,7 +7823,7 @@ _AssistantStream_addEvent = function _AssistantStream_addEvent(event) {
7639
7823
  for (const contentElement of data.delta.content) {
7640
7824
  if (contentElement.index in snapshot.content) {
7641
7825
  let currentContent = snapshot.content[contentElement.index];
7642
- snapshot.content[contentElement.index] = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateContent).call(this, contentElement, currentContent);
7826
+ snapshot.content[contentElement.index] = __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_accumulateContent).call(this, contentElement, currentContent);
7643
7827
  }
7644
7828
  else {
7645
7829
  snapshot.content[contentElement.index] = contentElement;
@@ -7664,7 +7848,7 @@ _AssistantStream_addEvent = function _AssistantStream_addEvent(event) {
7664
7848
  }, _AssistantStream_accumulateContent = function _AssistantStream_accumulateContent(contentElement, currentContent) {
7665
7849
  return AssistantStream.accumulateDelta(currentContent, contentElement);
7666
7850
  }, _AssistantStream_handleRun = function _AssistantStream_handleRun(event) {
7667
- __classPrivateFieldSet(this, _AssistantStream_currentRunSnapshot, event.data, "f");
7851
+ __classPrivateFieldSet$1(this, _AssistantStream_currentRunSnapshot, event.data, "f");
7668
7852
  switch (event.event) {
7669
7853
  case 'thread.run.created':
7670
7854
  break;
@@ -7677,10 +7861,10 @@ _AssistantStream_addEvent = function _AssistantStream_addEvent(event) {
7677
7861
  case 'thread.run.failed':
7678
7862
  case 'thread.run.completed':
7679
7863
  case 'thread.run.expired':
7680
- __classPrivateFieldSet(this, _AssistantStream_finalRun, event.data, "f");
7681
- if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) {
7682
- this._emit('toolCallDone', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f"));
7683
- __classPrivateFieldSet(this, _AssistantStream_currentToolCall, undefined, "f");
7864
+ __classPrivateFieldSet$1(this, _AssistantStream_finalRun, event.data, "f");
7865
+ if (__classPrivateFieldGet$1(this, _AssistantStream_currentToolCall, "f")) {
7866
+ this._emit('toolCallDone', __classPrivateFieldGet$1(this, _AssistantStream_currentToolCall, "f"));
7867
+ __classPrivateFieldSet$1(this, _AssistantStream_currentToolCall, undefined, "f");
7684
7868
  }
7685
7869
  break;
7686
7870
  }
@@ -7997,663 +8181,1117 @@ Threads.RunsPage = RunsPage;
7997
8181
  Threads.Messages = Messages;
7998
8182
  Threads.MessagesPage = MessagesPage;
7999
8183
 
8000
- /**
8001
- * Like `Promise.allSettled()` but throws an error if any promises are rejected.
8002
- */
8003
- const allSettledWithThrow = async (promises) => {
8004
- const results = await Promise.allSettled(promises);
8005
- const rejected = results.filter((result) => result.status === 'rejected');
8006
- if (rejected.length) {
8007
- for (const result of rejected) {
8008
- console.error(result.reason);
8009
- }
8010
- throw new Error(`${rejected.length} promise(s) failed - see the above errors`);
8184
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8185
+ class Beta extends APIResource {
8186
+ constructor() {
8187
+ super(...arguments);
8188
+ this.realtime = new Realtime(this._client);
8189
+ this.chat = new Chat(this._client);
8190
+ this.assistants = new Assistants(this._client);
8191
+ this.threads = new Threads(this._client);
8011
8192
  }
8012
- // Note: TS was complaining about using `.filter().map()` here for some reason
8013
- const values = [];
8014
- for (const result of results) {
8015
- if (result.status === 'fulfilled') {
8016
- values.push(result.value);
8017
- }
8193
+ }
8194
+ Beta.Realtime = Realtime;
8195
+ Beta.Assistants = Assistants;
8196
+ Beta.AssistantsPage = AssistantsPage;
8197
+ Beta.Threads = Threads;
8198
+
8199
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8200
+ class Completions extends APIResource {
8201
+ create(body, options) {
8202
+ return this._client.post('/completions', { body, ...options, stream: body.stream ?? false });
8018
8203
  }
8019
- return values;
8020
- };
8204
+ }
8205
+
8206
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8207
+ class Embeddings extends APIResource {
8208
+ /**
8209
+ * Creates an embedding vector representing the input text.
8210
+ */
8211
+ create(body, options) {
8212
+ return this._client.post('/embeddings', { body, ...options });
8213
+ }
8214
+ }
8021
8215
 
8022
8216
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8023
8217
  let Files$1 = class Files extends APIResource {
8024
8218
  /**
8025
- * Create a vector store file by attaching a
8026
- * [File](https://platform.openai.com/docs/api-reference/files) to a
8027
- * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object).
8219
+ * Upload a file that can be used across various endpoints. Individual files can be
8220
+ * up to 512 MB, and the size of all files uploaded by one organization can be up
8221
+ * to 100 GB.
8222
+ *
8223
+ * The Assistants API supports files up to 2 million tokens and of specific file
8224
+ * types. See the
8225
+ * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for
8226
+ * details.
8227
+ *
8228
+ * The Fine-tuning API only supports `.jsonl` files. The input also has certain
8229
+ * required formats for fine-tuning
8230
+ * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or
8231
+ * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input)
8232
+ * models.
8233
+ *
8234
+ * The Batch API only supports `.jsonl` files up to 200 MB in size. The input also
8235
+ * has a specific required
8236
+ * [format](https://platform.openai.com/docs/api-reference/batch/request-input).
8237
+ *
8238
+ * Please [contact us](https://help.openai.com/) if you need to increase these
8239
+ * storage limits.
8028
8240
  */
8029
- create(vectorStoreId, body, options) {
8030
- return this._client.post(`/vector_stores/${vectorStoreId}/files`, {
8031
- body,
8032
- ...options,
8033
- headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8034
- });
8241
+ create(body, options) {
8242
+ return this._client.post('/files', multipartFormRequestOptions({ body, ...options }));
8035
8243
  }
8036
8244
  /**
8037
- * Retrieves a vector store file.
8245
+ * Returns information about a specific file.
8038
8246
  */
8039
- retrieve(vectorStoreId, fileId, options) {
8040
- return this._client.get(`/vector_stores/${vectorStoreId}/files/${fileId}`, {
8041
- ...options,
8042
- headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8043
- });
8247
+ retrieve(fileId, options) {
8248
+ return this._client.get(`/files/${fileId}`, options);
8044
8249
  }
8045
- list(vectorStoreId, query = {}, options) {
8250
+ list(query = {}, options) {
8046
8251
  if (isRequestOptions(query)) {
8047
- return this.list(vectorStoreId, {}, query);
8252
+ return this.list({}, query);
8048
8253
  }
8049
- return this._client.getAPIList(`/vector_stores/${vectorStoreId}/files`, VectorStoreFilesPage, {
8050
- query,
8051
- ...options,
8052
- headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8053
- });
8254
+ return this._client.getAPIList('/files', FileObjectsPage, { query, ...options });
8054
8255
  }
8055
8256
  /**
8056
- * Delete a vector store file. This will remove the file from the vector store but
8057
- * the file itself will not be deleted. To delete the file, use the
8058
- * [delete file](https://platform.openai.com/docs/api-reference/files/delete)
8059
- * endpoint.
8257
+ * Delete a file.
8060
8258
  */
8061
- del(vectorStoreId, fileId, options) {
8062
- return this._client.delete(`/vector_stores/${vectorStoreId}/files/${fileId}`, {
8259
+ del(fileId, options) {
8260
+ return this._client.delete(`/files/${fileId}`, options);
8261
+ }
8262
+ /**
8263
+ * Returns the contents of the specified file.
8264
+ */
8265
+ content(fileId, options) {
8266
+ return this._client.get(`/files/${fileId}/content`, {
8063
8267
  ...options,
8064
- headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8268
+ headers: { Accept: 'application/binary', ...options?.headers },
8269
+ __binaryResponse: true,
8065
8270
  });
8066
8271
  }
8067
8272
  /**
8068
- * Attach a file to the given vector store and wait for it to be processed.
8273
+ * Returns the contents of the specified file.
8274
+ *
8275
+ * @deprecated The `.content()` method should be used instead
8069
8276
  */
8070
- async createAndPoll(vectorStoreId, body, options) {
8071
- const file = await this.create(vectorStoreId, body, options);
8072
- return await this.poll(vectorStoreId, file.id, options);
8277
+ retrieveContent(fileId, options) {
8278
+ return this._client.get(`/files/${fileId}/content`, options);
8073
8279
  }
8074
8280
  /**
8075
- * Wait for the vector store file to finish processing.
8076
- *
8077
- * Note: this will return even if the file failed to process, you need to check
8078
- * file.last_error and file.status to handle these cases
8281
+ * Waits for the given file to be processed, default timeout is 30 mins.
8079
8282
  */
8080
- async poll(vectorStoreId, fileId, options) {
8081
- const headers = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' };
8082
- if (options?.pollIntervalMs) {
8083
- headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString();
8084
- }
8085
- while (true) {
8086
- const fileResponse = await this.retrieve(vectorStoreId, fileId, {
8087
- ...options,
8088
- headers,
8089
- }).withResponse();
8090
- const file = fileResponse.data;
8091
- switch (file.status) {
8092
- case 'in_progress':
8093
- let sleepInterval = 5000;
8094
- if (options?.pollIntervalMs) {
8095
- sleepInterval = options.pollIntervalMs;
8096
- }
8097
- else {
8098
- const headerInterval = fileResponse.response.headers.get('openai-poll-after-ms');
8099
- if (headerInterval) {
8100
- const headerIntervalMs = parseInt(headerInterval);
8101
- if (!isNaN(headerIntervalMs)) {
8102
- sleepInterval = headerIntervalMs;
8103
- }
8104
- }
8105
- }
8106
- await sleep(sleepInterval);
8107
- break;
8108
- case 'failed':
8109
- case 'completed':
8110
- return file;
8283
+ async waitForProcessing(id, { pollInterval = 5000, maxWait = 30 * 60 * 1000 } = {}) {
8284
+ const TERMINAL_STATES = new Set(['processed', 'error', 'deleted']);
8285
+ const start = Date.now();
8286
+ let file = await this.retrieve(id);
8287
+ while (!file.status || !TERMINAL_STATES.has(file.status)) {
8288
+ await sleep(pollInterval);
8289
+ file = await this.retrieve(id);
8290
+ if (Date.now() - start > maxWait) {
8291
+ throw new APIConnectionTimeoutError({
8292
+ message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`,
8293
+ });
8111
8294
  }
8112
8295
  }
8296
+ return file;
8297
+ }
8298
+ };
8299
+ class FileObjectsPage extends CursorPage {
8300
+ }
8301
+ Files$1.FileObjectsPage = FileObjectsPage;
8302
+
8303
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8304
+ class Checkpoints extends APIResource {
8305
+ list(fineTuningJobId, query = {}, options) {
8306
+ if (isRequestOptions(query)) {
8307
+ return this.list(fineTuningJobId, {}, query);
8308
+ }
8309
+ return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/checkpoints`, FineTuningJobCheckpointsPage, { query, ...options });
8310
+ }
8311
+ }
8312
+ class FineTuningJobCheckpointsPage extends CursorPage {
8313
+ }
8314
+ Checkpoints.FineTuningJobCheckpointsPage = FineTuningJobCheckpointsPage;
8315
+
8316
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8317
+ class Jobs extends APIResource {
8318
+ constructor() {
8319
+ super(...arguments);
8320
+ this.checkpoints = new Checkpoints(this._client);
8113
8321
  }
8114
8322
  /**
8115
- * Upload a file to the `files` API and then attach it to the given vector store.
8323
+ * Creates a fine-tuning job which begins the process of creating a new model from
8324
+ * a given dataset.
8116
8325
  *
8117
- * Note the file will be asynchronously processed (you can use the alternative
8118
- * polling helper method to wait for processing to complete).
8326
+ * Response includes details of the enqueued job including job status and the name
8327
+ * of the fine-tuned models once complete.
8328
+ *
8329
+ * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning)
8119
8330
  */
8120
- async upload(vectorStoreId, file, options) {
8121
- const fileInfo = await this._client.files.create({ file: file, purpose: 'assistants' }, options);
8122
- return this.create(vectorStoreId, { file_id: fileInfo.id }, options);
8331
+ create(body, options) {
8332
+ return this._client.post('/fine_tuning/jobs', { body, ...options });
8123
8333
  }
8124
8334
  /**
8125
- * Add a file to a vector store and poll until processing is complete.
8335
+ * Get info about a fine-tuning job.
8336
+ *
8337
+ * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning)
8126
8338
  */
8127
- async uploadAndPoll(vectorStoreId, file, options) {
8128
- const fileInfo = await this.upload(vectorStoreId, file, options);
8129
- return await this.poll(vectorStoreId, fileInfo.id, options);
8339
+ retrieve(fineTuningJobId, options) {
8340
+ return this._client.get(`/fine_tuning/jobs/${fineTuningJobId}`, options);
8130
8341
  }
8131
- };
8132
- class VectorStoreFilesPage extends CursorPage {
8133
- }
8134
- Files$1.VectorStoreFilesPage = VectorStoreFilesPage;
8135
-
8136
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8137
- class FileBatches extends APIResource {
8138
- /**
8139
- * Create a vector store file batch.
8140
- */
8141
- create(vectorStoreId, body, options) {
8142
- return this._client.post(`/vector_stores/${vectorStoreId}/file_batches`, {
8143
- body,
8144
- ...options,
8145
- headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8146
- });
8147
- }
8148
- /**
8149
- * Retrieves a vector store file batch.
8150
- */
8151
- retrieve(vectorStoreId, batchId, options) {
8152
- return this._client.get(`/vector_stores/${vectorStoreId}/file_batches/${batchId}`, {
8153
- ...options,
8154
- headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8155
- });
8156
- }
8157
- /**
8158
- * Cancel a vector store file batch. This attempts to cancel the processing of
8159
- * files in this batch as soon as possible.
8160
- */
8161
- cancel(vectorStoreId, batchId, options) {
8162
- return this._client.post(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/cancel`, {
8163
- ...options,
8164
- headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8165
- });
8166
- }
8167
- /**
8168
- * Create a vector store batch and poll until all files have been processed.
8169
- */
8170
- async createAndPoll(vectorStoreId, body, options) {
8171
- const batch = await this.create(vectorStoreId, body);
8172
- return await this.poll(vectorStoreId, batch.id, options);
8173
- }
8174
- listFiles(vectorStoreId, batchId, query = {}, options) {
8342
+ list(query = {}, options) {
8175
8343
  if (isRequestOptions(query)) {
8176
- return this.listFiles(vectorStoreId, batchId, {}, query);
8344
+ return this.list({}, query);
8177
8345
  }
8178
- return this._client.getAPIList(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/files`, VectorStoreFilesPage, { query, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers } });
8346
+ return this._client.getAPIList('/fine_tuning/jobs', FineTuningJobsPage, { query, ...options });
8179
8347
  }
8180
8348
  /**
8181
- * Wait for the given file batch to be processed.
8182
- *
8183
- * Note: this will return even if one of the files failed to process, you need to
8184
- * check batch.file_counts.failed_count to handle this case.
8349
+ * Immediately cancel a fine-tune job.
8185
8350
  */
8186
- async poll(vectorStoreId, batchId, options) {
8187
- const headers = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' };
8188
- if (options?.pollIntervalMs) {
8189
- headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString();
8190
- }
8191
- while (true) {
8192
- const { data: batch, response } = await this.retrieve(vectorStoreId, batchId, {
8193
- ...options,
8194
- headers,
8195
- }).withResponse();
8196
- switch (batch.status) {
8197
- case 'in_progress':
8198
- let sleepInterval = 5000;
8199
- if (options?.pollIntervalMs) {
8200
- sleepInterval = options.pollIntervalMs;
8201
- }
8202
- else {
8203
- const headerInterval = response.headers.get('openai-poll-after-ms');
8204
- if (headerInterval) {
8205
- const headerIntervalMs = parseInt(headerInterval);
8206
- if (!isNaN(headerIntervalMs)) {
8207
- sleepInterval = headerIntervalMs;
8208
- }
8209
- }
8210
- }
8211
- await sleep(sleepInterval);
8212
- break;
8213
- case 'failed':
8214
- case 'cancelled':
8215
- case 'completed':
8216
- return batch;
8217
- }
8218
- }
8351
+ cancel(fineTuningJobId, options) {
8352
+ return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/cancel`, options);
8219
8353
  }
8220
- /**
8221
- * Uploads the given files concurrently and then creates a vector store file batch.
8222
- *
8223
- * The concurrency limit is configurable using the `maxConcurrency` parameter.
8224
- */
8225
- async uploadAndPoll(vectorStoreId, { files, fileIds = [] }, options) {
8226
- if (files == null || files.length == 0) {
8227
- throw new Error(`No \`files\` provided to process. If you've already uploaded files you should use \`.createAndPoll()\` instead`);
8228
- }
8229
- const configuredConcurrency = options?.maxConcurrency ?? 5;
8230
- // We cap the number of workers at the number of files (so we don't start any unnecessary workers)
8231
- const concurrencyLimit = Math.min(configuredConcurrency, files.length);
8232
- const client = this._client;
8233
- const fileIterator = files.values();
8234
- const allFileIds = [...fileIds];
8235
- // This code is based on this design. The libraries don't accommodate our environment limits.
8236
- // https://stackoverflow.com/questions/40639432/what-is-the-best-way-to-limit-concurrency-when-using-es6s-promise-all
8237
- async function processFiles(iterator) {
8238
- for (let item of iterator) {
8239
- const fileObj = await client.files.create({ file: item, purpose: 'assistants' }, options);
8240
- allFileIds.push(fileObj.id);
8241
- }
8354
+ listEvents(fineTuningJobId, query = {}, options) {
8355
+ if (isRequestOptions(query)) {
8356
+ return this.listEvents(fineTuningJobId, {}, query);
8242
8357
  }
8243
- // Start workers to process results
8244
- const workers = Array(concurrencyLimit).fill(fileIterator).map(processFiles);
8245
- // Wait for all processing to complete.
8246
- await allSettledWithThrow(workers);
8247
- return await this.createAndPoll(vectorStoreId, {
8248
- file_ids: allFileIds,
8358
+ return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/events`, FineTuningJobEventsPage, {
8359
+ query,
8360
+ ...options,
8249
8361
  });
8250
8362
  }
8251
8363
  }
8364
+ class FineTuningJobsPage extends CursorPage {
8365
+ }
8366
+ class FineTuningJobEventsPage extends CursorPage {
8367
+ }
8368
+ Jobs.FineTuningJobsPage = FineTuningJobsPage;
8369
+ Jobs.FineTuningJobEventsPage = FineTuningJobEventsPage;
8370
+ Jobs.Checkpoints = Checkpoints;
8371
+ Jobs.FineTuningJobCheckpointsPage = FineTuningJobCheckpointsPage;
8252
8372
 
8253
8373
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8254
- class VectorStores extends APIResource {
8374
+ class FineTuning extends APIResource {
8255
8375
  constructor() {
8256
8376
  super(...arguments);
8257
- this.files = new Files$1(this._client);
8258
- this.fileBatches = new FileBatches(this._client);
8377
+ this.jobs = new Jobs(this._client);
8259
8378
  }
8379
+ }
8380
+ FineTuning.Jobs = Jobs;
8381
+ FineTuning.FineTuningJobsPage = FineTuningJobsPage;
8382
+ FineTuning.FineTuningJobEventsPage = FineTuningJobEventsPage;
8383
+
8384
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8385
+ class Images extends APIResource {
8260
8386
  /**
8261
- * Create a vector store.
8387
+ * Creates a variation of a given image.
8262
8388
  */
8263
- create(body, options) {
8264
- return this._client.post('/vector_stores', {
8265
- body,
8266
- ...options,
8267
- headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8268
- });
8389
+ createVariation(body, options) {
8390
+ return this._client.post('/images/variations', multipartFormRequestOptions({ body, ...options }));
8269
8391
  }
8270
8392
  /**
8271
- * Retrieves a vector store.
8393
+ * Creates an edited or extended image given an original image and a prompt.
8272
8394
  */
8273
- retrieve(vectorStoreId, options) {
8274
- return this._client.get(`/vector_stores/${vectorStoreId}`, {
8275
- ...options,
8276
- headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8277
- });
8395
+ edit(body, options) {
8396
+ return this._client.post('/images/edits', multipartFormRequestOptions({ body, ...options }));
8278
8397
  }
8279
8398
  /**
8280
- * Modifies a vector store.
8399
+ * Creates an image given a prompt.
8281
8400
  */
8282
- update(vectorStoreId, body, options) {
8283
- return this._client.post(`/vector_stores/${vectorStoreId}`, {
8284
- body,
8285
- ...options,
8286
- headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8287
- });
8401
+ generate(body, options) {
8402
+ return this._client.post('/images/generations', { body, ...options });
8288
8403
  }
8289
- list(query = {}, options) {
8290
- if (isRequestOptions(query)) {
8291
- return this.list({}, query);
8292
- }
8293
- return this._client.getAPIList('/vector_stores', VectorStoresPage, {
8294
- query,
8295
- ...options,
8296
- headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8297
- });
8404
+ }
8405
+
8406
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8407
+ class Models extends APIResource {
8408
+ /**
8409
+ * Retrieves a model instance, providing basic information about the model such as
8410
+ * the owner and permissioning.
8411
+ */
8412
+ retrieve(model, options) {
8413
+ return this._client.get(`/models/${model}`, options);
8298
8414
  }
8299
8415
  /**
8300
- * Delete a vector store.
8416
+ * Lists the currently available models, and provides basic information about each
8417
+ * one such as the owner and availability.
8301
8418
  */
8302
- del(vectorStoreId, options) {
8303
- return this._client.delete(`/vector_stores/${vectorStoreId}`, {
8304
- ...options,
8305
- headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8306
- });
8419
+ list(options) {
8420
+ return this._client.getAPIList('/models', ModelsPage, options);
8307
8421
  }
8308
- }
8309
- class VectorStoresPage extends CursorPage {
8310
- }
8311
- VectorStores.VectorStoresPage = VectorStoresPage;
8312
- VectorStores.Files = Files$1;
8313
- VectorStores.VectorStoreFilesPage = VectorStoreFilesPage;
8314
- VectorStores.FileBatches = FileBatches;
8315
-
8316
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8317
- class Beta extends APIResource {
8318
- constructor() {
8319
- super(...arguments);
8320
- this.vectorStores = new VectorStores(this._client);
8321
- this.chat = new Chat(this._client);
8322
- this.assistants = new Assistants(this._client);
8323
- this.threads = new Threads(this._client);
8422
+ /**
8423
+ * Delete a fine-tuned model. You must have the Owner role in your organization to
8424
+ * delete a model.
8425
+ */
8426
+ del(model, options) {
8427
+ return this._client.delete(`/models/${model}`, options);
8324
8428
  }
8325
8429
  }
8326
- Beta.VectorStores = VectorStores;
8327
- Beta.VectorStoresPage = VectorStoresPage;
8328
- Beta.Assistants = Assistants;
8329
- Beta.AssistantsPage = AssistantsPage;
8330
- Beta.Threads = Threads;
8331
-
8332
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8333
- class Completions extends APIResource {
8334
- create(body, options) {
8335
- return this._client.post('/completions', { body, ...options, stream: body.stream ?? false });
8336
- }
8430
+ /**
8431
+ * Note: no pagination actually occurs yet, this is for forwards-compatibility.
8432
+ */
8433
+ class ModelsPage extends Page {
8337
8434
  }
8435
+ Models.ModelsPage = ModelsPage;
8338
8436
 
8339
8437
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8340
- class Embeddings extends APIResource {
8438
+ class Moderations extends APIResource {
8341
8439
  /**
8342
- * Creates an embedding vector representing the input text.
8440
+ * Classifies if text and/or image inputs are potentially harmful. Learn more in
8441
+ * the [moderation guide](https://platform.openai.com/docs/guides/moderation).
8343
8442
  */
8344
8443
  create(body, options) {
8345
- return this._client.post('/embeddings', { body, ...options });
8444
+ return this._client.post('/moderations', { body, ...options });
8346
8445
  }
8347
8446
  }
8348
8447
 
8349
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8350
- class Files extends APIResource {
8351
- /**
8352
- * Upload a file that can be used across various endpoints. Individual files can be
8353
- * up to 512 MB, and the size of all files uploaded by one organization can be up
8354
- * to 100 GB.
8355
- *
8356
- * The Assistants API supports files up to 2 million tokens and of specific file
8357
- * types. See the
8358
- * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for
8359
- * details.
8360
- *
8361
- * The Fine-tuning API only supports `.jsonl` files. The input also has certain
8362
- * required formats for fine-tuning
8363
- * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or
8364
- * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input)
8365
- * models.
8366
- *
8367
- * The Batch API only supports `.jsonl` files up to 200 MB in size. The input also
8368
- * has a specific required
8369
- * [format](https://platform.openai.com/docs/api-reference/batch/request-input).
8370
- *
8371
- * Please [contact us](https://help.openai.com/) if you need to increase these
8372
- * storage limits.
8373
- */
8374
- create(body, options) {
8375
- return this._client.post('/files', multipartFormRequestOptions({ body, ...options }));
8448
+ function maybeParseResponse(response, params) {
8449
+ if (!params || !hasAutoParseableInput(params)) {
8450
+ return {
8451
+ ...response,
8452
+ output_parsed: null,
8453
+ output: response.output.map((item) => {
8454
+ if (item.type === 'function_call') {
8455
+ return {
8456
+ ...item,
8457
+ parsed_arguments: null,
8458
+ };
8459
+ }
8460
+ if (item.type === 'message') {
8461
+ return {
8462
+ ...item,
8463
+ content: item.content.map((content) => ({
8464
+ ...content,
8465
+ parsed: null,
8466
+ })),
8467
+ };
8468
+ }
8469
+ else {
8470
+ return item;
8471
+ }
8472
+ }),
8473
+ };
8376
8474
  }
8377
- /**
8378
- * Returns information about a specific file.
8379
- */
8380
- retrieve(fileId, options) {
8381
- return this._client.get(`/files/${fileId}`, options);
8475
+ return parseResponse(response, params);
8476
+ }
8477
+ function parseResponse(response, params) {
8478
+ const output = response.output.map((item) => {
8479
+ if (item.type === 'function_call') {
8480
+ return {
8481
+ ...item,
8482
+ parsed_arguments: parseToolCall(params, item),
8483
+ };
8484
+ }
8485
+ if (item.type === 'message') {
8486
+ const content = item.content.map((content) => {
8487
+ if (content.type === 'output_text') {
8488
+ return {
8489
+ ...content,
8490
+ parsed: parseTextFormat(params, content.text),
8491
+ };
8492
+ }
8493
+ return content;
8494
+ });
8495
+ return {
8496
+ ...item,
8497
+ content,
8498
+ };
8499
+ }
8500
+ return item;
8501
+ });
8502
+ const parsed = Object.assign({}, response, { output });
8503
+ if (!Object.getOwnPropertyDescriptor(response, 'output_text')) {
8504
+ addOutputText(parsed);
8505
+ }
8506
+ Object.defineProperty(parsed, 'output_parsed', {
8507
+ enumerable: true,
8508
+ get() {
8509
+ for (const output of parsed.output) {
8510
+ if (output.type !== 'message') {
8511
+ continue;
8512
+ }
8513
+ for (const content of output.content) {
8514
+ if (content.type === 'output_text' && content.parsed !== null) {
8515
+ return content.parsed;
8516
+ }
8517
+ }
8518
+ }
8519
+ return null;
8520
+ },
8521
+ });
8522
+ return parsed;
8523
+ }
8524
+ function parseTextFormat(params, content) {
8525
+ if (params.text?.format?.type !== 'json_schema') {
8526
+ return null;
8382
8527
  }
8383
- list(query = {}, options) {
8528
+ if ('$parseRaw' in params.text?.format) {
8529
+ const text_format = params.text?.format;
8530
+ return text_format.$parseRaw(content);
8531
+ }
8532
+ return JSON.parse(content);
8533
+ }
8534
+ function hasAutoParseableInput(params) {
8535
+ if (isAutoParsableResponseFormat(params.text?.format)) {
8536
+ return true;
8537
+ }
8538
+ return false;
8539
+ }
8540
+ function isAutoParsableTool(tool) {
8541
+ return tool?.['$brand'] === 'auto-parseable-tool';
8542
+ }
8543
+ function getInputToolByName(input_tools, name) {
8544
+ return input_tools.find((tool) => tool.type === 'function' && tool.name === name);
8545
+ }
8546
+ function parseToolCall(params, toolCall) {
8547
+ const inputTool = getInputToolByName(params.tools ?? [], toolCall.name);
8548
+ return {
8549
+ ...toolCall,
8550
+ ...toolCall,
8551
+ parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.arguments)
8552
+ : inputTool?.strict ? JSON.parse(toolCall.arguments)
8553
+ : null,
8554
+ };
8555
+ }
8556
+ function addOutputText(rsp) {
8557
+ const texts = [];
8558
+ for (const output of rsp.output) {
8559
+ if (output.type !== 'message') {
8560
+ continue;
8561
+ }
8562
+ for (const content of output.content) {
8563
+ if (content.type === 'output_text') {
8564
+ texts.push(content.text);
8565
+ }
8566
+ }
8567
+ }
8568
+ rsp.output_text = texts.join('');
8569
+ }
8570
+
8571
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8572
+ class InputItems extends APIResource {
8573
+ list(responseId, query = {}, options) {
8384
8574
  if (isRequestOptions(query)) {
8385
- return this.list({}, query);
8575
+ return this.list(responseId, {}, query);
8386
8576
  }
8387
- return this._client.getAPIList('/files', FileObjectsPage, { query, ...options });
8577
+ return this._client.getAPIList(`/responses/${responseId}/input_items`, ResponseItemListDataPage, {
8578
+ query,
8579
+ ...options,
8580
+ });
8388
8581
  }
8389
- /**
8390
- * Delete a file.
8391
- */
8392
- del(fileId, options) {
8393
- return this._client.delete(`/files/${fileId}`, options);
8582
+ }
8583
+ class ResponseItemListDataPage extends CursorPage {
8584
+ }
8585
+ InputItems.ResponseItemListDataPage = ResponseItemListDataPage;
8586
+
8587
+ var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
8588
+ if (kind === "m") throw new TypeError("Private method is not writable");
8589
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
8590
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
8591
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
8592
+ };
8593
+ var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8594
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
8595
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
8596
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
8597
+ };
8598
+ var _ResponseStream_instances, _ResponseStream_params, _ResponseStream_currentResponseSnapshot, _ResponseStream_finalResponse, _ResponseStream_beginRequest, _ResponseStream_addEvent, _ResponseStream_endRequest, _ResponseStream_accumulateResponse;
8599
+ class ResponseStream extends EventStream {
8600
+ constructor(params) {
8601
+ super();
8602
+ _ResponseStream_instances.add(this);
8603
+ _ResponseStream_params.set(this, void 0);
8604
+ _ResponseStream_currentResponseSnapshot.set(this, void 0);
8605
+ _ResponseStream_finalResponse.set(this, void 0);
8606
+ __classPrivateFieldSet(this, _ResponseStream_params, params, "f");
8607
+ }
8608
+ static createResponse(client, params, options) {
8609
+ const runner = new ResponseStream(params);
8610
+ runner._run(() => runner._createResponse(client, params, {
8611
+ ...options,
8612
+ headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' },
8613
+ }));
8614
+ return runner;
8394
8615
  }
8395
- /**
8396
- * Returns the contents of the specified file.
8397
- */
8398
- content(fileId, options) {
8399
- return this._client.get(`/files/${fileId}/content`, { ...options, __binaryResponse: true });
8616
+ async _createResponse(client, params, options) {
8617
+ const signal = options?.signal;
8618
+ if (signal) {
8619
+ if (signal.aborted)
8620
+ this.controller.abort();
8621
+ signal.addEventListener('abort', () => this.controller.abort());
8622
+ }
8623
+ __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_beginRequest).call(this);
8624
+ const stream = await client.responses.create({ ...params, stream: true }, { ...options, signal: this.controller.signal });
8625
+ this._connected();
8626
+ for await (const event of stream) {
8627
+ __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_addEvent).call(this, event);
8628
+ }
8629
+ if (stream.controller.signal?.aborted) {
8630
+ throw new APIUserAbortError();
8631
+ }
8632
+ return __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_endRequest).call(this);
8400
8633
  }
8401
- /**
8402
- * Returns the contents of the specified file.
8403
- *
8404
- * @deprecated The `.content()` method should be used instead
8405
- */
8406
- retrieveContent(fileId, options) {
8407
- return this._client.get(`/files/${fileId}/content`, {
8408
- ...options,
8409
- headers: { Accept: 'application/json', ...options?.headers },
8634
+ [(_ResponseStream_params = new WeakMap(), _ResponseStream_currentResponseSnapshot = new WeakMap(), _ResponseStream_finalResponse = new WeakMap(), _ResponseStream_instances = new WeakSet(), _ResponseStream_beginRequest = function _ResponseStream_beginRequest() {
8635
+ if (this.ended)
8636
+ return;
8637
+ __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, undefined, "f");
8638
+ }, _ResponseStream_addEvent = function _ResponseStream_addEvent(event) {
8639
+ if (this.ended)
8640
+ return;
8641
+ const response = __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_accumulateResponse).call(this, event);
8642
+ this._emit('event', event);
8643
+ switch (event.type) {
8644
+ case 'response.output_text.delta': {
8645
+ const output = response.output[event.output_index];
8646
+ if (!output) {
8647
+ throw new OpenAIError(`missing output at index ${event.output_index}`);
8648
+ }
8649
+ if (output.type === 'message') {
8650
+ const content = output.content[event.content_index];
8651
+ if (!content) {
8652
+ throw new OpenAIError(`missing content at index ${event.content_index}`);
8653
+ }
8654
+ if (content.type !== 'output_text') {
8655
+ throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
8656
+ }
8657
+ this._emit('response.output_text.delta', {
8658
+ ...event,
8659
+ snapshot: content.text,
8660
+ });
8661
+ }
8662
+ break;
8663
+ }
8664
+ case 'response.function_call_arguments.delta': {
8665
+ const output = response.output[event.output_index];
8666
+ if (!output) {
8667
+ throw new OpenAIError(`missing output at index ${event.output_index}`);
8668
+ }
8669
+ if (output.type === 'function_call') {
8670
+ this._emit('response.function_call_arguments.delta', {
8671
+ ...event,
8672
+ snapshot: output.arguments,
8673
+ });
8674
+ }
8675
+ break;
8676
+ }
8677
+ default:
8678
+ // @ts-ignore
8679
+ this._emit(event.type, event);
8680
+ break;
8681
+ }
8682
+ }, _ResponseStream_endRequest = function _ResponseStream_endRequest() {
8683
+ if (this.ended) {
8684
+ throw new OpenAIError(`stream has ended, this shouldn't happen`);
8685
+ }
8686
+ const snapshot = __classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f");
8687
+ if (!snapshot) {
8688
+ throw new OpenAIError(`request ended without sending any events`);
8689
+ }
8690
+ __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, undefined, "f");
8691
+ const parsedResponse = finalizeResponse(snapshot, __classPrivateFieldGet(this, _ResponseStream_params, "f"));
8692
+ __classPrivateFieldSet(this, _ResponseStream_finalResponse, parsedResponse, "f");
8693
+ return parsedResponse;
8694
+ }, _ResponseStream_accumulateResponse = function _ResponseStream_accumulateResponse(event) {
8695
+ let snapshot = __classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f");
8696
+ if (!snapshot) {
8697
+ if (event.type !== 'response.created') {
8698
+ throw new OpenAIError(`When snapshot hasn't been set yet, expected 'response.created' event, got ${event.type}`);
8699
+ }
8700
+ snapshot = __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, event.response, "f");
8701
+ return snapshot;
8702
+ }
8703
+ switch (event.type) {
8704
+ case 'response.output_item.added': {
8705
+ snapshot.output.push(event.item);
8706
+ break;
8707
+ }
8708
+ case 'response.content_part.added': {
8709
+ const output = snapshot.output[event.output_index];
8710
+ if (!output) {
8711
+ throw new OpenAIError(`missing output at index ${event.output_index}`);
8712
+ }
8713
+ if (output.type === 'message') {
8714
+ output.content.push(event.part);
8715
+ }
8716
+ break;
8717
+ }
8718
+ case 'response.output_text.delta': {
8719
+ const output = snapshot.output[event.output_index];
8720
+ if (!output) {
8721
+ throw new OpenAIError(`missing output at index ${event.output_index}`);
8722
+ }
8723
+ if (output.type === 'message') {
8724
+ const content = output.content[event.content_index];
8725
+ if (!content) {
8726
+ throw new OpenAIError(`missing content at index ${event.content_index}`);
8727
+ }
8728
+ if (content.type !== 'output_text') {
8729
+ throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
8730
+ }
8731
+ content.text += event.delta;
8732
+ }
8733
+ break;
8734
+ }
8735
+ case 'response.function_call_arguments.delta': {
8736
+ const output = snapshot.output[event.output_index];
8737
+ if (!output) {
8738
+ throw new OpenAIError(`missing output at index ${event.output_index}`);
8739
+ }
8740
+ if (output.type === 'function_call') {
8741
+ output.arguments += event.delta;
8742
+ }
8743
+ break;
8744
+ }
8745
+ case 'response.completed': {
8746
+ __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, event.response, "f");
8747
+ break;
8748
+ }
8749
+ }
8750
+ return snapshot;
8751
+ }, Symbol.asyncIterator)]() {
8752
+ const pushQueue = [];
8753
+ const readQueue = [];
8754
+ let done = false;
8755
+ this.on('event', (event) => {
8756
+ const reader = readQueue.shift();
8757
+ if (reader) {
8758
+ reader.resolve(event);
8759
+ }
8760
+ else {
8761
+ pushQueue.push(event);
8762
+ }
8763
+ });
8764
+ this.on('end', () => {
8765
+ done = true;
8766
+ for (const reader of readQueue) {
8767
+ reader.resolve(undefined);
8768
+ }
8769
+ readQueue.length = 0;
8410
8770
  });
8771
+ this.on('abort', (err) => {
8772
+ done = true;
8773
+ for (const reader of readQueue) {
8774
+ reader.reject(err);
8775
+ }
8776
+ readQueue.length = 0;
8777
+ });
8778
+ this.on('error', (err) => {
8779
+ done = true;
8780
+ for (const reader of readQueue) {
8781
+ reader.reject(err);
8782
+ }
8783
+ readQueue.length = 0;
8784
+ });
8785
+ return {
8786
+ next: async () => {
8787
+ if (!pushQueue.length) {
8788
+ if (done) {
8789
+ return { value: undefined, done: true };
8790
+ }
8791
+ return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((event) => (event ? { value: event, done: false } : { value: undefined, done: true }));
8792
+ }
8793
+ const event = pushQueue.shift();
8794
+ return { value: event, done: false };
8795
+ },
8796
+ return: async () => {
8797
+ this.abort();
8798
+ return { value: undefined, done: true };
8799
+ },
8800
+ };
8411
8801
  }
8412
8802
  /**
8413
- * Waits for the given file to be processed, default timeout is 30 mins.
8803
+ * @returns a promise that resolves with the final Response, or rejects
8804
+ * if an error occurred or the stream ended prematurely without producing a REsponse.
8414
8805
  */
8415
- async waitForProcessing(id, { pollInterval = 5000, maxWait = 30 * 60 * 1000 } = {}) {
8416
- const TERMINAL_STATES = new Set(['processed', 'error', 'deleted']);
8417
- const start = Date.now();
8418
- let file = await this.retrieve(id);
8419
- while (!file.status || !TERMINAL_STATES.has(file.status)) {
8420
- await sleep(pollInterval);
8421
- file = await this.retrieve(id);
8422
- if (Date.now() - start > maxWait) {
8423
- throw new APIConnectionTimeoutError({
8424
- message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`,
8425
- });
8806
+ async finalResponse() {
8807
+ await this.done();
8808
+ const response = __classPrivateFieldGet(this, _ResponseStream_finalResponse, "f");
8809
+ if (!response)
8810
+ throw new OpenAIError('stream ended without producing a ChatCompletion');
8811
+ return response;
8812
+ }
8813
+ }
8814
+ function finalizeResponse(snapshot, params) {
8815
+ return maybeParseResponse(snapshot, params);
8816
+ }
8817
+
8818
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8819
+ class Responses extends APIResource {
8820
+ constructor() {
8821
+ super(...arguments);
8822
+ this.inputItems = new InputItems(this._client);
8823
+ }
8824
+ create(body, options) {
8825
+ return this._client.post('/responses', { body, ...options, stream: body.stream ?? false })._thenUnwrap((rsp) => {
8826
+ if ('object' in rsp && rsp.object === 'response') {
8827
+ addOutputText(rsp);
8426
8828
  }
8829
+ return rsp;
8830
+ });
8831
+ }
8832
+ retrieve(responseId, query = {}, options) {
8833
+ if (isRequestOptions(query)) {
8834
+ return this.retrieve(responseId, {}, query);
8427
8835
  }
8428
- return file;
8836
+ return this._client.get(`/responses/${responseId}`, { query, ...options });
8837
+ }
8838
+ /**
8839
+ * Deletes a model response with the given ID.
8840
+ */
8841
+ del(responseId, options) {
8842
+ return this._client.delete(`/responses/${responseId}`, {
8843
+ ...options,
8844
+ headers: { Accept: '*/*', ...options?.headers },
8845
+ });
8846
+ }
8847
+ parse(body, options) {
8848
+ return this._client.responses
8849
+ .create(body, options)
8850
+ ._thenUnwrap((response) => parseResponse(response, body));
8851
+ }
8852
+ /**
8853
+ * Creates a chat completion stream
8854
+ */
8855
+ stream(body, options) {
8856
+ return ResponseStream.createResponse(this._client, body, options);
8429
8857
  }
8430
8858
  }
8431
- class FileObjectsPage extends CursorPage {
8432
- }
8433
- Files.FileObjectsPage = FileObjectsPage;
8859
+ Responses.InputItems = InputItems;
8860
+ Responses.ResponseItemListDataPage = ResponseItemListDataPage;
8434
8861
 
8435
8862
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8436
- class Checkpoints extends APIResource {
8437
- list(fineTuningJobId, query = {}, options) {
8438
- if (isRequestOptions(query)) {
8439
- return this.list(fineTuningJobId, {}, query);
8440
- }
8441
- return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/checkpoints`, FineTuningJobCheckpointsPage, { query, ...options });
8863
+ class Parts extends APIResource {
8864
+ /**
8865
+ * Adds a
8866
+ * [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an
8867
+ * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object.
8868
+ * A Part represents a chunk of bytes from the file you are trying to upload.
8869
+ *
8870
+ * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload
8871
+ * maximum of 8 GB.
8872
+ *
8873
+ * It is possible to add multiple Parts in parallel. You can decide the intended
8874
+ * order of the Parts when you
8875
+ * [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete).
8876
+ */
8877
+ create(uploadId, body, options) {
8878
+ return this._client.post(`/uploads/${uploadId}/parts`, multipartFormRequestOptions({ body, ...options }));
8442
8879
  }
8443
8880
  }
8444
- class FineTuningJobCheckpointsPage extends CursorPage {
8445
- }
8446
- Checkpoints.FineTuningJobCheckpointsPage = FineTuningJobCheckpointsPage;
8447
8881
 
8448
8882
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8449
- class Jobs extends APIResource {
8883
+ class Uploads extends APIResource {
8450
8884
  constructor() {
8451
8885
  super(...arguments);
8452
- this.checkpoints = new Checkpoints(this._client);
8886
+ this.parts = new Parts(this._client);
8453
8887
  }
8454
8888
  /**
8455
- * Creates a fine-tuning job which begins the process of creating a new model from
8456
- * a given dataset.
8889
+ * Creates an intermediate
8890
+ * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object
8891
+ * that you can add
8892
+ * [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to.
8893
+ * Currently, an Upload can accept at most 8 GB in total and expires after an hour
8894
+ * after you create it.
8457
8895
  *
8458
- * Response includes details of the enqueued job including job status and the name
8459
- * of the fine-tuned models once complete.
8896
+ * Once you complete the Upload, we will create a
8897
+ * [File](https://platform.openai.com/docs/api-reference/files/object) object that
8898
+ * contains all the parts you uploaded. This File is usable in the rest of our
8899
+ * platform as a regular File object.
8460
8900
  *
8461
- * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning)
8901
+ * For certain `purpose` values, the correct `mime_type` must be specified. Please
8902
+ * refer to documentation for the
8903
+ * [supported MIME types for your use case](https://platform.openai.com/docs/assistants/tools/file-search#supported-files).
8904
+ *
8905
+ * For guidance on the proper filename extensions for each purpose, please follow
8906
+ * the documentation on
8907
+ * [creating a File](https://platform.openai.com/docs/api-reference/files/create).
8462
8908
  */
8463
8909
  create(body, options) {
8464
- return this._client.post('/fine_tuning/jobs', { body, ...options });
8910
+ return this._client.post('/uploads', { body, ...options });
8465
8911
  }
8466
8912
  /**
8467
- * Get info about a fine-tuning job.
8913
+ * Cancels the Upload. No Parts may be added after an Upload is cancelled.
8914
+ */
8915
+ cancel(uploadId, options) {
8916
+ return this._client.post(`/uploads/${uploadId}/cancel`, options);
8917
+ }
8918
+ /**
8919
+ * Completes the
8920
+ * [Upload](https://platform.openai.com/docs/api-reference/uploads/object).
8468
8921
  *
8469
- * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning)
8922
+ * Within the returned Upload object, there is a nested
8923
+ * [File](https://platform.openai.com/docs/api-reference/files/object) object that
8924
+ * is ready to use in the rest of the platform.
8925
+ *
8926
+ * You can specify the order of the Parts by passing in an ordered list of the Part
8927
+ * IDs.
8928
+ *
8929
+ * The number of bytes uploaded upon completion must match the number of bytes
8930
+ * initially specified when creating the Upload object. No Parts may be added after
8931
+ * an Upload is completed.
8470
8932
  */
8471
- retrieve(fineTuningJobId, options) {
8472
- return this._client.get(`/fine_tuning/jobs/${fineTuningJobId}`, options);
8933
+ complete(uploadId, body, options) {
8934
+ return this._client.post(`/uploads/${uploadId}/complete`, { body, ...options });
8473
8935
  }
8474
- list(query = {}, options) {
8475
- if (isRequestOptions(query)) {
8476
- return this.list({}, query);
8936
+ }
8937
+ Uploads.Parts = Parts;
8938
+
8939
+ /**
8940
+ * Like `Promise.allSettled()` but throws an error if any promises are rejected.
8941
+ */
8942
+ const allSettledWithThrow = async (promises) => {
8943
+ const results = await Promise.allSettled(promises);
8944
+ const rejected = results.filter((result) => result.status === 'rejected');
8945
+ if (rejected.length) {
8946
+ for (const result of rejected) {
8947
+ console.error(result.reason);
8948
+ }
8949
+ throw new Error(`${rejected.length} promise(s) failed - see the above errors`);
8950
+ }
8951
+ // Note: TS was complaining about using `.filter().map()` here for some reason
8952
+ const values = [];
8953
+ for (const result of results) {
8954
+ if (result.status === 'fulfilled') {
8955
+ values.push(result.value);
8477
8956
  }
8478
- return this._client.getAPIList('/fine_tuning/jobs', FineTuningJobsPage, { query, ...options });
8479
8957
  }
8958
+ return values;
8959
+ };
8960
+
8961
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8962
+ class Files extends APIResource {
8480
8963
  /**
8481
- * Immediately cancel a fine-tune job.
8964
+ * Create a vector store file by attaching a
8965
+ * [File](https://platform.openai.com/docs/api-reference/files) to a
8966
+ * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object).
8482
8967
  */
8483
- cancel(fineTuningJobId, options) {
8484
- return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/cancel`, options);
8968
+ create(vectorStoreId, body, options) {
8969
+ return this._client.post(`/vector_stores/${vectorStoreId}/files`, {
8970
+ body,
8971
+ ...options,
8972
+ headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8973
+ });
8485
8974
  }
8486
- listEvents(fineTuningJobId, query = {}, options) {
8975
+ /**
8976
+ * Retrieves a vector store file.
8977
+ */
8978
+ retrieve(vectorStoreId, fileId, options) {
8979
+ return this._client.get(`/vector_stores/${vectorStoreId}/files/${fileId}`, {
8980
+ ...options,
8981
+ headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8982
+ });
8983
+ }
8984
+ /**
8985
+ * Update attributes on a vector store file.
8986
+ */
8987
+ update(vectorStoreId, fileId, body, options) {
8988
+ return this._client.post(`/vector_stores/${vectorStoreId}/files/${fileId}`, {
8989
+ body,
8990
+ ...options,
8991
+ headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8992
+ });
8993
+ }
8994
+ list(vectorStoreId, query = {}, options) {
8487
8995
  if (isRequestOptions(query)) {
8488
- return this.listEvents(fineTuningJobId, {}, query);
8996
+ return this.list(vectorStoreId, {}, query);
8489
8997
  }
8490
- return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/events`, FineTuningJobEventsPage, {
8998
+ return this._client.getAPIList(`/vector_stores/${vectorStoreId}/files`, VectorStoreFilesPage, {
8491
8999
  query,
8492
9000
  ...options,
9001
+ headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8493
9002
  });
8494
9003
  }
8495
- }
8496
- class FineTuningJobsPage extends CursorPage {
8497
- }
8498
- class FineTuningJobEventsPage extends CursorPage {
8499
- }
8500
- Jobs.FineTuningJobsPage = FineTuningJobsPage;
8501
- Jobs.FineTuningJobEventsPage = FineTuningJobEventsPage;
8502
- Jobs.Checkpoints = Checkpoints;
8503
- Jobs.FineTuningJobCheckpointsPage = FineTuningJobCheckpointsPage;
8504
-
8505
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8506
- class FineTuning extends APIResource {
8507
- constructor() {
8508
- super(...arguments);
8509
- this.jobs = new Jobs(this._client);
8510
- }
8511
- }
8512
- FineTuning.Jobs = Jobs;
8513
- FineTuning.FineTuningJobsPage = FineTuningJobsPage;
8514
- FineTuning.FineTuningJobEventsPage = FineTuningJobEventsPage;
8515
-
8516
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8517
- class Images extends APIResource {
8518
9004
  /**
8519
- * Creates a variation of a given image.
9005
+ * Delete a vector store file. This will remove the file from the vector store but
9006
+ * the file itself will not be deleted. To delete the file, use the
9007
+ * [delete file](https://platform.openai.com/docs/api-reference/files/delete)
9008
+ * endpoint.
8520
9009
  */
8521
- createVariation(body, options) {
8522
- return this._client.post('/images/variations', multipartFormRequestOptions({ body, ...options }));
9010
+ del(vectorStoreId, fileId, options) {
9011
+ return this._client.delete(`/vector_stores/${vectorStoreId}/files/${fileId}`, {
9012
+ ...options,
9013
+ headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
9014
+ });
8523
9015
  }
8524
9016
  /**
8525
- * Creates an edited or extended image given an original image and a prompt.
9017
+ * Attach a file to the given vector store and wait for it to be processed.
8526
9018
  */
8527
- edit(body, options) {
8528
- return this._client.post('/images/edits', multipartFormRequestOptions({ body, ...options }));
9019
+ async createAndPoll(vectorStoreId, body, options) {
9020
+ const file = await this.create(vectorStoreId, body, options);
9021
+ return await this.poll(vectorStoreId, file.id, options);
8529
9022
  }
8530
9023
  /**
8531
- * Creates an image given a prompt.
9024
+ * Wait for the vector store file to finish processing.
9025
+ *
9026
+ * Note: this will return even if the file failed to process, you need to check
9027
+ * file.last_error and file.status to handle these cases
8532
9028
  */
8533
- generate(body, options) {
8534
- return this._client.post('/images/generations', { body, ...options });
9029
+ async poll(vectorStoreId, fileId, options) {
9030
+ const headers = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' };
9031
+ if (options?.pollIntervalMs) {
9032
+ headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString();
9033
+ }
9034
+ while (true) {
9035
+ const fileResponse = await this.retrieve(vectorStoreId, fileId, {
9036
+ ...options,
9037
+ headers,
9038
+ }).withResponse();
9039
+ const file = fileResponse.data;
9040
+ switch (file.status) {
9041
+ case 'in_progress':
9042
+ let sleepInterval = 5000;
9043
+ if (options?.pollIntervalMs) {
9044
+ sleepInterval = options.pollIntervalMs;
9045
+ }
9046
+ else {
9047
+ const headerInterval = fileResponse.response.headers.get('openai-poll-after-ms');
9048
+ if (headerInterval) {
9049
+ const headerIntervalMs = parseInt(headerInterval);
9050
+ if (!isNaN(headerIntervalMs)) {
9051
+ sleepInterval = headerIntervalMs;
9052
+ }
9053
+ }
9054
+ }
9055
+ await sleep(sleepInterval);
9056
+ break;
9057
+ case 'failed':
9058
+ case 'completed':
9059
+ return file;
9060
+ }
9061
+ }
8535
9062
  }
8536
- }
8537
-
8538
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8539
- class Models extends APIResource {
8540
9063
  /**
8541
- * Retrieves a model instance, providing basic information about the model such as
8542
- * the owner and permissioning.
9064
+ * Upload a file to the `files` API and then attach it to the given vector store.
9065
+ *
9066
+ * Note the file will be asynchronously processed (you can use the alternative
9067
+ * polling helper method to wait for processing to complete).
8543
9068
  */
8544
- retrieve(model, options) {
8545
- return this._client.get(`/models/${model}`, options);
9069
+ async upload(vectorStoreId, file, options) {
9070
+ const fileInfo = await this._client.files.create({ file: file, purpose: 'assistants' }, options);
9071
+ return this.create(vectorStoreId, { file_id: fileInfo.id }, options);
8546
9072
  }
8547
9073
  /**
8548
- * Lists the currently available models, and provides basic information about each
8549
- * one such as the owner and availability.
9074
+ * Add a file to a vector store and poll until processing is complete.
8550
9075
  */
8551
- list(options) {
8552
- return this._client.getAPIList('/models', ModelsPage, options);
9076
+ async uploadAndPoll(vectorStoreId, file, options) {
9077
+ const fileInfo = await this.upload(vectorStoreId, file, options);
9078
+ return await this.poll(vectorStoreId, fileInfo.id, options);
8553
9079
  }
8554
9080
  /**
8555
- * Delete a fine-tuned model. You must have the Owner role in your organization to
8556
- * delete a model.
9081
+ * Retrieve the parsed contents of a vector store file.
8557
9082
  */
8558
- del(model, options) {
8559
- return this._client.delete(`/models/${model}`, options);
9083
+ content(vectorStoreId, fileId, options) {
9084
+ return this._client.getAPIList(`/vector_stores/${vectorStoreId}/files/${fileId}/content`, FileContentResponsesPage, { ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers } });
8560
9085
  }
8561
9086
  }
9087
+ class VectorStoreFilesPage extends CursorPage {
9088
+ }
8562
9089
  /**
8563
9090
  * Note: no pagination actually occurs yet, this is for forwards-compatibility.
8564
9091
  */
8565
- class ModelsPage extends Page {
9092
+ class FileContentResponsesPage extends Page {
8566
9093
  }
8567
- Models.ModelsPage = ModelsPage;
9094
+ Files.VectorStoreFilesPage = VectorStoreFilesPage;
9095
+ Files.FileContentResponsesPage = FileContentResponsesPage;
8568
9096
 
8569
9097
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8570
- class Moderations extends APIResource {
9098
+ class FileBatches extends APIResource {
8571
9099
  /**
8572
- * Classifies if text and/or image inputs are potentially harmful. Learn more in
8573
- * the [moderation guide](https://platform.openai.com/docs/guides/moderation).
9100
+ * Create a vector store file batch.
8574
9101
  */
8575
- create(body, options) {
8576
- return this._client.post('/moderations', { body, ...options });
9102
+ create(vectorStoreId, body, options) {
9103
+ return this._client.post(`/vector_stores/${vectorStoreId}/file_batches`, {
9104
+ body,
9105
+ ...options,
9106
+ headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
9107
+ });
8577
9108
  }
8578
- }
8579
-
8580
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8581
- class Parts extends APIResource {
8582
9109
  /**
8583
- * Adds a
8584
- * [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an
8585
- * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object.
8586
- * A Part represents a chunk of bytes from the file you are trying to upload.
9110
+ * Retrieves a vector store file batch.
9111
+ */
9112
+ retrieve(vectorStoreId, batchId, options) {
9113
+ return this._client.get(`/vector_stores/${vectorStoreId}/file_batches/${batchId}`, {
9114
+ ...options,
9115
+ headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
9116
+ });
9117
+ }
9118
+ /**
9119
+ * Cancel a vector store file batch. This attempts to cancel the processing of
9120
+ * files in this batch as soon as possible.
9121
+ */
9122
+ cancel(vectorStoreId, batchId, options) {
9123
+ return this._client.post(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/cancel`, {
9124
+ ...options,
9125
+ headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
9126
+ });
9127
+ }
9128
+ /**
9129
+ * Create a vector store batch and poll until all files have been processed.
9130
+ */
9131
+ async createAndPoll(vectorStoreId, body, options) {
9132
+ const batch = await this.create(vectorStoreId, body);
9133
+ return await this.poll(vectorStoreId, batch.id, options);
9134
+ }
9135
+ listFiles(vectorStoreId, batchId, query = {}, options) {
9136
+ if (isRequestOptions(query)) {
9137
+ return this.listFiles(vectorStoreId, batchId, {}, query);
9138
+ }
9139
+ return this._client.getAPIList(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/files`, VectorStoreFilesPage, { query, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers } });
9140
+ }
9141
+ /**
9142
+ * Wait for the given file batch to be processed.
8587
9143
  *
8588
- * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload
8589
- * maximum of 8 GB.
9144
+ * Note: this will return even if one of the files failed to process, you need to
9145
+ * check batch.file_counts.failed_count to handle this case.
9146
+ */
9147
+ async poll(vectorStoreId, batchId, options) {
9148
+ const headers = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' };
9149
+ if (options?.pollIntervalMs) {
9150
+ headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString();
9151
+ }
9152
+ while (true) {
9153
+ const { data: batch, response } = await this.retrieve(vectorStoreId, batchId, {
9154
+ ...options,
9155
+ headers,
9156
+ }).withResponse();
9157
+ switch (batch.status) {
9158
+ case 'in_progress':
9159
+ let sleepInterval = 5000;
9160
+ if (options?.pollIntervalMs) {
9161
+ sleepInterval = options.pollIntervalMs;
9162
+ }
9163
+ else {
9164
+ const headerInterval = response.headers.get('openai-poll-after-ms');
9165
+ if (headerInterval) {
9166
+ const headerIntervalMs = parseInt(headerInterval);
9167
+ if (!isNaN(headerIntervalMs)) {
9168
+ sleepInterval = headerIntervalMs;
9169
+ }
9170
+ }
9171
+ }
9172
+ await sleep(sleepInterval);
9173
+ break;
9174
+ case 'failed':
9175
+ case 'cancelled':
9176
+ case 'completed':
9177
+ return batch;
9178
+ }
9179
+ }
9180
+ }
9181
+ /**
9182
+ * Uploads the given files concurrently and then creates a vector store file batch.
8590
9183
  *
8591
- * It is possible to add multiple Parts in parallel. You can decide the intended
8592
- * order of the Parts when you
8593
- * [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete).
9184
+ * The concurrency limit is configurable using the `maxConcurrency` parameter.
8594
9185
  */
8595
- create(uploadId, body, options) {
8596
- return this._client.post(`/uploads/${uploadId}/parts`, multipartFormRequestOptions({ body, ...options }));
9186
+ async uploadAndPoll(vectorStoreId, { files, fileIds = [] }, options) {
9187
+ if (files == null || files.length == 0) {
9188
+ throw new Error(`No \`files\` provided to process. If you've already uploaded files you should use \`.createAndPoll()\` instead`);
9189
+ }
9190
+ const configuredConcurrency = options?.maxConcurrency ?? 5;
9191
+ // We cap the number of workers at the number of files (so we don't start any unnecessary workers)
9192
+ const concurrencyLimit = Math.min(configuredConcurrency, files.length);
9193
+ const client = this._client;
9194
+ const fileIterator = files.values();
9195
+ const allFileIds = [...fileIds];
9196
+ // This code is based on this design. The libraries don't accommodate our environment limits.
9197
+ // https://stackoverflow.com/questions/40639432/what-is-the-best-way-to-limit-concurrency-when-using-es6s-promise-all
9198
+ async function processFiles(iterator) {
9199
+ for (let item of iterator) {
9200
+ const fileObj = await client.files.create({ file: item, purpose: 'assistants' }, options);
9201
+ allFileIds.push(fileObj.id);
9202
+ }
9203
+ }
9204
+ // Start workers to process results
9205
+ const workers = Array(concurrencyLimit).fill(fileIterator).map(processFiles);
9206
+ // Wait for all processing to complete.
9207
+ await allSettledWithThrow(workers);
9208
+ return await this.createAndPoll(vectorStoreId, {
9209
+ file_ids: allFileIds,
9210
+ });
8597
9211
  }
8598
9212
  }
8599
9213
 
8600
9214
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8601
- class Uploads extends APIResource {
9215
+ class VectorStores extends APIResource {
8602
9216
  constructor() {
8603
9217
  super(...arguments);
8604
- this.parts = new Parts(this._client);
9218
+ this.files = new Files(this._client);
9219
+ this.fileBatches = new FileBatches(this._client);
8605
9220
  }
8606
9221
  /**
8607
- * Creates an intermediate
8608
- * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object
8609
- * that you can add
8610
- * [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to.
8611
- * Currently, an Upload can accept at most 8 GB in total and expires after an hour
8612
- * after you create it.
8613
- *
8614
- * Once you complete the Upload, we will create a
8615
- * [File](https://platform.openai.com/docs/api-reference/files/object) object that
8616
- * contains all the parts you uploaded. This File is usable in the rest of our
8617
- * platform as a regular File object.
8618
- *
8619
- * For certain `purpose`s, the correct `mime_type` must be specified. Please refer
8620
- * to documentation for the supported MIME types for your use case:
8621
- *
8622
- * - [Assistants](https://platform.openai.com/docs/assistants/tools/file-search#supported-files)
8623
- *
8624
- * For guidance on the proper filename extensions for each purpose, please follow
8625
- * the documentation on
8626
- * [creating a File](https://platform.openai.com/docs/api-reference/files/create).
9222
+ * Create a vector store.
8627
9223
  */
8628
9224
  create(body, options) {
8629
- return this._client.post('/uploads', { body, ...options });
9225
+ return this._client.post('/vector_stores', {
9226
+ body,
9227
+ ...options,
9228
+ headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
9229
+ });
8630
9230
  }
8631
9231
  /**
8632
- * Cancels the Upload. No Parts may be added after an Upload is cancelled.
9232
+ * Retrieves a vector store.
8633
9233
  */
8634
- cancel(uploadId, options) {
8635
- return this._client.post(`/uploads/${uploadId}/cancel`, options);
9234
+ retrieve(vectorStoreId, options) {
9235
+ return this._client.get(`/vector_stores/${vectorStoreId}`, {
9236
+ ...options,
9237
+ headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
9238
+ });
8636
9239
  }
8637
9240
  /**
8638
- * Completes the
8639
- * [Upload](https://platform.openai.com/docs/api-reference/uploads/object).
8640
- *
8641
- * Within the returned Upload object, there is a nested
8642
- * [File](https://platform.openai.com/docs/api-reference/files/object) object that
8643
- * is ready to use in the rest of the platform.
8644
- *
8645
- * You can specify the order of the Parts by passing in an ordered list of the Part
8646
- * IDs.
8647
- *
8648
- * The number of bytes uploaded upon completion must match the number of bytes
8649
- * initially specified when creating the Upload object. No Parts may be added after
8650
- * an Upload is completed.
9241
+ * Modifies a vector store.
8651
9242
  */
8652
- complete(uploadId, body, options) {
8653
- return this._client.post(`/uploads/${uploadId}/complete`, { body, ...options });
9243
+ update(vectorStoreId, body, options) {
9244
+ return this._client.post(`/vector_stores/${vectorStoreId}`, {
9245
+ body,
9246
+ ...options,
9247
+ headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
9248
+ });
9249
+ }
9250
+ list(query = {}, options) {
9251
+ if (isRequestOptions(query)) {
9252
+ return this.list({}, query);
9253
+ }
9254
+ return this._client.getAPIList('/vector_stores', VectorStoresPage, {
9255
+ query,
9256
+ ...options,
9257
+ headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
9258
+ });
9259
+ }
9260
+ /**
9261
+ * Delete a vector store.
9262
+ */
9263
+ del(vectorStoreId, options) {
9264
+ return this._client.delete(`/vector_stores/${vectorStoreId}`, {
9265
+ ...options,
9266
+ headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
9267
+ });
9268
+ }
9269
+ /**
9270
+ * Search a vector store for relevant chunks based on a query and file attributes
9271
+ * filter.
9272
+ */
9273
+ search(vectorStoreId, body, options) {
9274
+ return this._client.getAPIList(`/vector_stores/${vectorStoreId}/search`, VectorStoreSearchResponsesPage, {
9275
+ body,
9276
+ method: 'post',
9277
+ ...options,
9278
+ headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
9279
+ });
8654
9280
  }
8655
9281
  }
8656
- Uploads.Parts = Parts;
9282
+ class VectorStoresPage extends CursorPage {
9283
+ }
9284
+ /**
9285
+ * Note: no pagination actually occurs yet, this is for forwards-compatibility.
9286
+ */
9287
+ class VectorStoreSearchResponsesPage extends Page {
9288
+ }
9289
+ VectorStores.VectorStoresPage = VectorStoresPage;
9290
+ VectorStores.VectorStoreSearchResponsesPage = VectorStoreSearchResponsesPage;
9291
+ VectorStores.Files = Files;
9292
+ VectorStores.VectorStoreFilesPage = VectorStoreFilesPage;
9293
+ VectorStores.FileContentResponsesPage = FileContentResponsesPage;
9294
+ VectorStores.FileBatches = FileBatches;
8657
9295
 
8658
9296
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8659
9297
  var _a;
@@ -8700,15 +9338,17 @@ class OpenAI extends APIClient {
8700
9338
  this.completions = new Completions(this);
8701
9339
  this.chat = new Chat$1(this);
8702
9340
  this.embeddings = new Embeddings(this);
8703
- this.files = new Files(this);
9341
+ this.files = new Files$1(this);
8704
9342
  this.images = new Images(this);
8705
9343
  this.audio = new Audio(this);
8706
9344
  this.moderations = new Moderations(this);
8707
9345
  this.models = new Models(this);
8708
9346
  this.fineTuning = new FineTuning(this);
9347
+ this.vectorStores = new VectorStores(this);
8709
9348
  this.beta = new Beta(this);
8710
9349
  this.batches = new Batches(this);
8711
9350
  this.uploads = new Uploads(this);
9351
+ this.responses = new Responses(this);
8712
9352
  this._options = options;
8713
9353
  this.apiKey = apiKey;
8714
9354
  this.organization = organization;
@@ -8752,8 +9392,9 @@ OpenAI.toFile = toFile;
8752
9392
  OpenAI.fileFromPath = fileFromPath;
8753
9393
  OpenAI.Completions = Completions;
8754
9394
  OpenAI.Chat = Chat$1;
9395
+ OpenAI.ChatCompletionsPage = ChatCompletionsPage;
8755
9396
  OpenAI.Embeddings = Embeddings;
8756
- OpenAI.Files = Files;
9397
+ OpenAI.Files = Files$1;
8757
9398
  OpenAI.FileObjectsPage = FileObjectsPage;
8758
9399
  OpenAI.Images = Images;
8759
9400
  OpenAI.Audio = Audio;
@@ -8761,10 +9402,14 @@ OpenAI.Moderations = Moderations;
8761
9402
  OpenAI.Models = Models;
8762
9403
  OpenAI.ModelsPage = ModelsPage;
8763
9404
  OpenAI.FineTuning = FineTuning;
9405
+ OpenAI.VectorStores = VectorStores;
9406
+ OpenAI.VectorStoresPage = VectorStoresPage;
9407
+ OpenAI.VectorStoreSearchResponsesPage = VectorStoreSearchResponsesPage;
8764
9408
  OpenAI.Beta = Beta;
8765
9409
  OpenAI.Batches = Batches;
8766
9410
  OpenAI.BatchesPage = BatchesPage;
8767
9411
  OpenAI.Uploads = Uploads;
9412
+ OpenAI.Responses = Responses;
8768
9413
 
8769
9414
  class OpenaiProvider {
8770
9415
  constructor(param, defaultModel, options) {
@@ -9382,7 +10027,7 @@ ${JSON.stringify(nodeOutputs)}
9382
10027
  return {
9383
10028
  isSuccessful: contextVariables.get("__isSuccessful__"),
9384
10029
  summary: response.toolCalls[0].input.summary,
9385
- payload: response.toolCalls[0].input.document,
10030
+ payload: (response.toolCalls[0].input.isDocumentGenerationTask ? response.toolCalls[0].input.document : undefined),
9386
10031
  };
9387
10032
  }
9388
10033
 
@@ -10185,6 +10830,18 @@ Navigation Bar or Menu Changes: After logging in, the navigation bar will includ
10185
10830
  // "type": "string",
10186
10831
  // "description": 'Your observation of the previous steps. Should start with "In the previous step, I\'ve ...".',
10187
10832
  // },
10833
+ evaluate_previous_goal: {
10834
+ "type": "string",
10835
+ "description": "Success|Failed|Unknown - Analyze the current elements and the image to check if the previous goals/actions are successful like intended by the task. Mention if something unexpected happened. Shortly state why/why not"
10836
+ },
10837
+ memory: {
10838
+ "type": "string",
10839
+ "description": "Description of what has been done and what you need to remember. Be very specific. Count here ALWAYS how many times you have done something and how many remain. E.g. 0 out of 10 websites analyzed. Continue with abc and xyz",
10840
+ },
10841
+ next_goal: {
10842
+ "type": "string",
10843
+ "description": "What needs to be done with the next immediate action",
10844
+ },
10188
10845
  thinking: {
10189
10846
  "type": "string",
10190
10847
  "description": 'Your thinking draft.',
@@ -10200,6 +10857,9 @@ Navigation Bar or Menu Changes: After logging in, the navigation bar will includ
10200
10857
  // "observation",
10201
10858
  "thinking",
10202
10859
  "userSidePrompt",
10860
+ "memory",
10861
+ "next_goal",
10862
+ "evaluate_previous_goal",
10203
10863
  "toolCall",
10204
10864
  ],
10205
10865
  };
@@ -10210,6 +10870,9 @@ Navigation Bar or Menu Changes: After logging in, the navigation bar will includ
10210
10870
  observation: toolCall.input.observation,
10211
10871
  thinking: toolCall.input.thinking,
10212
10872
  userSidePrompt: toolCall.input.userSidePrompt,
10873
+ evaluate_previous_goal: toolCall.input.evaluate_previous_goal,
10874
+ memory: toolCall.input.memory,
10875
+ next_goal: toolCall.input.next_goal,
10213
10876
  toolCall: {
10214
10877
  id: toolCall.id,
10215
10878
  name: toolCall.name,
@@ -10270,6 +10933,8 @@ class WorkflowGenerator {
10270
10933
  }
10271
10934
  async doGenerateWorkflow(prompt, modify, ekoConfig) {
10272
10935
  // Create prompts with current set of tools
10936
+ logger.debug("doGenerateWorkflow...");
10937
+ let retry_counter = 3;
10273
10938
  const prompts = createWorkflowPrompts(this.toolRegistry.getToolDefinitions());
10274
10939
  let messages = [];
10275
10940
  if (modify) {
@@ -10297,41 +10962,38 @@ class WorkflowGenerator {
10297
10962
  tools: [createWorkflowGenerationTool(this.toolRegistry)],
10298
10963
  toolChoice: { type: 'tool', name: 'generate_workflow' },
10299
10964
  };
10300
- console.time('Workflow Generation Time'); // 开始计时
10301
- const response = await this.llmProvider.generateText(messages, params);
10302
- console.timeEnd('Workflow Generation Time'); // 结束计时并输出时间差
10303
- if (!response.toolCalls.length || !response.toolCalls[0].input.workflow) {
10304
- messages.pop();
10305
- throw new Error('Failed to generate workflow: Invalid response from LLM');
10306
- }
10307
- messages.push({
10308
- role: 'assistant',
10309
- content: [
10310
- {
10311
- type: 'tool_use',
10312
- id: response.toolCalls[0].id,
10313
- name: response.toolCalls[0].name,
10314
- input: response.toolCalls[0].input,
10315
- },
10316
- ],
10317
- }, {
10318
- role: 'user',
10319
- content: [
10320
- {
10321
- type: 'tool_result',
10322
- tool_use_id: response.toolCalls[0].id,
10323
- content: 'ok',
10324
- },
10325
- ],
10326
- });
10327
- const workflowData = response.toolCalls[0].input.workflow;
10328
- // debug
10329
- logger.debug("Debug the workflow...", { ...workflowData });
10330
- // Generate a new UUID if not provided
10331
- if (!workflowData.id) {
10332
- workflowData.id = uuid.v4();
10965
+ while (retry_counter > 0) {
10966
+ try {
10967
+ console.time('Workflow Generation Time'); // 开始计时
10968
+ const response = await this.llmProvider.generateText(messages, params);
10969
+ console.timeEnd('Workflow Generation Time'); // 结束计时并输出时间差
10970
+ logger.debug("generateText() done!");
10971
+ if (!response.toolCalls.length || !response.toolCalls[0].input.workflow) {
10972
+ messages.pop();
10973
+ throw new Error('Failed to generate workflow: Invalid response from LLM');
10974
+ }
10975
+ let workflowData = response.toolCalls[0].input.workflow;
10976
+ // debug
10977
+ if (typeof workflowData == "string") {
10978
+ logger.warn("workflowData is string, try to transform it into object...");
10979
+ logger.debug("workflowData string:", workflowData);
10980
+ workflowData = JSON.parse(workflowData);
10981
+ }
10982
+ logger.debug("Debug the workflow...", { ...workflowData });
10983
+ // Generate a new UUID if not provided
10984
+ if (!workflowData.id) {
10985
+ workflowData.id = uuid.v4();
10986
+ }
10987
+ return this.createFastWorkflowFromData(workflowData, ekoConfig);
10988
+ }
10989
+ catch (e) {
10990
+ logger.warn("an error occured when generating workflow:", e);
10991
+ logger.info(`retry...${retry_counter}`);
10992
+ retry_counter -= 1;
10993
+ }
10333
10994
  }
10334
- return this.createFastWorkflowFromData(workflowData, ekoConfig);
10995
+ logger.error("cannot generate workflow with retry");
10996
+ throw Error("many errors occured when generating workflow");
10335
10997
  }
10336
10998
  createWorkflowFromData(data, ekoConfig) {
10337
10999
  const workflow = new WorkflowImpl(data.id, data.name, ekoConfig, data, data.description || '', [], new Map(Object.entries(data.variables || {})), this.llmProvider, {
@@ -10370,7 +11032,7 @@ class WorkflowGenerator {
10370
11032
  // Add nodes to workflow
10371
11033
  if (Array.isArray(data.nodes)) {
10372
11034
  data.nodes.forEach((nodeData) => {
10373
- const action = ActionImpl.createPromptAction(nodeData.action.name, nodeData.action.description, [this.toolRegistry.getTool('browser_use')], this.llmProvider, { maxTokens: 8192 });
11035
+ const action = ActionImpl.createPromptAction(nodeData.action.name, nodeData.action.description, [this.toolRegistry.getTool('browser_action')], this.llmProvider, { maxTokens: 8192 });
10374
11036
  const node = {
10375
11037
  id: nodeData.id,
10376
11038
  name: nodeData.name || nodeData.id,
@@ -10501,7 +11163,7 @@ class Eko {
10501
11163
  this.llmProvider = LLMProviderFactory.buildLLMProvider(llmConfig);
10502
11164
  this.ekoConfig = this.buildEkoConfig(ekoConfig);
10503
11165
  this.registerTools();
10504
- logger.info("using Eko@" + "0b8135fc46d59eb59eb56c57564e2db06526249b");
11166
+ logger.info("using Eko@" + "a5c3c50087c75ad4abcf1d0dbb58aa4bf0227c13");
10505
11167
  logger.debug("caller's ekoConfig:", ekoConfig);
10506
11168
  }
10507
11169
  static getLogger() {
@@ -10594,7 +11256,7 @@ class Eko {
10594
11256
  'name': prompt,
10595
11257
  'description': description,
10596
11258
  'tools': [
10597
- 'browser_use',
11259
+ 'browser_action',
10598
11260
  'document_agent',
10599
11261
  'export_file',
10600
11262
  'extract_content',