@eko-ai/eko 1.2.3 → 1.2.5

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.esm.js CHANGED
@@ -366,7 +366,7 @@ let Stream$1 = class Stream {
366
366
  let consumed = false;
367
367
  async function* iterLines() {
368
368
  const lineDecoder = new LineDecoder$1();
369
- const iter = readableStreamAsyncIterable(readableStream);
369
+ const iter = readableStreamAsyncIterable$1(readableStream);
370
370
  for await (const chunk of iter) {
371
371
  for (const line of lineDecoder.decode(chunk)) {
372
372
  yield line;
@@ -471,7 +471,7 @@ async function* _iterSSEMessages$1(response, controller) {
471
471
  }
472
472
  const sseDecoder = new SSEDecoder$1();
473
473
  const lineDecoder = new LineDecoder$1();
474
- const iter = readableStreamAsyncIterable(response.body);
474
+ const iter = readableStreamAsyncIterable$1(response.body);
475
475
  for await (const sseChunk of iterSSEChunks$1(iter)) {
476
476
  for (const line of lineDecoder.decode(sseChunk)) {
477
477
  const sse = sseDecoder.decode(line);
@@ -592,7 +592,7 @@ function partition$1(str, delimiter) {
592
592
  *
593
593
  * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490
594
594
  */
595
- function readableStreamAsyncIterable(stream) {
595
+ function readableStreamAsyncIterable$1(stream) {
596
596
  if (stream[Symbol.asyncIterator])
597
597
  return stream;
598
598
  const reader = stream.getReader();
@@ -718,13 +718,13 @@ const getStringFromMaybeBuffer$1 = (x) => {
718
718
  const isAsyncIterableIterator$1 = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function';
719
719
  const isMultipartBody$1 = (body) => body && typeof body === 'object' && body.body && body[Symbol.toStringTag] === 'MultipartBody';
720
720
 
721
- var __classPrivateFieldSet$7 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
721
+ var __classPrivateFieldSet$5 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
722
722
  if (kind === "m") throw new TypeError("Private method is not writable");
723
723
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
724
724
  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");
725
725
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
726
726
  };
727
- var __classPrivateFieldGet$8 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
727
+ var __classPrivateFieldGet$6 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
728
728
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
729
729
  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");
730
730
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
@@ -1156,7 +1156,7 @@ let APIClient$1 = class APIClient {
1156
1156
  let AbstractPage$1 = class AbstractPage {
1157
1157
  constructor(client, response, body, options) {
1158
1158
  _AbstractPage_client$1.set(this, void 0);
1159
- __classPrivateFieldSet$7(this, _AbstractPage_client$1, client, "f");
1159
+ __classPrivateFieldSet$5(this, _AbstractPage_client$1, client, "f");
1160
1160
  this.options = options;
1161
1161
  this.response = response;
1162
1162
  this.body = body;
@@ -1184,7 +1184,7 @@ let AbstractPage$1 = class AbstractPage {
1184
1184
  nextOptions.query = undefined;
1185
1185
  nextOptions.path = nextInfo.url.toString();
1186
1186
  }
1187
- return await __classPrivateFieldGet$8(this, _AbstractPage_client$1, "f").requestAPIList(this.constructor, nextOptions);
1187
+ return await __classPrivateFieldGet$6(this, _AbstractPage_client$1, "f").requestAPIList(this.constructor, nextOptions);
1188
1188
  }
1189
1189
  async *iterPages() {
1190
1190
  // eslint-disable-next-line @typescript-eslint/no-this-alias
@@ -1634,7 +1634,7 @@ class JSONLDecoder {
1634
1634
  controller.abort();
1635
1635
  throw new AnthropicError(`Attempted to iterate over a response with no body`);
1636
1636
  }
1637
- return new JSONLDecoder(readableStreamAsyncIterable(response.body), controller);
1637
+ return new JSONLDecoder(readableStreamAsyncIterable$1(response.body), controller);
1638
1638
  }
1639
1639
  }
1640
1640
 
@@ -1724,7 +1724,7 @@ class BetaMessageBatchesPage extends Page$1 {
1724
1724
  Batches$2.BetaMessageBatchesPage = BetaMessageBatchesPage;
1725
1725
 
1726
1726
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
1727
- let Messages$3 = class Messages extends APIResource$1 {
1727
+ let Messages$2 = class Messages extends APIResource$1 {
1728
1728
  constructor() {
1729
1729
  super(...arguments);
1730
1730
  this.batches = new Batches$2(this._client);
@@ -1760,20 +1760,20 @@ let Messages$3 = class Messages extends APIResource$1 {
1760
1760
  });
1761
1761
  }
1762
1762
  };
1763
- Messages$3.Batches = Batches$2;
1764
- Messages$3.BetaMessageBatchesPage = BetaMessageBatchesPage;
1763
+ Messages$2.Batches = Batches$2;
1764
+ Messages$2.BetaMessageBatchesPage = BetaMessageBatchesPage;
1765
1765
 
1766
1766
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
1767
1767
  let Beta$1 = class Beta extends APIResource$1 {
1768
1768
  constructor() {
1769
1769
  super(...arguments);
1770
1770
  this.models = new Models$2(this._client);
1771
- this.messages = new Messages$3(this._client);
1771
+ this.messages = new Messages$2(this._client);
1772
1772
  }
1773
1773
  };
1774
1774
  Beta$1.Models = Models$2;
1775
1775
  Beta$1.BetaModelInfosPage = BetaModelInfosPage;
1776
- Beta$1.Messages = Messages$3;
1776
+ Beta$1.Messages = Messages$2;
1777
1777
 
1778
1778
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
1779
1779
  let Completions$3 = class Completions extends APIResource$1 {
@@ -2068,13 +2068,13 @@ const tokenize = (input) => {
2068
2068
  return output;
2069
2069
  }, partialParse$1 = (input) => JSON.parse(generate(unstrip(strip(tokenize(input)))));
2070
2070
 
2071
- var __classPrivateFieldSet$6 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2071
+ var __classPrivateFieldSet$4 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2072
2072
  if (kind === "m") throw new TypeError("Private method is not writable");
2073
2073
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
2074
2074
  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");
2075
2075
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
2076
2076
  };
2077
- var __classPrivateFieldGet$7 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
2077
+ var __classPrivateFieldGet$5 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
2078
2078
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
2079
2079
  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");
2080
2080
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
@@ -2100,12 +2100,12 @@ class MessageStream {
2100
2100
  _MessageStream_aborted.set(this, false);
2101
2101
  _MessageStream_catchingPromiseCreated.set(this, false);
2102
2102
  _MessageStream_handleError.set(this, (error) => {
2103
- __classPrivateFieldSet$6(this, _MessageStream_errored, true, "f");
2103
+ __classPrivateFieldSet$4(this, _MessageStream_errored, true, "f");
2104
2104
  if (error instanceof Error && error.name === 'AbortError') {
2105
2105
  error = new APIUserAbortError$1();
2106
2106
  }
2107
2107
  if (error instanceof APIUserAbortError$1) {
2108
- __classPrivateFieldSet$6(this, _MessageStream_aborted, true, "f");
2108
+ __classPrivateFieldSet$4(this, _MessageStream_aborted, true, "f");
2109
2109
  return this._emit('abort', error);
2110
2110
  }
2111
2111
  if (error instanceof AnthropicError) {
@@ -2119,20 +2119,20 @@ class MessageStream {
2119
2119
  }
2120
2120
  return this._emit('error', new AnthropicError(String(error)));
2121
2121
  });
2122
- __classPrivateFieldSet$6(this, _MessageStream_connectedPromise, new Promise((resolve, reject) => {
2123
- __classPrivateFieldSet$6(this, _MessageStream_resolveConnectedPromise, resolve, "f");
2124
- __classPrivateFieldSet$6(this, _MessageStream_rejectConnectedPromise, reject, "f");
2122
+ __classPrivateFieldSet$4(this, _MessageStream_connectedPromise, new Promise((resolve, reject) => {
2123
+ __classPrivateFieldSet$4(this, _MessageStream_resolveConnectedPromise, resolve, "f");
2124
+ __classPrivateFieldSet$4(this, _MessageStream_rejectConnectedPromise, reject, "f");
2125
2125
  }), "f");
2126
- __classPrivateFieldSet$6(this, _MessageStream_endPromise, new Promise((resolve, reject) => {
2127
- __classPrivateFieldSet$6(this, _MessageStream_resolveEndPromise, resolve, "f");
2128
- __classPrivateFieldSet$6(this, _MessageStream_rejectEndPromise, reject, "f");
2126
+ __classPrivateFieldSet$4(this, _MessageStream_endPromise, new Promise((resolve, reject) => {
2127
+ __classPrivateFieldSet$4(this, _MessageStream_resolveEndPromise, resolve, "f");
2128
+ __classPrivateFieldSet$4(this, _MessageStream_rejectEndPromise, reject, "f");
2129
2129
  }), "f");
2130
2130
  // Don't let these promises cause unhandled rejection errors.
2131
2131
  // we will manually cause an unhandled rejection error later
2132
2132
  // if the user hasn't registered any error listener or called
2133
2133
  // any promise-returning method.
2134
- __classPrivateFieldGet$7(this, _MessageStream_connectedPromise, "f").catch(() => { });
2135
- __classPrivateFieldGet$7(this, _MessageStream_endPromise, "f").catch(() => { });
2134
+ __classPrivateFieldGet$5(this, _MessageStream_connectedPromise, "f").catch(() => { });
2135
+ __classPrivateFieldGet$5(this, _MessageStream_endPromise, "f").catch(() => { });
2136
2136
  }
2137
2137
  /**
2138
2138
  * Intended for use on the frontend, consuming a stream produced with
@@ -2158,7 +2158,7 @@ class MessageStream {
2158
2158
  executor().then(() => {
2159
2159
  this._emitFinal();
2160
2160
  this._emit('end');
2161
- }, __classPrivateFieldGet$7(this, _MessageStream_handleError, "f"));
2161
+ }, __classPrivateFieldGet$5(this, _MessageStream_handleError, "f"));
2162
2162
  }
2163
2163
  _addMessageParam(message) {
2164
2164
  this.messages.push(message);
@@ -2176,31 +2176,31 @@ class MessageStream {
2176
2176
  this.controller.abort();
2177
2177
  signal.addEventListener('abort', () => this.controller.abort());
2178
2178
  }
2179
- __classPrivateFieldGet$7(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this);
2179
+ __classPrivateFieldGet$5(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this);
2180
2180
  const stream = await messages.create({ ...params, stream: true }, { ...options, signal: this.controller.signal });
2181
2181
  this._connected();
2182
2182
  for await (const event of stream) {
2183
- __classPrivateFieldGet$7(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event);
2183
+ __classPrivateFieldGet$5(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event);
2184
2184
  }
2185
2185
  if (stream.controller.signal?.aborted) {
2186
2186
  throw new APIUserAbortError$1();
2187
2187
  }
2188
- __classPrivateFieldGet$7(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this);
2188
+ __classPrivateFieldGet$5(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this);
2189
2189
  }
2190
2190
  _connected() {
2191
2191
  if (this.ended)
2192
2192
  return;
2193
- __classPrivateFieldGet$7(this, _MessageStream_resolveConnectedPromise, "f").call(this);
2193
+ __classPrivateFieldGet$5(this, _MessageStream_resolveConnectedPromise, "f").call(this);
2194
2194
  this._emit('connect');
2195
2195
  }
2196
2196
  get ended() {
2197
- return __classPrivateFieldGet$7(this, _MessageStream_ended, "f");
2197
+ return __classPrivateFieldGet$5(this, _MessageStream_ended, "f");
2198
2198
  }
2199
2199
  get errored() {
2200
- return __classPrivateFieldGet$7(this, _MessageStream_errored, "f");
2200
+ return __classPrivateFieldGet$5(this, _MessageStream_errored, "f");
2201
2201
  }
2202
2202
  get aborted() {
2203
- return __classPrivateFieldGet$7(this, _MessageStream_aborted, "f");
2203
+ return __classPrivateFieldGet$5(this, _MessageStream_aborted, "f");
2204
2204
  }
2205
2205
  abort() {
2206
2206
  this.controller.abort();
@@ -2213,7 +2213,7 @@ class MessageStream {
2213
2213
  * @returns this MessageStream, so that calls can be chained
2214
2214
  */
2215
2215
  on(event, listener) {
2216
- const listeners = __classPrivateFieldGet$7(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet$7(this, _MessageStream_listeners, "f")[event] = []);
2216
+ const listeners = __classPrivateFieldGet$5(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet$5(this, _MessageStream_listeners, "f")[event] = []);
2217
2217
  listeners.push({ listener });
2218
2218
  return this;
2219
2219
  }
@@ -2225,7 +2225,7 @@ class MessageStream {
2225
2225
  * @returns this MessageStream, so that calls can be chained
2226
2226
  */
2227
2227
  off(event, listener) {
2228
- const listeners = __classPrivateFieldGet$7(this, _MessageStream_listeners, "f")[event];
2228
+ const listeners = __classPrivateFieldGet$5(this, _MessageStream_listeners, "f")[event];
2229
2229
  if (!listeners)
2230
2230
  return this;
2231
2231
  const index = listeners.findIndex((l) => l.listener === listener);
@@ -2239,7 +2239,7 @@ class MessageStream {
2239
2239
  * @returns this MessageStream, so that calls can be chained
2240
2240
  */
2241
2241
  once(event, listener) {
2242
- const listeners = __classPrivateFieldGet$7(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet$7(this, _MessageStream_listeners, "f")[event] = []);
2242
+ const listeners = __classPrivateFieldGet$5(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet$5(this, _MessageStream_listeners, "f")[event] = []);
2243
2243
  listeners.push({ listener, once: true });
2244
2244
  return this;
2245
2245
  }
@@ -2256,18 +2256,18 @@ class MessageStream {
2256
2256
  */
2257
2257
  emitted(event) {
2258
2258
  return new Promise((resolve, reject) => {
2259
- __classPrivateFieldSet$6(this, _MessageStream_catchingPromiseCreated, true, "f");
2259
+ __classPrivateFieldSet$4(this, _MessageStream_catchingPromiseCreated, true, "f");
2260
2260
  if (event !== 'error')
2261
2261
  this.once('error', reject);
2262
2262
  this.once(event, resolve);
2263
2263
  });
2264
2264
  }
2265
2265
  async done() {
2266
- __classPrivateFieldSet$6(this, _MessageStream_catchingPromiseCreated, true, "f");
2267
- await __classPrivateFieldGet$7(this, _MessageStream_endPromise, "f");
2266
+ __classPrivateFieldSet$4(this, _MessageStream_catchingPromiseCreated, true, "f");
2267
+ await __classPrivateFieldGet$5(this, _MessageStream_endPromise, "f");
2268
2268
  }
2269
2269
  get currentMessage() {
2270
- return __classPrivateFieldGet$7(this, _MessageStream_currentMessageSnapshot, "f");
2270
+ return __classPrivateFieldGet$5(this, _MessageStream_currentMessageSnapshot, "f");
2271
2271
  }
2272
2272
  /**
2273
2273
  * @returns a promise that resolves with the the final assistant Message response,
@@ -2275,7 +2275,7 @@ class MessageStream {
2275
2275
  */
2276
2276
  async finalMessage() {
2277
2277
  await this.done();
2278
- return __classPrivateFieldGet$7(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this);
2278
+ return __classPrivateFieldGet$5(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this);
2279
2279
  }
2280
2280
  /**
2281
2281
  * @returns a promise that resolves with the the final assistant Message's text response, concatenated
@@ -2284,35 +2284,35 @@ class MessageStream {
2284
2284
  */
2285
2285
  async finalText() {
2286
2286
  await this.done();
2287
- return __classPrivateFieldGet$7(this, _MessageStream_instances, "m", _MessageStream_getFinalText).call(this);
2287
+ return __classPrivateFieldGet$5(this, _MessageStream_instances, "m", _MessageStream_getFinalText).call(this);
2288
2288
  }
2289
2289
  _emit(event, ...args) {
2290
2290
  // make sure we don't emit any MessageStreamEvents after end
2291
- if (__classPrivateFieldGet$7(this, _MessageStream_ended, "f"))
2291
+ if (__classPrivateFieldGet$5(this, _MessageStream_ended, "f"))
2292
2292
  return;
2293
2293
  if (event === 'end') {
2294
- __classPrivateFieldSet$6(this, _MessageStream_ended, true, "f");
2295
- __classPrivateFieldGet$7(this, _MessageStream_resolveEndPromise, "f").call(this);
2294
+ __classPrivateFieldSet$4(this, _MessageStream_ended, true, "f");
2295
+ __classPrivateFieldGet$5(this, _MessageStream_resolveEndPromise, "f").call(this);
2296
2296
  }
2297
- const listeners = __classPrivateFieldGet$7(this, _MessageStream_listeners, "f")[event];
2297
+ const listeners = __classPrivateFieldGet$5(this, _MessageStream_listeners, "f")[event];
2298
2298
  if (listeners) {
2299
- __classPrivateFieldGet$7(this, _MessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once);
2299
+ __classPrivateFieldGet$5(this, _MessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once);
2300
2300
  listeners.forEach(({ listener }) => listener(...args));
2301
2301
  }
2302
2302
  if (event === 'abort') {
2303
2303
  const error = args[0];
2304
- if (!__classPrivateFieldGet$7(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
2304
+ if (!__classPrivateFieldGet$5(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
2305
2305
  Promise.reject(error);
2306
2306
  }
2307
- __classPrivateFieldGet$7(this, _MessageStream_rejectConnectedPromise, "f").call(this, error);
2308
- __classPrivateFieldGet$7(this, _MessageStream_rejectEndPromise, "f").call(this, error);
2307
+ __classPrivateFieldGet$5(this, _MessageStream_rejectConnectedPromise, "f").call(this, error);
2308
+ __classPrivateFieldGet$5(this, _MessageStream_rejectEndPromise, "f").call(this, error);
2309
2309
  this._emit('end');
2310
2310
  return;
2311
2311
  }
2312
2312
  if (event === 'error') {
2313
2313
  // NOTE: _emit('error', error) should only be called from #handleError().
2314
2314
  const error = args[0];
2315
- if (!__classPrivateFieldGet$7(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
2315
+ if (!__classPrivateFieldGet$5(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
2316
2316
  // Trigger an unhandled rejection if the user hasn't registered any error handlers.
2317
2317
  // If you are seeing stack traces here, make sure to handle errors via either:
2318
2318
  // - runner.on('error', () => ...)
@@ -2321,15 +2321,15 @@ class MessageStream {
2321
2321
  // - etc.
2322
2322
  Promise.reject(error);
2323
2323
  }
2324
- __classPrivateFieldGet$7(this, _MessageStream_rejectConnectedPromise, "f").call(this, error);
2325
- __classPrivateFieldGet$7(this, _MessageStream_rejectEndPromise, "f").call(this, error);
2324
+ __classPrivateFieldGet$5(this, _MessageStream_rejectConnectedPromise, "f").call(this, error);
2325
+ __classPrivateFieldGet$5(this, _MessageStream_rejectEndPromise, "f").call(this, error);
2326
2326
  this._emit('end');
2327
2327
  }
2328
2328
  }
2329
2329
  _emitFinal() {
2330
2330
  const finalMessage = this.receivedMessages.at(-1);
2331
2331
  if (finalMessage) {
2332
- this._emit('finalMessage', __classPrivateFieldGet$7(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this));
2332
+ this._emit('finalMessage', __classPrivateFieldGet$5(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this));
2333
2333
  }
2334
2334
  }
2335
2335
  async _fromReadableStream(readableStream, options) {
@@ -2339,16 +2339,16 @@ class MessageStream {
2339
2339
  this.controller.abort();
2340
2340
  signal.addEventListener('abort', () => this.controller.abort());
2341
2341
  }
2342
- __classPrivateFieldGet$7(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this);
2342
+ __classPrivateFieldGet$5(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this);
2343
2343
  this._connected();
2344
2344
  const stream = Stream$1.fromReadableStream(readableStream, this.controller);
2345
2345
  for await (const event of stream) {
2346
- __classPrivateFieldGet$7(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event);
2346
+ __classPrivateFieldGet$5(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event);
2347
2347
  }
2348
2348
  if (stream.controller.signal?.aborted) {
2349
2349
  throw new APIUserAbortError$1();
2350
2350
  }
2351
- __classPrivateFieldGet$7(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this);
2351
+ __classPrivateFieldGet$5(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this);
2352
2352
  }
2353
2353
  [(_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() {
2354
2354
  if (this.receivedMessages.length === 0) {
@@ -2370,11 +2370,11 @@ class MessageStream {
2370
2370
  }, _MessageStream_beginRequest = function _MessageStream_beginRequest() {
2371
2371
  if (this.ended)
2372
2372
  return;
2373
- __classPrivateFieldSet$6(this, _MessageStream_currentMessageSnapshot, undefined, "f");
2373
+ __classPrivateFieldSet$4(this, _MessageStream_currentMessageSnapshot, undefined, "f");
2374
2374
  }, _MessageStream_addStreamEvent = function _MessageStream_addStreamEvent(event) {
2375
2375
  if (this.ended)
2376
2376
  return;
2377
- const messageSnapshot = __classPrivateFieldGet$7(this, _MessageStream_instances, "m", _MessageStream_accumulateMessage).call(this, event);
2377
+ const messageSnapshot = __classPrivateFieldGet$5(this, _MessageStream_instances, "m", _MessageStream_accumulateMessage).call(this, event);
2378
2378
  this._emit('streamEvent', event, messageSnapshot);
2379
2379
  switch (event.type) {
2380
2380
  case 'content_block_delta': {
@@ -2399,7 +2399,7 @@ class MessageStream {
2399
2399
  break;
2400
2400
  }
2401
2401
  case 'message_start': {
2402
- __classPrivateFieldSet$6(this, _MessageStream_currentMessageSnapshot, messageSnapshot, "f");
2402
+ __classPrivateFieldSet$4(this, _MessageStream_currentMessageSnapshot, messageSnapshot, "f");
2403
2403
  break;
2404
2404
  }
2405
2405
  }
@@ -2407,14 +2407,14 @@ class MessageStream {
2407
2407
  if (this.ended) {
2408
2408
  throw new AnthropicError(`stream has ended, this shouldn't happen`);
2409
2409
  }
2410
- const snapshot = __classPrivateFieldGet$7(this, _MessageStream_currentMessageSnapshot, "f");
2410
+ const snapshot = __classPrivateFieldGet$5(this, _MessageStream_currentMessageSnapshot, "f");
2411
2411
  if (!snapshot) {
2412
2412
  throw new AnthropicError(`request ended without sending any chunks`);
2413
2413
  }
2414
- __classPrivateFieldSet$6(this, _MessageStream_currentMessageSnapshot, undefined, "f");
2414
+ __classPrivateFieldSet$4(this, _MessageStream_currentMessageSnapshot, undefined, "f");
2415
2415
  return snapshot;
2416
2416
  }, _MessageStream_accumulateMessage = function _MessageStream_accumulateMessage(event) {
2417
- let snapshot = __classPrivateFieldGet$7(this, _MessageStream_currentMessageSnapshot, "f");
2417
+ let snapshot = __classPrivateFieldGet$5(this, _MessageStream_currentMessageSnapshot, "f");
2418
2418
  if (event.type === 'message_start') {
2419
2419
  if (snapshot) {
2420
2420
  throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`);
@@ -2518,7 +2518,7 @@ class MessageStream {
2518
2518
  }
2519
2519
 
2520
2520
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2521
- let Messages$2 = class Messages extends APIResource$1 {
2521
+ let Messages$1 = class Messages extends APIResource$1 {
2522
2522
  constructor() {
2523
2523
  super(...arguments);
2524
2524
  this.batches = new Batches$1(this._client);
@@ -2557,8 +2557,8 @@ const DEPRECATED_MODELS = {
2557
2557
  'claude-instant-1.1-100k': 'November 6th, 2024',
2558
2558
  'claude-instant-1.2': 'November 6th, 2024',
2559
2559
  };
2560
- Messages$2.Batches = Batches$1;
2561
- Messages$2.MessageBatchesPage = MessageBatchesPage;
2560
+ Messages$1.Batches = Batches$1;
2561
+ Messages$1.MessageBatchesPage = MessageBatchesPage;
2562
2562
 
2563
2563
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2564
2564
  let Models$1 = class Models extends APIResource$1 {
@@ -2620,7 +2620,7 @@ class Anthropic extends APIClient$1 {
2620
2620
  fetch: options.fetch,
2621
2621
  });
2622
2622
  this.completions = new Completions$3(this);
2623
- this.messages = new Messages$2(this);
2623
+ this.messages = new Messages$1(this);
2624
2624
  this.models = new Models$1(this);
2625
2625
  this.beta = new Beta$1(this);
2626
2626
  this._options = options;
@@ -2700,11 +2700,10 @@ Anthropic.UnprocessableEntityError = UnprocessableEntityError$1;
2700
2700
  Anthropic.toFile = toFile$1;
2701
2701
  Anthropic.fileFromPath = fileFromPath$1;
2702
2702
  Anthropic.Completions = Completions$3;
2703
- Anthropic.Messages = Messages$2;
2703
+ Anthropic.Messages = Messages$1;
2704
2704
  Anthropic.Models = Models$1;
2705
2705
  Anthropic.ModelInfosPage = ModelInfosPage;
2706
2706
  Anthropic.Beta = Beta$1;
2707
- const { HUMAN_PROMPT, AI_PROMPT } = Anthropic;
2708
2707
 
2709
2708
  const prettyLogStyles = {
2710
2709
  reset: [0, 0],
@@ -3630,7 +3629,7 @@ function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, al
3630
3629
  let tmp_sc = sideChannel;
3631
3630
  let step = 0;
3632
3631
  let find_flag = false;
3633
- while ((tmp_sc = tmp_sc.get(sentinel)) !== void 0 && !find_flag) {
3632
+ while ((tmp_sc = tmp_sc.get(sentinel)) !== void undefined && !find_flag) {
3634
3633
  // Where object last appeared in the ref tree
3635
3634
  const pos = tmp_sc.get(object);
3636
3635
  step += 1;
@@ -3694,7 +3693,7 @@ function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, al
3694
3693
  // @ts-expect-error values only
3695
3694
  obj = maybe_map(obj, encoder);
3696
3695
  }
3697
- obj_keys = [{ value: obj.length > 0 ? obj.join(',') || null : void 0 }];
3696
+ obj_keys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }];
3698
3697
  }
3699
3698
  else if (is_array(filter)) {
3700
3699
  obj_keys = filter;
@@ -3850,7 +3849,7 @@ function stringify(object, opts = {}) {
3850
3849
  return joined.length > 0 ? prefix + joined : '';
3851
3850
  }
3852
3851
 
3853
- const VERSION = '4.87.3'; // x-release-please-version
3852
+ const VERSION = '4.77.0'; // x-release-please-version
3854
3853
 
3855
3854
  let auto = false;
3856
3855
  let kind = undefined;
@@ -4079,18 +4078,6 @@ class ContentFilterFinishReasonError extends OpenAIError {
4079
4078
  }
4080
4079
  }
4081
4080
 
4082
- var __classPrivateFieldSet$5 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
4083
- if (kind === "m") throw new TypeError("Private method is not writable");
4084
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4085
- 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");
4086
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
4087
- };
4088
- var __classPrivateFieldGet$6 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
4089
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
4090
- 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");
4091
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
4092
- };
4093
- var _LineDecoder_carriageReturnIndex;
4094
4081
  /**
4095
4082
  * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally
4096
4083
  * reading lines from text.
@@ -4099,42 +4086,39 @@ var _LineDecoder_carriageReturnIndex;
4099
4086
  */
4100
4087
  class LineDecoder {
4101
4088
  constructor() {
4102
- _LineDecoder_carriageReturnIndex.set(this, void 0);
4103
- this.buffer = new Uint8Array();
4104
- __classPrivateFieldSet$5(this, _LineDecoder_carriageReturnIndex, null, "f");
4089
+ this.buffer = [];
4090
+ this.trailingCR = false;
4105
4091
  }
4106
4092
  decode(chunk) {
4107
- if (chunk == null) {
4093
+ let text = this.decodeText(chunk);
4094
+ if (this.trailingCR) {
4095
+ text = '\r' + text;
4096
+ this.trailingCR = false;
4097
+ }
4098
+ if (text.endsWith('\r')) {
4099
+ this.trailingCR = true;
4100
+ text = text.slice(0, -1);
4101
+ }
4102
+ if (!text) {
4108
4103
  return [];
4109
4104
  }
4110
- const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)
4111
- : typeof chunk === 'string' ? new TextEncoder().encode(chunk)
4112
- : chunk;
4113
- let newData = new Uint8Array(this.buffer.length + binaryChunk.length);
4114
- newData.set(this.buffer);
4115
- newData.set(binaryChunk, this.buffer.length);
4116
- this.buffer = newData;
4117
- const lines = [];
4118
- let patternIndex;
4119
- while ((patternIndex = findNewlineIndex(this.buffer, __classPrivateFieldGet$6(this, _LineDecoder_carriageReturnIndex, "f"))) != null) {
4120
- if (patternIndex.carriage && __classPrivateFieldGet$6(this, _LineDecoder_carriageReturnIndex, "f") == null) {
4121
- // skip until we either get a corresponding `\n`, a new `\r` or nothing
4122
- __classPrivateFieldSet$5(this, _LineDecoder_carriageReturnIndex, patternIndex.index, "f");
4123
- continue;
4124
- }
4125
- // we got double \r or \rtext\n
4126
- if (__classPrivateFieldGet$6(this, _LineDecoder_carriageReturnIndex, "f") != null &&
4127
- (patternIndex.index !== __classPrivateFieldGet$6(this, _LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) {
4128
- lines.push(this.decodeText(this.buffer.slice(0, __classPrivateFieldGet$6(this, _LineDecoder_carriageReturnIndex, "f") - 1)));
4129
- this.buffer = this.buffer.slice(__classPrivateFieldGet$6(this, _LineDecoder_carriageReturnIndex, "f"));
4130
- __classPrivateFieldSet$5(this, _LineDecoder_carriageReturnIndex, null, "f");
4131
- continue;
4132
- }
4133
- const endIndex = __classPrivateFieldGet$6(this, _LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding;
4134
- const line = this.decodeText(this.buffer.slice(0, endIndex));
4135
- lines.push(line);
4136
- this.buffer = this.buffer.slice(patternIndex.index);
4137
- __classPrivateFieldSet$5(this, _LineDecoder_carriageReturnIndex, null, "f");
4105
+ const trailingNewline = LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || '');
4106
+ let lines = text.split(LineDecoder.NEWLINE_REGEXP);
4107
+ // if there is a trailing new line then the last entry will be an empty
4108
+ // string which we don't care about
4109
+ if (trailingNewline) {
4110
+ lines.pop();
4111
+ }
4112
+ if (lines.length === 1 && !trailingNewline) {
4113
+ this.buffer.push(lines[0]);
4114
+ return [];
4115
+ }
4116
+ if (this.buffer.length > 0) {
4117
+ lines = [this.buffer.join('') + lines[0], ...lines.slice(1)];
4118
+ this.buffer = [];
4119
+ }
4120
+ if (!trailingNewline) {
4121
+ this.buffer = [lines.pop() || ''];
4138
4122
  }
4139
4123
  return lines;
4140
4124
  }
@@ -4164,99 +4148,18 @@ class LineDecoder {
4164
4148
  throw new OpenAIError(`Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`);
4165
4149
  }
4166
4150
  flush() {
4167
- if (!this.buffer.length) {
4151
+ if (!this.buffer.length && !this.trailingCR) {
4168
4152
  return [];
4169
4153
  }
4170
- return this.decode('\n');
4154
+ const lines = [this.buffer.join('')];
4155
+ this.buffer = [];
4156
+ this.trailingCR = false;
4157
+ return lines;
4171
4158
  }
4172
4159
  }
4173
- _LineDecoder_carriageReturnIndex = new WeakMap();
4174
4160
  // prettier-ignore
4175
4161
  LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r']);
4176
4162
  LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
4177
- /**
4178
- * This function searches the buffer for the end patterns, (\r or \n)
4179
- * and returns an object with the index preceding the matched newline and the
4180
- * index after the newline char. `null` is returned if no new line is found.
4181
- *
4182
- * ```ts
4183
- * findNewLineIndex('abc\ndef') -> { preceding: 2, index: 3 }
4184
- * ```
4185
- */
4186
- function findNewlineIndex(buffer, startIndex) {
4187
- const newline = 0x0a; // \n
4188
- const carriage = 0x0d; // \r
4189
- for (let i = startIndex ?? 0; i < buffer.length; i++) {
4190
- if (buffer[i] === newline) {
4191
- return { preceding: i, index: i + 1, carriage: false };
4192
- }
4193
- if (buffer[i] === carriage) {
4194
- return { preceding: i, index: i + 1, carriage: true };
4195
- }
4196
- }
4197
- return null;
4198
- }
4199
- function findDoubleNewlineIndex(buffer) {
4200
- // This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n)
4201
- // and returns the index right after the first occurrence of any pattern,
4202
- // or -1 if none of the patterns are found.
4203
- const newline = 0x0a; // \n
4204
- const carriage = 0x0d; // \r
4205
- for (let i = 0; i < buffer.length - 1; i++) {
4206
- if (buffer[i] === newline && buffer[i + 1] === newline) {
4207
- // \n\n
4208
- return i + 2;
4209
- }
4210
- if (buffer[i] === carriage && buffer[i + 1] === carriage) {
4211
- // \r\r
4212
- return i + 2;
4213
- }
4214
- if (buffer[i] === carriage &&
4215
- buffer[i + 1] === newline &&
4216
- i + 3 < buffer.length &&
4217
- buffer[i + 2] === carriage &&
4218
- buffer[i + 3] === newline) {
4219
- // \r\n\r\n
4220
- return i + 4;
4221
- }
4222
- }
4223
- return -1;
4224
- }
4225
-
4226
- /**
4227
- * Most browsers don't yet have async iterable support for ReadableStream,
4228
- * and Node has a very different way of reading bytes from its "ReadableStream".
4229
- *
4230
- * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490
4231
- */
4232
- function ReadableStreamToAsyncIterable(stream) {
4233
- if (stream[Symbol.asyncIterator])
4234
- return stream;
4235
- const reader = stream.getReader();
4236
- return {
4237
- async next() {
4238
- try {
4239
- const result = await reader.read();
4240
- if (result?.done)
4241
- reader.releaseLock(); // release lock when stream becomes closed
4242
- return result;
4243
- }
4244
- catch (e) {
4245
- reader.releaseLock(); // release lock when stream becomes errored
4246
- throw e;
4247
- }
4248
- },
4249
- async return() {
4250
- const cancelPromise = reader.cancel();
4251
- reader.releaseLock();
4252
- await cancelPromise;
4253
- return { done: true, value: undefined };
4254
- },
4255
- [Symbol.asyncIterator]() {
4256
- return this;
4257
- },
4258
- };
4259
- }
4260
4163
 
4261
4164
  class Stream {
4262
4165
  constructor(iterator, controller) {
@@ -4279,7 +4182,7 @@ class Stream {
4279
4182
  done = true;
4280
4183
  continue;
4281
4184
  }
4282
- if (sse.event === null || sse.event.startsWith('response.')) {
4185
+ if (sse.event === null) {
4283
4186
  let data;
4284
4187
  try {
4285
4188
  data = JSON.parse(sse.data);
@@ -4335,7 +4238,7 @@ class Stream {
4335
4238
  let consumed = false;
4336
4239
  async function* iterLines() {
4337
4240
  const lineDecoder = new LineDecoder();
4338
- const iter = ReadableStreamToAsyncIterable(readableStream);
4241
+ const iter = readableStreamAsyncIterable(readableStream);
4339
4242
  for await (const chunk of iter) {
4340
4243
  for (const line of lineDecoder.decode(chunk)) {
4341
4244
  yield line;
@@ -4440,7 +4343,7 @@ async function* _iterSSEMessages(response, controller) {
4440
4343
  }
4441
4344
  const sseDecoder = new SSEDecoder();
4442
4345
  const lineDecoder = new LineDecoder();
4443
- const iter = ReadableStreamToAsyncIterable(response.body);
4346
+ const iter = readableStreamAsyncIterable(response.body);
4444
4347
  for await (const sseChunk of iterSSEChunks(iter)) {
4445
4348
  for (const line of lineDecoder.decode(sseChunk)) {
4446
4349
  const sse = sseDecoder.decode(line);
@@ -4481,6 +4384,32 @@ async function* iterSSEChunks(iterator) {
4481
4384
  yield data;
4482
4385
  }
4483
4386
  }
4387
+ function findDoubleNewlineIndex(buffer) {
4388
+ // This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n)
4389
+ // and returns the index right after the first occurrence of any pattern,
4390
+ // or -1 if none of the patterns are found.
4391
+ const newline = 0x0a; // \n
4392
+ const carriage = 0x0d; // \r
4393
+ for (let i = 0; i < buffer.length - 2; i++) {
4394
+ if (buffer[i] === newline && buffer[i + 1] === newline) {
4395
+ // \n\n
4396
+ return i + 2;
4397
+ }
4398
+ if (buffer[i] === carriage && buffer[i + 1] === carriage) {
4399
+ // \r\r
4400
+ return i + 2;
4401
+ }
4402
+ if (buffer[i] === carriage &&
4403
+ buffer[i + 1] === newline &&
4404
+ i + 3 < buffer.length &&
4405
+ buffer[i + 2] === carriage &&
4406
+ buffer[i + 3] === newline) {
4407
+ // \r\n\r\n
4408
+ return i + 4;
4409
+ }
4410
+ }
4411
+ return -1;
4412
+ }
4484
4413
  class SSEDecoder {
4485
4414
  constructor() {
4486
4415
  this.event = null;
@@ -4529,6 +4458,40 @@ function partition(str, delimiter) {
4529
4458
  }
4530
4459
  return [str, '', ''];
4531
4460
  }
4461
+ /**
4462
+ * Most browsers don't yet have async iterable support for ReadableStream,
4463
+ * and Node has a very different way of reading bytes from its "ReadableStream".
4464
+ *
4465
+ * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490
4466
+ */
4467
+ function readableStreamAsyncIterable(stream) {
4468
+ if (stream[Symbol.asyncIterator])
4469
+ return stream;
4470
+ const reader = stream.getReader();
4471
+ return {
4472
+ async next() {
4473
+ try {
4474
+ const result = await reader.read();
4475
+ if (result?.done)
4476
+ reader.releaseLock(); // release lock when stream becomes closed
4477
+ return result;
4478
+ }
4479
+ catch (e) {
4480
+ reader.releaseLock(); // release lock when stream becomes errored
4481
+ throw e;
4482
+ }
4483
+ },
4484
+ async return() {
4485
+ const cancelPromise = reader.cancel();
4486
+ reader.releaseLock();
4487
+ await cancelPromise;
4488
+ return { done: true, value: undefined };
4489
+ },
4490
+ [Symbol.asyncIterator]() {
4491
+ return this;
4492
+ },
4493
+ };
4494
+ }
4532
4495
 
4533
4496
  const isResponseLike = (value) => value != null &&
4534
4497
  typeof value === 'object' &&
@@ -4663,13 +4626,13 @@ const addFormValue = async (form, key, value) => {
4663
4626
  }
4664
4627
  };
4665
4628
 
4666
- var __classPrivateFieldSet$4 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
4629
+ var __classPrivateFieldSet$3 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
4667
4630
  if (kind === "m") throw new TypeError("Private method is not writable");
4668
4631
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4669
4632
  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");
4670
4633
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
4671
4634
  };
4672
- var __classPrivateFieldGet$5 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
4635
+ var __classPrivateFieldGet$4 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
4673
4636
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
4674
4637
  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");
4675
4638
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
@@ -4694,8 +4657,7 @@ async function defaultParseResponse(props) {
4694
4657
  return response;
4695
4658
  }
4696
4659
  const contentType = response.headers.get('content-type');
4697
- const mediaType = contentType?.split(';')[0]?.trim();
4698
- const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json');
4660
+ const isJSON = contentType?.includes('application/json') || contentType?.includes('application/vnd.api+json');
4699
4661
  if (isJSON) {
4700
4662
  const json = await response.json();
4701
4663
  debug('response', response.status, response.url, response.headers, json);
@@ -4865,7 +4827,6 @@ class APIClient {
4865
4827
  return null;
4866
4828
  }
4867
4829
  buildRequest(options, { retryCount = 0 } = {}) {
4868
- options = { ...options };
4869
4830
  const { method, path, query, headers: headers = {} } = options;
4870
4831
  const body = ArrayBuffer.isView(options.body) || (options.__binaryRequest && typeof options.body === 'string') ?
4871
4832
  options.body
@@ -4876,9 +4837,9 @@ class APIClient {
4876
4837
  const url = this.buildURL(path, query);
4877
4838
  if ('timeout' in options)
4878
4839
  validatePositiveInteger('timeout', options.timeout);
4879
- options.timeout = options.timeout ?? this.timeout;
4840
+ const timeout = options.timeout ?? this.timeout;
4880
4841
  const httpAgent = options.httpAgent ?? this.httpAgent ?? getDefaultAgent(url);
4881
- const minAgentTimeout = options.timeout + 1000;
4842
+ const minAgentTimeout = timeout + 1000;
4882
4843
  if (typeof httpAgent?.options?.timeout === 'number' &&
4883
4844
  minAgentTimeout > (httpAgent.options.timeout ?? 0)) {
4884
4845
  // Allow any given request to bump our agent active socket timeout.
@@ -4902,7 +4863,7 @@ class APIClient {
4902
4863
  // not compatible with standard web types
4903
4864
  signal: options.signal ?? null,
4904
4865
  };
4905
- return { req, url, timeout: options.timeout };
4866
+ return { req, url, timeout };
4906
4867
  }
4907
4868
  buildHeaders({ options, headers, contentLength, retryCount, }) {
4908
4869
  const reqHeaders = {};
@@ -4916,18 +4877,13 @@ class APIClient {
4916
4877
  if (isMultipartBody(options.body) && kind !== 'node') {
4917
4878
  delete reqHeaders['content-type'];
4918
4879
  }
4919
- // Don't set theses headers if they were already set or removed through default headers or by the caller.
4920
- // We check `defaultHeaders` and `headers`, which can contain nulls, instead of `reqHeaders` to account
4921
- // for the removal case.
4880
+ // Don't set the retry count header if it was already set or removed through default headers or by the
4881
+ // caller. We check `defaultHeaders` and `headers`, which can contain nulls, instead of `reqHeaders` to
4882
+ // account for the removal case.
4922
4883
  if (getHeader(defaultHeaders, 'x-stainless-retry-count') === undefined &&
4923
4884
  getHeader(headers, 'x-stainless-retry-count') === undefined) {
4924
4885
  reqHeaders['x-stainless-retry-count'] = String(retryCount);
4925
4886
  }
4926
- if (getHeader(defaultHeaders, 'x-stainless-timeout') === undefined &&
4927
- getHeader(headers, 'x-stainless-timeout') === undefined &&
4928
- options.timeout) {
4929
- reqHeaders['x-stainless-timeout'] = String(options.timeout);
4930
- }
4931
4887
  this.validateHeaders(reqHeaders, headers);
4932
4888
  return reqHeaders;
4933
4889
  }
@@ -5034,18 +4990,9 @@ class APIClient {
5034
4990
  if (signal)
5035
4991
  signal.addEventListener('abort', () => controller.abort());
5036
4992
  const timeout = setTimeout(() => controller.abort(), ms);
5037
- const fetchOptions = {
5038
- signal: controller.signal,
5039
- ...options,
5040
- };
5041
- if (fetchOptions.method) {
5042
- // Custom methods like 'patch' need to be uppercased
5043
- // See https://github.com/nodejs/undici/issues/2294
5044
- fetchOptions.method = fetchOptions.method.toUpperCase();
5045
- }
5046
4993
  return (
5047
4994
  // use undefined this binding; fetch errors if bound to something else in browser/cloudflare
5048
- this.fetch.call(undefined, url, fetchOptions).finally(() => {
4995
+ this.fetch.call(undefined, url, { signal: controller.signal, ...options }).finally(() => {
5049
4996
  clearTimeout(timeout);
5050
4997
  }));
5051
4998
  }
@@ -5118,7 +5065,7 @@ class APIClient {
5118
5065
  class AbstractPage {
5119
5066
  constructor(client, response, body, options) {
5120
5067
  _AbstractPage_client.set(this, void 0);
5121
- __classPrivateFieldSet$4(this, _AbstractPage_client, client, "f");
5068
+ __classPrivateFieldSet$3(this, _AbstractPage_client, client, "f");
5122
5069
  this.options = options;
5123
5070
  this.response = response;
5124
5071
  this.body = body;
@@ -5146,7 +5093,7 @@ class AbstractPage {
5146
5093
  nextOptions.query = undefined;
5147
5094
  nextOptions.path = nextInfo.url.toString();
5148
5095
  }
5149
- return await __classPrivateFieldGet$5(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
5096
+ return await __classPrivateFieldGet$4(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
5150
5097
  }
5151
5098
  async *iterPages() {
5152
5099
  // eslint-disable-next-line @typescript-eslint/no-this-alias
@@ -5217,7 +5164,6 @@ const requestOptionsKeys = {
5217
5164
  httpAgent: true,
5218
5165
  signal: true,
5219
5166
  idempotencyKey: true,
5220
- __metadata: true,
5221
5167
  __binaryRequest: true,
5222
5168
  __binaryResponse: true,
5223
5169
  __streamClass: true,
@@ -5441,36 +5387,9 @@ function applyHeadersMut(targetHeaders, newHeaders) {
5441
5387
  }
5442
5388
  }
5443
5389
  }
5444
- const SENSITIVE_HEADERS = new Set(['authorization', 'api-key']);
5445
5390
  function debug(action, ...args) {
5446
5391
  if (typeof process !== 'undefined' && process?.env?.['DEBUG'] === 'true') {
5447
- const modifiedArgs = args.map((arg) => {
5448
- if (!arg) {
5449
- return arg;
5450
- }
5451
- // Check for sensitive headers in request body 'headers' object
5452
- if (arg['headers']) {
5453
- // clone so we don't mutate
5454
- const modifiedArg = { ...arg, headers: { ...arg['headers'] } };
5455
- for (const header in arg['headers']) {
5456
- if (SENSITIVE_HEADERS.has(header.toLowerCase())) {
5457
- modifiedArg['headers'][header] = 'REDACTED';
5458
- }
5459
- }
5460
- return modifiedArg;
5461
- }
5462
- let modifiedArg = null;
5463
- // Check for sensitive headers in headers object
5464
- for (const header in arg) {
5465
- if (SENSITIVE_HEADERS.has(header.toLowerCase())) {
5466
- // avoid making a copy until we need to
5467
- modifiedArg ?? (modifiedArg = { ...arg });
5468
- modifiedArg[header] = 'REDACTED';
5469
- }
5470
- }
5471
- return modifiedArg ?? arg;
5472
- });
5473
- console.log(`OpenAI:DEBUG:${action}`, ...modifiedArgs);
5392
+ console.log(`OpenAI:DEBUG:${action}`, ...args);
5474
5393
  }
5475
5394
  }
5476
5395
  /**
@@ -5554,17 +5473,10 @@ class CursorPage extends AbstractPage {
5554
5473
  constructor(client, response, body, options) {
5555
5474
  super(client, response, body, options);
5556
5475
  this.data = body.data || [];
5557
- this.has_more = body.has_more || false;
5558
5476
  }
5559
5477
  getPaginatedItems() {
5560
5478
  return this.data ?? [];
5561
5479
  }
5562
- hasNextPage() {
5563
- if (this.has_more === false) {
5564
- return false;
5565
- }
5566
- return super.hasNextPage();
5567
- }
5568
5480
  // @deprecated Please use `nextPageInfo()` instead
5569
5481
  nextPageParams() {
5570
5482
  const info = this.nextPageInfo();
@@ -5597,60 +5509,12 @@ class APIResource {
5597
5509
  }
5598
5510
  }
5599
5511
 
5600
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
5601
- let Messages$1 = class Messages extends APIResource {
5602
- list(completionId, query = {}, options) {
5603
- if (isRequestOptions(query)) {
5604
- return this.list(completionId, {}, query);
5605
- }
5606
- return this._client.getAPIList(`/chat/completions/${completionId}/messages`, ChatCompletionStoreMessagesPage, { query, ...options });
5607
- }
5608
- };
5609
-
5610
5512
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
5611
5513
  let Completions$2 = class Completions extends APIResource {
5612
- constructor() {
5613
- super(...arguments);
5614
- this.messages = new Messages$1(this._client);
5615
- }
5616
5514
  create(body, options) {
5617
5515
  return this._client.post('/chat/completions', { body, ...options, stream: body.stream ?? false });
5618
5516
  }
5619
- /**
5620
- * Get a stored chat completion. Only Chat Completions that have been created with
5621
- * the `store` parameter set to `true` will be returned.
5622
- */
5623
- retrieve(completionId, options) {
5624
- return this._client.get(`/chat/completions/${completionId}`, options);
5625
- }
5626
- /**
5627
- * Modify a stored chat completion. Only Chat Completions that have been created
5628
- * with the `store` parameter set to `true` can be modified. Currently, the only
5629
- * supported modification is to update the `metadata` field.
5630
- */
5631
- update(completionId, body, options) {
5632
- return this._client.post(`/chat/completions/${completionId}`, { body, ...options });
5633
- }
5634
- list(query = {}, options) {
5635
- if (isRequestOptions(query)) {
5636
- return this.list({}, query);
5637
- }
5638
- return this._client.getAPIList('/chat/completions', ChatCompletionsPage, { query, ...options });
5639
- }
5640
- /**
5641
- * Delete a stored chat completion. Only Chat Completions that have been created
5642
- * with the `store` parameter set to `true` can be deleted.
5643
- */
5644
- del(completionId, options) {
5645
- return this._client.delete(`/chat/completions/${completionId}`, options);
5646
- }
5647
5517
  };
5648
- class ChatCompletionsPage extends CursorPage {
5649
- }
5650
- class ChatCompletionStoreMessagesPage extends CursorPage {
5651
- }
5652
- Completions$2.ChatCompletionsPage = ChatCompletionsPage;
5653
- Completions$2.Messages = Messages$1;
5654
5518
 
5655
5519
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
5656
5520
  let Chat$1 = class Chat extends APIResource {
@@ -5660,7 +5524,6 @@ let Chat$1 = class Chat extends APIResource {
5660
5524
  }
5661
5525
  };
5662
5526
  Chat$1.Completions = Completions$2;
5663
- Chat$1.ChatCompletionsPage = ChatCompletionsPage;
5664
5527
 
5665
5528
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
5666
5529
  class Speech extends APIResource {
@@ -5668,26 +5531,21 @@ class Speech extends APIResource {
5668
5531
  * Generates audio from the input text.
5669
5532
  */
5670
5533
  create(body, options) {
5671
- return this._client.post('/audio/speech', {
5672
- body,
5673
- ...options,
5674
- headers: { Accept: 'application/octet-stream', ...options?.headers },
5675
- __binaryResponse: true,
5676
- });
5534
+ return this._client.post('/audio/speech', { body, ...options, __binaryResponse: true });
5677
5535
  }
5678
5536
  }
5679
5537
 
5680
5538
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
5681
5539
  class Transcriptions extends APIResource {
5682
5540
  create(body, options) {
5683
- return this._client.post('/audio/transcriptions', multipartFormRequestOptions({ body, ...options, __metadata: { model: body.model } }));
5541
+ return this._client.post('/audio/transcriptions', multipartFormRequestOptions({ body, ...options }));
5684
5542
  }
5685
5543
  }
5686
5544
 
5687
5545
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
5688
5546
  class Translations extends APIResource {
5689
5547
  create(body, options) {
5690
- return this._client.post('/audio/translations', multipartFormRequestOptions({ body, ...options, __metadata: { model: body.model } }));
5548
+ return this._client.post('/audio/translations', multipartFormRequestOptions({ body, ...options }));
5691
5549
  }
5692
5550
  }
5693
5551
 
@@ -5806,13 +5664,13 @@ const isToolMessage = (message) => {
5806
5664
  return message?.role === 'tool';
5807
5665
  };
5808
5666
 
5809
- var __classPrivateFieldSet$3 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
5667
+ var __classPrivateFieldSet$2 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
5810
5668
  if (kind === "m") throw new TypeError("Private method is not writable");
5811
5669
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5812
5670
  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");
5813
5671
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
5814
5672
  };
5815
- var __classPrivateFieldGet$4 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
5673
+ var __classPrivateFieldGet$3 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
5816
5674
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
5817
5675
  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");
5818
5676
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
@@ -5833,20 +5691,20 @@ class EventStream {
5833
5691
  _EventStream_errored.set(this, false);
5834
5692
  _EventStream_aborted.set(this, false);
5835
5693
  _EventStream_catchingPromiseCreated.set(this, false);
5836
- __classPrivateFieldSet$3(this, _EventStream_connectedPromise, new Promise((resolve, reject) => {
5837
- __classPrivateFieldSet$3(this, _EventStream_resolveConnectedPromise, resolve, "f");
5838
- __classPrivateFieldSet$3(this, _EventStream_rejectConnectedPromise, reject, "f");
5694
+ __classPrivateFieldSet$2(this, _EventStream_connectedPromise, new Promise((resolve, reject) => {
5695
+ __classPrivateFieldSet$2(this, _EventStream_resolveConnectedPromise, resolve, "f");
5696
+ __classPrivateFieldSet$2(this, _EventStream_rejectConnectedPromise, reject, "f");
5839
5697
  }), "f");
5840
- __classPrivateFieldSet$3(this, _EventStream_endPromise, new Promise((resolve, reject) => {
5841
- __classPrivateFieldSet$3(this, _EventStream_resolveEndPromise, resolve, "f");
5842
- __classPrivateFieldSet$3(this, _EventStream_rejectEndPromise, reject, "f");
5698
+ __classPrivateFieldSet$2(this, _EventStream_endPromise, new Promise((resolve, reject) => {
5699
+ __classPrivateFieldSet$2(this, _EventStream_resolveEndPromise, resolve, "f");
5700
+ __classPrivateFieldSet$2(this, _EventStream_rejectEndPromise, reject, "f");
5843
5701
  }), "f");
5844
5702
  // Don't let these promises cause unhandled rejection errors.
5845
5703
  // we will manually cause an unhandled rejection error later
5846
5704
  // if the user hasn't registered any error listener or called
5847
5705
  // any promise-returning method.
5848
- __classPrivateFieldGet$4(this, _EventStream_connectedPromise, "f").catch(() => { });
5849
- __classPrivateFieldGet$4(this, _EventStream_endPromise, "f").catch(() => { });
5706
+ __classPrivateFieldGet$3(this, _EventStream_connectedPromise, "f").catch(() => { });
5707
+ __classPrivateFieldGet$3(this, _EventStream_endPromise, "f").catch(() => { });
5850
5708
  }
5851
5709
  _run(executor) {
5852
5710
  // Unfortunately if we call `executor()` immediately we get runtime errors about
@@ -5855,23 +5713,23 @@ class EventStream {
5855
5713
  executor().then(() => {
5856
5714
  this._emitFinal();
5857
5715
  this._emit('end');
5858
- }, __classPrivateFieldGet$4(this, _EventStream_instances, "m", _EventStream_handleError).bind(this));
5716
+ }, __classPrivateFieldGet$3(this, _EventStream_instances, "m", _EventStream_handleError).bind(this));
5859
5717
  }, 0);
5860
5718
  }
5861
5719
  _connected() {
5862
5720
  if (this.ended)
5863
5721
  return;
5864
- __classPrivateFieldGet$4(this, _EventStream_resolveConnectedPromise, "f").call(this);
5722
+ __classPrivateFieldGet$3(this, _EventStream_resolveConnectedPromise, "f").call(this);
5865
5723
  this._emit('connect');
5866
5724
  }
5867
5725
  get ended() {
5868
- return __classPrivateFieldGet$4(this, _EventStream_ended, "f");
5726
+ return __classPrivateFieldGet$3(this, _EventStream_ended, "f");
5869
5727
  }
5870
5728
  get errored() {
5871
- return __classPrivateFieldGet$4(this, _EventStream_errored, "f");
5729
+ return __classPrivateFieldGet$3(this, _EventStream_errored, "f");
5872
5730
  }
5873
5731
  get aborted() {
5874
- return __classPrivateFieldGet$4(this, _EventStream_aborted, "f");
5732
+ return __classPrivateFieldGet$3(this, _EventStream_aborted, "f");
5875
5733
  }
5876
5734
  abort() {
5877
5735
  this.controller.abort();
@@ -5884,7 +5742,7 @@ class EventStream {
5884
5742
  * @returns this ChatCompletionStream, so that calls can be chained
5885
5743
  */
5886
5744
  on(event, listener) {
5887
- const listeners = __classPrivateFieldGet$4(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet$4(this, _EventStream_listeners, "f")[event] = []);
5745
+ const listeners = __classPrivateFieldGet$3(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet$3(this, _EventStream_listeners, "f")[event] = []);
5888
5746
  listeners.push({ listener });
5889
5747
  return this;
5890
5748
  }
@@ -5896,7 +5754,7 @@ class EventStream {
5896
5754
  * @returns this ChatCompletionStream, so that calls can be chained
5897
5755
  */
5898
5756
  off(event, listener) {
5899
- const listeners = __classPrivateFieldGet$4(this, _EventStream_listeners, "f")[event];
5757
+ const listeners = __classPrivateFieldGet$3(this, _EventStream_listeners, "f")[event];
5900
5758
  if (!listeners)
5901
5759
  return this;
5902
5760
  const index = listeners.findIndex((l) => l.listener === listener);
@@ -5910,7 +5768,7 @@ class EventStream {
5910
5768
  * @returns this ChatCompletionStream, so that calls can be chained
5911
5769
  */
5912
5770
  once(event, listener) {
5913
- const listeners = __classPrivateFieldGet$4(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet$4(this, _EventStream_listeners, "f")[event] = []);
5771
+ const listeners = __classPrivateFieldGet$3(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet$3(this, _EventStream_listeners, "f")[event] = []);
5914
5772
  listeners.push({ listener, once: true });
5915
5773
  return this;
5916
5774
  }
@@ -5927,44 +5785,44 @@ class EventStream {
5927
5785
  */
5928
5786
  emitted(event) {
5929
5787
  return new Promise((resolve, reject) => {
5930
- __classPrivateFieldSet$3(this, _EventStream_catchingPromiseCreated, true, "f");
5788
+ __classPrivateFieldSet$2(this, _EventStream_catchingPromiseCreated, true, "f");
5931
5789
  if (event !== 'error')
5932
5790
  this.once('error', reject);
5933
5791
  this.once(event, resolve);
5934
5792
  });
5935
5793
  }
5936
5794
  async done() {
5937
- __classPrivateFieldSet$3(this, _EventStream_catchingPromiseCreated, true, "f");
5938
- await __classPrivateFieldGet$4(this, _EventStream_endPromise, "f");
5795
+ __classPrivateFieldSet$2(this, _EventStream_catchingPromiseCreated, true, "f");
5796
+ await __classPrivateFieldGet$3(this, _EventStream_endPromise, "f");
5939
5797
  }
5940
5798
  _emit(event, ...args) {
5941
5799
  // make sure we don't emit any events after end
5942
- if (__classPrivateFieldGet$4(this, _EventStream_ended, "f")) {
5800
+ if (__classPrivateFieldGet$3(this, _EventStream_ended, "f")) {
5943
5801
  return;
5944
5802
  }
5945
5803
  if (event === 'end') {
5946
- __classPrivateFieldSet$3(this, _EventStream_ended, true, "f");
5947
- __classPrivateFieldGet$4(this, _EventStream_resolveEndPromise, "f").call(this);
5804
+ __classPrivateFieldSet$2(this, _EventStream_ended, true, "f");
5805
+ __classPrivateFieldGet$3(this, _EventStream_resolveEndPromise, "f").call(this);
5948
5806
  }
5949
- const listeners = __classPrivateFieldGet$4(this, _EventStream_listeners, "f")[event];
5807
+ const listeners = __classPrivateFieldGet$3(this, _EventStream_listeners, "f")[event];
5950
5808
  if (listeners) {
5951
- __classPrivateFieldGet$4(this, _EventStream_listeners, "f")[event] = listeners.filter((l) => !l.once);
5809
+ __classPrivateFieldGet$3(this, _EventStream_listeners, "f")[event] = listeners.filter((l) => !l.once);
5952
5810
  listeners.forEach(({ listener }) => listener(...args));
5953
5811
  }
5954
5812
  if (event === 'abort') {
5955
5813
  const error = args[0];
5956
- if (!__classPrivateFieldGet$4(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) {
5814
+ if (!__classPrivateFieldGet$3(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) {
5957
5815
  Promise.reject(error);
5958
5816
  }
5959
- __classPrivateFieldGet$4(this, _EventStream_rejectConnectedPromise, "f").call(this, error);
5960
- __classPrivateFieldGet$4(this, _EventStream_rejectEndPromise, "f").call(this, error);
5817
+ __classPrivateFieldGet$3(this, _EventStream_rejectConnectedPromise, "f").call(this, error);
5818
+ __classPrivateFieldGet$3(this, _EventStream_rejectEndPromise, "f").call(this, error);
5961
5819
  this._emit('end');
5962
5820
  return;
5963
5821
  }
5964
5822
  if (event === 'error') {
5965
5823
  // NOTE: _emit('error', error) should only be called from #handleError().
5966
5824
  const error = args[0];
5967
- if (!__classPrivateFieldGet$4(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) {
5825
+ if (!__classPrivateFieldGet$3(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) {
5968
5826
  // Trigger an unhandled rejection if the user hasn't registered any error handlers.
5969
5827
  // If you are seeing stack traces here, make sure to handle errors via either:
5970
5828
  // - runner.on('error', () => ...)
@@ -5973,20 +5831,20 @@ class EventStream {
5973
5831
  // - etc.
5974
5832
  Promise.reject(error);
5975
5833
  }
5976
- __classPrivateFieldGet$4(this, _EventStream_rejectConnectedPromise, "f").call(this, error);
5977
- __classPrivateFieldGet$4(this, _EventStream_rejectEndPromise, "f").call(this, error);
5834
+ __classPrivateFieldGet$3(this, _EventStream_rejectConnectedPromise, "f").call(this, error);
5835
+ __classPrivateFieldGet$3(this, _EventStream_rejectEndPromise, "f").call(this, error);
5978
5836
  this._emit('end');
5979
5837
  }
5980
5838
  }
5981
5839
  _emitFinal() { }
5982
5840
  }
5983
5841
  _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) {
5984
- __classPrivateFieldSet$3(this, _EventStream_errored, true, "f");
5842
+ __classPrivateFieldSet$2(this, _EventStream_errored, true, "f");
5985
5843
  if (error instanceof Error && error.name === 'AbortError') {
5986
5844
  error = new APIUserAbortError();
5987
5845
  }
5988
5846
  if (error instanceof APIUserAbortError) {
5989
- __classPrivateFieldSet$3(this, _EventStream_aborted, true, "f");
5847
+ __classPrivateFieldSet$2(this, _EventStream_aborted, true, "f");
5990
5848
  return this._emit('abort', error);
5991
5849
  }
5992
5850
  if (error instanceof OpenAIError) {
@@ -6004,24 +5862,16 @@ _EventStream_connectedPromise = new WeakMap(), _EventStream_resolveConnectedProm
6004
5862
  function isAutoParsableResponseFormat(response_format) {
6005
5863
  return response_format?.['$brand'] === 'auto-parseable-response-format';
6006
5864
  }
6007
- function isAutoParsableTool$1(tool) {
5865
+ function isAutoParsableTool(tool) {
6008
5866
  return tool?.['$brand'] === 'auto-parseable-tool';
6009
5867
  }
6010
5868
  function maybeParseChatCompletion(completion, params) {
6011
- if (!params || !hasAutoParseableInput$1(params)) {
5869
+ if (!params || !hasAutoParseableInput(params)) {
6012
5870
  return {
6013
5871
  ...completion,
6014
5872
  choices: completion.choices.map((choice) => ({
6015
5873
  ...choice,
6016
- message: {
6017
- ...choice.message,
6018
- parsed: null,
6019
- ...(choice.message.tool_calls ?
6020
- {
6021
- tool_calls: choice.message.tool_calls,
6022
- }
6023
- : undefined),
6024
- },
5874
+ message: { ...choice.message, parsed: null, tool_calls: choice.message.tool_calls ?? [] },
6025
5875
  })),
6026
5876
  };
6027
5877
  }
@@ -6039,11 +5889,7 @@ function parseChatCompletion(completion, params) {
6039
5889
  ...choice,
6040
5890
  message: {
6041
5891
  ...choice.message,
6042
- ...(choice.message.tool_calls ?
6043
- {
6044
- tool_calls: choice.message.tool_calls?.map((toolCall) => parseToolCall$1(params, toolCall)) ?? undefined,
6045
- }
6046
- : undefined),
5892
+ tool_calls: choice.message.tool_calls?.map((toolCall) => parseToolCall(params, toolCall)) ?? [],
6047
5893
  parsed: choice.message.content && !choice.message.refusal ?
6048
5894
  parseResponseFormat(params, choice.message.content)
6049
5895
  : null,
@@ -6065,13 +5911,13 @@ function parseResponseFormat(params, content) {
6065
5911
  }
6066
5912
  return null;
6067
5913
  }
6068
- function parseToolCall$1(params, toolCall) {
5914
+ function parseToolCall(params, toolCall) {
6069
5915
  const inputTool = params.tools?.find((inputTool) => inputTool.function?.name === toolCall.function.name);
6070
5916
  return {
6071
5917
  ...toolCall,
6072
5918
  function: {
6073
5919
  ...toolCall.function,
6074
- parsed_arguments: isAutoParsableTool$1(inputTool) ? inputTool.$parseRaw(toolCall.function.arguments)
5920
+ parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.function.arguments)
6075
5921
  : inputTool?.function.strict ? JSON.parse(toolCall.function.arguments)
6076
5922
  : null,
6077
5923
  },
@@ -6082,13 +5928,13 @@ function shouldParseToolCall(params, toolCall) {
6082
5928
  return false;
6083
5929
  }
6084
5930
  const inputTool = params.tools?.find((inputTool) => inputTool.function?.name === toolCall.function.name);
6085
- return isAutoParsableTool$1(inputTool) || inputTool?.function.strict || false;
5931
+ return isAutoParsableTool(inputTool) || inputTool?.function.strict || false;
6086
5932
  }
6087
- function hasAutoParseableInput$1(params) {
5933
+ function hasAutoParseableInput(params) {
6088
5934
  if (isAutoParsableResponseFormat(params.response_format)) {
6089
5935
  return true;
6090
5936
  }
6091
- return (params.tools?.some((t) => isAutoParsableTool$1(t) || (t.type === 'function' && t.function.strict === true)) ?? false);
5937
+ return (params.tools?.some((t) => isAutoParsableTool(t) || (t.type === 'function' && t.function.strict === true)) ?? false);
6092
5938
  }
6093
5939
  function validateInputTools(tools) {
6094
5940
  for (const tool of tools ?? []) {
@@ -6101,7 +5947,7 @@ function validateInputTools(tools) {
6101
5947
  }
6102
5948
  }
6103
5949
 
6104
- var __classPrivateFieldGet$3 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
5950
+ var __classPrivateFieldGet$2 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
6105
5951
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
6106
5952
  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");
6107
5953
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
@@ -6162,7 +6008,7 @@ class AbstractChatCompletionRunner extends EventStream {
6162
6008
  */
6163
6009
  async finalContent() {
6164
6010
  await this.done();
6165
- return __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this);
6011
+ return __classPrivateFieldGet$2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this);
6166
6012
  }
6167
6013
  /**
6168
6014
  * @returns a promise that resolves with the the final assistant ChatCompletionMessage response,
@@ -6170,7 +6016,7 @@ class AbstractChatCompletionRunner extends EventStream {
6170
6016
  */
6171
6017
  async finalMessage() {
6172
6018
  await this.done();
6173
- return __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this);
6019
+ return __classPrivateFieldGet$2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this);
6174
6020
  }
6175
6021
  /**
6176
6022
  * @returns a promise that resolves with the content of the final FunctionCall, or rejects
@@ -6178,15 +6024,15 @@ class AbstractChatCompletionRunner extends EventStream {
6178
6024
  */
6179
6025
  async finalFunctionCall() {
6180
6026
  await this.done();
6181
- return __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this);
6027
+ return __classPrivateFieldGet$2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this);
6182
6028
  }
6183
6029
  async finalFunctionCallResult() {
6184
6030
  await this.done();
6185
- return __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this);
6031
+ return __classPrivateFieldGet$2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this);
6186
6032
  }
6187
6033
  async totalUsage() {
6188
6034
  await this.done();
6189
- return __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this);
6035
+ return __classPrivateFieldGet$2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this);
6190
6036
  }
6191
6037
  allChatCompletions() {
6192
6038
  return [...this._chatCompletions];
@@ -6195,20 +6041,20 @@ class AbstractChatCompletionRunner extends EventStream {
6195
6041
  const completion = this._chatCompletions[this._chatCompletions.length - 1];
6196
6042
  if (completion)
6197
6043
  this._emit('finalChatCompletion', completion);
6198
- const finalMessage = __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this);
6044
+ const finalMessage = __classPrivateFieldGet$2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this);
6199
6045
  if (finalMessage)
6200
6046
  this._emit('finalMessage', finalMessage);
6201
- const finalContent = __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this);
6047
+ const finalContent = __classPrivateFieldGet$2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this);
6202
6048
  if (finalContent)
6203
6049
  this._emit('finalContent', finalContent);
6204
- const finalFunctionCall = __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this);
6050
+ const finalFunctionCall = __classPrivateFieldGet$2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this);
6205
6051
  if (finalFunctionCall)
6206
6052
  this._emit('finalFunctionCall', finalFunctionCall);
6207
- const finalFunctionCallResult = __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this);
6053
+ const finalFunctionCallResult = __classPrivateFieldGet$2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this);
6208
6054
  if (finalFunctionCallResult != null)
6209
6055
  this._emit('finalFunctionCallResult', finalFunctionCallResult);
6210
6056
  if (this._chatCompletions.some((c) => c.usage)) {
6211
- this._emit('totalUsage', __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this));
6057
+ this._emit('totalUsage', __classPrivateFieldGet$2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this));
6212
6058
  }
6213
6059
  }
6214
6060
  async _createChatCompletion(client, params, options) {
@@ -6218,7 +6064,7 @@ class AbstractChatCompletionRunner extends EventStream {
6218
6064
  this.controller.abort();
6219
6065
  signal.addEventListener('abort', () => this.controller.abort());
6220
6066
  }
6221
- __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params);
6067
+ __classPrivateFieldGet$2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params);
6222
6068
  const chatCompletion = await client.chat.completions.create({ ...params, stream: false }, { ...options, signal: this.controller.signal });
6223
6069
  this._connected();
6224
6070
  return this._addChatCompletion(parseChatCompletion(chatCompletion, params));
@@ -6287,7 +6133,7 @@ class AbstractChatCompletionRunner extends EventStream {
6287
6133
  }
6288
6134
  // @ts-expect-error it can't rule out `never` type.
6289
6135
  const rawContent = await fn.function(parsed, this);
6290
- const content = __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent);
6136
+ const content = __classPrivateFieldGet$2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent);
6291
6137
  this._addMessage({ role, name, content });
6292
6138
  if (singleFunctionToCall)
6293
6139
  return;
@@ -6300,7 +6146,7 @@ class AbstractChatCompletionRunner extends EventStream {
6300
6146
  const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {};
6301
6147
  // TODO(someday): clean this logic up
6302
6148
  const inputTools = params.tools.map((tool) => {
6303
- if (isAutoParsableTool$1(tool)) {
6149
+ if (isAutoParsableTool(tool)) {
6304
6150
  if (!tool.$callback) {
6305
6151
  throw new OpenAIError('Tool given to `.runTools()` that does not have an associated function');
6306
6152
  }
@@ -6383,7 +6229,7 @@ class AbstractChatCompletionRunner extends EventStream {
6383
6229
  }
6384
6230
  // @ts-expect-error it can't rule out `never` type.
6385
6231
  const rawContent = await fn.function(parsed, this);
6386
- const content = __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent);
6232
+ const content = __classPrivateFieldGet$2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent);
6387
6233
  this._addMessage({ role, tool_call_id, content });
6388
6234
  if (singleFunctionToCall) {
6389
6235
  return;
@@ -6394,7 +6240,7 @@ class AbstractChatCompletionRunner extends EventStream {
6394
6240
  }
6395
6241
  }
6396
6242
  _AbstractChatCompletionRunner_instances = new WeakSet(), _AbstractChatCompletionRunner_getFinalContent = function _AbstractChatCompletionRunner_getFinalContent() {
6397
- return __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null;
6243
+ return __classPrivateFieldGet$2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null;
6398
6244
  }, _AbstractChatCompletionRunner_getFinalMessage = function _AbstractChatCompletionRunner_getFinalMessage() {
6399
6245
  let i = this.messages.length;
6400
6246
  while (i-- > 0) {
@@ -6732,13 +6578,13 @@ const _parseJSON = (jsonString, allow) => {
6732
6578
  // using this function with malformed JSON is undefined behavior
6733
6579
  const partialParse = (input) => parseJSON(input, Allow.ALL ^ Allow.NUM);
6734
6580
 
6735
- var __classPrivateFieldSet$2 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
6581
+ var __classPrivateFieldSet$1 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
6736
6582
  if (kind === "m") throw new TypeError("Private method is not writable");
6737
6583
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
6738
6584
  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");
6739
6585
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6740
6586
  };
6741
- var __classPrivateFieldGet$2 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
6587
+ var __classPrivateFieldGet$1 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
6742
6588
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
6743
6589
  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");
6744
6590
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
@@ -6751,11 +6597,11 @@ class ChatCompletionStream extends AbstractChatCompletionRunner {
6751
6597
  _ChatCompletionStream_params.set(this, void 0);
6752
6598
  _ChatCompletionStream_choiceEventStates.set(this, void 0);
6753
6599
  _ChatCompletionStream_currentChatCompletionSnapshot.set(this, void 0);
6754
- __classPrivateFieldSet$2(this, _ChatCompletionStream_params, params, "f");
6755
- __classPrivateFieldSet$2(this, _ChatCompletionStream_choiceEventStates, [], "f");
6600
+ __classPrivateFieldSet$1(this, _ChatCompletionStream_params, params, "f");
6601
+ __classPrivateFieldSet$1(this, _ChatCompletionStream_choiceEventStates, [], "f");
6756
6602
  }
6757
6603
  get currentChatCompletionSnapshot() {
6758
- return __classPrivateFieldGet$2(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
6604
+ return __classPrivateFieldGet$1(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
6759
6605
  }
6760
6606
  /**
6761
6607
  * Intended for use on the frontend, consuming a stream produced with
@@ -6782,16 +6628,16 @@ class ChatCompletionStream extends AbstractChatCompletionRunner {
6782
6628
  this.controller.abort();
6783
6629
  signal.addEventListener('abort', () => this.controller.abort());
6784
6630
  }
6785
- __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
6631
+ __classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
6786
6632
  const stream = await client.chat.completions.create({ ...params, stream: true }, { ...options, signal: this.controller.signal });
6787
6633
  this._connected();
6788
6634
  for await (const chunk of stream) {
6789
- __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
6635
+ __classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
6790
6636
  }
6791
6637
  if (stream.controller.signal?.aborted) {
6792
6638
  throw new APIUserAbortError();
6793
6639
  }
6794
- return this._addChatCompletion(__classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
6640
+ return this._addChatCompletion(__classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
6795
6641
  }
6796
6642
  async _fromReadableStream(readableStream, options) {
6797
6643
  const signal = options?.signal;
@@ -6800,29 +6646,29 @@ class ChatCompletionStream extends AbstractChatCompletionRunner {
6800
6646
  this.controller.abort();
6801
6647
  signal.addEventListener('abort', () => this.controller.abort());
6802
6648
  }
6803
- __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
6649
+ __classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
6804
6650
  this._connected();
6805
6651
  const stream = Stream.fromReadableStream(readableStream, this.controller);
6806
6652
  let chatId;
6807
6653
  for await (const chunk of stream) {
6808
6654
  if (chatId && chatId !== chunk.id) {
6809
6655
  // A new request has been made.
6810
- this._addChatCompletion(__classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
6656
+ this._addChatCompletion(__classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
6811
6657
  }
6812
- __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
6658
+ __classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
6813
6659
  chatId = chunk.id;
6814
6660
  }
6815
6661
  if (stream.controller.signal?.aborted) {
6816
6662
  throw new APIUserAbortError();
6817
6663
  }
6818
- return this._addChatCompletion(__classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
6664
+ return this._addChatCompletion(__classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
6819
6665
  }
6820
6666
  [(_ChatCompletionStream_params = new WeakMap(), _ChatCompletionStream_choiceEventStates = new WeakMap(), _ChatCompletionStream_currentChatCompletionSnapshot = new WeakMap(), _ChatCompletionStream_instances = new WeakSet(), _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest() {
6821
6667
  if (this.ended)
6822
6668
  return;
6823
- __classPrivateFieldSet$2(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f");
6669
+ __classPrivateFieldSet$1(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f");
6824
6670
  }, _ChatCompletionStream_getChoiceEventState = function _ChatCompletionStream_getChoiceEventState(choice) {
6825
- let state = __classPrivateFieldGet$2(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index];
6671
+ let state = __classPrivateFieldGet$1(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index];
6826
6672
  if (state) {
6827
6673
  return state;
6828
6674
  }
@@ -6834,12 +6680,12 @@ class ChatCompletionStream extends AbstractChatCompletionRunner {
6834
6680
  done_tool_calls: new Set(),
6835
6681
  current_tool_call_index: null,
6836
6682
  };
6837
- __classPrivateFieldGet$2(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index] = state;
6683
+ __classPrivateFieldGet$1(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index] = state;
6838
6684
  return state;
6839
6685
  }, _ChatCompletionStream_addChunk = function _ChatCompletionStream_addChunk(chunk) {
6840
6686
  if (this.ended)
6841
6687
  return;
6842
- const completion = __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk);
6688
+ const completion = __classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk);
6843
6689
  this._emit('chunk', chunk, completion);
6844
6690
  for (const choice of chunk.choices) {
6845
6691
  const choiceSnapshot = completion.choices[choice.index];
@@ -6873,19 +6719,19 @@ class ChatCompletionStream extends AbstractChatCompletionRunner {
6873
6719
  snapshot: choiceSnapshot.logprobs?.refusal ?? [],
6874
6720
  });
6875
6721
  }
6876
- const state = __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
6722
+ const state = __classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
6877
6723
  if (choiceSnapshot.finish_reason) {
6878
- __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);
6724
+ __classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);
6879
6725
  if (state.current_tool_call_index != null) {
6880
- __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index);
6726
+ __classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index);
6881
6727
  }
6882
6728
  }
6883
6729
  for (const toolCall of choice.delta.tool_calls ?? []) {
6884
6730
  if (state.current_tool_call_index !== toolCall.index) {
6885
- __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);
6731
+ __classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);
6886
6732
  // new tool call started, the previous one is done
6887
6733
  if (state.current_tool_call_index != null) {
6888
- __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index);
6734
+ __classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index);
6889
6735
  }
6890
6736
  }
6891
6737
  state.current_tool_call_index = toolCall.index;
@@ -6910,7 +6756,7 @@ class ChatCompletionStream extends AbstractChatCompletionRunner {
6910
6756
  }
6911
6757
  }
6912
6758
  }, _ChatCompletionStream_emitToolCallDoneEvent = function _ChatCompletionStream_emitToolCallDoneEvent(choiceSnapshot, toolCallIndex) {
6913
- const state = __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
6759
+ const state = __classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
6914
6760
  if (state.done_tool_calls.has(toolCallIndex)) {
6915
6761
  // we've already fired the done event
6916
6762
  return;
@@ -6923,12 +6769,12 @@ class ChatCompletionStream extends AbstractChatCompletionRunner {
6923
6769
  throw new Error('tool call snapshot missing `type`');
6924
6770
  }
6925
6771
  if (toolCallSnapshot.type === 'function') {
6926
- const inputTool = __classPrivateFieldGet$2(this, _ChatCompletionStream_params, "f")?.tools?.find((tool) => tool.type === 'function' && tool.function.name === toolCallSnapshot.function.name);
6772
+ const inputTool = __classPrivateFieldGet$1(this, _ChatCompletionStream_params, "f")?.tools?.find((tool) => tool.type === 'function' && tool.function.name === toolCallSnapshot.function.name);
6927
6773
  this._emit('tool_calls.function.arguments.done', {
6928
6774
  name: toolCallSnapshot.function.name,
6929
6775
  index: toolCallIndex,
6930
6776
  arguments: toolCallSnapshot.function.arguments,
6931
- parsed_arguments: isAutoParsableTool$1(inputTool) ? inputTool.$parseRaw(toolCallSnapshot.function.arguments)
6777
+ parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCallSnapshot.function.arguments)
6932
6778
  : inputTool?.function.strict ? JSON.parse(toolCallSnapshot.function.arguments)
6933
6779
  : null,
6934
6780
  });
@@ -6937,10 +6783,10 @@ class ChatCompletionStream extends AbstractChatCompletionRunner {
6937
6783
  assertNever(toolCallSnapshot.type);
6938
6784
  }
6939
6785
  }, _ChatCompletionStream_emitContentDoneEvents = function _ChatCompletionStream_emitContentDoneEvents(choiceSnapshot) {
6940
- const state = __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
6786
+ const state = __classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
6941
6787
  if (choiceSnapshot.message.content && !state.content_done) {
6942
6788
  state.content_done = true;
6943
- const responseFormat = __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this);
6789
+ const responseFormat = __classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this);
6944
6790
  this._emit('content.done', {
6945
6791
  content: choiceSnapshot.message.content,
6946
6792
  parsed: responseFormat ? responseFormat.$parseRaw(choiceSnapshot.message.content) : null,
@@ -6962,25 +6808,25 @@ class ChatCompletionStream extends AbstractChatCompletionRunner {
6962
6808
  if (this.ended) {
6963
6809
  throw new OpenAIError(`stream has ended, this shouldn't happen`);
6964
6810
  }
6965
- const snapshot = __classPrivateFieldGet$2(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
6811
+ const snapshot = __classPrivateFieldGet$1(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
6966
6812
  if (!snapshot) {
6967
6813
  throw new OpenAIError(`request ended without sending any chunks`);
6968
6814
  }
6969
- __classPrivateFieldSet$2(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f");
6970
- __classPrivateFieldSet$2(this, _ChatCompletionStream_choiceEventStates, [], "f");
6971
- return finalizeChatCompletion(snapshot, __classPrivateFieldGet$2(this, _ChatCompletionStream_params, "f"));
6815
+ __classPrivateFieldSet$1(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f");
6816
+ __classPrivateFieldSet$1(this, _ChatCompletionStream_choiceEventStates, [], "f");
6817
+ return finalizeChatCompletion(snapshot, __classPrivateFieldGet$1(this, _ChatCompletionStream_params, "f"));
6972
6818
  }, _ChatCompletionStream_getAutoParseableResponseFormat = function _ChatCompletionStream_getAutoParseableResponseFormat() {
6973
- const responseFormat = __classPrivateFieldGet$2(this, _ChatCompletionStream_params, "f")?.response_format;
6819
+ const responseFormat = __classPrivateFieldGet$1(this, _ChatCompletionStream_params, "f")?.response_format;
6974
6820
  if (isAutoParsableResponseFormat(responseFormat)) {
6975
6821
  return responseFormat;
6976
6822
  }
6977
6823
  return null;
6978
6824
  }, _ChatCompletionStream_accumulateChatCompletion = function _ChatCompletionStream_accumulateChatCompletion(chunk) {
6979
6825
  var _a, _b, _c, _d;
6980
- let snapshot = __classPrivateFieldGet$2(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
6826
+ let snapshot = __classPrivateFieldGet$1(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
6981
6827
  const { choices, ...rest } = chunk;
6982
6828
  if (!snapshot) {
6983
- snapshot = __classPrivateFieldSet$2(this, _ChatCompletionStream_currentChatCompletionSnapshot, {
6829
+ snapshot = __classPrivateFieldSet$1(this, _ChatCompletionStream_currentChatCompletionSnapshot, {
6984
6830
  ...rest,
6985
6831
  choices: [],
6986
6832
  }, "f");
@@ -7012,7 +6858,7 @@ class ChatCompletionStream extends AbstractChatCompletionRunner {
7012
6858
  }
7013
6859
  if (finish_reason) {
7014
6860
  choice.finish_reason = finish_reason;
7015
- if (__classPrivateFieldGet$2(this, _ChatCompletionStream_params, "f") && hasAutoParseableInput$1(__classPrivateFieldGet$2(this, _ChatCompletionStream_params, "f"))) {
6861
+ if (__classPrivateFieldGet$1(this, _ChatCompletionStream_params, "f") && hasAutoParseableInput(__classPrivateFieldGet$1(this, _ChatCompletionStream_params, "f"))) {
7016
6862
  if (finish_reason === 'length') {
7017
6863
  throw new LengthFinishReasonError();
7018
6864
  }
@@ -7046,7 +6892,7 @@ class ChatCompletionStream extends AbstractChatCompletionRunner {
7046
6892
  }
7047
6893
  if (content) {
7048
6894
  choice.message.content = (choice.message.content || '') + content;
7049
- if (!choice.message.refusal && __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this)) {
6895
+ if (!choice.message.refusal && __classPrivateFieldGet$1(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this)) {
7050
6896
  choice.message.parsed = partialParse(choice.message.content);
7051
6897
  }
7052
6898
  }
@@ -7066,7 +6912,7 @@ class ChatCompletionStream extends AbstractChatCompletionRunner {
7066
6912
  tool_call.function.name = fn.name;
7067
6913
  if (fn?.arguments) {
7068
6914
  tool_call.function.arguments += fn.arguments;
7069
- if (shouldParseToolCall(__classPrivateFieldGet$2(this, _ChatCompletionStream_params, "f"), tool_call)) {
6915
+ if (shouldParseToolCall(__classPrivateFieldGet$1(this, _ChatCompletionStream_params, "f"), tool_call)) {
7070
6916
  tool_call.function.parsed_arguments = partialParse(tool_call.function.arguments);
7071
6917
  }
7072
6918
  }
@@ -7290,41 +7136,12 @@ class Chat extends APIResource {
7290
7136
  Chat.Completions = Completions$1;
7291
7137
  })(Chat || (Chat = {}));
7292
7138
 
7293
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
7294
- class Sessions extends APIResource {
7295
- /**
7296
- * Create an ephemeral API token for use in client-side applications with the
7297
- * Realtime API. Can be configured with the same session parameters as the
7298
- * `session.update` client event.
7299
- *
7300
- * It responds with a session object, plus a `client_secret` key which contains a
7301
- * usable ephemeral API token that can be used to authenticate browser clients for
7302
- * the Realtime API.
7303
- */
7304
- create(body, options) {
7305
- return this._client.post('/realtime/sessions', {
7306
- body,
7307
- ...options,
7308
- headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
7309
- });
7310
- }
7311
- }
7312
-
7313
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
7314
- class Realtime extends APIResource {
7315
- constructor() {
7316
- super(...arguments);
7317
- this.sessions = new Sessions(this._client);
7318
- }
7319
- }
7320
- Realtime.Sessions = Sessions;
7321
-
7322
- var __classPrivateFieldGet$1 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
7139
+ var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
7323
7140
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
7324
7141
  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");
7325
7142
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
7326
7143
  };
7327
- var __classPrivateFieldSet$1 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
7144
+ var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
7328
7145
  if (kind === "m") throw new TypeError("Private method is not writable");
7329
7146
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
7330
7147
  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");
@@ -7419,12 +7236,12 @@ class AssistantStream extends EventStream {
7419
7236
  this._connected();
7420
7237
  const stream = Stream.fromReadableStream(readableStream, this.controller);
7421
7238
  for await (const event of stream) {
7422
- __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
7239
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
7423
7240
  }
7424
7241
  if (stream.controller.signal?.aborted) {
7425
7242
  throw new APIUserAbortError();
7426
7243
  }
7427
- return this._addRun(__classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
7244
+ return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
7428
7245
  }
7429
7246
  toReadableStream() {
7430
7247
  const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);
@@ -7452,12 +7269,12 @@ class AssistantStream extends EventStream {
7452
7269
  });
7453
7270
  this._connected();
7454
7271
  for await (const event of stream) {
7455
- __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
7272
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
7456
7273
  }
7457
7274
  if (stream.controller.signal?.aborted) {
7458
7275
  throw new APIUserAbortError();
7459
7276
  }
7460
- return this._addRun(__classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
7277
+ return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
7461
7278
  }
7462
7279
  static createThreadAssistantStream(params, thread, options) {
7463
7280
  const runner = new AssistantStream();
@@ -7476,30 +7293,30 @@ class AssistantStream extends EventStream {
7476
7293
  return runner;
7477
7294
  }
7478
7295
  currentEvent() {
7479
- return __classPrivateFieldGet$1(this, _AssistantStream_currentEvent, "f");
7296
+ return __classPrivateFieldGet(this, _AssistantStream_currentEvent, "f");
7480
7297
  }
7481
7298
  currentRun() {
7482
- return __classPrivateFieldGet$1(this, _AssistantStream_currentRunSnapshot, "f");
7299
+ return __classPrivateFieldGet(this, _AssistantStream_currentRunSnapshot, "f");
7483
7300
  }
7484
7301
  currentMessageSnapshot() {
7485
- return __classPrivateFieldGet$1(this, _AssistantStream_messageSnapshot, "f");
7302
+ return __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f");
7486
7303
  }
7487
7304
  currentRunStepSnapshot() {
7488
- return __classPrivateFieldGet$1(this, _AssistantStream_currentRunStepSnapshot, "f");
7305
+ return __classPrivateFieldGet(this, _AssistantStream_currentRunStepSnapshot, "f");
7489
7306
  }
7490
7307
  async finalRunSteps() {
7491
7308
  await this.done();
7492
- return Object.values(__classPrivateFieldGet$1(this, _AssistantStream_runStepSnapshots, "f"));
7309
+ return Object.values(__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f"));
7493
7310
  }
7494
7311
  async finalMessages() {
7495
7312
  await this.done();
7496
- return Object.values(__classPrivateFieldGet$1(this, _AssistantStream_messageSnapshots, "f"));
7313
+ return Object.values(__classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f"));
7497
7314
  }
7498
7315
  async finalRun() {
7499
7316
  await this.done();
7500
- if (!__classPrivateFieldGet$1(this, _AssistantStream_finalRun, "f"))
7317
+ if (!__classPrivateFieldGet(this, _AssistantStream_finalRun, "f"))
7501
7318
  throw Error('Final run was not received.');
7502
- return __classPrivateFieldGet$1(this, _AssistantStream_finalRun, "f");
7319
+ return __classPrivateFieldGet(this, _AssistantStream_finalRun, "f");
7503
7320
  }
7504
7321
  async _createThreadAssistantStream(thread, params, options) {
7505
7322
  const signal = options?.signal;
@@ -7512,12 +7329,12 @@ class AssistantStream extends EventStream {
7512
7329
  const stream = await thread.createAndRun(body, { ...options, signal: this.controller.signal });
7513
7330
  this._connected();
7514
7331
  for await (const event of stream) {
7515
- __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
7332
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
7516
7333
  }
7517
7334
  if (stream.controller.signal?.aborted) {
7518
7335
  throw new APIUserAbortError();
7519
7336
  }
7520
- return this._addRun(__classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
7337
+ return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
7521
7338
  }
7522
7339
  async _createAssistantStream(run, threadId, params, options) {
7523
7340
  const signal = options?.signal;
@@ -7530,12 +7347,12 @@ class AssistantStream extends EventStream {
7530
7347
  const stream = await run.create(threadId, body, { ...options, signal: this.controller.signal });
7531
7348
  this._connected();
7532
7349
  for await (const event of stream) {
7533
- __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
7350
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
7534
7351
  }
7535
7352
  if (stream.controller.signal?.aborted) {
7536
7353
  throw new APIUserAbortError();
7537
7354
  }
7538
- return this._addRun(__classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
7355
+ return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
7539
7356
  }
7540
7357
  static accumulateDelta(acc, delta) {
7541
7358
  for (const [key, deltaValue] of Object.entries(delta)) {
@@ -7613,8 +7430,8 @@ class AssistantStream extends EventStream {
7613
7430
  _AssistantStream_addEvent = function _AssistantStream_addEvent(event) {
7614
7431
  if (this.ended)
7615
7432
  return;
7616
- __classPrivateFieldSet$1(this, _AssistantStream_currentEvent, event, "f");
7617
- __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_handleEvent).call(this, event);
7433
+ __classPrivateFieldSet(this, _AssistantStream_currentEvent, event, "f");
7434
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleEvent).call(this, event);
7618
7435
  switch (event.event) {
7619
7436
  case 'thread.created':
7620
7437
  //No action on this event.
@@ -7624,12 +7441,11 @@ _AssistantStream_addEvent = function _AssistantStream_addEvent(event) {
7624
7441
  case 'thread.run.in_progress':
7625
7442
  case 'thread.run.requires_action':
7626
7443
  case 'thread.run.completed':
7627
- case 'thread.run.incomplete':
7628
7444
  case 'thread.run.failed':
7629
7445
  case 'thread.run.cancelling':
7630
7446
  case 'thread.run.cancelled':
7631
7447
  case 'thread.run.expired':
7632
- __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_handleRun).call(this, event);
7448
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRun).call(this, event);
7633
7449
  break;
7634
7450
  case 'thread.run.step.created':
7635
7451
  case 'thread.run.step.in_progress':
@@ -7638,14 +7454,14 @@ _AssistantStream_addEvent = function _AssistantStream_addEvent(event) {
7638
7454
  case 'thread.run.step.failed':
7639
7455
  case 'thread.run.step.cancelled':
7640
7456
  case 'thread.run.step.expired':
7641
- __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_handleRunStep).call(this, event);
7457
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRunStep).call(this, event);
7642
7458
  break;
7643
7459
  case 'thread.message.created':
7644
7460
  case 'thread.message.in_progress':
7645
7461
  case 'thread.message.delta':
7646
7462
  case 'thread.message.completed':
7647
7463
  case 'thread.message.incomplete':
7648
- __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_handleMessage).call(this, event);
7464
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleMessage).call(this, event);
7649
7465
  break;
7650
7466
  case 'error':
7651
7467
  //This is included for completeness, but errors are processed in the SSE event processing so this should not occur
@@ -7655,13 +7471,13 @@ _AssistantStream_addEvent = function _AssistantStream_addEvent(event) {
7655
7471
  if (this.ended) {
7656
7472
  throw new OpenAIError(`stream has ended, this shouldn't happen`);
7657
7473
  }
7658
- if (!__classPrivateFieldGet$1(this, _AssistantStream_finalRun, "f"))
7474
+ if (!__classPrivateFieldGet(this, _AssistantStream_finalRun, "f"))
7659
7475
  throw Error('Final run has not been received');
7660
- return __classPrivateFieldGet$1(this, _AssistantStream_finalRun, "f");
7476
+ return __classPrivateFieldGet(this, _AssistantStream_finalRun, "f");
7661
7477
  }, _AssistantStream_handleMessage = function _AssistantStream_handleMessage(event) {
7662
- const [accumulatedMessage, newContent] = __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_accumulateMessage).call(this, event, __classPrivateFieldGet$1(this, _AssistantStream_messageSnapshot, "f"));
7663
- __classPrivateFieldSet$1(this, _AssistantStream_messageSnapshot, accumulatedMessage, "f");
7664
- __classPrivateFieldGet$1(this, _AssistantStream_messageSnapshots, "f")[accumulatedMessage.id] = accumulatedMessage;
7478
+ const [accumulatedMessage, newContent] = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateMessage).call(this, event, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
7479
+ __classPrivateFieldSet(this, _AssistantStream_messageSnapshot, accumulatedMessage, "f");
7480
+ __classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f")[accumulatedMessage.id] = accumulatedMessage;
7665
7481
  for (const content of newContent) {
7666
7482
  const snapshotContent = accumulatedMessage.content[content.index];
7667
7483
  if (snapshotContent?.type == 'text') {
@@ -7689,48 +7505,48 @@ _AssistantStream_addEvent = function _AssistantStream_addEvent(event) {
7689
7505
  throw Error('The snapshot associated with this text delta is not text or missing');
7690
7506
  }
7691
7507
  }
7692
- if (content.index != __classPrivateFieldGet$1(this, _AssistantStream_currentContentIndex, "f")) {
7508
+ if (content.index != __classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")) {
7693
7509
  //See if we have in progress content
7694
- if (__classPrivateFieldGet$1(this, _AssistantStream_currentContent, "f")) {
7695
- switch (__classPrivateFieldGet$1(this, _AssistantStream_currentContent, "f").type) {
7510
+ if (__classPrivateFieldGet(this, _AssistantStream_currentContent, "f")) {
7511
+ switch (__classPrivateFieldGet(this, _AssistantStream_currentContent, "f").type) {
7696
7512
  case 'text':
7697
- this._emit('textDone', __classPrivateFieldGet$1(this, _AssistantStream_currentContent, "f").text, __classPrivateFieldGet$1(this, _AssistantStream_messageSnapshot, "f"));
7513
+ this._emit('textDone', __classPrivateFieldGet(this, _AssistantStream_currentContent, "f").text, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
7698
7514
  break;
7699
7515
  case 'image_file':
7700
- this._emit('imageFileDone', __classPrivateFieldGet$1(this, _AssistantStream_currentContent, "f").image_file, __classPrivateFieldGet$1(this, _AssistantStream_messageSnapshot, "f"));
7516
+ this._emit('imageFileDone', __classPrivateFieldGet(this, _AssistantStream_currentContent, "f").image_file, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
7701
7517
  break;
7702
7518
  }
7703
7519
  }
7704
- __classPrivateFieldSet$1(this, _AssistantStream_currentContentIndex, content.index, "f");
7520
+ __classPrivateFieldSet(this, _AssistantStream_currentContentIndex, content.index, "f");
7705
7521
  }
7706
- __classPrivateFieldSet$1(this, _AssistantStream_currentContent, accumulatedMessage.content[content.index], "f");
7522
+ __classPrivateFieldSet(this, _AssistantStream_currentContent, accumulatedMessage.content[content.index], "f");
7707
7523
  }
7708
7524
  }
7709
7525
  break;
7710
7526
  case 'thread.message.completed':
7711
7527
  case 'thread.message.incomplete':
7712
7528
  //We emit the latest content we were working on on completion (including incomplete)
7713
- if (__classPrivateFieldGet$1(this, _AssistantStream_currentContentIndex, "f") !== undefined) {
7714
- const currentContent = event.data.content[__classPrivateFieldGet$1(this, _AssistantStream_currentContentIndex, "f")];
7529
+ if (__classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f") !== undefined) {
7530
+ const currentContent = event.data.content[__classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")];
7715
7531
  if (currentContent) {
7716
7532
  switch (currentContent.type) {
7717
7533
  case 'image_file':
7718
- this._emit('imageFileDone', currentContent.image_file, __classPrivateFieldGet$1(this, _AssistantStream_messageSnapshot, "f"));
7534
+ this._emit('imageFileDone', currentContent.image_file, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
7719
7535
  break;
7720
7536
  case 'text':
7721
- this._emit('textDone', currentContent.text, __classPrivateFieldGet$1(this, _AssistantStream_messageSnapshot, "f"));
7537
+ this._emit('textDone', currentContent.text, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
7722
7538
  break;
7723
7539
  }
7724
7540
  }
7725
7541
  }
7726
- if (__classPrivateFieldGet$1(this, _AssistantStream_messageSnapshot, "f")) {
7542
+ if (__classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")) {
7727
7543
  this._emit('messageDone', event.data);
7728
7544
  }
7729
- __classPrivateFieldSet$1(this, _AssistantStream_messageSnapshot, undefined, "f");
7545
+ __classPrivateFieldSet(this, _AssistantStream_messageSnapshot, undefined, "f");
7730
7546
  }
7731
7547
  }, _AssistantStream_handleRunStep = function _AssistantStream_handleRunStep(event) {
7732
- const accumulatedRunStep = __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_accumulateRunStep).call(this, event);
7733
- __classPrivateFieldSet$1(this, _AssistantStream_currentRunStepSnapshot, accumulatedRunStep, "f");
7548
+ const accumulatedRunStep = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateRunStep).call(this, event);
7549
+ __classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, accumulatedRunStep, "f");
7734
7550
  switch (event.event) {
7735
7551
  case 'thread.run.step.created':
7736
7552
  this._emit('runStepCreated', event.data);
@@ -7742,17 +7558,17 @@ _AssistantStream_addEvent = function _AssistantStream_addEvent(event) {
7742
7558
  delta.step_details.tool_calls &&
7743
7559
  accumulatedRunStep.step_details.type == 'tool_calls') {
7744
7560
  for (const toolCall of delta.step_details.tool_calls) {
7745
- if (toolCall.index == __classPrivateFieldGet$1(this, _AssistantStream_currentToolCallIndex, "f")) {
7561
+ if (toolCall.index == __classPrivateFieldGet(this, _AssistantStream_currentToolCallIndex, "f")) {
7746
7562
  this._emit('toolCallDelta', toolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index]);
7747
7563
  }
7748
7564
  else {
7749
- if (__classPrivateFieldGet$1(this, _AssistantStream_currentToolCall, "f")) {
7750
- this._emit('toolCallDone', __classPrivateFieldGet$1(this, _AssistantStream_currentToolCall, "f"));
7565
+ if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) {
7566
+ this._emit('toolCallDone', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f"));
7751
7567
  }
7752
- __classPrivateFieldSet$1(this, _AssistantStream_currentToolCallIndex, toolCall.index, "f");
7753
- __classPrivateFieldSet$1(this, _AssistantStream_currentToolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index], "f");
7754
- if (__classPrivateFieldGet$1(this, _AssistantStream_currentToolCall, "f"))
7755
- this._emit('toolCallCreated', __classPrivateFieldGet$1(this, _AssistantStream_currentToolCall, "f"));
7568
+ __classPrivateFieldSet(this, _AssistantStream_currentToolCallIndex, toolCall.index, "f");
7569
+ __classPrivateFieldSet(this, _AssistantStream_currentToolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index], "f");
7570
+ if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f"))
7571
+ this._emit('toolCallCreated', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f"));
7756
7572
  }
7757
7573
  }
7758
7574
  }
@@ -7762,46 +7578,46 @@ _AssistantStream_addEvent = function _AssistantStream_addEvent(event) {
7762
7578
  case 'thread.run.step.failed':
7763
7579
  case 'thread.run.step.cancelled':
7764
7580
  case 'thread.run.step.expired':
7765
- __classPrivateFieldSet$1(this, _AssistantStream_currentRunStepSnapshot, undefined, "f");
7581
+ __classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, undefined, "f");
7766
7582
  const details = event.data.step_details;
7767
7583
  if (details.type == 'tool_calls') {
7768
- if (__classPrivateFieldGet$1(this, _AssistantStream_currentToolCall, "f")) {
7769
- this._emit('toolCallDone', __classPrivateFieldGet$1(this, _AssistantStream_currentToolCall, "f"));
7770
- __classPrivateFieldSet$1(this, _AssistantStream_currentToolCall, undefined, "f");
7584
+ if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) {
7585
+ this._emit('toolCallDone', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f"));
7586
+ __classPrivateFieldSet(this, _AssistantStream_currentToolCall, undefined, "f");
7771
7587
  }
7772
7588
  }
7773
7589
  this._emit('runStepDone', event.data, accumulatedRunStep);
7774
7590
  break;
7775
7591
  }
7776
7592
  }, _AssistantStream_handleEvent = function _AssistantStream_handleEvent(event) {
7777
- __classPrivateFieldGet$1(this, _AssistantStream_events, "f").push(event);
7593
+ __classPrivateFieldGet(this, _AssistantStream_events, "f").push(event);
7778
7594
  this._emit('event', event);
7779
7595
  }, _AssistantStream_accumulateRunStep = function _AssistantStream_accumulateRunStep(event) {
7780
7596
  switch (event.event) {
7781
7597
  case 'thread.run.step.created':
7782
- __classPrivateFieldGet$1(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data;
7598
+ __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data;
7783
7599
  return event.data;
7784
7600
  case 'thread.run.step.delta':
7785
- let snapshot = __classPrivateFieldGet$1(this, _AssistantStream_runStepSnapshots, "f")[event.data.id];
7601
+ let snapshot = __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id];
7786
7602
  if (!snapshot) {
7787
7603
  throw Error('Received a RunStepDelta before creation of a snapshot');
7788
7604
  }
7789
7605
  let data = event.data;
7790
7606
  if (data.delta) {
7791
7607
  const accumulated = AssistantStream.accumulateDelta(snapshot, data.delta);
7792
- __classPrivateFieldGet$1(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = accumulated;
7608
+ __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = accumulated;
7793
7609
  }
7794
- return __classPrivateFieldGet$1(this, _AssistantStream_runStepSnapshots, "f")[event.data.id];
7610
+ return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id];
7795
7611
  case 'thread.run.step.completed':
7796
7612
  case 'thread.run.step.failed':
7797
7613
  case 'thread.run.step.cancelled':
7798
7614
  case 'thread.run.step.expired':
7799
7615
  case 'thread.run.step.in_progress':
7800
- __classPrivateFieldGet$1(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data;
7616
+ __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data;
7801
7617
  break;
7802
7618
  }
7803
- if (__classPrivateFieldGet$1(this, _AssistantStream_runStepSnapshots, "f")[event.data.id])
7804
- return __classPrivateFieldGet$1(this, _AssistantStream_runStepSnapshots, "f")[event.data.id];
7619
+ if (__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id])
7620
+ return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id];
7805
7621
  throw new Error('No snapshot available');
7806
7622
  }, _AssistantStream_accumulateMessage = function _AssistantStream_accumulateMessage(event, snapshot) {
7807
7623
  let newContent = [];
@@ -7819,7 +7635,7 @@ _AssistantStream_addEvent = function _AssistantStream_addEvent(event) {
7819
7635
  for (const contentElement of data.delta.content) {
7820
7636
  if (contentElement.index in snapshot.content) {
7821
7637
  let currentContent = snapshot.content[contentElement.index];
7822
- snapshot.content[contentElement.index] = __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_accumulateContent).call(this, contentElement, currentContent);
7638
+ snapshot.content[contentElement.index] = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateContent).call(this, contentElement, currentContent);
7823
7639
  }
7824
7640
  else {
7825
7641
  snapshot.content[contentElement.index] = contentElement;
@@ -7844,7 +7660,7 @@ _AssistantStream_addEvent = function _AssistantStream_addEvent(event) {
7844
7660
  }, _AssistantStream_accumulateContent = function _AssistantStream_accumulateContent(contentElement, currentContent) {
7845
7661
  return AssistantStream.accumulateDelta(currentContent, contentElement);
7846
7662
  }, _AssistantStream_handleRun = function _AssistantStream_handleRun(event) {
7847
- __classPrivateFieldSet$1(this, _AssistantStream_currentRunSnapshot, event.data, "f");
7663
+ __classPrivateFieldSet(this, _AssistantStream_currentRunSnapshot, event.data, "f");
7848
7664
  switch (event.event) {
7849
7665
  case 'thread.run.created':
7850
7666
  break;
@@ -7857,10 +7673,10 @@ _AssistantStream_addEvent = function _AssistantStream_addEvent(event) {
7857
7673
  case 'thread.run.failed':
7858
7674
  case 'thread.run.completed':
7859
7675
  case 'thread.run.expired':
7860
- __classPrivateFieldSet$1(this, _AssistantStream_finalRun, event.data, "f");
7861
- if (__classPrivateFieldGet$1(this, _AssistantStream_currentToolCall, "f")) {
7862
- this._emit('toolCallDone', __classPrivateFieldGet$1(this, _AssistantStream_currentToolCall, "f"));
7863
- __classPrivateFieldSet$1(this, _AssistantStream_currentToolCall, undefined, "f");
7676
+ __classPrivateFieldSet(this, _AssistantStream_finalRun, event.data, "f");
7677
+ if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) {
7678
+ this._emit('toolCallDone', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f"));
7679
+ __classPrivateFieldSet(this, _AssistantStream_currentToolCall, undefined, "f");
7864
7680
  }
7865
7681
  break;
7866
7682
  }
@@ -8177,1117 +7993,663 @@ Threads.RunsPage = RunsPage;
8177
7993
  Threads.Messages = Messages;
8178
7994
  Threads.MessagesPage = MessagesPage;
8179
7995
 
8180
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8181
- class Beta extends APIResource {
8182
- constructor() {
8183
- super(...arguments);
8184
- this.realtime = new Realtime(this._client);
8185
- this.chat = new Chat(this._client);
8186
- this.assistants = new Assistants(this._client);
8187
- this.threads = new Threads(this._client);
8188
- }
8189
- }
8190
- Beta.Realtime = Realtime;
8191
- Beta.Assistants = Assistants;
8192
- Beta.AssistantsPage = AssistantsPage;
8193
- Beta.Threads = Threads;
8194
-
8195
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8196
- class Completions extends APIResource {
8197
- create(body, options) {
8198
- return this._client.post('/completions', { body, ...options, stream: body.stream ?? false });
7996
+ /**
7997
+ * Like `Promise.allSettled()` but throws an error if any promises are rejected.
7998
+ */
7999
+ const allSettledWithThrow = async (promises) => {
8000
+ const results = await Promise.allSettled(promises);
8001
+ const rejected = results.filter((result) => result.status === 'rejected');
8002
+ if (rejected.length) {
8003
+ for (const result of rejected) {
8004
+ console.error(result.reason);
8005
+ }
8006
+ throw new Error(`${rejected.length} promise(s) failed - see the above errors`);
8199
8007
  }
8200
- }
8201
-
8202
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8203
- class Embeddings extends APIResource {
8204
- /**
8205
- * Creates an embedding vector representing the input text.
8206
- */
8207
- create(body, options) {
8208
- return this._client.post('/embeddings', { body, ...options });
8008
+ // Note: TS was complaining about using `.filter().map()` here for some reason
8009
+ const values = [];
8010
+ for (const result of results) {
8011
+ if (result.status === 'fulfilled') {
8012
+ values.push(result.value);
8013
+ }
8209
8014
  }
8210
- }
8015
+ return values;
8016
+ };
8211
8017
 
8212
8018
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8213
8019
  let Files$1 = class Files extends APIResource {
8214
8020
  /**
8215
- * Upload a file that can be used across various endpoints. Individual files can be
8216
- * up to 512 MB, and the size of all files uploaded by one organization can be up
8217
- * to 100 GB.
8218
- *
8219
- * The Assistants API supports files up to 2 million tokens and of specific file
8220
- * types. See the
8221
- * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for
8222
- * details.
8223
- *
8224
- * The Fine-tuning API only supports `.jsonl` files. The input also has certain
8225
- * required formats for fine-tuning
8226
- * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or
8227
- * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input)
8228
- * models.
8229
- *
8230
- * The Batch API only supports `.jsonl` files up to 200 MB in size. The input also
8231
- * has a specific required
8232
- * [format](https://platform.openai.com/docs/api-reference/batch/request-input).
8233
- *
8234
- * Please [contact us](https://help.openai.com/) if you need to increase these
8235
- * storage limits.
8021
+ * Create a vector store file by attaching a
8022
+ * [File](https://platform.openai.com/docs/api-reference/files) to a
8023
+ * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object).
8236
8024
  */
8237
- create(body, options) {
8238
- return this._client.post('/files', multipartFormRequestOptions({ body, ...options }));
8025
+ create(vectorStoreId, body, options) {
8026
+ return this._client.post(`/vector_stores/${vectorStoreId}/files`, {
8027
+ body,
8028
+ ...options,
8029
+ headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8030
+ });
8239
8031
  }
8240
8032
  /**
8241
- * Returns information about a specific file.
8033
+ * Retrieves a vector store file.
8242
8034
  */
8243
- retrieve(fileId, options) {
8244
- return this._client.get(`/files/${fileId}`, options);
8035
+ retrieve(vectorStoreId, fileId, options) {
8036
+ return this._client.get(`/vector_stores/${vectorStoreId}/files/${fileId}`, {
8037
+ ...options,
8038
+ headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8039
+ });
8245
8040
  }
8246
- list(query = {}, options) {
8041
+ list(vectorStoreId, query = {}, options) {
8247
8042
  if (isRequestOptions(query)) {
8248
- return this.list({}, query);
8043
+ return this.list(vectorStoreId, {}, query);
8249
8044
  }
8250
- return this._client.getAPIList('/files', FileObjectsPage, { query, ...options });
8251
- }
8252
- /**
8253
- * Delete a file.
8254
- */
8255
- del(fileId, options) {
8256
- return this._client.delete(`/files/${fileId}`, options);
8045
+ return this._client.getAPIList(`/vector_stores/${vectorStoreId}/files`, VectorStoreFilesPage, {
8046
+ query,
8047
+ ...options,
8048
+ headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8049
+ });
8257
8050
  }
8258
8051
  /**
8259
- * Returns the contents of the specified file.
8052
+ * Delete a vector store file. This will remove the file from the vector store but
8053
+ * the file itself will not be deleted. To delete the file, use the
8054
+ * [delete file](https://platform.openai.com/docs/api-reference/files/delete)
8055
+ * endpoint.
8260
8056
  */
8261
- content(fileId, options) {
8262
- return this._client.get(`/files/${fileId}/content`, {
8057
+ del(vectorStoreId, fileId, options) {
8058
+ return this._client.delete(`/vector_stores/${vectorStoreId}/files/${fileId}`, {
8263
8059
  ...options,
8264
- headers: { Accept: 'application/binary', ...options?.headers },
8265
- __binaryResponse: true,
8060
+ headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8266
8061
  });
8267
8062
  }
8268
8063
  /**
8269
- * Returns the contents of the specified file.
8270
- *
8271
- * @deprecated The `.content()` method should be used instead
8064
+ * Attach a file to the given vector store and wait for it to be processed.
8272
8065
  */
8273
- retrieveContent(fileId, options) {
8274
- return this._client.get(`/files/${fileId}/content`, options);
8066
+ async createAndPoll(vectorStoreId, body, options) {
8067
+ const file = await this.create(vectorStoreId, body, options);
8068
+ return await this.poll(vectorStoreId, file.id, options);
8275
8069
  }
8276
8070
  /**
8277
- * Waits for the given file to be processed, default timeout is 30 mins.
8071
+ * Wait for the vector store file to finish processing.
8072
+ *
8073
+ * Note: this will return even if the file failed to process, you need to check
8074
+ * file.last_error and file.status to handle these cases
8278
8075
  */
8279
- async waitForProcessing(id, { pollInterval = 5000, maxWait = 30 * 60 * 1000 } = {}) {
8280
- const TERMINAL_STATES = new Set(['processed', 'error', 'deleted']);
8281
- const start = Date.now();
8282
- let file = await this.retrieve(id);
8283
- while (!file.status || !TERMINAL_STATES.has(file.status)) {
8284
- await sleep(pollInterval);
8285
- file = await this.retrieve(id);
8286
- if (Date.now() - start > maxWait) {
8287
- throw new APIConnectionTimeoutError({
8288
- message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`,
8289
- });
8290
- }
8076
+ async poll(vectorStoreId, fileId, options) {
8077
+ const headers = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' };
8078
+ if (options?.pollIntervalMs) {
8079
+ headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString();
8291
8080
  }
8292
- return file;
8293
- }
8294
- };
8295
- class FileObjectsPage extends CursorPage {
8296
- }
8297
- Files$1.FileObjectsPage = FileObjectsPage;
8298
-
8299
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8300
- class Checkpoints extends APIResource {
8301
- list(fineTuningJobId, query = {}, options) {
8302
- if (isRequestOptions(query)) {
8303
- return this.list(fineTuningJobId, {}, query);
8081
+ while (true) {
8082
+ const fileResponse = await this.retrieve(vectorStoreId, fileId, {
8083
+ ...options,
8084
+ headers,
8085
+ }).withResponse();
8086
+ const file = fileResponse.data;
8087
+ switch (file.status) {
8088
+ case 'in_progress':
8089
+ let sleepInterval = 5000;
8090
+ if (options?.pollIntervalMs) {
8091
+ sleepInterval = options.pollIntervalMs;
8092
+ }
8093
+ else {
8094
+ const headerInterval = fileResponse.response.headers.get('openai-poll-after-ms');
8095
+ if (headerInterval) {
8096
+ const headerIntervalMs = parseInt(headerInterval);
8097
+ if (!isNaN(headerIntervalMs)) {
8098
+ sleepInterval = headerIntervalMs;
8099
+ }
8100
+ }
8101
+ }
8102
+ await sleep(sleepInterval);
8103
+ break;
8104
+ case 'failed':
8105
+ case 'completed':
8106
+ return file;
8107
+ }
8304
8108
  }
8305
- return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/checkpoints`, FineTuningJobCheckpointsPage, { query, ...options });
8306
- }
8307
- }
8308
- class FineTuningJobCheckpointsPage extends CursorPage {
8309
- }
8310
- Checkpoints.FineTuningJobCheckpointsPage = FineTuningJobCheckpointsPage;
8311
-
8312
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8313
- class Jobs extends APIResource {
8314
- constructor() {
8315
- super(...arguments);
8316
- this.checkpoints = new Checkpoints(this._client);
8317
8109
  }
8318
8110
  /**
8319
- * Creates a fine-tuning job which begins the process of creating a new model from
8320
- * a given dataset.
8321
- *
8322
- * Response includes details of the enqueued job including job status and the name
8323
- * of the fine-tuned models once complete.
8111
+ * Upload a file to the `files` API and then attach it to the given vector store.
8324
8112
  *
8325
- * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning)
8113
+ * Note the file will be asynchronously processed (you can use the alternative
8114
+ * polling helper method to wait for processing to complete).
8326
8115
  */
8327
- create(body, options) {
8328
- return this._client.post('/fine_tuning/jobs', { body, ...options });
8116
+ async upload(vectorStoreId, file, options) {
8117
+ const fileInfo = await this._client.files.create({ file: file, purpose: 'assistants' }, options);
8118
+ return this.create(vectorStoreId, { file_id: fileInfo.id }, options);
8329
8119
  }
8330
8120
  /**
8331
- * Get info about a fine-tuning job.
8332
- *
8333
- * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning)
8121
+ * Add a file to a vector store and poll until processing is complete.
8334
8122
  */
8335
- retrieve(fineTuningJobId, options) {
8336
- return this._client.get(`/fine_tuning/jobs/${fineTuningJobId}`, options);
8337
- }
8338
- list(query = {}, options) {
8339
- if (isRequestOptions(query)) {
8340
- return this.list({}, query);
8341
- }
8342
- return this._client.getAPIList('/fine_tuning/jobs', FineTuningJobsPage, { query, ...options });
8343
- }
8344
- /**
8345
- * Immediately cancel a fine-tune job.
8346
- */
8347
- cancel(fineTuningJobId, options) {
8348
- return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/cancel`, options);
8349
- }
8350
- listEvents(fineTuningJobId, query = {}, options) {
8351
- if (isRequestOptions(query)) {
8352
- return this.listEvents(fineTuningJobId, {}, query);
8353
- }
8354
- return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/events`, FineTuningJobEventsPage, {
8355
- query,
8356
- ...options,
8357
- });
8358
- }
8359
- }
8360
- class FineTuningJobsPage extends CursorPage {
8361
- }
8362
- class FineTuningJobEventsPage extends CursorPage {
8363
- }
8364
- Jobs.FineTuningJobsPage = FineTuningJobsPage;
8365
- Jobs.FineTuningJobEventsPage = FineTuningJobEventsPage;
8366
- Jobs.Checkpoints = Checkpoints;
8367
- Jobs.FineTuningJobCheckpointsPage = FineTuningJobCheckpointsPage;
8368
-
8369
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8370
- class FineTuning extends APIResource {
8371
- constructor() {
8372
- super(...arguments);
8373
- this.jobs = new Jobs(this._client);
8123
+ async uploadAndPoll(vectorStoreId, file, options) {
8124
+ const fileInfo = await this.upload(vectorStoreId, file, options);
8125
+ return await this.poll(vectorStoreId, fileInfo.id, options);
8374
8126
  }
8127
+ };
8128
+ class VectorStoreFilesPage extends CursorPage {
8375
8129
  }
8376
- FineTuning.Jobs = Jobs;
8377
- FineTuning.FineTuningJobsPage = FineTuningJobsPage;
8378
- FineTuning.FineTuningJobEventsPage = FineTuningJobEventsPage;
8130
+ Files$1.VectorStoreFilesPage = VectorStoreFilesPage;
8379
8131
 
8380
8132
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8381
- class Images extends APIResource {
8382
- /**
8383
- * Creates a variation of a given image.
8384
- */
8385
- createVariation(body, options) {
8386
- return this._client.post('/images/variations', multipartFormRequestOptions({ body, ...options }));
8387
- }
8133
+ class FileBatches extends APIResource {
8388
8134
  /**
8389
- * Creates an edited or extended image given an original image and a prompt.
8135
+ * Create a vector store file batch.
8390
8136
  */
8391
- edit(body, options) {
8392
- return this._client.post('/images/edits', multipartFormRequestOptions({ body, ...options }));
8137
+ create(vectorStoreId, body, options) {
8138
+ return this._client.post(`/vector_stores/${vectorStoreId}/file_batches`, {
8139
+ body,
8140
+ ...options,
8141
+ headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8142
+ });
8393
8143
  }
8394
8144
  /**
8395
- * Creates an image given a prompt.
8145
+ * Retrieves a vector store file batch.
8396
8146
  */
8397
- generate(body, options) {
8398
- return this._client.post('/images/generations', { body, ...options });
8147
+ retrieve(vectorStoreId, batchId, options) {
8148
+ return this._client.get(`/vector_stores/${vectorStoreId}/file_batches/${batchId}`, {
8149
+ ...options,
8150
+ headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8151
+ });
8399
8152
  }
8400
- }
8401
-
8402
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8403
- class Models extends APIResource {
8404
8153
  /**
8405
- * Retrieves a model instance, providing basic information about the model such as
8406
- * the owner and permissioning.
8154
+ * Cancel a vector store file batch. This attempts to cancel the processing of
8155
+ * files in this batch as soon as possible.
8407
8156
  */
8408
- retrieve(model, options) {
8409
- return this._client.get(`/models/${model}`, options);
8157
+ cancel(vectorStoreId, batchId, options) {
8158
+ return this._client.post(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/cancel`, {
8159
+ ...options,
8160
+ headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8161
+ });
8410
8162
  }
8411
8163
  /**
8412
- * Lists the currently available models, and provides basic information about each
8413
- * one such as the owner and availability.
8164
+ * Create a vector store batch and poll until all files have been processed.
8414
8165
  */
8415
- list(options) {
8416
- return this._client.getAPIList('/models', ModelsPage, options);
8166
+ async createAndPoll(vectorStoreId, body, options) {
8167
+ const batch = await this.create(vectorStoreId, body);
8168
+ return await this.poll(vectorStoreId, batch.id, options);
8417
8169
  }
8418
- /**
8419
- * Delete a fine-tuned model. You must have the Owner role in your organization to
8420
- * delete a model.
8421
- */
8422
- del(model, options) {
8423
- return this._client.delete(`/models/${model}`, options);
8170
+ listFiles(vectorStoreId, batchId, query = {}, options) {
8171
+ if (isRequestOptions(query)) {
8172
+ return this.listFiles(vectorStoreId, batchId, {}, query);
8173
+ }
8174
+ return this._client.getAPIList(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/files`, VectorStoreFilesPage, { query, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers } });
8424
8175
  }
8425
- }
8426
- /**
8427
- * Note: no pagination actually occurs yet, this is for forwards-compatibility.
8428
- */
8429
- class ModelsPage extends Page {
8430
- }
8431
- Models.ModelsPage = ModelsPage;
8432
-
8433
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8434
- class Moderations extends APIResource {
8435
8176
  /**
8436
- * Classifies if text and/or image inputs are potentially harmful. Learn more in
8437
- * the [moderation guide](https://platform.openai.com/docs/guides/moderation).
8177
+ * Wait for the given file batch to be processed.
8178
+ *
8179
+ * Note: this will return even if one of the files failed to process, you need to
8180
+ * check batch.file_counts.failed_count to handle this case.
8438
8181
  */
8439
- create(body, options) {
8440
- return this._client.post('/moderations', { body, ...options });
8441
- }
8442
- }
8443
-
8444
- function maybeParseResponse(response, params) {
8445
- if (!params || !hasAutoParseableInput(params)) {
8446
- return {
8447
- ...response,
8448
- output_parsed: null,
8449
- output: response.output.map((item) => {
8450
- if (item.type === 'function_call') {
8451
- return {
8452
- ...item,
8453
- parsed_arguments: null,
8454
- };
8455
- }
8456
- if (item.type === 'message') {
8457
- return {
8458
- ...item,
8459
- content: item.content.map((content) => ({
8460
- ...content,
8461
- parsed: null,
8462
- })),
8463
- };
8464
- }
8465
- else {
8466
- return item;
8467
- }
8468
- }),
8469
- };
8470
- }
8471
- return parseResponse(response, params);
8472
- }
8473
- function parseResponse(response, params) {
8474
- const output = response.output.map((item) => {
8475
- if (item.type === 'function_call') {
8476
- return {
8477
- ...item,
8478
- parsed_arguments: parseToolCall(params, item),
8479
- };
8480
- }
8481
- if (item.type === 'message') {
8482
- const content = item.content.map((content) => {
8483
- if (content.type === 'output_text') {
8484
- return {
8485
- ...content,
8486
- parsed: parseTextFormat(params, content.text),
8487
- };
8488
- }
8489
- return content;
8490
- });
8491
- return {
8492
- ...item,
8493
- content,
8494
- };
8182
+ async poll(vectorStoreId, batchId, options) {
8183
+ const headers = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' };
8184
+ if (options?.pollIntervalMs) {
8185
+ headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString();
8495
8186
  }
8496
- return item;
8497
- });
8498
- const parsed = Object.assign({}, response, { output });
8499
- if (!Object.getOwnPropertyDescriptor(response, 'output_text')) {
8500
- addOutputText(parsed);
8501
- }
8502
- Object.defineProperty(parsed, 'output_parsed', {
8503
- enumerable: true,
8504
- get() {
8505
- for (const output of parsed.output) {
8506
- if (output.type !== 'message') {
8507
- continue;
8508
- }
8509
- for (const content of output.content) {
8510
- if (content.type === 'output_text' && content.parsed !== null) {
8511
- return content.parsed;
8187
+ while (true) {
8188
+ const { data: batch, response } = await this.retrieve(vectorStoreId, batchId, {
8189
+ ...options,
8190
+ headers,
8191
+ }).withResponse();
8192
+ switch (batch.status) {
8193
+ case 'in_progress':
8194
+ let sleepInterval = 5000;
8195
+ if (options?.pollIntervalMs) {
8196
+ sleepInterval = options.pollIntervalMs;
8512
8197
  }
8513
- }
8198
+ else {
8199
+ const headerInterval = response.headers.get('openai-poll-after-ms');
8200
+ if (headerInterval) {
8201
+ const headerIntervalMs = parseInt(headerInterval);
8202
+ if (!isNaN(headerIntervalMs)) {
8203
+ sleepInterval = headerIntervalMs;
8204
+ }
8205
+ }
8206
+ }
8207
+ await sleep(sleepInterval);
8208
+ break;
8209
+ case 'failed':
8210
+ case 'cancelled':
8211
+ case 'completed':
8212
+ return batch;
8514
8213
  }
8515
- return null;
8516
- },
8517
- });
8518
- return parsed;
8519
- }
8520
- function parseTextFormat(params, content) {
8521
- if (params.text?.format?.type !== 'json_schema') {
8522
- return null;
8523
- }
8524
- if ('$parseRaw' in params.text?.format) {
8525
- const text_format = params.text?.format;
8526
- return text_format.$parseRaw(content);
8527
- }
8528
- return JSON.parse(content);
8529
- }
8530
- function hasAutoParseableInput(params) {
8531
- if (isAutoParsableResponseFormat(params.text?.format)) {
8532
- return true;
8214
+ }
8533
8215
  }
8534
- return false;
8535
- }
8536
- function isAutoParsableTool(tool) {
8537
- return tool?.['$brand'] === 'auto-parseable-tool';
8538
- }
8539
- function getInputToolByName(input_tools, name) {
8540
- return input_tools.find((tool) => tool.type === 'function' && tool.name === name);
8541
- }
8542
- function parseToolCall(params, toolCall) {
8543
- const inputTool = getInputToolByName(params.tools ?? [], toolCall.name);
8544
- return {
8545
- ...toolCall,
8546
- ...toolCall,
8547
- parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.arguments)
8548
- : inputTool?.strict ? JSON.parse(toolCall.arguments)
8549
- : null,
8550
- };
8551
- }
8552
- function addOutputText(rsp) {
8553
- const texts = [];
8554
- for (const output of rsp.output) {
8555
- if (output.type !== 'message') {
8556
- continue;
8216
+ /**
8217
+ * Uploads the given files concurrently and then creates a vector store file batch.
8218
+ *
8219
+ * The concurrency limit is configurable using the `maxConcurrency` parameter.
8220
+ */
8221
+ async uploadAndPoll(vectorStoreId, { files, fileIds = [] }, options) {
8222
+ if (files == null || files.length == 0) {
8223
+ throw new Error(`No \`files\` provided to process. If you've already uploaded files you should use \`.createAndPoll()\` instead`);
8557
8224
  }
8558
- for (const content of output.content) {
8559
- if (content.type === 'output_text') {
8560
- texts.push(content.text);
8225
+ const configuredConcurrency = options?.maxConcurrency ?? 5;
8226
+ // We cap the number of workers at the number of files (so we don't start any unnecessary workers)
8227
+ const concurrencyLimit = Math.min(configuredConcurrency, files.length);
8228
+ const client = this._client;
8229
+ const fileIterator = files.values();
8230
+ const allFileIds = [...fileIds];
8231
+ // This code is based on this design. The libraries don't accommodate our environment limits.
8232
+ // https://stackoverflow.com/questions/40639432/what-is-the-best-way-to-limit-concurrency-when-using-es6s-promise-all
8233
+ async function processFiles(iterator) {
8234
+ for (let item of iterator) {
8235
+ const fileObj = await client.files.create({ file: item, purpose: 'assistants' }, options);
8236
+ allFileIds.push(fileObj.id);
8561
8237
  }
8562
8238
  }
8239
+ // Start workers to process results
8240
+ const workers = Array(concurrencyLimit).fill(fileIterator).map(processFiles);
8241
+ // Wait for all processing to complete.
8242
+ await allSettledWithThrow(workers);
8243
+ return await this.createAndPoll(vectorStoreId, {
8244
+ file_ids: allFileIds,
8245
+ });
8563
8246
  }
8564
- rsp.output_text = texts.join('');
8565
8247
  }
8566
8248
 
8567
8249
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8568
- class InputItems extends APIResource {
8569
- list(responseId, query = {}, options) {
8570
- if (isRequestOptions(query)) {
8571
- return this.list(responseId, {}, query);
8572
- }
8573
- return this._client.getAPIList(`/responses/${responseId}/input_items`, ResponseItemListDataPage, {
8574
- query,
8250
+ class VectorStores extends APIResource {
8251
+ constructor() {
8252
+ super(...arguments);
8253
+ this.files = new Files$1(this._client);
8254
+ this.fileBatches = new FileBatches(this._client);
8255
+ }
8256
+ /**
8257
+ * Create a vector store.
8258
+ */
8259
+ create(body, options) {
8260
+ return this._client.post('/vector_stores', {
8261
+ body,
8575
8262
  ...options,
8263
+ headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8576
8264
  });
8577
8265
  }
8578
- }
8579
- class ResponseItemListDataPage extends CursorPage {
8580
- }
8581
- InputItems.ResponseItemListDataPage = ResponseItemListDataPage;
8582
-
8583
- var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
8584
- if (kind === "m") throw new TypeError("Private method is not writable");
8585
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
8586
- 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");
8587
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
8588
- };
8589
- var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8590
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
8591
- 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");
8592
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
8593
- };
8594
- var _ResponseStream_instances, _ResponseStream_params, _ResponseStream_currentResponseSnapshot, _ResponseStream_finalResponse, _ResponseStream_beginRequest, _ResponseStream_addEvent, _ResponseStream_endRequest, _ResponseStream_accumulateResponse;
8595
- class ResponseStream extends EventStream {
8596
- constructor(params) {
8597
- super();
8598
- _ResponseStream_instances.add(this);
8599
- _ResponseStream_params.set(this, void 0);
8600
- _ResponseStream_currentResponseSnapshot.set(this, void 0);
8601
- _ResponseStream_finalResponse.set(this, void 0);
8602
- __classPrivateFieldSet(this, _ResponseStream_params, params, "f");
8603
- }
8604
- static createResponse(client, params, options) {
8605
- const runner = new ResponseStream(params);
8606
- runner._run(() => runner._createResponse(client, params, {
8266
+ /**
8267
+ * Retrieves a vector store.
8268
+ */
8269
+ retrieve(vectorStoreId, options) {
8270
+ return this._client.get(`/vector_stores/${vectorStoreId}`, {
8607
8271
  ...options,
8608
- headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' },
8609
- }));
8610
- return runner;
8272
+ headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8273
+ });
8611
8274
  }
8612
- async _createResponse(client, params, options) {
8613
- const signal = options?.signal;
8614
- if (signal) {
8615
- if (signal.aborted)
8616
- this.controller.abort();
8617
- signal.addEventListener('abort', () => this.controller.abort());
8618
- }
8619
- __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_beginRequest).call(this);
8620
- const stream = await client.responses.create({ ...params, stream: true }, { ...options, signal: this.controller.signal });
8621
- this._connected();
8622
- for await (const event of stream) {
8623
- __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_addEvent).call(this, event);
8624
- }
8625
- if (stream.controller.signal?.aborted) {
8626
- throw new APIUserAbortError();
8627
- }
8628
- return __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_endRequest).call(this);
8275
+ /**
8276
+ * Modifies a vector store.
8277
+ */
8278
+ update(vectorStoreId, body, options) {
8279
+ return this._client.post(`/vector_stores/${vectorStoreId}`, {
8280
+ body,
8281
+ ...options,
8282
+ headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8283
+ });
8629
8284
  }
8630
- [(_ResponseStream_params = new WeakMap(), _ResponseStream_currentResponseSnapshot = new WeakMap(), _ResponseStream_finalResponse = new WeakMap(), _ResponseStream_instances = new WeakSet(), _ResponseStream_beginRequest = function _ResponseStream_beginRequest() {
8631
- if (this.ended)
8632
- return;
8633
- __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, undefined, "f");
8634
- }, _ResponseStream_addEvent = function _ResponseStream_addEvent(event) {
8635
- if (this.ended)
8636
- return;
8637
- const response = __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_accumulateResponse).call(this, event);
8638
- this._emit('event', event);
8639
- switch (event.type) {
8640
- case 'response.output_text.delta': {
8641
- const output = response.output[event.output_index];
8642
- if (!output) {
8643
- throw new OpenAIError(`missing output at index ${event.output_index}`);
8644
- }
8645
- if (output.type === 'message') {
8646
- const content = output.content[event.content_index];
8647
- if (!content) {
8648
- throw new OpenAIError(`missing content at index ${event.content_index}`);
8649
- }
8650
- if (content.type !== 'output_text') {
8651
- throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
8652
- }
8653
- this._emit('response.output_text.delta', {
8654
- ...event,
8655
- snapshot: content.text,
8656
- });
8657
- }
8658
- break;
8659
- }
8660
- case 'response.function_call_arguments.delta': {
8661
- const output = response.output[event.output_index];
8662
- if (!output) {
8663
- throw new OpenAIError(`missing output at index ${event.output_index}`);
8664
- }
8665
- if (output.type === 'function_call') {
8666
- this._emit('response.function_call_arguments.delta', {
8667
- ...event,
8668
- snapshot: output.arguments,
8669
- });
8670
- }
8671
- break;
8672
- }
8673
- default:
8674
- // @ts-ignore
8675
- this._emit(event.type, event);
8676
- break;
8677
- }
8678
- }, _ResponseStream_endRequest = function _ResponseStream_endRequest() {
8679
- if (this.ended) {
8680
- throw new OpenAIError(`stream has ended, this shouldn't happen`);
8681
- }
8682
- const snapshot = __classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f");
8683
- if (!snapshot) {
8684
- throw new OpenAIError(`request ended without sending any events`);
8685
- }
8686
- __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, undefined, "f");
8687
- const parsedResponse = finalizeResponse(snapshot, __classPrivateFieldGet(this, _ResponseStream_params, "f"));
8688
- __classPrivateFieldSet(this, _ResponseStream_finalResponse, parsedResponse, "f");
8689
- return parsedResponse;
8690
- }, _ResponseStream_accumulateResponse = function _ResponseStream_accumulateResponse(event) {
8691
- let snapshot = __classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f");
8692
- if (!snapshot) {
8693
- if (event.type !== 'response.created') {
8694
- throw new OpenAIError(`When snapshot hasn't been set yet, expected 'response.created' event, got ${event.type}`);
8695
- }
8696
- snapshot = __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, event.response, "f");
8697
- return snapshot;
8698
- }
8699
- switch (event.type) {
8700
- case 'response.output_item.added': {
8701
- snapshot.output.push(event.item);
8702
- break;
8703
- }
8704
- case 'response.content_part.added': {
8705
- const output = snapshot.output[event.output_index];
8706
- if (!output) {
8707
- throw new OpenAIError(`missing output at index ${event.output_index}`);
8708
- }
8709
- if (output.type === 'message') {
8710
- output.content.push(event.part);
8711
- }
8712
- break;
8713
- }
8714
- case 'response.output_text.delta': {
8715
- const output = snapshot.output[event.output_index];
8716
- if (!output) {
8717
- throw new OpenAIError(`missing output at index ${event.output_index}`);
8718
- }
8719
- if (output.type === 'message') {
8720
- const content = output.content[event.content_index];
8721
- if (!content) {
8722
- throw new OpenAIError(`missing content at index ${event.content_index}`);
8723
- }
8724
- if (content.type !== 'output_text') {
8725
- throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
8726
- }
8727
- content.text += event.delta;
8728
- }
8729
- break;
8730
- }
8731
- case 'response.function_call_arguments.delta': {
8732
- const output = snapshot.output[event.output_index];
8733
- if (!output) {
8734
- throw new OpenAIError(`missing output at index ${event.output_index}`);
8735
- }
8736
- if (output.type === 'function_call') {
8737
- output.arguments += event.delta;
8738
- }
8739
- break;
8740
- }
8741
- case 'response.completed': {
8742
- __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, event.response, "f");
8743
- break;
8744
- }
8285
+ list(query = {}, options) {
8286
+ if (isRequestOptions(query)) {
8287
+ return this.list({}, query);
8745
8288
  }
8746
- return snapshot;
8747
- }, Symbol.asyncIterator)]() {
8748
- const pushQueue = [];
8749
- const readQueue = [];
8750
- let done = false;
8751
- this.on('event', (event) => {
8752
- const reader = readQueue.shift();
8753
- if (reader) {
8754
- reader.resolve(event);
8755
- }
8756
- else {
8757
- pushQueue.push(event);
8758
- }
8759
- });
8760
- this.on('end', () => {
8761
- done = true;
8762
- for (const reader of readQueue) {
8763
- reader.resolve(undefined);
8764
- }
8765
- readQueue.length = 0;
8766
- });
8767
- this.on('abort', (err) => {
8768
- done = true;
8769
- for (const reader of readQueue) {
8770
- reader.reject(err);
8771
- }
8772
- readQueue.length = 0;
8773
- });
8774
- this.on('error', (err) => {
8775
- done = true;
8776
- for (const reader of readQueue) {
8777
- reader.reject(err);
8778
- }
8779
- readQueue.length = 0;
8289
+ return this._client.getAPIList('/vector_stores', VectorStoresPage, {
8290
+ query,
8291
+ ...options,
8292
+ headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8780
8293
  });
8781
- return {
8782
- next: async () => {
8783
- if (!pushQueue.length) {
8784
- if (done) {
8785
- return { value: undefined, done: true };
8786
- }
8787
- return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((event) => (event ? { value: event, done: false } : { value: undefined, done: true }));
8788
- }
8789
- const event = pushQueue.shift();
8790
- return { value: event, done: false };
8791
- },
8792
- return: async () => {
8793
- this.abort();
8794
- return { value: undefined, done: true };
8795
- },
8796
- };
8797
8294
  }
8798
8295
  /**
8799
- * @returns a promise that resolves with the final Response, or rejects
8800
- * if an error occurred or the stream ended prematurely without producing a REsponse.
8296
+ * Delete a vector store.
8801
8297
  */
8802
- async finalResponse() {
8803
- await this.done();
8804
- const response = __classPrivateFieldGet(this, _ResponseStream_finalResponse, "f");
8805
- if (!response)
8806
- throw new OpenAIError('stream ended without producing a ChatCompletion');
8807
- return response;
8298
+ del(vectorStoreId, options) {
8299
+ return this._client.delete(`/vector_stores/${vectorStoreId}`, {
8300
+ ...options,
8301
+ headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8302
+ });
8808
8303
  }
8809
8304
  }
8810
- function finalizeResponse(snapshot, params) {
8811
- return maybeParseResponse(snapshot, params);
8305
+ class VectorStoresPage extends CursorPage {
8812
8306
  }
8307
+ VectorStores.VectorStoresPage = VectorStoresPage;
8308
+ VectorStores.Files = Files$1;
8309
+ VectorStores.VectorStoreFilesPage = VectorStoreFilesPage;
8310
+ VectorStores.FileBatches = FileBatches;
8813
8311
 
8814
8312
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8815
- class Responses extends APIResource {
8313
+ class Beta extends APIResource {
8816
8314
  constructor() {
8817
8315
  super(...arguments);
8818
- this.inputItems = new InputItems(this._client);
8316
+ this.vectorStores = new VectorStores(this._client);
8317
+ this.chat = new Chat(this._client);
8318
+ this.assistants = new Assistants(this._client);
8319
+ this.threads = new Threads(this._client);
8819
8320
  }
8321
+ }
8322
+ Beta.VectorStores = VectorStores;
8323
+ Beta.VectorStoresPage = VectorStoresPage;
8324
+ Beta.Assistants = Assistants;
8325
+ Beta.AssistantsPage = AssistantsPage;
8326
+ Beta.Threads = Threads;
8327
+
8328
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8329
+ class Completions extends APIResource {
8820
8330
  create(body, options) {
8821
- return this._client.post('/responses', { body, ...options, stream: body.stream ?? false })._thenUnwrap((rsp) => {
8822
- if ('object' in rsp && rsp.object === 'response') {
8823
- addOutputText(rsp);
8824
- }
8825
- return rsp;
8826
- });
8331
+ return this._client.post('/completions', { body, ...options, stream: body.stream ?? false });
8332
+ }
8333
+ }
8334
+
8335
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8336
+ class Embeddings extends APIResource {
8337
+ /**
8338
+ * Creates an embedding vector representing the input text.
8339
+ */
8340
+ create(body, options) {
8341
+ return this._client.post('/embeddings', { body, ...options });
8342
+ }
8343
+ }
8344
+
8345
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8346
+ class Files extends APIResource {
8347
+ /**
8348
+ * Upload a file that can be used across various endpoints. Individual files can be
8349
+ * up to 512 MB, and the size of all files uploaded by one organization can be up
8350
+ * to 100 GB.
8351
+ *
8352
+ * The Assistants API supports files up to 2 million tokens and of specific file
8353
+ * types. See the
8354
+ * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for
8355
+ * details.
8356
+ *
8357
+ * The Fine-tuning API only supports `.jsonl` files. The input also has certain
8358
+ * required formats for fine-tuning
8359
+ * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or
8360
+ * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input)
8361
+ * models.
8362
+ *
8363
+ * The Batch API only supports `.jsonl` files up to 200 MB in size. The input also
8364
+ * has a specific required
8365
+ * [format](https://platform.openai.com/docs/api-reference/batch/request-input).
8366
+ *
8367
+ * Please [contact us](https://help.openai.com/) if you need to increase these
8368
+ * storage limits.
8369
+ */
8370
+ create(body, options) {
8371
+ return this._client.post('/files', multipartFormRequestOptions({ body, ...options }));
8827
8372
  }
8828
- retrieve(responseId, query = {}, options) {
8373
+ /**
8374
+ * Returns information about a specific file.
8375
+ */
8376
+ retrieve(fileId, options) {
8377
+ return this._client.get(`/files/${fileId}`, options);
8378
+ }
8379
+ list(query = {}, options) {
8829
8380
  if (isRequestOptions(query)) {
8830
- return this.retrieve(responseId, {}, query);
8381
+ return this.list({}, query);
8831
8382
  }
8832
- return this._client.get(`/responses/${responseId}`, { query, ...options });
8383
+ return this._client.getAPIList('/files', FileObjectsPage, { query, ...options });
8384
+ }
8385
+ /**
8386
+ * Delete a file.
8387
+ */
8388
+ del(fileId, options) {
8389
+ return this._client.delete(`/files/${fileId}`, options);
8390
+ }
8391
+ /**
8392
+ * Returns the contents of the specified file.
8393
+ */
8394
+ content(fileId, options) {
8395
+ return this._client.get(`/files/${fileId}/content`, { ...options, __binaryResponse: true });
8833
8396
  }
8834
8397
  /**
8835
- * Deletes a model response with the given ID.
8398
+ * Returns the contents of the specified file.
8399
+ *
8400
+ * @deprecated The `.content()` method should be used instead
8836
8401
  */
8837
- del(responseId, options) {
8838
- return this._client.delete(`/responses/${responseId}`, {
8402
+ retrieveContent(fileId, options) {
8403
+ return this._client.get(`/files/${fileId}/content`, {
8839
8404
  ...options,
8840
- headers: { Accept: '*/*', ...options?.headers },
8405
+ headers: { Accept: 'application/json', ...options?.headers },
8841
8406
  });
8842
8407
  }
8843
- parse(body, options) {
8844
- return this._client.responses
8845
- .create(body, options)
8846
- ._thenUnwrap((response) => parseResponse(response, body));
8847
- }
8848
8408
  /**
8849
- * Creates a chat completion stream
8409
+ * Waits for the given file to be processed, default timeout is 30 mins.
8850
8410
  */
8851
- stream(body, options) {
8852
- return ResponseStream.createResponse(this._client, body, options);
8411
+ async waitForProcessing(id, { pollInterval = 5000, maxWait = 30 * 60 * 1000 } = {}) {
8412
+ const TERMINAL_STATES = new Set(['processed', 'error', 'deleted']);
8413
+ const start = Date.now();
8414
+ let file = await this.retrieve(id);
8415
+ while (!file.status || !TERMINAL_STATES.has(file.status)) {
8416
+ await sleep(pollInterval);
8417
+ file = await this.retrieve(id);
8418
+ if (Date.now() - start > maxWait) {
8419
+ throw new APIConnectionTimeoutError({
8420
+ message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`,
8421
+ });
8422
+ }
8423
+ }
8424
+ return file;
8853
8425
  }
8854
8426
  }
8855
- Responses.InputItems = InputItems;
8856
- Responses.ResponseItemListDataPage = ResponseItemListDataPage;
8427
+ class FileObjectsPage extends CursorPage {
8428
+ }
8429
+ Files.FileObjectsPage = FileObjectsPage;
8857
8430
 
8858
8431
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8859
- class Parts extends APIResource {
8860
- /**
8861
- * Adds a
8862
- * [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an
8863
- * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object.
8864
- * A Part represents a chunk of bytes from the file you are trying to upload.
8865
- *
8866
- * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload
8867
- * maximum of 8 GB.
8868
- *
8869
- * It is possible to add multiple Parts in parallel. You can decide the intended
8870
- * order of the Parts when you
8871
- * [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete).
8872
- */
8873
- create(uploadId, body, options) {
8874
- return this._client.post(`/uploads/${uploadId}/parts`, multipartFormRequestOptions({ body, ...options }));
8432
+ class Checkpoints extends APIResource {
8433
+ list(fineTuningJobId, query = {}, options) {
8434
+ if (isRequestOptions(query)) {
8435
+ return this.list(fineTuningJobId, {}, query);
8436
+ }
8437
+ return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/checkpoints`, FineTuningJobCheckpointsPage, { query, ...options });
8875
8438
  }
8876
8439
  }
8440
+ class FineTuningJobCheckpointsPage extends CursorPage {
8441
+ }
8442
+ Checkpoints.FineTuningJobCheckpointsPage = FineTuningJobCheckpointsPage;
8877
8443
 
8878
8444
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8879
- class Uploads extends APIResource {
8445
+ class Jobs extends APIResource {
8880
8446
  constructor() {
8881
8447
  super(...arguments);
8882
- this.parts = new Parts(this._client);
8448
+ this.checkpoints = new Checkpoints(this._client);
8883
8449
  }
8884
8450
  /**
8885
- * Creates an intermediate
8886
- * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object
8887
- * that you can add
8888
- * [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to.
8889
- * Currently, an Upload can accept at most 8 GB in total and expires after an hour
8890
- * after you create it.
8891
- *
8892
- * Once you complete the Upload, we will create a
8893
- * [File](https://platform.openai.com/docs/api-reference/files/object) object that
8894
- * contains all the parts you uploaded. This File is usable in the rest of our
8895
- * platform as a regular File object.
8451
+ * Creates a fine-tuning job which begins the process of creating a new model from
8452
+ * a given dataset.
8896
8453
  *
8897
- * For certain `purpose` values, the correct `mime_type` must be specified. Please
8898
- * refer to documentation for the
8899
- * [supported MIME types for your use case](https://platform.openai.com/docs/assistants/tools/file-search#supported-files).
8454
+ * Response includes details of the enqueued job including job status and the name
8455
+ * of the fine-tuned models once complete.
8900
8456
  *
8901
- * For guidance on the proper filename extensions for each purpose, please follow
8902
- * the documentation on
8903
- * [creating a File](https://platform.openai.com/docs/api-reference/files/create).
8457
+ * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning)
8904
8458
  */
8905
8459
  create(body, options) {
8906
- return this._client.post('/uploads', { body, ...options });
8907
- }
8908
- /**
8909
- * Cancels the Upload. No Parts may be added after an Upload is cancelled.
8910
- */
8911
- cancel(uploadId, options) {
8912
- return this._client.post(`/uploads/${uploadId}/cancel`, options);
8460
+ return this._client.post('/fine_tuning/jobs', { body, ...options });
8913
8461
  }
8914
8462
  /**
8915
- * Completes the
8916
- * [Upload](https://platform.openai.com/docs/api-reference/uploads/object).
8917
- *
8918
- * Within the returned Upload object, there is a nested
8919
- * [File](https://platform.openai.com/docs/api-reference/files/object) object that
8920
- * is ready to use in the rest of the platform.
8921
- *
8922
- * You can specify the order of the Parts by passing in an ordered list of the Part
8923
- * IDs.
8463
+ * Get info about a fine-tuning job.
8924
8464
  *
8925
- * The number of bytes uploaded upon completion must match the number of bytes
8926
- * initially specified when creating the Upload object. No Parts may be added after
8927
- * an Upload is completed.
8465
+ * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning)
8928
8466
  */
8929
- complete(uploadId, body, options) {
8930
- return this._client.post(`/uploads/${uploadId}/complete`, { body, ...options });
8931
- }
8932
- }
8933
- Uploads.Parts = Parts;
8934
-
8935
- /**
8936
- * Like `Promise.allSettled()` but throws an error if any promises are rejected.
8937
- */
8938
- const allSettledWithThrow = async (promises) => {
8939
- const results = await Promise.allSettled(promises);
8940
- const rejected = results.filter((result) => result.status === 'rejected');
8941
- if (rejected.length) {
8942
- for (const result of rejected) {
8943
- console.error(result.reason);
8944
- }
8945
- throw new Error(`${rejected.length} promise(s) failed - see the above errors`);
8467
+ retrieve(fineTuningJobId, options) {
8468
+ return this._client.get(`/fine_tuning/jobs/${fineTuningJobId}`, options);
8946
8469
  }
8947
- // Note: TS was complaining about using `.filter().map()` here for some reason
8948
- const values = [];
8949
- for (const result of results) {
8950
- if (result.status === 'fulfilled') {
8951
- values.push(result.value);
8470
+ list(query = {}, options) {
8471
+ if (isRequestOptions(query)) {
8472
+ return this.list({}, query);
8952
8473
  }
8953
- }
8954
- return values;
8955
- };
8956
-
8957
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8958
- class Files extends APIResource {
8959
- /**
8960
- * Create a vector store file by attaching a
8961
- * [File](https://platform.openai.com/docs/api-reference/files) to a
8962
- * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object).
8963
- */
8964
- create(vectorStoreId, body, options) {
8965
- return this._client.post(`/vector_stores/${vectorStoreId}/files`, {
8966
- body,
8967
- ...options,
8968
- headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8969
- });
8970
- }
8971
- /**
8972
- * Retrieves a vector store file.
8973
- */
8974
- retrieve(vectorStoreId, fileId, options) {
8975
- return this._client.get(`/vector_stores/${vectorStoreId}/files/${fileId}`, {
8976
- ...options,
8977
- headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8978
- });
8474
+ return this._client.getAPIList('/fine_tuning/jobs', FineTuningJobsPage, { query, ...options });
8979
8475
  }
8980
8476
  /**
8981
- * Update attributes on a vector store file.
8477
+ * Immediately cancel a fine-tune job.
8982
8478
  */
8983
- update(vectorStoreId, fileId, body, options) {
8984
- return this._client.post(`/vector_stores/${vectorStoreId}/files/${fileId}`, {
8985
- body,
8986
- ...options,
8987
- headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8988
- });
8479
+ cancel(fineTuningJobId, options) {
8480
+ return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/cancel`, options);
8989
8481
  }
8990
- list(vectorStoreId, query = {}, options) {
8482
+ listEvents(fineTuningJobId, query = {}, options) {
8991
8483
  if (isRequestOptions(query)) {
8992
- return this.list(vectorStoreId, {}, query);
8484
+ return this.listEvents(fineTuningJobId, {}, query);
8993
8485
  }
8994
- return this._client.getAPIList(`/vector_stores/${vectorStoreId}/files`, VectorStoreFilesPage, {
8486
+ return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/events`, FineTuningJobEventsPage, {
8995
8487
  query,
8996
8488
  ...options,
8997
- headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
8998
- });
8999
- }
9000
- /**
9001
- * Delete a vector store file. This will remove the file from the vector store but
9002
- * the file itself will not be deleted. To delete the file, use the
9003
- * [delete file](https://platform.openai.com/docs/api-reference/files/delete)
9004
- * endpoint.
9005
- */
9006
- del(vectorStoreId, fileId, options) {
9007
- return this._client.delete(`/vector_stores/${vectorStoreId}/files/${fileId}`, {
9008
- ...options,
9009
- headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
9010
8489
  });
9011
8490
  }
9012
- /**
9013
- * Attach a file to the given vector store and wait for it to be processed.
9014
- */
9015
- async createAndPoll(vectorStoreId, body, options) {
9016
- const file = await this.create(vectorStoreId, body, options);
9017
- return await this.poll(vectorStoreId, file.id, options);
9018
- }
9019
- /**
9020
- * Wait for the vector store file to finish processing.
9021
- *
9022
- * Note: this will return even if the file failed to process, you need to check
9023
- * file.last_error and file.status to handle these cases
9024
- */
9025
- async poll(vectorStoreId, fileId, options) {
9026
- const headers = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' };
9027
- if (options?.pollIntervalMs) {
9028
- headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString();
9029
- }
9030
- while (true) {
9031
- const fileResponse = await this.retrieve(vectorStoreId, fileId, {
9032
- ...options,
9033
- headers,
9034
- }).withResponse();
9035
- const file = fileResponse.data;
9036
- switch (file.status) {
9037
- case 'in_progress':
9038
- let sleepInterval = 5000;
9039
- if (options?.pollIntervalMs) {
9040
- sleepInterval = options.pollIntervalMs;
9041
- }
9042
- else {
9043
- const headerInterval = fileResponse.response.headers.get('openai-poll-after-ms');
9044
- if (headerInterval) {
9045
- const headerIntervalMs = parseInt(headerInterval);
9046
- if (!isNaN(headerIntervalMs)) {
9047
- sleepInterval = headerIntervalMs;
9048
- }
9049
- }
9050
- }
9051
- await sleep(sleepInterval);
9052
- break;
9053
- case 'failed':
9054
- case 'completed':
9055
- return file;
9056
- }
9057
- }
8491
+ }
8492
+ class FineTuningJobsPage extends CursorPage {
8493
+ }
8494
+ class FineTuningJobEventsPage extends CursorPage {
8495
+ }
8496
+ Jobs.FineTuningJobsPage = FineTuningJobsPage;
8497
+ Jobs.FineTuningJobEventsPage = FineTuningJobEventsPage;
8498
+ Jobs.Checkpoints = Checkpoints;
8499
+ Jobs.FineTuningJobCheckpointsPage = FineTuningJobCheckpointsPage;
8500
+
8501
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8502
+ class FineTuning extends APIResource {
8503
+ constructor() {
8504
+ super(...arguments);
8505
+ this.jobs = new Jobs(this._client);
9058
8506
  }
8507
+ }
8508
+ FineTuning.Jobs = Jobs;
8509
+ FineTuning.FineTuningJobsPage = FineTuningJobsPage;
8510
+ FineTuning.FineTuningJobEventsPage = FineTuningJobEventsPage;
8511
+
8512
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8513
+ class Images extends APIResource {
9059
8514
  /**
9060
- * Upload a file to the `files` API and then attach it to the given vector store.
9061
- *
9062
- * Note the file will be asynchronously processed (you can use the alternative
9063
- * polling helper method to wait for processing to complete).
9064
- */
9065
- async upload(vectorStoreId, file, options) {
9066
- const fileInfo = await this._client.files.create({ file: file, purpose: 'assistants' }, options);
9067
- return this.create(vectorStoreId, { file_id: fileInfo.id }, options);
8515
+ * Creates a variation of a given image.
8516
+ */
8517
+ createVariation(body, options) {
8518
+ return this._client.post('/images/variations', multipartFormRequestOptions({ body, ...options }));
9068
8519
  }
9069
8520
  /**
9070
- * Add a file to a vector store and poll until processing is complete.
8521
+ * Creates an edited or extended image given an original image and a prompt.
9071
8522
  */
9072
- async uploadAndPoll(vectorStoreId, file, options) {
9073
- const fileInfo = await this.upload(vectorStoreId, file, options);
9074
- return await this.poll(vectorStoreId, fileInfo.id, options);
8523
+ edit(body, options) {
8524
+ return this._client.post('/images/edits', multipartFormRequestOptions({ body, ...options }));
9075
8525
  }
9076
8526
  /**
9077
- * Retrieve the parsed contents of a vector store file.
8527
+ * Creates an image given a prompt.
9078
8528
  */
9079
- content(vectorStoreId, fileId, options) {
9080
- return this._client.getAPIList(`/vector_stores/${vectorStoreId}/files/${fileId}/content`, FileContentResponsesPage, { ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers } });
8529
+ generate(body, options) {
8530
+ return this._client.post('/images/generations', { body, ...options });
9081
8531
  }
9082
8532
  }
9083
- class VectorStoreFilesPage extends CursorPage {
9084
- }
9085
- /**
9086
- * Note: no pagination actually occurs yet, this is for forwards-compatibility.
9087
- */
9088
- class FileContentResponsesPage extends Page {
9089
- }
9090
- Files.VectorStoreFilesPage = VectorStoreFilesPage;
9091
- Files.FileContentResponsesPage = FileContentResponsesPage;
9092
8533
 
9093
8534
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
9094
- class FileBatches extends APIResource {
8535
+ class Models extends APIResource {
9095
8536
  /**
9096
- * Create a vector store file batch.
8537
+ * Retrieves a model instance, providing basic information about the model such as
8538
+ * the owner and permissioning.
9097
8539
  */
9098
- create(vectorStoreId, body, options) {
9099
- return this._client.post(`/vector_stores/${vectorStoreId}/file_batches`, {
9100
- body,
9101
- ...options,
9102
- headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
9103
- });
8540
+ retrieve(model, options) {
8541
+ return this._client.get(`/models/${model}`, options);
9104
8542
  }
9105
8543
  /**
9106
- * Retrieves a vector store file batch.
8544
+ * Lists the currently available models, and provides basic information about each
8545
+ * one such as the owner and availability.
9107
8546
  */
9108
- retrieve(vectorStoreId, batchId, options) {
9109
- return this._client.get(`/vector_stores/${vectorStoreId}/file_batches/${batchId}`, {
9110
- ...options,
9111
- headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
9112
- });
8547
+ list(options) {
8548
+ return this._client.getAPIList('/models', ModelsPage, options);
9113
8549
  }
9114
8550
  /**
9115
- * Cancel a vector store file batch. This attempts to cancel the processing of
9116
- * files in this batch as soon as possible.
8551
+ * Delete a fine-tuned model. You must have the Owner role in your organization to
8552
+ * delete a model.
9117
8553
  */
9118
- cancel(vectorStoreId, batchId, options) {
9119
- return this._client.post(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/cancel`, {
9120
- ...options,
9121
- headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
9122
- });
8554
+ del(model, options) {
8555
+ return this._client.delete(`/models/${model}`, options);
9123
8556
  }
8557
+ }
8558
+ /**
8559
+ * Note: no pagination actually occurs yet, this is for forwards-compatibility.
8560
+ */
8561
+ class ModelsPage extends Page {
8562
+ }
8563
+ Models.ModelsPage = ModelsPage;
8564
+
8565
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8566
+ class Moderations extends APIResource {
9124
8567
  /**
9125
- * Create a vector store batch and poll until all files have been processed.
8568
+ * Classifies if text and/or image inputs are potentially harmful. Learn more in
8569
+ * the [moderation guide](https://platform.openai.com/docs/guides/moderation).
9126
8570
  */
9127
- async createAndPoll(vectorStoreId, body, options) {
9128
- const batch = await this.create(vectorStoreId, body);
9129
- return await this.poll(vectorStoreId, batch.id, options);
9130
- }
9131
- listFiles(vectorStoreId, batchId, query = {}, options) {
9132
- if (isRequestOptions(query)) {
9133
- return this.listFiles(vectorStoreId, batchId, {}, query);
9134
- }
9135
- return this._client.getAPIList(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/files`, VectorStoreFilesPage, { query, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers } });
8571
+ create(body, options) {
8572
+ return this._client.post('/moderations', { body, ...options });
9136
8573
  }
8574
+ }
8575
+
8576
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8577
+ class Parts extends APIResource {
9137
8578
  /**
9138
- * Wait for the given file batch to be processed.
8579
+ * Adds a
8580
+ * [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an
8581
+ * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object.
8582
+ * A Part represents a chunk of bytes from the file you are trying to upload.
9139
8583
  *
9140
- * Note: this will return even if one of the files failed to process, you need to
9141
- * check batch.file_counts.failed_count to handle this case.
9142
- */
9143
- async poll(vectorStoreId, batchId, options) {
9144
- const headers = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' };
9145
- if (options?.pollIntervalMs) {
9146
- headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString();
9147
- }
9148
- while (true) {
9149
- const { data: batch, response } = await this.retrieve(vectorStoreId, batchId, {
9150
- ...options,
9151
- headers,
9152
- }).withResponse();
9153
- switch (batch.status) {
9154
- case 'in_progress':
9155
- let sleepInterval = 5000;
9156
- if (options?.pollIntervalMs) {
9157
- sleepInterval = options.pollIntervalMs;
9158
- }
9159
- else {
9160
- const headerInterval = response.headers.get('openai-poll-after-ms');
9161
- if (headerInterval) {
9162
- const headerIntervalMs = parseInt(headerInterval);
9163
- if (!isNaN(headerIntervalMs)) {
9164
- sleepInterval = headerIntervalMs;
9165
- }
9166
- }
9167
- }
9168
- await sleep(sleepInterval);
9169
- break;
9170
- case 'failed':
9171
- case 'cancelled':
9172
- case 'completed':
9173
- return batch;
9174
- }
9175
- }
9176
- }
9177
- /**
9178
- * Uploads the given files concurrently and then creates a vector store file batch.
8584
+ * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload
8585
+ * maximum of 8 GB.
9179
8586
  *
9180
- * The concurrency limit is configurable using the `maxConcurrency` parameter.
8587
+ * It is possible to add multiple Parts in parallel. You can decide the intended
8588
+ * order of the Parts when you
8589
+ * [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete).
9181
8590
  */
9182
- async uploadAndPoll(vectorStoreId, { files, fileIds = [] }, options) {
9183
- if (files == null || files.length == 0) {
9184
- throw new Error(`No \`files\` provided to process. If you've already uploaded files you should use \`.createAndPoll()\` instead`);
9185
- }
9186
- const configuredConcurrency = options?.maxConcurrency ?? 5;
9187
- // We cap the number of workers at the number of files (so we don't start any unnecessary workers)
9188
- const concurrencyLimit = Math.min(configuredConcurrency, files.length);
9189
- const client = this._client;
9190
- const fileIterator = files.values();
9191
- const allFileIds = [...fileIds];
9192
- // This code is based on this design. The libraries don't accommodate our environment limits.
9193
- // https://stackoverflow.com/questions/40639432/what-is-the-best-way-to-limit-concurrency-when-using-es6s-promise-all
9194
- async function processFiles(iterator) {
9195
- for (let item of iterator) {
9196
- const fileObj = await client.files.create({ file: item, purpose: 'assistants' }, options);
9197
- allFileIds.push(fileObj.id);
9198
- }
9199
- }
9200
- // Start workers to process results
9201
- const workers = Array(concurrencyLimit).fill(fileIterator).map(processFiles);
9202
- // Wait for all processing to complete.
9203
- await allSettledWithThrow(workers);
9204
- return await this.createAndPoll(vectorStoreId, {
9205
- file_ids: allFileIds,
9206
- });
8591
+ create(uploadId, body, options) {
8592
+ return this._client.post(`/uploads/${uploadId}/parts`, multipartFormRequestOptions({ body, ...options }));
9207
8593
  }
9208
8594
  }
9209
8595
 
9210
8596
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
9211
- class VectorStores extends APIResource {
8597
+ class Uploads extends APIResource {
9212
8598
  constructor() {
9213
8599
  super(...arguments);
9214
- this.files = new Files(this._client);
9215
- this.fileBatches = new FileBatches(this._client);
8600
+ this.parts = new Parts(this._client);
9216
8601
  }
9217
8602
  /**
9218
- * Create a vector store.
8603
+ * Creates an intermediate
8604
+ * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object
8605
+ * that you can add
8606
+ * [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to.
8607
+ * Currently, an Upload can accept at most 8 GB in total and expires after an hour
8608
+ * after you create it.
8609
+ *
8610
+ * Once you complete the Upload, we will create a
8611
+ * [File](https://platform.openai.com/docs/api-reference/files/object) object that
8612
+ * contains all the parts you uploaded. This File is usable in the rest of our
8613
+ * platform as a regular File object.
8614
+ *
8615
+ * For certain `purpose`s, the correct `mime_type` must be specified. Please refer
8616
+ * to documentation for the supported MIME types for your use case:
8617
+ *
8618
+ * - [Assistants](https://platform.openai.com/docs/assistants/tools/file-search#supported-files)
8619
+ *
8620
+ * For guidance on the proper filename extensions for each purpose, please follow
8621
+ * the documentation on
8622
+ * [creating a File](https://platform.openai.com/docs/api-reference/files/create).
9219
8623
  */
9220
8624
  create(body, options) {
9221
- return this._client.post('/vector_stores', {
9222
- body,
9223
- ...options,
9224
- headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
9225
- });
9226
- }
9227
- /**
9228
- * Retrieves a vector store.
9229
- */
9230
- retrieve(vectorStoreId, options) {
9231
- return this._client.get(`/vector_stores/${vectorStoreId}`, {
9232
- ...options,
9233
- headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
9234
- });
9235
- }
9236
- /**
9237
- * Modifies a vector store.
9238
- */
9239
- update(vectorStoreId, body, options) {
9240
- return this._client.post(`/vector_stores/${vectorStoreId}`, {
9241
- body,
9242
- ...options,
9243
- headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
9244
- });
9245
- }
9246
- list(query = {}, options) {
9247
- if (isRequestOptions(query)) {
9248
- return this.list({}, query);
9249
- }
9250
- return this._client.getAPIList('/vector_stores', VectorStoresPage, {
9251
- query,
9252
- ...options,
9253
- headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
9254
- });
8625
+ return this._client.post('/uploads', { body, ...options });
9255
8626
  }
9256
8627
  /**
9257
- * Delete a vector store.
8628
+ * Cancels the Upload. No Parts may be added after an Upload is cancelled.
9258
8629
  */
9259
- del(vectorStoreId, options) {
9260
- return this._client.delete(`/vector_stores/${vectorStoreId}`, {
9261
- ...options,
9262
- headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
9263
- });
8630
+ cancel(uploadId, options) {
8631
+ return this._client.post(`/uploads/${uploadId}/cancel`, options);
9264
8632
  }
9265
8633
  /**
9266
- * Search a vector store for relevant chunks based on a query and file attributes
9267
- * filter.
8634
+ * Completes the
8635
+ * [Upload](https://platform.openai.com/docs/api-reference/uploads/object).
8636
+ *
8637
+ * Within the returned Upload object, there is a nested
8638
+ * [File](https://platform.openai.com/docs/api-reference/files/object) object that
8639
+ * is ready to use in the rest of the platform.
8640
+ *
8641
+ * You can specify the order of the Parts by passing in an ordered list of the Part
8642
+ * IDs.
8643
+ *
8644
+ * The number of bytes uploaded upon completion must match the number of bytes
8645
+ * initially specified when creating the Upload object. No Parts may be added after
8646
+ * an Upload is completed.
9268
8647
  */
9269
- search(vectorStoreId, body, options) {
9270
- return this._client.getAPIList(`/vector_stores/${vectorStoreId}/search`, VectorStoreSearchResponsesPage, {
9271
- body,
9272
- method: 'post',
9273
- ...options,
9274
- headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },
9275
- });
8648
+ complete(uploadId, body, options) {
8649
+ return this._client.post(`/uploads/${uploadId}/complete`, { body, ...options });
9276
8650
  }
9277
8651
  }
9278
- class VectorStoresPage extends CursorPage {
9279
- }
9280
- /**
9281
- * Note: no pagination actually occurs yet, this is for forwards-compatibility.
9282
- */
9283
- class VectorStoreSearchResponsesPage extends Page {
9284
- }
9285
- VectorStores.VectorStoresPage = VectorStoresPage;
9286
- VectorStores.VectorStoreSearchResponsesPage = VectorStoreSearchResponsesPage;
9287
- VectorStores.Files = Files;
9288
- VectorStores.VectorStoreFilesPage = VectorStoreFilesPage;
9289
- VectorStores.FileContentResponsesPage = FileContentResponsesPage;
9290
- VectorStores.FileBatches = FileBatches;
8652
+ Uploads.Parts = Parts;
9291
8653
 
9292
8654
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
9293
8655
  var _a;
@@ -9334,17 +8696,15 @@ class OpenAI extends APIClient {
9334
8696
  this.completions = new Completions(this);
9335
8697
  this.chat = new Chat$1(this);
9336
8698
  this.embeddings = new Embeddings(this);
9337
- this.files = new Files$1(this);
8699
+ this.files = new Files(this);
9338
8700
  this.images = new Images(this);
9339
8701
  this.audio = new Audio(this);
9340
8702
  this.moderations = new Moderations(this);
9341
8703
  this.models = new Models(this);
9342
8704
  this.fineTuning = new FineTuning(this);
9343
- this.vectorStores = new VectorStores(this);
9344
8705
  this.beta = new Beta(this);
9345
8706
  this.batches = new Batches(this);
9346
8707
  this.uploads = new Uploads(this);
9347
- this.responses = new Responses(this);
9348
8708
  this._options = options;
9349
8709
  this.apiKey = apiKey;
9350
8710
  this.organization = organization;
@@ -9388,9 +8748,8 @@ OpenAI.toFile = toFile;
9388
8748
  OpenAI.fileFromPath = fileFromPath;
9389
8749
  OpenAI.Completions = Completions;
9390
8750
  OpenAI.Chat = Chat$1;
9391
- OpenAI.ChatCompletionsPage = ChatCompletionsPage;
9392
8751
  OpenAI.Embeddings = Embeddings;
9393
- OpenAI.Files = Files$1;
8752
+ OpenAI.Files = Files;
9394
8753
  OpenAI.FileObjectsPage = FileObjectsPage;
9395
8754
  OpenAI.Images = Images;
9396
8755
  OpenAI.Audio = Audio;
@@ -9398,14 +8757,10 @@ OpenAI.Moderations = Moderations;
9398
8757
  OpenAI.Models = Models;
9399
8758
  OpenAI.ModelsPage = ModelsPage;
9400
8759
  OpenAI.FineTuning = FineTuning;
9401
- OpenAI.VectorStores = VectorStores;
9402
- OpenAI.VectorStoresPage = VectorStoresPage;
9403
- OpenAI.VectorStoreSearchResponsesPage = VectorStoreSearchResponsesPage;
9404
8760
  OpenAI.Beta = Beta;
9405
8761
  OpenAI.Batches = Batches;
9406
8762
  OpenAI.BatchesPage = BatchesPage;
9407
8763
  OpenAI.Uploads = Uploads;
9408
- OpenAI.Responses = Responses;
9409
8764
 
9410
8765
  class OpenaiProvider {
9411
8766
  constructor(param, defaultModel, options) {
@@ -9986,7 +9341,7 @@ ${JSON.stringify(nodeOutputs)}
9986
9341
  `,
9987
9342
  },
9988
9343
  ];
9989
- logger.debug(messages);
9344
+ logger.debug(JSON.stringify(messages));
9990
9345
  const params = {
9991
9346
  temperature: 0.7,
9992
9347
  maxTokens: 8192,
@@ -10319,13 +9674,13 @@ class ActionImpl {
10319
9674
  }
10320
9675
  },
10321
9676
  onToolUse: async (toolCall) => {
10322
- logger.info("toolCall start", {
9677
+ logger.info("toolCall start", JSON.stringify({
10323
9678
  assistant: assistantTextMessage,
10324
9679
  toolCall: {
10325
9680
  name: toolCall.name,
10326
9681
  input: toolCall.input,
10327
9682
  },
10328
- });
9683
+ }));
10329
9684
  hasToolUse = true;
10330
9685
  const tool = toolMap.get(toolCall.name);
10331
9686
  if (!tool) {
@@ -10450,12 +9805,12 @@ class ActionImpl {
10450
9805
  return s.slice(0, maxLength) + "...(truncated)";
10451
9806
  }
10452
9807
  };
10453
- logger.info("toolCall done", {
9808
+ logger.info("toolCall done", JSON.stringify({
10454
9809
  toolCall: {
10455
9810
  name: tool.name,
10456
9811
  result: truncate(result),
10457
9812
  },
10458
- });
9813
+ }));
10459
9814
  // Store tool results except for the return_output tool
10460
9815
  if (tool.name !== 'return_output') {
10461
9816
  this.toolResults.set(toolCall.id, resultContentText);
@@ -10589,6 +9944,7 @@ class ActionImpl {
10589
9944
  if (context.ekoConfig.patchServerUrl) {
10590
9945
  patchs = await this.getPatchs(this.name, context.ekoConfig.patchServerUrl);
10591
9946
  }
9947
+ logger.debug("patchs:", patchs);
10592
9948
  // Prepare initial messages
10593
9949
  const messages = [
10594
9950
  { role: 'system', content: this.formatSystemPrompt() },
@@ -10831,7 +10187,7 @@ Navigation Bar or Menu Changes: After logging in, the navigation bar will includ
10831
10187
  },
10832
10188
  userSidePrompt: {
10833
10189
  "type": "string",
10834
- "description": 'The user-side prompt, showing why calling this tool. Should start with "I\'m calling the ...(tool) to ...(target)". Rememeber to keep the same language of the ultimate task.',
10190
+ "description": 'The user-side prompt, showing what you are doing. e.g. "Openning x.com." or "Writing the post."',
10835
10191
  },
10836
10192
  toolCall: definition.input_schema,
10837
10193
  },
@@ -11135,13 +10491,14 @@ class Eko {
11135
10491
  constructor(llmConfig, ekoConfig) {
11136
10492
  this.toolRegistry = new ToolRegistry();
11137
10493
  this.workflowGeneratorMap = new Map();
11138
- this.prompt = "";
10494
+ this.prompt = '';
11139
10495
  this.tabs = [];
11140
10496
  this.workflow = undefined;
11141
10497
  this.llmProvider = LLMProviderFactory.buildLLMProvider(llmConfig);
11142
10498
  this.ekoConfig = this.buildEkoConfig(ekoConfig);
11143
10499
  this.registerTools();
11144
- logger.info("using Eko@" + "0fbae27efeeb93942eb22d3594375674b23788cb");
10500
+ logger.info("using Eko@" + "0b8135fc46d59eb59eb56c57564e2db06526249b");
10501
+ logger.debug("caller's ekoConfig:", ekoConfig);
11145
10502
  }
11146
10503
  static getLogger() {
11147
10504
  return logger;
@@ -11169,10 +10526,10 @@ class Eko {
11169
10526
  const hooks = callback.hooks;
11170
10527
  // these tools could not work without corresponding hook
11171
10528
  const tool2isHookExists = {
11172
- "human_input_text": Boolean(hooks.onHumanInputText),
11173
- "human_input_single_choice": Boolean(hooks.onHumanInputSingleChoice),
11174
- "human_input_multiple_choice": Boolean(hooks.onHumanInputMultipleChoice),
11175
- "human_operate": Boolean(hooks.onHumanOperate),
10529
+ 'human_input_text': Boolean(hooks.onHumanInputText),
10530
+ 'human_input_single_choice': Boolean(hooks.onHumanInputSingleChoice),
10531
+ 'human_input_multiple_choice': Boolean(hooks.onHumanInputMultipleChoice),
10532
+ 'human_operate': Boolean(hooks.onHumanOperate),
11176
10533
  };
11177
10534
  tools = tools.filter(tool => {
11178
10535
  if (tool.name in tool2isHookExists) {
@@ -11190,7 +10547,7 @@ class Eko {
11190
10547
  tools.forEach(tool => this.toolRegistry.registerTool(tool));
11191
10548
  }
11192
10549
  async generate(prompt, tabs = [], param) {
11193
- logger.info("workflow generating...");
10550
+ logger.info("workflow generating...", prompt);
11194
10551
  this.prompt = prompt;
11195
10552
  this.tabs = tabs;
11196
10553
  let toolRegistry = this.toolRegistry;
@@ -11216,37 +10573,38 @@ class Eko {
11216
10573
  async execute(workflow) {
11217
10574
  logger.info("workflow executing...");
11218
10575
  let prompt = this.prompt;
11219
- let description = "";
10576
+ let description = '';
11220
10577
  workflow.nodes.forEach(node => {
11221
- description += node.name + "\n";
10578
+ description += node.name + '\n';
11222
10579
  });
11223
10580
  const json = {
11224
- "id": "workflow_id",
11225
- "name": prompt,
11226
- "description": prompt,
11227
- "nodes": [
10581
+ 'id': 'workflow_id',
10582
+ 'name': prompt,
10583
+ 'description': prompt,
10584
+ 'nodes': [
11228
10585
  {
11229
- "id": "sub_task_id",
11230
- "type": "action",
11231
- "action": {
11232
- "type": "prompt",
11233
- "name": prompt,
11234
- "description": description,
11235
- "tools": [
11236
- "browser_use",
11237
- "document_agent",
11238
- "export_file",
11239
- "extract_content",
11240
- "open_url",
11241
- "tab_management",
11242
- "web_search",
11243
- "human_input_text",
11244
- "human_input_single_choice",
11245
- "human_input_multiple_choice",
11246
- "human_operate",
10586
+ 'id': 'sub_task_id',
10587
+ 'type': 'action',
10588
+ 'action': {
10589
+ 'type': 'prompt',
10590
+ 'name': prompt,
10591
+ 'description': description,
10592
+ 'tools': [
10593
+ 'browser_use',
10594
+ 'document_agent',
10595
+ 'export_file',
10596
+ 'extract_content',
10597
+ 'open_url',
10598
+ 'tab_management',
10599
+ 'switch_tab',
10600
+ 'web_search',
10601
+ 'human_input_text',
10602
+ 'human_input_single_choice',
10603
+ 'human_input_multiple_choice',
10604
+ 'human_operate',
11247
10605
  ],
11248
10606
  },
11249
- "dependencies": []
10607
+ 'dependencies': [],
11250
10608
  },
11251
10609
  ],
11252
10610
  };
@@ -11284,7 +10642,7 @@ class Eko {
11284
10642
  return await this.workflow.cancel();
11285
10643
  }
11286
10644
  else {
11287
- throw Error("`Eko` instance do not have a `workflow` member");
10645
+ throw Error('`Eko` instance do not have a `workflow` member');
11288
10646
  }
11289
10647
  }
11290
10648
  async modify(workflow, prompt) {