ai 3.0.8 → 3.1.0-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +10 -4
  2. package/core/dist/index.d.mts +480 -0
  3. package/core/dist/index.d.ts +480 -0
  4. package/core/dist/index.js +1528 -0
  5. package/core/dist/index.js.map +1 -0
  6. package/core/dist/index.mjs +1479 -0
  7. package/core/dist/index.mjs.map +1 -0
  8. package/package.json +20 -3
  9. package/provider/dist/chunk-3DTRVHCT.mjs +5046 -0
  10. package/provider/dist/chunk-3DTRVHCT.mjs.map +1 -0
  11. package/provider/dist/chunk-4OUDS3CP.mjs +30 -0
  12. package/provider/dist/chunk-4OUDS3CP.mjs.map +1 -0
  13. package/provider/dist/chunk-5IYCPJBV.mjs +56 -0
  14. package/provider/dist/chunk-5IYCPJBV.mjs.map +1 -0
  15. package/provider/dist/chunk-VB2TCVQ4.mjs +6746 -0
  16. package/provider/dist/chunk-VB2TCVQ4.mjs.map +1 -0
  17. package/provider/dist/chunk-VYIXVZ6L.mjs +317 -0
  18. package/provider/dist/chunk-VYIXVZ6L.mjs.map +1 -0
  19. package/provider/dist/chunk-WTOUHN6A.mjs +2251 -0
  20. package/provider/dist/chunk-WTOUHN6A.mjs.map +1 -0
  21. package/provider/dist/client-22WAAXR7.mjs +10 -0
  22. package/provider/dist/client-22WAAXR7.mjs.map +1 -0
  23. package/provider/dist/fileFromPath-23RINPB2.mjs +115 -0
  24. package/provider/dist/fileFromPath-23RINPB2.mjs.map +1 -0
  25. package/provider/dist/index.d.mts +387 -0
  26. package/provider/dist/index.d.ts +387 -0
  27. package/provider/dist/index.js +26487 -0
  28. package/provider/dist/index.js.map +1 -0
  29. package/provider/dist/index.mjs +8087 -0
  30. package/provider/dist/index.mjs.map +1 -0
  31. package/provider/dist/lib-BZMMM4HX.mjs +20 -0
  32. package/provider/dist/lib-BZMMM4HX.mjs.map +1 -0
  33. package/provider/dist/openai-3YL4AWLI.mjs +3451 -0
  34. package/provider/dist/openai-3YL4AWLI.mjs.map +1 -0
  35. package/rsc/dist/index.d.ts +4 -3
  36. package/rsc/dist/rsc-server.d.mts +3 -2
  37. package/rsc/dist/rsc-server.mjs.map +1 -1
@@ -0,0 +1,3451 @@
1
+ import {
2
+ require_abort_controller,
3
+ require_agentkeepalive,
4
+ require_ponyfill_es2018
5
+ } from "./chunk-3DTRVHCT.mjs";
6
+ import {
7
+ Headers,
8
+ Request,
9
+ Response,
10
+ init_lib,
11
+ lib_default
12
+ } from "./chunk-VB2TCVQ4.mjs";
13
+ import {
14
+ Blob,
15
+ File,
16
+ isFile,
17
+ isFunction
18
+ } from "./chunk-WTOUHN6A.mjs";
19
+ import {
20
+ __export,
21
+ __toESM
22
+ } from "./chunk-5IYCPJBV.mjs";
23
+
24
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/version.mjs
25
+ var VERSION = "4.28.4";
26
+
27
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/_shims/registry.mjs
28
+ var auto = false;
29
+ var kind = void 0;
30
+ var fetch = void 0;
31
+ var Request2 = void 0;
32
+ var Response2 = void 0;
33
+ var Headers2 = void 0;
34
+ var FormData = void 0;
35
+ var Blob2 = void 0;
36
+ var File2 = void 0;
37
+ var ReadableStream = void 0;
38
+ var getMultipartRequestOptions = void 0;
39
+ var getDefaultAgent = void 0;
40
+ var fileFromPath = void 0;
41
+ var isFsReadStream = void 0;
42
+ function setShims(shims, options = { auto: false }) {
43
+ if (auto) {
44
+ throw new Error(`you must \`import 'openai/shims/${shims.kind}'\` before importing anything else from openai`);
45
+ }
46
+ if (kind) {
47
+ throw new Error(`can't \`import 'openai/shims/${shims.kind}'\` after \`import 'openai/shims/${kind}'\``);
48
+ }
49
+ auto = options.auto;
50
+ kind = shims.kind;
51
+ fetch = shims.fetch;
52
+ Request2 = shims.Request;
53
+ Response2 = shims.Response;
54
+ Headers2 = shims.Headers;
55
+ FormData = shims.FormData;
56
+ Blob2 = shims.Blob;
57
+ File2 = shims.File;
58
+ ReadableStream = shims.ReadableStream;
59
+ getMultipartRequestOptions = shims.getMultipartRequestOptions;
60
+ getDefaultAgent = shims.getDefaultAgent;
61
+ fileFromPath = shims.fileFromPath;
62
+ isFsReadStream = shims.isFsReadStream;
63
+ }
64
+
65
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/_shims/node-runtime.mjs
66
+ init_lib();
67
+
68
+ // ../../node_modules/.pnpm/formdata-node@4.4.1/node_modules/formdata-node/lib/esm/FormData.js
69
+ import { inspect } from "util";
70
+
71
+ // ../../node_modules/.pnpm/formdata-node@4.4.1/node_modules/formdata-node/lib/esm/isBlob.js
72
+ var isBlob = (value) => value instanceof Blob;
73
+
74
+ // ../../node_modules/.pnpm/formdata-node@4.4.1/node_modules/formdata-node/lib/esm/deprecateConstructorEntries.js
75
+ import { deprecate } from "util";
76
+ var deprecateConstructorEntries = deprecate(() => {
77
+ }, 'Constructor "entries" argument is not spec-compliant and will be removed in next major release.');
78
+
79
+ // ../../node_modules/.pnpm/formdata-node@4.4.1/node_modules/formdata-node/lib/esm/FormData.js
80
+ var __classPrivateFieldGet = function(receiver, state, kind2, f) {
81
+ if (kind2 === "a" && !f)
82
+ throw new TypeError("Private accessor was defined without a getter");
83
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
84
+ throw new TypeError("Cannot read private member from an object whose class did not declare it");
85
+ return kind2 === "m" ? f : kind2 === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
86
+ };
87
+ var _FormData_instances;
88
+ var _FormData_entries;
89
+ var _FormData_setEntry;
90
+ var FormData2 = class {
91
+ constructor(entries) {
92
+ _FormData_instances.add(this);
93
+ _FormData_entries.set(this, /* @__PURE__ */ new Map());
94
+ if (entries) {
95
+ deprecateConstructorEntries();
96
+ entries.forEach(({ name, value, fileName }) => this.append(name, value, fileName));
97
+ }
98
+ }
99
+ static [(_FormData_entries = /* @__PURE__ */ new WeakMap(), _FormData_instances = /* @__PURE__ */ new WeakSet(), Symbol.hasInstance)](value) {
100
+ return Boolean(value && isFunction(value.constructor) && value[Symbol.toStringTag] === "FormData" && isFunction(value.append) && isFunction(value.set) && isFunction(value.get) && isFunction(value.getAll) && isFunction(value.has) && isFunction(value.delete) && isFunction(value.entries) && isFunction(value.values) && isFunction(value.keys) && isFunction(value[Symbol.iterator]) && isFunction(value.forEach));
101
+ }
102
+ append(name, value, fileName) {
103
+ __classPrivateFieldGet(this, _FormData_instances, "m", _FormData_setEntry).call(this, {
104
+ name,
105
+ fileName,
106
+ append: true,
107
+ rawValue: value,
108
+ argsLength: arguments.length
109
+ });
110
+ }
111
+ set(name, value, fileName) {
112
+ __classPrivateFieldGet(this, _FormData_instances, "m", _FormData_setEntry).call(this, {
113
+ name,
114
+ fileName,
115
+ append: false,
116
+ rawValue: value,
117
+ argsLength: arguments.length
118
+ });
119
+ }
120
+ get(name) {
121
+ const field = __classPrivateFieldGet(this, _FormData_entries, "f").get(String(name));
122
+ if (!field) {
123
+ return null;
124
+ }
125
+ return field[0];
126
+ }
127
+ getAll(name) {
128
+ const field = __classPrivateFieldGet(this, _FormData_entries, "f").get(String(name));
129
+ if (!field) {
130
+ return [];
131
+ }
132
+ return field.slice();
133
+ }
134
+ has(name) {
135
+ return __classPrivateFieldGet(this, _FormData_entries, "f").has(String(name));
136
+ }
137
+ delete(name) {
138
+ __classPrivateFieldGet(this, _FormData_entries, "f").delete(String(name));
139
+ }
140
+ *keys() {
141
+ for (const key of __classPrivateFieldGet(this, _FormData_entries, "f").keys()) {
142
+ yield key;
143
+ }
144
+ }
145
+ *entries() {
146
+ for (const name of this.keys()) {
147
+ const values = this.getAll(name);
148
+ for (const value of values) {
149
+ yield [name, value];
150
+ }
151
+ }
152
+ }
153
+ *values() {
154
+ for (const [, value] of this) {
155
+ yield value;
156
+ }
157
+ }
158
+ [(_FormData_setEntry = function _FormData_setEntry2({ name, rawValue, append, fileName, argsLength }) {
159
+ const methodName = append ? "append" : "set";
160
+ if (argsLength < 2) {
161
+ throw new TypeError(`Failed to execute '${methodName}' on 'FormData': 2 arguments required, but only ${argsLength} present.`);
162
+ }
163
+ name = String(name);
164
+ let value;
165
+ if (isFile(rawValue)) {
166
+ value = fileName === void 0 ? rawValue : new File([rawValue], fileName, {
167
+ type: rawValue.type,
168
+ lastModified: rawValue.lastModified
169
+ });
170
+ } else if (isBlob(rawValue)) {
171
+ value = new File([rawValue], fileName === void 0 ? "blob" : fileName, {
172
+ type: rawValue.type
173
+ });
174
+ } else if (fileName) {
175
+ throw new TypeError(`Failed to execute '${methodName}' on 'FormData': parameter 2 is not of type 'Blob'.`);
176
+ } else {
177
+ value = String(rawValue);
178
+ }
179
+ const values = __classPrivateFieldGet(this, _FormData_entries, "f").get(name);
180
+ if (!values) {
181
+ return void __classPrivateFieldGet(this, _FormData_entries, "f").set(name, [value]);
182
+ }
183
+ if (!append) {
184
+ return void __classPrivateFieldGet(this, _FormData_entries, "f").set(name, [value]);
185
+ }
186
+ values.push(value);
187
+ }, Symbol.iterator)]() {
188
+ return this.entries();
189
+ }
190
+ forEach(callback, thisArg) {
191
+ for (const [name, value] of this) {
192
+ callback.call(thisArg, value, name, this);
193
+ }
194
+ }
195
+ get [Symbol.toStringTag]() {
196
+ return "FormData";
197
+ }
198
+ [inspect.custom]() {
199
+ return this[Symbol.toStringTag];
200
+ }
201
+ };
202
+
203
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/_shims/node-runtime.mjs
204
+ var import_agentkeepalive = __toESM(require_agentkeepalive(), 1);
205
+ var import_abort_controller = __toESM(require_abort_controller(), 1);
206
+ import { ReadStream as FsReadStream } from "fs";
207
+
208
+ // ../../node_modules/.pnpm/form-data-encoder@1.7.2/node_modules/form-data-encoder/lib/esm/util/createBoundary.js
209
+ var alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
210
+ function createBoundary() {
211
+ let size = 16;
212
+ let res = "";
213
+ while (size--) {
214
+ res += alphabet[Math.random() * alphabet.length << 0];
215
+ }
216
+ return res;
217
+ }
218
+ var createBoundary_default = createBoundary;
219
+
220
+ // ../../node_modules/.pnpm/form-data-encoder@1.7.2/node_modules/form-data-encoder/lib/esm/util/isPlainObject.js
221
+ var getType = (value) => Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
222
+ function isPlainObject(value) {
223
+ if (getType(value) !== "object") {
224
+ return false;
225
+ }
226
+ const pp = Object.getPrototypeOf(value);
227
+ if (pp === null || pp === void 0) {
228
+ return true;
229
+ }
230
+ const Ctor = pp.constructor && pp.constructor.toString();
231
+ return Ctor === Object.toString();
232
+ }
233
+ var isPlainObject_default = isPlainObject;
234
+
235
+ // ../../node_modules/.pnpm/form-data-encoder@1.7.2/node_modules/form-data-encoder/lib/esm/util/normalizeValue.js
236
+ var normalizeValue = (value) => String(value).replace(/\r|\n/g, (match, i, str2) => {
237
+ if (match === "\r" && str2[i + 1] !== "\n" || match === "\n" && str2[i - 1] !== "\r") {
238
+ return "\r\n";
239
+ }
240
+ return match;
241
+ });
242
+ var normalizeValue_default = normalizeValue;
243
+
244
+ // ../../node_modules/.pnpm/form-data-encoder@1.7.2/node_modules/form-data-encoder/lib/esm/util/escapeName.js
245
+ var escapeName = (name) => String(name).replace(/\r/g, "%0D").replace(/\n/g, "%0A").replace(/"/g, "%22");
246
+ var escapeName_default = escapeName;
247
+
248
+ // ../../node_modules/.pnpm/form-data-encoder@1.7.2/node_modules/form-data-encoder/lib/esm/util/isFunction.js
249
+ var isFunction2 = (value) => typeof value === "function";
250
+ var isFunction_default = isFunction2;
251
+
252
+ // ../../node_modules/.pnpm/form-data-encoder@1.7.2/node_modules/form-data-encoder/lib/esm/util/isFileLike.js
253
+ var isFileLike = (value) => Boolean(value && typeof value === "object" && isFunction_default(value.constructor) && value[Symbol.toStringTag] === "File" && isFunction_default(value.stream) && value.name != null && value.size != null && value.lastModified != null);
254
+
255
+ // ../../node_modules/.pnpm/form-data-encoder@1.7.2/node_modules/form-data-encoder/lib/esm/util/isFormData.js
256
+ var isFormData = (value) => Boolean(value && isFunction_default(value.constructor) && value[Symbol.toStringTag] === "FormData" && isFunction_default(value.append) && isFunction_default(value.getAll) && isFunction_default(value.entries) && isFunction_default(value[Symbol.iterator]));
257
+
258
+ // ../../node_modules/.pnpm/form-data-encoder@1.7.2/node_modules/form-data-encoder/lib/esm/FormDataEncoder.js
259
+ var __classPrivateFieldSet = function(receiver, state, value, kind2, f) {
260
+ if (kind2 === "m")
261
+ throw new TypeError("Private method is not writable");
262
+ if (kind2 === "a" && !f)
263
+ throw new TypeError("Private accessor was defined without a setter");
264
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
265
+ throw new TypeError("Cannot write private member to an object whose class did not declare it");
266
+ return kind2 === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
267
+ };
268
+ var __classPrivateFieldGet2 = function(receiver, state, kind2, f) {
269
+ if (kind2 === "a" && !f)
270
+ throw new TypeError("Private accessor was defined without a getter");
271
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
272
+ throw new TypeError("Cannot read private member from an object whose class did not declare it");
273
+ return kind2 === "m" ? f : kind2 === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
274
+ };
275
+ var _FormDataEncoder_instances;
276
+ var _FormDataEncoder_CRLF;
277
+ var _FormDataEncoder_CRLF_BYTES;
278
+ var _FormDataEncoder_CRLF_BYTES_LENGTH;
279
+ var _FormDataEncoder_DASHES;
280
+ var _FormDataEncoder_encoder;
281
+ var _FormDataEncoder_footer;
282
+ var _FormDataEncoder_form;
283
+ var _FormDataEncoder_options;
284
+ var _FormDataEncoder_getFieldHeader;
285
+ var defaultOptions = {
286
+ enableAdditionalHeaders: false
287
+ };
288
+ var FormDataEncoder = class {
289
+ constructor(form, boundaryOrOptions, options) {
290
+ _FormDataEncoder_instances.add(this);
291
+ _FormDataEncoder_CRLF.set(this, "\r\n");
292
+ _FormDataEncoder_CRLF_BYTES.set(this, void 0);
293
+ _FormDataEncoder_CRLF_BYTES_LENGTH.set(this, void 0);
294
+ _FormDataEncoder_DASHES.set(this, "-".repeat(2));
295
+ _FormDataEncoder_encoder.set(this, new TextEncoder());
296
+ _FormDataEncoder_footer.set(this, void 0);
297
+ _FormDataEncoder_form.set(this, void 0);
298
+ _FormDataEncoder_options.set(this, void 0);
299
+ if (!isFormData(form)) {
300
+ throw new TypeError("Expected first argument to be a FormData instance.");
301
+ }
302
+ let boundary;
303
+ if (isPlainObject_default(boundaryOrOptions)) {
304
+ options = boundaryOrOptions;
305
+ } else {
306
+ boundary = boundaryOrOptions;
307
+ }
308
+ if (!boundary) {
309
+ boundary = createBoundary_default();
310
+ }
311
+ if (typeof boundary !== "string") {
312
+ throw new TypeError("Expected boundary argument to be a string.");
313
+ }
314
+ if (options && !isPlainObject_default(options)) {
315
+ throw new TypeError("Expected options argument to be an object.");
316
+ }
317
+ __classPrivateFieldSet(this, _FormDataEncoder_form, form, "f");
318
+ __classPrivateFieldSet(this, _FormDataEncoder_options, { ...defaultOptions, ...options }, "f");
319
+ __classPrivateFieldSet(this, _FormDataEncoder_CRLF_BYTES, __classPrivateFieldGet2(this, _FormDataEncoder_encoder, "f").encode(__classPrivateFieldGet2(this, _FormDataEncoder_CRLF, "f")), "f");
320
+ __classPrivateFieldSet(this, _FormDataEncoder_CRLF_BYTES_LENGTH, __classPrivateFieldGet2(this, _FormDataEncoder_CRLF_BYTES, "f").byteLength, "f");
321
+ this.boundary = `form-data-boundary-${boundary}`;
322
+ this.contentType = `multipart/form-data; boundary=${this.boundary}`;
323
+ __classPrivateFieldSet(this, _FormDataEncoder_footer, __classPrivateFieldGet2(this, _FormDataEncoder_encoder, "f").encode(`${__classPrivateFieldGet2(this, _FormDataEncoder_DASHES, "f")}${this.boundary}${__classPrivateFieldGet2(this, _FormDataEncoder_DASHES, "f")}${__classPrivateFieldGet2(this, _FormDataEncoder_CRLF, "f").repeat(2)}`), "f");
324
+ this.contentLength = String(this.getContentLength());
325
+ this.headers = Object.freeze({
326
+ "Content-Type": this.contentType,
327
+ "Content-Length": this.contentLength
328
+ });
329
+ Object.defineProperties(this, {
330
+ boundary: { writable: false, configurable: false },
331
+ contentType: { writable: false, configurable: false },
332
+ contentLength: { writable: false, configurable: false },
333
+ headers: { writable: false, configurable: false }
334
+ });
335
+ }
336
+ getContentLength() {
337
+ let length = 0;
338
+ for (const [name, raw] of __classPrivateFieldGet2(this, _FormDataEncoder_form, "f")) {
339
+ const value = isFileLike(raw) ? raw : __classPrivateFieldGet2(this, _FormDataEncoder_encoder, "f").encode(normalizeValue_default(raw));
340
+ length += __classPrivateFieldGet2(this, _FormDataEncoder_instances, "m", _FormDataEncoder_getFieldHeader).call(this, name, value).byteLength;
341
+ length += isFileLike(value) ? value.size : value.byteLength;
342
+ length += __classPrivateFieldGet2(this, _FormDataEncoder_CRLF_BYTES_LENGTH, "f");
343
+ }
344
+ return length + __classPrivateFieldGet2(this, _FormDataEncoder_footer, "f").byteLength;
345
+ }
346
+ *values() {
347
+ for (const [name, raw] of __classPrivateFieldGet2(this, _FormDataEncoder_form, "f").entries()) {
348
+ const value = isFileLike(raw) ? raw : __classPrivateFieldGet2(this, _FormDataEncoder_encoder, "f").encode(normalizeValue_default(raw));
349
+ yield __classPrivateFieldGet2(this, _FormDataEncoder_instances, "m", _FormDataEncoder_getFieldHeader).call(this, name, value);
350
+ yield value;
351
+ yield __classPrivateFieldGet2(this, _FormDataEncoder_CRLF_BYTES, "f");
352
+ }
353
+ yield __classPrivateFieldGet2(this, _FormDataEncoder_footer, "f");
354
+ }
355
+ async *encode() {
356
+ for (const part of this.values()) {
357
+ if (isFileLike(part)) {
358
+ yield* part.stream();
359
+ } else {
360
+ yield part;
361
+ }
362
+ }
363
+ }
364
+ [(_FormDataEncoder_CRLF = /* @__PURE__ */ new WeakMap(), _FormDataEncoder_CRLF_BYTES = /* @__PURE__ */ new WeakMap(), _FormDataEncoder_CRLF_BYTES_LENGTH = /* @__PURE__ */ new WeakMap(), _FormDataEncoder_DASHES = /* @__PURE__ */ new WeakMap(), _FormDataEncoder_encoder = /* @__PURE__ */ new WeakMap(), _FormDataEncoder_footer = /* @__PURE__ */ new WeakMap(), _FormDataEncoder_form = /* @__PURE__ */ new WeakMap(), _FormDataEncoder_options = /* @__PURE__ */ new WeakMap(), _FormDataEncoder_instances = /* @__PURE__ */ new WeakSet(), _FormDataEncoder_getFieldHeader = function _FormDataEncoder_getFieldHeader2(name, value) {
365
+ let header = "";
366
+ header += `${__classPrivateFieldGet2(this, _FormDataEncoder_DASHES, "f")}${this.boundary}${__classPrivateFieldGet2(this, _FormDataEncoder_CRLF, "f")}`;
367
+ header += `Content-Disposition: form-data; name="${escapeName_default(name)}"`;
368
+ if (isFileLike(value)) {
369
+ header += `; filename="${escapeName_default(value.name)}"${__classPrivateFieldGet2(this, _FormDataEncoder_CRLF, "f")}`;
370
+ header += `Content-Type: ${value.type || "application/octet-stream"}`;
371
+ }
372
+ if (__classPrivateFieldGet2(this, _FormDataEncoder_options, "f").enableAdditionalHeaders === true) {
373
+ header += `${__classPrivateFieldGet2(this, _FormDataEncoder_CRLF, "f")}Content-Length: ${isFileLike(value) ? value.size : value.byteLength}`;
374
+ }
375
+ return __classPrivateFieldGet2(this, _FormDataEncoder_encoder, "f").encode(`${header}${__classPrivateFieldGet2(this, _FormDataEncoder_CRLF, "f").repeat(2)}`);
376
+ }, Symbol.iterator)]() {
377
+ return this.values();
378
+ }
379
+ [Symbol.asyncIterator]() {
380
+ return this.encode();
381
+ }
382
+ };
383
+
384
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/_shims/node-runtime.mjs
385
+ import { Readable } from "stream";
386
+
387
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/_shims/MultipartBody.mjs
388
+ var MultipartBody = class {
389
+ constructor(body) {
390
+ this.body = body;
391
+ }
392
+ get [Symbol.toStringTag]() {
393
+ return "MultipartBody";
394
+ }
395
+ };
396
+
397
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/_shims/node-runtime.mjs
398
+ var import_ponyfill_es2018 = __toESM(require_ponyfill_es2018(), 1);
399
+ var fileFromPathWarned = false;
400
+ async function fileFromPath2(path, ...args) {
401
+ const { fileFromPath: _fileFromPath } = await import("./fileFromPath-23RINPB2.mjs");
402
+ if (!fileFromPathWarned) {
403
+ console.warn(`fileFromPath is deprecated; use fs.createReadStream(${JSON.stringify(path)}) instead`);
404
+ fileFromPathWarned = true;
405
+ }
406
+ return await _fileFromPath(path, ...args);
407
+ }
408
+ var defaultHttpAgent = new import_agentkeepalive.default({ keepAlive: true, timeout: 5 * 60 * 1e3 });
409
+ var defaultHttpsAgent = new import_agentkeepalive.default.HttpsAgent({ keepAlive: true, timeout: 5 * 60 * 1e3 });
410
+ async function getMultipartRequestOptions2(form, opts) {
411
+ const encoder = new FormDataEncoder(form);
412
+ const readable = Readable.from(encoder);
413
+ const body = new MultipartBody(readable);
414
+ const headers = {
415
+ ...opts.headers,
416
+ ...encoder.headers,
417
+ "Content-Length": encoder.contentLength
418
+ };
419
+ return { ...opts, body, headers };
420
+ }
421
+ function getRuntime() {
422
+ if (typeof AbortController === "undefined") {
423
+ globalThis.AbortController = import_abort_controller.AbortController;
424
+ }
425
+ return {
426
+ kind: "node",
427
+ fetch: lib_default,
428
+ Request,
429
+ Response,
430
+ Headers,
431
+ FormData: FormData2,
432
+ Blob,
433
+ File,
434
+ ReadableStream: import_ponyfill_es2018.ReadableStream,
435
+ getMultipartRequestOptions: getMultipartRequestOptions2,
436
+ getDefaultAgent: (url) => url.startsWith("https") ? defaultHttpsAgent : defaultHttpAgent,
437
+ fileFromPath: fileFromPath2,
438
+ isFsReadStream: (value) => value instanceof FsReadStream
439
+ };
440
+ }
441
+
442
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/_shims/index.mjs
443
+ if (!kind)
444
+ setShims(getRuntime(), { auto: true });
445
+
446
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/error.mjs
447
+ var error_exports = {};
448
+ __export(error_exports, {
449
+ APIConnectionError: () => APIConnectionError,
450
+ APIConnectionTimeoutError: () => APIConnectionTimeoutError,
451
+ APIError: () => APIError,
452
+ APIUserAbortError: () => APIUserAbortError,
453
+ AuthenticationError: () => AuthenticationError,
454
+ BadRequestError: () => BadRequestError,
455
+ ConflictError: () => ConflictError,
456
+ InternalServerError: () => InternalServerError,
457
+ NotFoundError: () => NotFoundError,
458
+ OpenAIError: () => OpenAIError,
459
+ PermissionDeniedError: () => PermissionDeniedError,
460
+ RateLimitError: () => RateLimitError,
461
+ UnprocessableEntityError: () => UnprocessableEntityError
462
+ });
463
+ var OpenAIError = class extends Error {
464
+ };
465
+ var APIError = class _APIError extends OpenAIError {
466
+ constructor(status, error, message, headers) {
467
+ super(`${_APIError.makeMessage(status, error, message)}`);
468
+ this.status = status;
469
+ this.headers = headers;
470
+ const data = error;
471
+ this.error = data;
472
+ this.code = data == null ? void 0 : data["code"];
473
+ this.param = data == null ? void 0 : data["param"];
474
+ this.type = data == null ? void 0 : data["type"];
475
+ }
476
+ static makeMessage(status, error, message) {
477
+ const msg = (error == null ? void 0 : error.message) ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
478
+ if (status && msg) {
479
+ return `${status} ${msg}`;
480
+ }
481
+ if (status) {
482
+ return `${status} status code (no body)`;
483
+ }
484
+ if (msg) {
485
+ return msg;
486
+ }
487
+ return "(no status code or body)";
488
+ }
489
+ static generate(status, errorResponse, message, headers) {
490
+ if (!status) {
491
+ return new APIConnectionError({ cause: castToError(errorResponse) });
492
+ }
493
+ const error = errorResponse == null ? void 0 : errorResponse["error"];
494
+ if (status === 400) {
495
+ return new BadRequestError(status, error, message, headers);
496
+ }
497
+ if (status === 401) {
498
+ return new AuthenticationError(status, error, message, headers);
499
+ }
500
+ if (status === 403) {
501
+ return new PermissionDeniedError(status, error, message, headers);
502
+ }
503
+ if (status === 404) {
504
+ return new NotFoundError(status, error, message, headers);
505
+ }
506
+ if (status === 409) {
507
+ return new ConflictError(status, error, message, headers);
508
+ }
509
+ if (status === 422) {
510
+ return new UnprocessableEntityError(status, error, message, headers);
511
+ }
512
+ if (status === 429) {
513
+ return new RateLimitError(status, error, message, headers);
514
+ }
515
+ if (status >= 500) {
516
+ return new InternalServerError(status, error, message, headers);
517
+ }
518
+ return new _APIError(status, error, message, headers);
519
+ }
520
+ };
521
+ var APIUserAbortError = class extends APIError {
522
+ constructor({ message } = {}) {
523
+ super(void 0, void 0, message || "Request was aborted.", void 0);
524
+ this.status = void 0;
525
+ }
526
+ };
527
+ var APIConnectionError = class extends APIError {
528
+ constructor({ message, cause }) {
529
+ super(void 0, void 0, message || "Connection error.", void 0);
530
+ this.status = void 0;
531
+ if (cause)
532
+ this.cause = cause;
533
+ }
534
+ };
535
+ var APIConnectionTimeoutError = class extends APIConnectionError {
536
+ constructor({ message } = {}) {
537
+ super({ message: message != null ? message : "Request timed out." });
538
+ }
539
+ };
540
+ var BadRequestError = class extends APIError {
541
+ constructor() {
542
+ super(...arguments);
543
+ this.status = 400;
544
+ }
545
+ };
546
+ var AuthenticationError = class extends APIError {
547
+ constructor() {
548
+ super(...arguments);
549
+ this.status = 401;
550
+ }
551
+ };
552
+ var PermissionDeniedError = class extends APIError {
553
+ constructor() {
554
+ super(...arguments);
555
+ this.status = 403;
556
+ }
557
+ };
558
+ var NotFoundError = class extends APIError {
559
+ constructor() {
560
+ super(...arguments);
561
+ this.status = 404;
562
+ }
563
+ };
564
+ var ConflictError = class extends APIError {
565
+ constructor() {
566
+ super(...arguments);
567
+ this.status = 409;
568
+ }
569
+ };
570
+ var UnprocessableEntityError = class extends APIError {
571
+ constructor() {
572
+ super(...arguments);
573
+ this.status = 422;
574
+ }
575
+ };
576
+ var RateLimitError = class extends APIError {
577
+ constructor() {
578
+ super(...arguments);
579
+ this.status = 429;
580
+ }
581
+ };
582
+ var InternalServerError = class extends APIError {
583
+ };
584
+
585
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/streaming.mjs
586
+ var Stream = class _Stream {
587
+ constructor(iterator, controller) {
588
+ this.iterator = iterator;
589
+ this.controller = controller;
590
+ }
591
+ static fromSSEResponse(response, controller) {
592
+ let consumed = false;
593
+ const decoder = new SSEDecoder();
594
+ async function* iterMessages() {
595
+ if (!response.body) {
596
+ controller.abort();
597
+ throw new OpenAIError(`Attempted to iterate over a response with no body`);
598
+ }
599
+ const lineDecoder = new LineDecoder();
600
+ const iter = readableStreamAsyncIterable(response.body);
601
+ for await (const chunk of iter) {
602
+ for (const line of lineDecoder.decode(chunk)) {
603
+ const sse = decoder.decode(line);
604
+ if (sse)
605
+ yield sse;
606
+ }
607
+ }
608
+ for (const line of lineDecoder.flush()) {
609
+ const sse = decoder.decode(line);
610
+ if (sse)
611
+ yield sse;
612
+ }
613
+ }
614
+ async function* iterator() {
615
+ if (consumed) {
616
+ throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
617
+ }
618
+ consumed = true;
619
+ let done = false;
620
+ try {
621
+ for await (const sse of iterMessages()) {
622
+ if (done)
623
+ continue;
624
+ if (sse.data.startsWith("[DONE]")) {
625
+ done = true;
626
+ continue;
627
+ }
628
+ if (sse.event === null) {
629
+ let data;
630
+ try {
631
+ data = JSON.parse(sse.data);
632
+ } catch (e) {
633
+ console.error(`Could not parse message into JSON:`, sse.data);
634
+ console.error(`From chunk:`, sse.raw);
635
+ throw e;
636
+ }
637
+ if (data && data.error) {
638
+ throw new APIError(void 0, data.error, void 0, void 0);
639
+ }
640
+ yield data;
641
+ }
642
+ }
643
+ done = true;
644
+ } catch (e) {
645
+ if (e instanceof Error && e.name === "AbortError")
646
+ return;
647
+ throw e;
648
+ } finally {
649
+ if (!done)
650
+ controller.abort();
651
+ }
652
+ }
653
+ return new _Stream(iterator, controller);
654
+ }
655
+ /**
656
+ * Generates a Stream from a newline-separated ReadableStream
657
+ * where each item is a JSON value.
658
+ */
659
+ static fromReadableStream(readableStream, controller) {
660
+ let consumed = false;
661
+ async function* iterLines() {
662
+ const lineDecoder = new LineDecoder();
663
+ const iter = readableStreamAsyncIterable(readableStream);
664
+ for await (const chunk of iter) {
665
+ for (const line of lineDecoder.decode(chunk)) {
666
+ yield line;
667
+ }
668
+ }
669
+ for (const line of lineDecoder.flush()) {
670
+ yield line;
671
+ }
672
+ }
673
+ async function* iterator() {
674
+ if (consumed) {
675
+ throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
676
+ }
677
+ consumed = true;
678
+ let done = false;
679
+ try {
680
+ for await (const line of iterLines()) {
681
+ if (done)
682
+ continue;
683
+ if (line)
684
+ yield JSON.parse(line);
685
+ }
686
+ done = true;
687
+ } catch (e) {
688
+ if (e instanceof Error && e.name === "AbortError")
689
+ return;
690
+ throw e;
691
+ } finally {
692
+ if (!done)
693
+ controller.abort();
694
+ }
695
+ }
696
+ return new _Stream(iterator, controller);
697
+ }
698
+ [Symbol.asyncIterator]() {
699
+ return this.iterator();
700
+ }
701
+ /**
702
+ * Splits the stream into two streams which can be
703
+ * independently read from at different speeds.
704
+ */
705
+ tee() {
706
+ const left = [];
707
+ const right = [];
708
+ const iterator = this.iterator();
709
+ const teeIterator = (queue) => {
710
+ return {
711
+ next: () => {
712
+ if (queue.length === 0) {
713
+ const result = iterator.next();
714
+ left.push(result);
715
+ right.push(result);
716
+ }
717
+ return queue.shift();
718
+ }
719
+ };
720
+ };
721
+ return [
722
+ new _Stream(() => teeIterator(left), this.controller),
723
+ new _Stream(() => teeIterator(right), this.controller)
724
+ ];
725
+ }
726
+ /**
727
+ * Converts this stream to a newline-separated ReadableStream of
728
+ * JSON stringified values in the stream
729
+ * which can be turned back into a Stream with `Stream.fromReadableStream()`.
730
+ */
731
+ toReadableStream() {
732
+ const self = this;
733
+ let iter;
734
+ const encoder = new TextEncoder();
735
+ return new ReadableStream({
736
+ async start() {
737
+ iter = self[Symbol.asyncIterator]();
738
+ },
739
+ async pull(ctrl) {
740
+ try {
741
+ const { value, done } = await iter.next();
742
+ if (done)
743
+ return ctrl.close();
744
+ const bytes = encoder.encode(JSON.stringify(value) + "\n");
745
+ ctrl.enqueue(bytes);
746
+ } catch (err) {
747
+ ctrl.error(err);
748
+ }
749
+ },
750
+ async cancel() {
751
+ var _a2;
752
+ await ((_a2 = iter.return) == null ? void 0 : _a2.call(iter));
753
+ }
754
+ });
755
+ }
756
+ };
757
+ var SSEDecoder = class {
758
+ constructor() {
759
+ this.event = null;
760
+ this.data = [];
761
+ this.chunks = [];
762
+ }
763
+ decode(line) {
764
+ if (line.endsWith("\r")) {
765
+ line = line.substring(0, line.length - 1);
766
+ }
767
+ if (!line) {
768
+ if (!this.event && !this.data.length)
769
+ return null;
770
+ const sse = {
771
+ event: this.event,
772
+ data: this.data.join("\n"),
773
+ raw: this.chunks
774
+ };
775
+ this.event = null;
776
+ this.data = [];
777
+ this.chunks = [];
778
+ return sse;
779
+ }
780
+ this.chunks.push(line);
781
+ if (line.startsWith(":")) {
782
+ return null;
783
+ }
784
+ let [fieldname, _, value] = partition(line, ":");
785
+ if (value.startsWith(" ")) {
786
+ value = value.substring(1);
787
+ }
788
+ if (fieldname === "event") {
789
+ this.event = value;
790
+ } else if (fieldname === "data") {
791
+ this.data.push(value);
792
+ }
793
+ return null;
794
+ }
795
+ };
796
+ var LineDecoder = class _LineDecoder {
797
+ constructor() {
798
+ this.buffer = [];
799
+ this.trailingCR = false;
800
+ }
801
+ decode(chunk) {
802
+ let text = this.decodeText(chunk);
803
+ if (this.trailingCR) {
804
+ text = "\r" + text;
805
+ this.trailingCR = false;
806
+ }
807
+ if (text.endsWith("\r")) {
808
+ this.trailingCR = true;
809
+ text = text.slice(0, -1);
810
+ }
811
+ if (!text) {
812
+ return [];
813
+ }
814
+ const trailingNewline = _LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || "");
815
+ let lines = text.split(_LineDecoder.NEWLINE_REGEXP);
816
+ if (lines.length === 1 && !trailingNewline) {
817
+ this.buffer.push(lines[0]);
818
+ return [];
819
+ }
820
+ if (this.buffer.length > 0) {
821
+ lines = [this.buffer.join("") + lines[0], ...lines.slice(1)];
822
+ this.buffer = [];
823
+ }
824
+ if (!trailingNewline) {
825
+ this.buffer = [lines.pop() || ""];
826
+ }
827
+ return lines;
828
+ }
829
+ decodeText(bytes) {
830
+ var _a2;
831
+ if (bytes == null)
832
+ return "";
833
+ if (typeof bytes === "string")
834
+ return bytes;
835
+ if (typeof Buffer !== "undefined") {
836
+ if (bytes instanceof Buffer) {
837
+ return bytes.toString();
838
+ }
839
+ if (bytes instanceof Uint8Array) {
840
+ return Buffer.from(bytes).toString();
841
+ }
842
+ throw new OpenAIError(`Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`);
843
+ }
844
+ if (typeof TextDecoder !== "undefined") {
845
+ if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) {
846
+ (_a2 = this.textDecoder) != null ? _a2 : this.textDecoder = new TextDecoder("utf8");
847
+ return this.textDecoder.decode(bytes);
848
+ }
849
+ throw new OpenAIError(`Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`);
850
+ }
851
+ throw new OpenAIError(`Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`);
852
+ }
853
+ flush() {
854
+ if (!this.buffer.length && !this.trailingCR) {
855
+ return [];
856
+ }
857
+ const lines = [this.buffer.join("")];
858
+ this.buffer = [];
859
+ this.trailingCR = false;
860
+ return lines;
861
+ }
862
+ };
863
+ LineDecoder.NEWLINE_CHARS = /* @__PURE__ */ new Set(["\n", "\r", "\v", "\f", "", "", "", "\x85", "\u2028", "\u2029"]);
864
+ LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g;
865
+ function partition(str2, delimiter) {
866
+ const index = str2.indexOf(delimiter);
867
+ if (index !== -1) {
868
+ return [str2.substring(0, index), delimiter, str2.substring(index + delimiter.length)];
869
+ }
870
+ return [str2, "", ""];
871
+ }
872
+ function readableStreamAsyncIterable(stream) {
873
+ if (stream[Symbol.asyncIterator])
874
+ return stream;
875
+ const reader = stream.getReader();
876
+ return {
877
+ async next() {
878
+ try {
879
+ const result = await reader.read();
880
+ if (result == null ? void 0 : result.done)
881
+ reader.releaseLock();
882
+ return result;
883
+ } catch (e) {
884
+ reader.releaseLock();
885
+ throw e;
886
+ }
887
+ },
888
+ async return() {
889
+ const cancelPromise = reader.cancel();
890
+ reader.releaseLock();
891
+ await cancelPromise;
892
+ return { done: true, value: void 0 };
893
+ },
894
+ [Symbol.asyncIterator]() {
895
+ return this;
896
+ }
897
+ };
898
+ }
899
+
900
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/uploads.mjs
901
+ var isResponseLike = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function";
902
+ var isFileLike2 = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value);
903
+ var isBlobLike = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function";
904
+ var isUploadable = (value) => {
905
+ return isFileLike2(value) || isResponseLike(value) || isFsReadStream(value);
906
+ };
907
+ async function toFile(value, name, options = {}) {
908
+ var _a2, _b, _c;
909
+ value = await value;
910
+ if (isResponseLike(value)) {
911
+ const blob = await value.blob();
912
+ name || (name = (_a2 = new URL(value.url).pathname.split(/[\\/]/).pop()) != null ? _a2 : "unknown_file");
913
+ return new File2([blob], name, options);
914
+ }
915
+ const bits = await getBytes(value);
916
+ name || (name = (_b = getName(value)) != null ? _b : "unknown_file");
917
+ if (!options.type) {
918
+ const type = (_c = bits[0]) == null ? void 0 : _c.type;
919
+ if (typeof type === "string") {
920
+ options = { ...options, type };
921
+ }
922
+ }
923
+ return new File2(bits, name, options);
924
+ }
925
+ async function getBytes(value) {
926
+ var _a2;
927
+ let parts = [];
928
+ if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
929
+ value instanceof ArrayBuffer) {
930
+ parts.push(value);
931
+ } else if (isBlobLike(value)) {
932
+ parts.push(await value.arrayBuffer());
933
+ } else if (isAsyncIterableIterator(value)) {
934
+ for await (const chunk of value) {
935
+ parts.push(chunk);
936
+ }
937
+ } else {
938
+ throw new Error(`Unexpected data type: ${typeof value}; constructor: ${(_a2 = value == null ? void 0 : value.constructor) == null ? void 0 : _a2.name}; props: ${propsForError(value)}`);
939
+ }
940
+ return parts;
941
+ }
942
+ function propsForError(value) {
943
+ const props = Object.getOwnPropertyNames(value);
944
+ return `[${props.map((p) => `"${p}"`).join(", ")}]`;
945
+ }
946
+ function getName(value) {
947
+ var _a2;
948
+ return getStringFromMaybeBuffer(value.name) || getStringFromMaybeBuffer(value.filename) || // For fs.ReadStream
949
+ ((_a2 = getStringFromMaybeBuffer(value.path)) == null ? void 0 : _a2.split(/[\\/]/).pop());
950
+ }
951
+ var getStringFromMaybeBuffer = (x) => {
952
+ if (typeof x === "string")
953
+ return x;
954
+ if (typeof Buffer !== "undefined" && x instanceof Buffer)
955
+ return String(x);
956
+ return void 0;
957
+ };
958
+ var isAsyncIterableIterator = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function";
959
+ var isMultipartBody = (body) => body && typeof body === "object" && body.body && body[Symbol.toStringTag] === "MultipartBody";
960
+ var multipartFormRequestOptions = async (opts) => {
961
+ const form = await createForm(opts.body);
962
+ return getMultipartRequestOptions(form, opts);
963
+ };
964
+ var createForm = async (body) => {
965
+ const form = new FormData();
966
+ await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value)));
967
+ return form;
968
+ };
969
+ var addFormValue = async (form, key, value) => {
970
+ if (value === void 0)
971
+ return;
972
+ if (value == null) {
973
+ throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
974
+ }
975
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
976
+ form.append(key, String(value));
977
+ } else if (isUploadable(value)) {
978
+ const file = await toFile(value);
979
+ form.append(key, file);
980
+ } else if (Array.isArray(value)) {
981
+ await Promise.all(value.map((entry) => addFormValue(form, key + "[]", entry)));
982
+ } else if (typeof value === "object") {
983
+ await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop)));
984
+ } else {
985
+ throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
986
+ }
987
+ };
988
+
989
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/core.mjs
990
+ var __classPrivateFieldSet2 = function(receiver, state, value, kind2, f) {
991
+ if (kind2 === "m")
992
+ throw new TypeError("Private method is not writable");
993
+ if (kind2 === "a" && !f)
994
+ throw new TypeError("Private accessor was defined without a setter");
995
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
996
+ throw new TypeError("Cannot write private member to an object whose class did not declare it");
997
+ return kind2 === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
998
+ };
999
+ var __classPrivateFieldGet3 = function(receiver, state, kind2, f) {
1000
+ if (kind2 === "a" && !f)
1001
+ throw new TypeError("Private accessor was defined without a getter");
1002
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
1003
+ throw new TypeError("Cannot read private member from an object whose class did not declare it");
1004
+ return kind2 === "m" ? f : kind2 === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
1005
+ };
1006
+ var _AbstractPage_client;
1007
+ async function defaultParseResponse(props) {
1008
+ const { response } = props;
1009
+ if (props.options.stream) {
1010
+ debug("response", response.status, response.url, response.headers, response.body);
1011
+ if (props.options.__streamClass) {
1012
+ return props.options.__streamClass.fromSSEResponse(response, props.controller);
1013
+ }
1014
+ return Stream.fromSSEResponse(response, props.controller);
1015
+ }
1016
+ if (response.status === 204) {
1017
+ return null;
1018
+ }
1019
+ if (props.options.__binaryResponse) {
1020
+ return response;
1021
+ }
1022
+ const contentType = response.headers.get("content-type");
1023
+ const isJSON = (contentType == null ? void 0 : contentType.includes("application/json")) || (contentType == null ? void 0 : contentType.includes("application/vnd.api+json"));
1024
+ if (isJSON) {
1025
+ const json = await response.json();
1026
+ debug("response", response.status, response.url, response.headers, json);
1027
+ return json;
1028
+ }
1029
+ const text = await response.text();
1030
+ debug("response", response.status, response.url, response.headers, text);
1031
+ return text;
1032
+ }
1033
+ var APIPromise = class _APIPromise extends Promise {
1034
+ constructor(responsePromise, parseResponse = defaultParseResponse) {
1035
+ super((resolve) => {
1036
+ resolve(null);
1037
+ });
1038
+ this.responsePromise = responsePromise;
1039
+ this.parseResponse = parseResponse;
1040
+ }
1041
+ _thenUnwrap(transform) {
1042
+ return new _APIPromise(this.responsePromise, async (props) => transform(await this.parseResponse(props)));
1043
+ }
1044
+ /**
1045
+ * Gets the raw `Response` instance instead of parsing the response
1046
+ * data.
1047
+ *
1048
+ * If you want to parse the response body but still get the `Response`
1049
+ * instance, you can use {@link withResponse()}.
1050
+ *
1051
+ * 👋 Getting the wrong TypeScript type for `Response`?
1052
+ * Try setting `"moduleResolution": "NodeNext"` if you can,
1053
+ * or add one of these imports before your first `import … from 'openai'`:
1054
+ * - `import 'openai/shims/node'` (if you're running on Node)
1055
+ * - `import 'openai/shims/web'` (otherwise)
1056
+ */
1057
+ asResponse() {
1058
+ return this.responsePromise.then((p) => p.response);
1059
+ }
1060
+ /**
1061
+ * Gets the parsed response data and the raw `Response` instance.
1062
+ *
1063
+ * If you just want to get the raw `Response` instance without parsing it,
1064
+ * you can use {@link asResponse()}.
1065
+ *
1066
+ *
1067
+ * 👋 Getting the wrong TypeScript type for `Response`?
1068
+ * Try setting `"moduleResolution": "NodeNext"` if you can,
1069
+ * or add one of these imports before your first `import … from 'openai'`:
1070
+ * - `import 'openai/shims/node'` (if you're running on Node)
1071
+ * - `import 'openai/shims/web'` (otherwise)
1072
+ */
1073
+ async withResponse() {
1074
+ const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
1075
+ return { data, response };
1076
+ }
1077
+ parse() {
1078
+ if (!this.parsedPromise) {
1079
+ this.parsedPromise = this.responsePromise.then(this.parseResponse);
1080
+ }
1081
+ return this.parsedPromise;
1082
+ }
1083
+ then(onfulfilled, onrejected) {
1084
+ return this.parse().then(onfulfilled, onrejected);
1085
+ }
1086
+ catch(onrejected) {
1087
+ return this.parse().catch(onrejected);
1088
+ }
1089
+ finally(onfinally) {
1090
+ return this.parse().finally(onfinally);
1091
+ }
1092
+ };
1093
+ var APIClient = class {
1094
+ constructor({
1095
+ baseURL,
1096
+ maxRetries = 2,
1097
+ timeout = 6e5,
1098
+ // 10 minutes
1099
+ httpAgent,
1100
+ fetch: overridenFetch
1101
+ }) {
1102
+ this.baseURL = baseURL;
1103
+ this.maxRetries = validatePositiveInteger("maxRetries", maxRetries);
1104
+ this.timeout = validatePositiveInteger("timeout", timeout);
1105
+ this.httpAgent = httpAgent;
1106
+ this.fetch = overridenFetch != null ? overridenFetch : fetch;
1107
+ }
1108
+ authHeaders(opts) {
1109
+ return {};
1110
+ }
1111
+ /**
1112
+ * Override this to add your own default headers, for example:
1113
+ *
1114
+ * {
1115
+ * ...super.defaultHeaders(),
1116
+ * Authorization: 'Bearer 123',
1117
+ * }
1118
+ */
1119
+ defaultHeaders(opts) {
1120
+ return {
1121
+ Accept: "application/json",
1122
+ "Content-Type": "application/json",
1123
+ "User-Agent": this.getUserAgent(),
1124
+ ...getPlatformHeaders(),
1125
+ ...this.authHeaders(opts)
1126
+ };
1127
+ }
1128
+ /**
1129
+ * Override this to add your own headers validation:
1130
+ */
1131
+ validateHeaders(headers, customHeaders) {
1132
+ }
1133
+ defaultIdempotencyKey() {
1134
+ return `stainless-node-retry-${uuid4()}`;
1135
+ }
1136
+ get(path, opts) {
1137
+ return this.methodRequest("get", path, opts);
1138
+ }
1139
+ post(path, opts) {
1140
+ return this.methodRequest("post", path, opts);
1141
+ }
1142
+ patch(path, opts) {
1143
+ return this.methodRequest("patch", path, opts);
1144
+ }
1145
+ put(path, opts) {
1146
+ return this.methodRequest("put", path, opts);
1147
+ }
1148
+ delete(path, opts) {
1149
+ return this.methodRequest("delete", path, opts);
1150
+ }
1151
+ methodRequest(method, path, opts) {
1152
+ return this.request(Promise.resolve(opts).then((opts2) => ({ method, path, ...opts2 })));
1153
+ }
1154
+ getAPIList(path, Page2, opts) {
1155
+ return this.requestAPIList(Page2, { method: "get", path, ...opts });
1156
+ }
1157
+ calculateContentLength(body) {
1158
+ if (typeof body === "string") {
1159
+ if (typeof Buffer !== "undefined") {
1160
+ return Buffer.byteLength(body, "utf8").toString();
1161
+ }
1162
+ if (typeof TextEncoder !== "undefined") {
1163
+ const encoder = new TextEncoder();
1164
+ const encoded = encoder.encode(body);
1165
+ return encoded.length.toString();
1166
+ }
1167
+ }
1168
+ return null;
1169
+ }
1170
+ buildRequest(options) {
1171
+ var _a2, _b, _c, _d, _e, _f;
1172
+ const { method, path, query, headers = {} } = options;
1173
+ const body = isMultipartBody(options.body) ? options.body.body : options.body ? JSON.stringify(options.body, null, 2) : null;
1174
+ const contentLength = this.calculateContentLength(body);
1175
+ const url = this.buildURL(path, query);
1176
+ if ("timeout" in options)
1177
+ validatePositiveInteger("timeout", options.timeout);
1178
+ const timeout = (_a2 = options.timeout) != null ? _a2 : this.timeout;
1179
+ const httpAgent = (_c = (_b = options.httpAgent) != null ? _b : this.httpAgent) != null ? _c : getDefaultAgent(url);
1180
+ const minAgentTimeout = timeout + 1e3;
1181
+ if (typeof ((_d = httpAgent == null ? void 0 : httpAgent.options) == null ? void 0 : _d.timeout) === "number" && minAgentTimeout > ((_e = httpAgent.options.timeout) != null ? _e : 0)) {
1182
+ httpAgent.options.timeout = minAgentTimeout;
1183
+ }
1184
+ if (this.idempotencyHeader && method !== "get") {
1185
+ if (!options.idempotencyKey)
1186
+ options.idempotencyKey = this.defaultIdempotencyKey();
1187
+ headers[this.idempotencyHeader] = options.idempotencyKey;
1188
+ }
1189
+ const reqHeaders = this.buildHeaders({ options, headers, contentLength });
1190
+ const req = {
1191
+ method,
1192
+ ...body && { body },
1193
+ headers: reqHeaders,
1194
+ ...httpAgent && { agent: httpAgent },
1195
+ // @ts-ignore node-fetch uses a custom AbortSignal type that is
1196
+ // not compatible with standard web types
1197
+ signal: (_f = options.signal) != null ? _f : null
1198
+ };
1199
+ return { req, url, timeout };
1200
+ }
1201
+ buildHeaders({ options, headers, contentLength }) {
1202
+ const reqHeaders = {};
1203
+ if (contentLength) {
1204
+ reqHeaders["content-length"] = contentLength;
1205
+ }
1206
+ const defaultHeaders = this.defaultHeaders(options);
1207
+ applyHeadersMut(reqHeaders, defaultHeaders);
1208
+ applyHeadersMut(reqHeaders, headers);
1209
+ if (isMultipartBody(options.body) && kind !== "node") {
1210
+ delete reqHeaders["content-type"];
1211
+ }
1212
+ this.validateHeaders(reqHeaders, headers);
1213
+ return reqHeaders;
1214
+ }
1215
+ /**
1216
+ * Used as a callback for mutating the given `FinalRequestOptions` object.
1217
+ */
1218
+ async prepareOptions(options) {
1219
+ }
1220
+ /**
1221
+ * Used as a callback for mutating the given `RequestInit` object.
1222
+ *
1223
+ * This is useful for cases where you want to add certain headers based off of
1224
+ * the request properties, e.g. `method` or `url`.
1225
+ */
1226
+ async prepareRequest(request, { url, options }) {
1227
+ }
1228
+ parseHeaders(headers) {
1229
+ return !headers ? {} : Symbol.iterator in headers ? Object.fromEntries(Array.from(headers).map((header) => [...header])) : { ...headers };
1230
+ }
1231
+ makeStatusError(status, error, message, headers) {
1232
+ return APIError.generate(status, error, message, headers);
1233
+ }
1234
+ request(options, remainingRetries = null) {
1235
+ return new APIPromise(this.makeRequest(options, remainingRetries));
1236
+ }
1237
+ async makeRequest(optionsInput, retriesRemaining) {
1238
+ var _a2, _b, _c;
1239
+ const options = await optionsInput;
1240
+ if (retriesRemaining == null) {
1241
+ retriesRemaining = (_a2 = options.maxRetries) != null ? _a2 : this.maxRetries;
1242
+ }
1243
+ await this.prepareOptions(options);
1244
+ const { req, url, timeout } = this.buildRequest(options);
1245
+ await this.prepareRequest(req, { url, options });
1246
+ debug("request", url, options, req.headers);
1247
+ if ((_b = options.signal) == null ? void 0 : _b.aborted) {
1248
+ throw new APIUserAbortError();
1249
+ }
1250
+ const controller = new AbortController();
1251
+ const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
1252
+ if (response instanceof Error) {
1253
+ if ((_c = options.signal) == null ? void 0 : _c.aborted) {
1254
+ throw new APIUserAbortError();
1255
+ }
1256
+ if (retriesRemaining) {
1257
+ return this.retryRequest(options, retriesRemaining);
1258
+ }
1259
+ if (response.name === "AbortError") {
1260
+ throw new APIConnectionTimeoutError();
1261
+ }
1262
+ throw new APIConnectionError({ cause: response });
1263
+ }
1264
+ const responseHeaders = createResponseHeaders(response.headers);
1265
+ if (!response.ok) {
1266
+ if (retriesRemaining && this.shouldRetry(response)) {
1267
+ const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`;
1268
+ debug(`response (error; ${retryMessage2})`, response.status, url, responseHeaders);
1269
+ return this.retryRequest(options, retriesRemaining, responseHeaders);
1270
+ }
1271
+ const errText = await response.text().catch((e) => castToError(e).message);
1272
+ const errJSON = safeJSON(errText);
1273
+ const errMessage = errJSON ? void 0 : errText;
1274
+ const retryMessage = retriesRemaining ? `(error; no more retries left)` : `(error; not retryable)`;
1275
+ debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders, errMessage);
1276
+ const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders);
1277
+ throw err;
1278
+ }
1279
+ return { response, options, controller };
1280
+ }
1281
+ requestAPIList(Page2, options) {
1282
+ const request = this.makeRequest(options, null);
1283
+ return new PagePromise(this, request, Page2);
1284
+ }
1285
+ buildURL(path, query) {
1286
+ const url = isAbsoluteURL(path) ? new URL(path) : new URL(this.baseURL + (this.baseURL.endsWith("/") && path.startsWith("/") ? path.slice(1) : path));
1287
+ const defaultQuery = this.defaultQuery();
1288
+ if (!isEmptyObj(defaultQuery)) {
1289
+ query = { ...defaultQuery, ...query };
1290
+ }
1291
+ if (typeof query === "object" && query && !Array.isArray(query)) {
1292
+ url.search = this.stringifyQuery(query);
1293
+ }
1294
+ return url.toString();
1295
+ }
1296
+ stringifyQuery(query) {
1297
+ return Object.entries(query).filter(([_, value]) => typeof value !== "undefined").map(([key, value]) => {
1298
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
1299
+ return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
1300
+ }
1301
+ if (value === null) {
1302
+ return `${encodeURIComponent(key)}=`;
1303
+ }
1304
+ throw new OpenAIError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
1305
+ }).join("&");
1306
+ }
1307
+ async fetchWithTimeout(url, init, ms, controller) {
1308
+ const { signal, ...options } = init || {};
1309
+ if (signal)
1310
+ signal.addEventListener("abort", () => controller.abort());
1311
+ const timeout = setTimeout(() => controller.abort(), ms);
1312
+ return this.getRequestClient().fetch.call(void 0, url, { signal: controller.signal, ...options }).finally(() => {
1313
+ clearTimeout(timeout);
1314
+ });
1315
+ }
1316
+ getRequestClient() {
1317
+ return { fetch: this.fetch };
1318
+ }
1319
+ shouldRetry(response) {
1320
+ const shouldRetryHeader = response.headers.get("x-should-retry");
1321
+ if (shouldRetryHeader === "true")
1322
+ return true;
1323
+ if (shouldRetryHeader === "false")
1324
+ return false;
1325
+ if (response.status === 408)
1326
+ return true;
1327
+ if (response.status === 409)
1328
+ return true;
1329
+ if (response.status === 429)
1330
+ return true;
1331
+ if (response.status >= 500)
1332
+ return true;
1333
+ return false;
1334
+ }
1335
+ async retryRequest(options, retriesRemaining, responseHeaders) {
1336
+ var _a2;
1337
+ let timeoutMillis;
1338
+ const retryAfterMillisHeader = responseHeaders == null ? void 0 : responseHeaders["retry-after-ms"];
1339
+ if (retryAfterMillisHeader) {
1340
+ const timeoutMs = parseFloat(retryAfterMillisHeader);
1341
+ if (!Number.isNaN(timeoutMs)) {
1342
+ timeoutMillis = timeoutMs;
1343
+ }
1344
+ }
1345
+ const retryAfterHeader = responseHeaders == null ? void 0 : responseHeaders["retry-after"];
1346
+ if (retryAfterHeader && !timeoutMillis) {
1347
+ const timeoutSeconds = parseFloat(retryAfterHeader);
1348
+ if (!Number.isNaN(timeoutSeconds)) {
1349
+ timeoutMillis = timeoutSeconds * 1e3;
1350
+ } else {
1351
+ timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
1352
+ }
1353
+ }
1354
+ if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1e3)) {
1355
+ const maxRetries = (_a2 = options.maxRetries) != null ? _a2 : this.maxRetries;
1356
+ timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
1357
+ }
1358
+ await sleep(timeoutMillis);
1359
+ return this.makeRequest(options, retriesRemaining - 1);
1360
+ }
1361
+ calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
1362
+ const initialRetryDelay = 0.5;
1363
+ const maxRetryDelay = 8;
1364
+ const numRetries = maxRetries - retriesRemaining;
1365
+ const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
1366
+ const jitter = 1 - Math.random() * 0.25;
1367
+ return sleepSeconds * jitter * 1e3;
1368
+ }
1369
+ getUserAgent() {
1370
+ return `${this.constructor.name}/JS ${VERSION}`;
1371
+ }
1372
+ };
1373
+ var AbstractPage = class {
1374
+ constructor(client, response, body, options) {
1375
+ _AbstractPage_client.set(this, void 0);
1376
+ __classPrivateFieldSet2(this, _AbstractPage_client, client, "f");
1377
+ this.options = options;
1378
+ this.response = response;
1379
+ this.body = body;
1380
+ }
1381
+ hasNextPage() {
1382
+ const items = this.getPaginatedItems();
1383
+ if (!items.length)
1384
+ return false;
1385
+ return this.nextPageInfo() != null;
1386
+ }
1387
+ async getNextPage() {
1388
+ const nextInfo = this.nextPageInfo();
1389
+ if (!nextInfo) {
1390
+ throw new OpenAIError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");
1391
+ }
1392
+ const nextOptions = { ...this.options };
1393
+ if ("params" in nextInfo && typeof nextOptions.query === "object") {
1394
+ nextOptions.query = { ...nextOptions.query, ...nextInfo.params };
1395
+ } else if ("url" in nextInfo) {
1396
+ const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()];
1397
+ for (const [key, value] of params) {
1398
+ nextInfo.url.searchParams.set(key, value);
1399
+ }
1400
+ nextOptions.query = void 0;
1401
+ nextOptions.path = nextInfo.url.toString();
1402
+ }
1403
+ return await __classPrivateFieldGet3(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
1404
+ }
1405
+ async *iterPages() {
1406
+ let page = this;
1407
+ yield page;
1408
+ while (page.hasNextPage()) {
1409
+ page = await page.getNextPage();
1410
+ yield page;
1411
+ }
1412
+ }
1413
+ async *[(_AbstractPage_client = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() {
1414
+ for await (const page of this.iterPages()) {
1415
+ for (const item of page.getPaginatedItems()) {
1416
+ yield item;
1417
+ }
1418
+ }
1419
+ }
1420
+ };
1421
+ var PagePromise = class extends APIPromise {
1422
+ constructor(client, request, Page2) {
1423
+ super(request, async (props) => new Page2(client, props.response, await defaultParseResponse(props), props.options));
1424
+ }
1425
+ /**
1426
+ * Allow auto-paginating iteration on an unawaited list call, eg:
1427
+ *
1428
+ * for await (const item of client.items.list()) {
1429
+ * console.log(item)
1430
+ * }
1431
+ */
1432
+ async *[Symbol.asyncIterator]() {
1433
+ const page = await this;
1434
+ for await (const item of page) {
1435
+ yield item;
1436
+ }
1437
+ }
1438
+ };
1439
+ var createResponseHeaders = (headers) => {
1440
+ return new Proxy(Object.fromEntries(
1441
+ // @ts-ignore
1442
+ headers.entries()
1443
+ ), {
1444
+ get(target, name) {
1445
+ const key = name.toString();
1446
+ return target[key.toLowerCase()] || target[key];
1447
+ }
1448
+ });
1449
+ };
1450
+ var requestOptionsKeys = {
1451
+ method: true,
1452
+ path: true,
1453
+ query: true,
1454
+ body: true,
1455
+ headers: true,
1456
+ maxRetries: true,
1457
+ stream: true,
1458
+ timeout: true,
1459
+ httpAgent: true,
1460
+ signal: true,
1461
+ idempotencyKey: true,
1462
+ __binaryResponse: true,
1463
+ __streamClass: true
1464
+ };
1465
+ var isRequestOptions = (obj) => {
1466
+ return typeof obj === "object" && obj !== null && !isEmptyObj(obj) && Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k));
1467
+ };
1468
+ var getPlatformProperties = () => {
1469
+ if (typeof Deno !== "undefined" && Deno.build != null) {
1470
+ return {
1471
+ "X-Stainless-Lang": "js",
1472
+ "X-Stainless-Package-Version": VERSION,
1473
+ "X-Stainless-OS": normalizePlatform(Deno.build.os),
1474
+ "X-Stainless-Arch": normalizeArch(Deno.build.arch),
1475
+ "X-Stainless-Runtime": "deno",
1476
+ "X-Stainless-Runtime-Version": Deno.version
1477
+ };
1478
+ }
1479
+ if (typeof EdgeRuntime !== "undefined") {
1480
+ return {
1481
+ "X-Stainless-Lang": "js",
1482
+ "X-Stainless-Package-Version": VERSION,
1483
+ "X-Stainless-OS": "Unknown",
1484
+ "X-Stainless-Arch": `other:${EdgeRuntime}`,
1485
+ "X-Stainless-Runtime": "edge",
1486
+ "X-Stainless-Runtime-Version": process.version
1487
+ };
1488
+ }
1489
+ if (Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]") {
1490
+ return {
1491
+ "X-Stainless-Lang": "js",
1492
+ "X-Stainless-Package-Version": VERSION,
1493
+ "X-Stainless-OS": normalizePlatform(process.platform),
1494
+ "X-Stainless-Arch": normalizeArch(process.arch),
1495
+ "X-Stainless-Runtime": "node",
1496
+ "X-Stainless-Runtime-Version": process.version
1497
+ };
1498
+ }
1499
+ const browserInfo = getBrowserInfo();
1500
+ if (browserInfo) {
1501
+ return {
1502
+ "X-Stainless-Lang": "js",
1503
+ "X-Stainless-Package-Version": VERSION,
1504
+ "X-Stainless-OS": "Unknown",
1505
+ "X-Stainless-Arch": "unknown",
1506
+ "X-Stainless-Runtime": `browser:${browserInfo.browser}`,
1507
+ "X-Stainless-Runtime-Version": browserInfo.version
1508
+ };
1509
+ }
1510
+ return {
1511
+ "X-Stainless-Lang": "js",
1512
+ "X-Stainless-Package-Version": VERSION,
1513
+ "X-Stainless-OS": "Unknown",
1514
+ "X-Stainless-Arch": "unknown",
1515
+ "X-Stainless-Runtime": "unknown",
1516
+ "X-Stainless-Runtime-Version": "unknown"
1517
+ };
1518
+ };
1519
+ function getBrowserInfo() {
1520
+ if (typeof navigator === "undefined" || !navigator) {
1521
+ return null;
1522
+ }
1523
+ const browserPatterns = [
1524
+ { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
1525
+ { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
1526
+ { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
1527
+ { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
1528
+ { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
1529
+ { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }
1530
+ ];
1531
+ for (const { key, pattern } of browserPatterns) {
1532
+ const match = pattern.exec(navigator.userAgent);
1533
+ if (match) {
1534
+ const major = match[1] || 0;
1535
+ const minor = match[2] || 0;
1536
+ const patch = match[3] || 0;
1537
+ return { browser: key, version: `${major}.${minor}.${patch}` };
1538
+ }
1539
+ }
1540
+ return null;
1541
+ }
1542
+ var normalizeArch = (arch) => {
1543
+ if (arch === "x32")
1544
+ return "x32";
1545
+ if (arch === "x86_64" || arch === "x64")
1546
+ return "x64";
1547
+ if (arch === "arm")
1548
+ return "arm";
1549
+ if (arch === "aarch64" || arch === "arm64")
1550
+ return "arm64";
1551
+ if (arch)
1552
+ return `other:${arch}`;
1553
+ return "unknown";
1554
+ };
1555
+ var normalizePlatform = (platform) => {
1556
+ platform = platform.toLowerCase();
1557
+ if (platform.includes("ios"))
1558
+ return "iOS";
1559
+ if (platform === "android")
1560
+ return "Android";
1561
+ if (platform === "darwin")
1562
+ return "MacOS";
1563
+ if (platform === "win32")
1564
+ return "Windows";
1565
+ if (platform === "freebsd")
1566
+ return "FreeBSD";
1567
+ if (platform === "openbsd")
1568
+ return "OpenBSD";
1569
+ if (platform === "linux")
1570
+ return "Linux";
1571
+ if (platform)
1572
+ return `Other:${platform}`;
1573
+ return "Unknown";
1574
+ };
1575
+ var _platformHeaders;
1576
+ var getPlatformHeaders = () => {
1577
+ return _platformHeaders != null ? _platformHeaders : _platformHeaders = getPlatformProperties();
1578
+ };
1579
+ var safeJSON = (text) => {
1580
+ try {
1581
+ return JSON.parse(text);
1582
+ } catch (err) {
1583
+ return void 0;
1584
+ }
1585
+ };
1586
+ var startsWithSchemeRegexp = new RegExp("^(?:[a-z]+:)?//", "i");
1587
+ var isAbsoluteURL = (url) => {
1588
+ return startsWithSchemeRegexp.test(url);
1589
+ };
1590
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1591
+ var validatePositiveInteger = (name, n) => {
1592
+ if (typeof n !== "number" || !Number.isInteger(n)) {
1593
+ throw new OpenAIError(`${name} must be an integer`);
1594
+ }
1595
+ if (n < 0) {
1596
+ throw new OpenAIError(`${name} must be a positive integer`);
1597
+ }
1598
+ return n;
1599
+ };
1600
+ var castToError = (err) => {
1601
+ if (err instanceof Error)
1602
+ return err;
1603
+ return new Error(err);
1604
+ };
1605
+ var readEnv = (env) => {
1606
+ var _a2, _b, _c, _d, _e, _f;
1607
+ if (typeof process !== "undefined") {
1608
+ return (_c = (_b = (_a2 = process.env) == null ? void 0 : _a2[env]) == null ? void 0 : _b.trim()) != null ? _c : void 0;
1609
+ }
1610
+ if (typeof Deno !== "undefined") {
1611
+ return (_f = (_e = (_d = Deno.env) == null ? void 0 : _d.get) == null ? void 0 : _e.call(_d, env)) == null ? void 0 : _f.trim();
1612
+ }
1613
+ return void 0;
1614
+ };
1615
+ function isEmptyObj(obj) {
1616
+ if (!obj)
1617
+ return true;
1618
+ for (const _k in obj)
1619
+ return false;
1620
+ return true;
1621
+ }
1622
+ function hasOwn(obj, key) {
1623
+ return Object.prototype.hasOwnProperty.call(obj, key);
1624
+ }
1625
+ function applyHeadersMut(targetHeaders, newHeaders) {
1626
+ for (const k in newHeaders) {
1627
+ if (!hasOwn(newHeaders, k))
1628
+ continue;
1629
+ const lowerKey = k.toLowerCase();
1630
+ if (!lowerKey)
1631
+ continue;
1632
+ const val = newHeaders[k];
1633
+ if (val === null) {
1634
+ delete targetHeaders[lowerKey];
1635
+ } else if (val !== void 0) {
1636
+ targetHeaders[lowerKey] = val;
1637
+ }
1638
+ }
1639
+ }
1640
+ function debug(action, ...args) {
1641
+ if (typeof process !== "undefined" && process.env["DEBUG"] === "true") {
1642
+ console.log(`OpenAI:DEBUG:${action}`, ...args);
1643
+ }
1644
+ }
1645
+ var uuid4 = () => {
1646
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
1647
+ const r = Math.random() * 16 | 0;
1648
+ const v = c === "x" ? r : r & 3 | 8;
1649
+ return v.toString(16);
1650
+ });
1651
+ };
1652
+ var isRunningInBrowser = () => {
1653
+ return (
1654
+ // @ts-ignore
1655
+ typeof window !== "undefined" && // @ts-ignore
1656
+ typeof window.document !== "undefined" && // @ts-ignore
1657
+ typeof navigator !== "undefined"
1658
+ );
1659
+ };
1660
+
1661
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/pagination.mjs
1662
+ var Page = class extends AbstractPage {
1663
+ constructor(client, response, body, options) {
1664
+ super(client, response, body, options);
1665
+ this.data = body.data || [];
1666
+ this.object = body.object;
1667
+ }
1668
+ getPaginatedItems() {
1669
+ var _a2;
1670
+ return (_a2 = this.data) != null ? _a2 : [];
1671
+ }
1672
+ // @deprecated Please use `nextPageInfo()` instead
1673
+ /**
1674
+ * This page represents a response that isn't actually paginated at the API level
1675
+ * so there will never be any next page params.
1676
+ */
1677
+ nextPageParams() {
1678
+ return null;
1679
+ }
1680
+ nextPageInfo() {
1681
+ return null;
1682
+ }
1683
+ };
1684
+ var CursorPage = class extends AbstractPage {
1685
+ constructor(client, response, body, options) {
1686
+ super(client, response, body, options);
1687
+ this.data = body.data || [];
1688
+ }
1689
+ getPaginatedItems() {
1690
+ var _a2;
1691
+ return (_a2 = this.data) != null ? _a2 : [];
1692
+ }
1693
+ // @deprecated Please use `nextPageInfo()` instead
1694
+ nextPageParams() {
1695
+ const info = this.nextPageInfo();
1696
+ if (!info)
1697
+ return null;
1698
+ if ("params" in info)
1699
+ return info.params;
1700
+ const params = Object.fromEntries(info.url.searchParams);
1701
+ if (!Object.keys(params).length)
1702
+ return null;
1703
+ return params;
1704
+ }
1705
+ nextPageInfo() {
1706
+ var _a2;
1707
+ const data = this.getPaginatedItems();
1708
+ if (!data.length) {
1709
+ return null;
1710
+ }
1711
+ const id = (_a2 = data[data.length - 1]) == null ? void 0 : _a2.id;
1712
+ if (!id) {
1713
+ return null;
1714
+ }
1715
+ return { params: { after: id } };
1716
+ }
1717
+ };
1718
+
1719
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/resource.mjs
1720
+ var APIResource = class {
1721
+ constructor(client) {
1722
+ this._client = client;
1723
+ }
1724
+ };
1725
+
1726
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/resources/chat/completions.mjs
1727
+ var Completions = class extends APIResource {
1728
+ create(body, options) {
1729
+ var _a2;
1730
+ return this._client.post("/chat/completions", { body, ...options, stream: (_a2 = body.stream) != null ? _a2 : false });
1731
+ }
1732
+ };
1733
+ /* @__PURE__ */ (function(Completions4) {
1734
+ })(Completions || (Completions = {}));
1735
+
1736
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/resources/chat/chat.mjs
1737
+ var Chat = class extends APIResource {
1738
+ constructor() {
1739
+ super(...arguments);
1740
+ this.completions = new Completions(this._client);
1741
+ }
1742
+ };
1743
+ (function(Chat3) {
1744
+ Chat3.Completions = Completions;
1745
+ })(Chat || (Chat = {}));
1746
+
1747
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/resources/audio/speech.mjs
1748
+ var Speech = class extends APIResource {
1749
+ /**
1750
+ * Generates audio from the input text.
1751
+ */
1752
+ create(body, options) {
1753
+ return this._client.post("/audio/speech", { body, ...options, __binaryResponse: true });
1754
+ }
1755
+ };
1756
+ /* @__PURE__ */ (function(Speech2) {
1757
+ })(Speech || (Speech = {}));
1758
+
1759
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/resources/audio/transcriptions.mjs
1760
+ var Transcriptions = class extends APIResource {
1761
+ /**
1762
+ * Transcribes audio into the input language.
1763
+ */
1764
+ create(body, options) {
1765
+ return this._client.post("/audio/transcriptions", multipartFormRequestOptions({ body, ...options }));
1766
+ }
1767
+ };
1768
+ /* @__PURE__ */ (function(Transcriptions2) {
1769
+ })(Transcriptions || (Transcriptions = {}));
1770
+
1771
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/resources/audio/translations.mjs
1772
+ var Translations = class extends APIResource {
1773
+ /**
1774
+ * Translates audio into English.
1775
+ */
1776
+ create(body, options) {
1777
+ return this._client.post("/audio/translations", multipartFormRequestOptions({ body, ...options }));
1778
+ }
1779
+ };
1780
+ /* @__PURE__ */ (function(Translations2) {
1781
+ })(Translations || (Translations = {}));
1782
+
1783
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/resources/audio/audio.mjs
1784
+ var Audio = class extends APIResource {
1785
+ constructor() {
1786
+ super(...arguments);
1787
+ this.transcriptions = new Transcriptions(this._client);
1788
+ this.translations = new Translations(this._client);
1789
+ this.speech = new Speech(this._client);
1790
+ }
1791
+ };
1792
+ (function(Audio2) {
1793
+ Audio2.Transcriptions = Transcriptions;
1794
+ Audio2.Translations = Translations;
1795
+ Audio2.Speech = Speech;
1796
+ })(Audio || (Audio = {}));
1797
+
1798
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/resources/beta/assistants/files.mjs
1799
+ var Files = class extends APIResource {
1800
+ /**
1801
+ * Create an assistant file by attaching a
1802
+ * [File](https://platform.openai.com/docs/api-reference/files) to an
1803
+ * [assistant](https://platform.openai.com/docs/api-reference/assistants).
1804
+ */
1805
+ create(assistantId, body, options) {
1806
+ return this._client.post(`/assistants/${assistantId}/files`, {
1807
+ body,
1808
+ ...options,
1809
+ headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers }
1810
+ });
1811
+ }
1812
+ /**
1813
+ * Retrieves an AssistantFile.
1814
+ */
1815
+ retrieve(assistantId, fileId, options) {
1816
+ return this._client.get(`/assistants/${assistantId}/files/${fileId}`, {
1817
+ ...options,
1818
+ headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers }
1819
+ });
1820
+ }
1821
+ list(assistantId, query = {}, options) {
1822
+ if (isRequestOptions(query)) {
1823
+ return this.list(assistantId, {}, query);
1824
+ }
1825
+ return this._client.getAPIList(`/assistants/${assistantId}/files`, AssistantFilesPage, {
1826
+ query,
1827
+ ...options,
1828
+ headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers }
1829
+ });
1830
+ }
1831
+ /**
1832
+ * Delete an assistant file.
1833
+ */
1834
+ del(assistantId, fileId, options) {
1835
+ return this._client.delete(`/assistants/${assistantId}/files/${fileId}`, {
1836
+ ...options,
1837
+ headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers }
1838
+ });
1839
+ }
1840
+ };
1841
+ var AssistantFilesPage = class extends CursorPage {
1842
+ };
1843
+ (function(Files4) {
1844
+ Files4.AssistantFilesPage = AssistantFilesPage;
1845
+ })(Files || (Files = {}));
1846
+
1847
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/resources/beta/assistants/assistants.mjs
1848
+ var Assistants = class extends APIResource {
1849
+ constructor() {
1850
+ super(...arguments);
1851
+ this.files = new Files(this._client);
1852
+ }
1853
+ /**
1854
+ * Create an assistant with a model and instructions.
1855
+ */
1856
+ create(body, options) {
1857
+ return this._client.post("/assistants", {
1858
+ body,
1859
+ ...options,
1860
+ headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers }
1861
+ });
1862
+ }
1863
+ /**
1864
+ * Retrieves an assistant.
1865
+ */
1866
+ retrieve(assistantId, options) {
1867
+ return this._client.get(`/assistants/${assistantId}`, {
1868
+ ...options,
1869
+ headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers }
1870
+ });
1871
+ }
1872
+ /**
1873
+ * Modifies an assistant.
1874
+ */
1875
+ update(assistantId, body, options) {
1876
+ return this._client.post(`/assistants/${assistantId}`, {
1877
+ body,
1878
+ ...options,
1879
+ headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers }
1880
+ });
1881
+ }
1882
+ list(query = {}, options) {
1883
+ if (isRequestOptions(query)) {
1884
+ return this.list({}, query);
1885
+ }
1886
+ return this._client.getAPIList("/assistants", AssistantsPage, {
1887
+ query,
1888
+ ...options,
1889
+ headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers }
1890
+ });
1891
+ }
1892
+ /**
1893
+ * Delete an assistant.
1894
+ */
1895
+ del(assistantId, options) {
1896
+ return this._client.delete(`/assistants/${assistantId}`, {
1897
+ ...options,
1898
+ headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers }
1899
+ });
1900
+ }
1901
+ };
1902
+ var AssistantsPage = class extends CursorPage {
1903
+ };
1904
+ (function(Assistants2) {
1905
+ Assistants2.AssistantsPage = AssistantsPage;
1906
+ Assistants2.Files = Files;
1907
+ Assistants2.AssistantFilesPage = AssistantFilesPage;
1908
+ })(Assistants || (Assistants = {}));
1909
+
1910
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/lib/RunnableFunction.mjs
1911
+ function isRunnableFunctionWithParse(fn) {
1912
+ return typeof fn.parse === "function";
1913
+ }
1914
+
1915
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/lib/chatCompletionUtils.mjs
1916
+ var isAssistantMessage = (message) => {
1917
+ return (message == null ? void 0 : message.role) === "assistant";
1918
+ };
1919
+ var isFunctionMessage = (message) => {
1920
+ return (message == null ? void 0 : message.role) === "function";
1921
+ };
1922
+ var isToolMessage = (message) => {
1923
+ return (message == null ? void 0 : message.role) === "tool";
1924
+ };
1925
+
1926
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/lib/AbstractChatCompletionRunner.mjs
1927
+ var __classPrivateFieldSet3 = function(receiver, state, value, kind2, f) {
1928
+ if (kind2 === "m")
1929
+ throw new TypeError("Private method is not writable");
1930
+ if (kind2 === "a" && !f)
1931
+ throw new TypeError("Private accessor was defined without a setter");
1932
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
1933
+ throw new TypeError("Cannot write private member to an object whose class did not declare it");
1934
+ return kind2 === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
1935
+ };
1936
+ var __classPrivateFieldGet4 = function(receiver, state, kind2, f) {
1937
+ if (kind2 === "a" && !f)
1938
+ throw new TypeError("Private accessor was defined without a getter");
1939
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
1940
+ throw new TypeError("Cannot read private member from an object whose class did not declare it");
1941
+ return kind2 === "m" ? f : kind2 === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
1942
+ };
1943
+ var _AbstractChatCompletionRunner_instances;
1944
+ var _AbstractChatCompletionRunner_connectedPromise;
1945
+ var _AbstractChatCompletionRunner_resolveConnectedPromise;
1946
+ var _AbstractChatCompletionRunner_rejectConnectedPromise;
1947
+ var _AbstractChatCompletionRunner_endPromise;
1948
+ var _AbstractChatCompletionRunner_resolveEndPromise;
1949
+ var _AbstractChatCompletionRunner_rejectEndPromise;
1950
+ var _AbstractChatCompletionRunner_listeners;
1951
+ var _AbstractChatCompletionRunner_ended;
1952
+ var _AbstractChatCompletionRunner_errored;
1953
+ var _AbstractChatCompletionRunner_aborted;
1954
+ var _AbstractChatCompletionRunner_catchingPromiseCreated;
1955
+ var _AbstractChatCompletionRunner_getFinalContent;
1956
+ var _AbstractChatCompletionRunner_getFinalMessage;
1957
+ var _AbstractChatCompletionRunner_getFinalFunctionCall;
1958
+ var _AbstractChatCompletionRunner_getFinalFunctionCallResult;
1959
+ var _AbstractChatCompletionRunner_calculateTotalUsage;
1960
+ var _AbstractChatCompletionRunner_handleError;
1961
+ var _AbstractChatCompletionRunner_validateParams;
1962
+ var _AbstractChatCompletionRunner_stringifyFunctionCallResult;
1963
+ var DEFAULT_MAX_CHAT_COMPLETIONS = 10;
1964
+ var AbstractChatCompletionRunner = class {
1965
+ constructor() {
1966
+ _AbstractChatCompletionRunner_instances.add(this);
1967
+ this.controller = new AbortController();
1968
+ _AbstractChatCompletionRunner_connectedPromise.set(this, void 0);
1969
+ _AbstractChatCompletionRunner_resolveConnectedPromise.set(this, () => {
1970
+ });
1971
+ _AbstractChatCompletionRunner_rejectConnectedPromise.set(this, () => {
1972
+ });
1973
+ _AbstractChatCompletionRunner_endPromise.set(this, void 0);
1974
+ _AbstractChatCompletionRunner_resolveEndPromise.set(this, () => {
1975
+ });
1976
+ _AbstractChatCompletionRunner_rejectEndPromise.set(this, () => {
1977
+ });
1978
+ _AbstractChatCompletionRunner_listeners.set(this, {});
1979
+ this._chatCompletions = [];
1980
+ this.messages = [];
1981
+ _AbstractChatCompletionRunner_ended.set(this, false);
1982
+ _AbstractChatCompletionRunner_errored.set(this, false);
1983
+ _AbstractChatCompletionRunner_aborted.set(this, false);
1984
+ _AbstractChatCompletionRunner_catchingPromiseCreated.set(this, false);
1985
+ _AbstractChatCompletionRunner_handleError.set(this, (error) => {
1986
+ __classPrivateFieldSet3(this, _AbstractChatCompletionRunner_errored, true, "f");
1987
+ if (error instanceof Error && error.name === "AbortError") {
1988
+ error = new APIUserAbortError();
1989
+ }
1990
+ if (error instanceof APIUserAbortError) {
1991
+ __classPrivateFieldSet3(this, _AbstractChatCompletionRunner_aborted, true, "f");
1992
+ return this._emit("abort", error);
1993
+ }
1994
+ if (error instanceof OpenAIError) {
1995
+ return this._emit("error", error);
1996
+ }
1997
+ if (error instanceof Error) {
1998
+ const openAIError = new OpenAIError(error.message);
1999
+ openAIError.cause = error;
2000
+ return this._emit("error", openAIError);
2001
+ }
2002
+ return this._emit("error", new OpenAIError(String(error)));
2003
+ });
2004
+ __classPrivateFieldSet3(this, _AbstractChatCompletionRunner_connectedPromise, new Promise((resolve, reject) => {
2005
+ __classPrivateFieldSet3(this, _AbstractChatCompletionRunner_resolveConnectedPromise, resolve, "f");
2006
+ __classPrivateFieldSet3(this, _AbstractChatCompletionRunner_rejectConnectedPromise, reject, "f");
2007
+ }), "f");
2008
+ __classPrivateFieldSet3(this, _AbstractChatCompletionRunner_endPromise, new Promise((resolve, reject) => {
2009
+ __classPrivateFieldSet3(this, _AbstractChatCompletionRunner_resolveEndPromise, resolve, "f");
2010
+ __classPrivateFieldSet3(this, _AbstractChatCompletionRunner_rejectEndPromise, reject, "f");
2011
+ }), "f");
2012
+ __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_connectedPromise, "f").catch(() => {
2013
+ });
2014
+ __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_endPromise, "f").catch(() => {
2015
+ });
2016
+ }
2017
+ _run(executor) {
2018
+ setTimeout(() => {
2019
+ executor().then(() => {
2020
+ this._emitFinal();
2021
+ this._emit("end");
2022
+ }, __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_handleError, "f"));
2023
+ }, 0);
2024
+ }
2025
+ _addChatCompletion(chatCompletion) {
2026
+ var _a2;
2027
+ this._chatCompletions.push(chatCompletion);
2028
+ this._emit("chatCompletion", chatCompletion);
2029
+ const message = (_a2 = chatCompletion.choices[0]) == null ? void 0 : _a2.message;
2030
+ if (message)
2031
+ this._addMessage(message);
2032
+ return chatCompletion;
2033
+ }
2034
+ _addMessage(message, emit = true) {
2035
+ if (!("content" in message))
2036
+ message.content = null;
2037
+ this.messages.push(message);
2038
+ if (emit) {
2039
+ this._emit("message", message);
2040
+ if ((isFunctionMessage(message) || isToolMessage(message)) && message.content) {
2041
+ this._emit("functionCallResult", message.content);
2042
+ } else if (isAssistantMessage(message) && message.function_call) {
2043
+ this._emit("functionCall", message.function_call);
2044
+ } else if (isAssistantMessage(message) && message.tool_calls) {
2045
+ for (const tool_call of message.tool_calls) {
2046
+ if (tool_call.type === "function") {
2047
+ this._emit("functionCall", tool_call.function);
2048
+ }
2049
+ }
2050
+ }
2051
+ }
2052
+ }
2053
+ _connected() {
2054
+ if (this.ended)
2055
+ return;
2056
+ __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_resolveConnectedPromise, "f").call(this);
2057
+ this._emit("connect");
2058
+ }
2059
+ get ended() {
2060
+ return __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_ended, "f");
2061
+ }
2062
+ get errored() {
2063
+ return __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_errored, "f");
2064
+ }
2065
+ get aborted() {
2066
+ return __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_aborted, "f");
2067
+ }
2068
+ abort() {
2069
+ this.controller.abort();
2070
+ }
2071
+ /**
2072
+ * Adds the listener function to the end of the listeners array for the event.
2073
+ * No checks are made to see if the listener has already been added. Multiple calls passing
2074
+ * the same combination of event and listener will result in the listener being added, and
2075
+ * called, multiple times.
2076
+ * @returns this ChatCompletionStream, so that calls can be chained
2077
+ */
2078
+ on(event, listener) {
2079
+ const listeners = __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_listeners, "f")[event] || (__classPrivateFieldGet4(this, _AbstractChatCompletionRunner_listeners, "f")[event] = []);
2080
+ listeners.push({ listener });
2081
+ return this;
2082
+ }
2083
+ /**
2084
+ * Removes the specified listener from the listener array for the event.
2085
+ * off() will remove, at most, one instance of a listener from the listener array. If any single
2086
+ * listener has been added multiple times to the listener array for the specified event, then
2087
+ * off() must be called multiple times to remove each instance.
2088
+ * @returns this ChatCompletionStream, so that calls can be chained
2089
+ */
2090
+ off(event, listener) {
2091
+ const listeners = __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_listeners, "f")[event];
2092
+ if (!listeners)
2093
+ return this;
2094
+ const index = listeners.findIndex((l) => l.listener === listener);
2095
+ if (index >= 0)
2096
+ listeners.splice(index, 1);
2097
+ return this;
2098
+ }
2099
+ /**
2100
+ * Adds a one-time listener function for the event. The next time the event is triggered,
2101
+ * this listener is removed and then invoked.
2102
+ * @returns this ChatCompletionStream, so that calls can be chained
2103
+ */
2104
+ once(event, listener) {
2105
+ const listeners = __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_listeners, "f")[event] || (__classPrivateFieldGet4(this, _AbstractChatCompletionRunner_listeners, "f")[event] = []);
2106
+ listeners.push({ listener, once: true });
2107
+ return this;
2108
+ }
2109
+ /**
2110
+ * This is similar to `.once()`, but returns a Promise that resolves the next time
2111
+ * the event is triggered, instead of calling a listener callback.
2112
+ * @returns a Promise that resolves the next time given event is triggered,
2113
+ * or rejects if an error is emitted. (If you request the 'error' event,
2114
+ * returns a promise that resolves with the error).
2115
+ *
2116
+ * Example:
2117
+ *
2118
+ * const message = await stream.emitted('message') // rejects if the stream errors
2119
+ */
2120
+ emitted(event) {
2121
+ return new Promise((resolve, reject) => {
2122
+ __classPrivateFieldSet3(this, _AbstractChatCompletionRunner_catchingPromiseCreated, true, "f");
2123
+ if (event !== "error")
2124
+ this.once("error", reject);
2125
+ this.once(event, resolve);
2126
+ });
2127
+ }
2128
+ async done() {
2129
+ __classPrivateFieldSet3(this, _AbstractChatCompletionRunner_catchingPromiseCreated, true, "f");
2130
+ await __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_endPromise, "f");
2131
+ }
2132
+ /**
2133
+ * @returns a promise that resolves with the final ChatCompletion, or rejects
2134
+ * if an error occurred or the stream ended prematurely without producing a ChatCompletion.
2135
+ */
2136
+ async finalChatCompletion() {
2137
+ await this.done();
2138
+ const completion = this._chatCompletions[this._chatCompletions.length - 1];
2139
+ if (!completion)
2140
+ throw new OpenAIError("stream ended without producing a ChatCompletion");
2141
+ return completion;
2142
+ }
2143
+ /**
2144
+ * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects
2145
+ * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.
2146
+ */
2147
+ async finalContent() {
2148
+ await this.done();
2149
+ return __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this);
2150
+ }
2151
+ /**
2152
+ * @returns a promise that resolves with the the final assistant ChatCompletionMessage response,
2153
+ * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.
2154
+ */
2155
+ async finalMessage() {
2156
+ await this.done();
2157
+ return __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this);
2158
+ }
2159
+ /**
2160
+ * @returns a promise that resolves with the content of the final FunctionCall, or rejects
2161
+ * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.
2162
+ */
2163
+ async finalFunctionCall() {
2164
+ await this.done();
2165
+ return __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this);
2166
+ }
2167
+ async finalFunctionCallResult() {
2168
+ await this.done();
2169
+ return __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this);
2170
+ }
2171
+ async totalUsage() {
2172
+ await this.done();
2173
+ return __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this);
2174
+ }
2175
+ allChatCompletions() {
2176
+ return [...this._chatCompletions];
2177
+ }
2178
+ _emit(event, ...args) {
2179
+ if (__classPrivateFieldGet4(this, _AbstractChatCompletionRunner_ended, "f")) {
2180
+ return;
2181
+ }
2182
+ if (event === "end") {
2183
+ __classPrivateFieldSet3(this, _AbstractChatCompletionRunner_ended, true, "f");
2184
+ __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_resolveEndPromise, "f").call(this);
2185
+ }
2186
+ const listeners = __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_listeners, "f")[event];
2187
+ if (listeners) {
2188
+ __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_listeners, "f")[event] = listeners.filter((l) => !l.once);
2189
+ listeners.forEach(({ listener }) => listener(...args));
2190
+ }
2191
+ if (event === "abort") {
2192
+ const error = args[0];
2193
+ if (!__classPrivateFieldGet4(this, _AbstractChatCompletionRunner_catchingPromiseCreated, "f") && !(listeners == null ? void 0 : listeners.length)) {
2194
+ Promise.reject(error);
2195
+ }
2196
+ __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_rejectConnectedPromise, "f").call(this, error);
2197
+ __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_rejectEndPromise, "f").call(this, error);
2198
+ this._emit("end");
2199
+ return;
2200
+ }
2201
+ if (event === "error") {
2202
+ const error = args[0];
2203
+ if (!__classPrivateFieldGet4(this, _AbstractChatCompletionRunner_catchingPromiseCreated, "f") && !(listeners == null ? void 0 : listeners.length)) {
2204
+ Promise.reject(error);
2205
+ }
2206
+ __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_rejectConnectedPromise, "f").call(this, error);
2207
+ __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_rejectEndPromise, "f").call(this, error);
2208
+ this._emit("end");
2209
+ }
2210
+ }
2211
+ _emitFinal() {
2212
+ const completion = this._chatCompletions[this._chatCompletions.length - 1];
2213
+ if (completion)
2214
+ this._emit("finalChatCompletion", completion);
2215
+ const finalMessage = __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this);
2216
+ if (finalMessage)
2217
+ this._emit("finalMessage", finalMessage);
2218
+ const finalContent = __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this);
2219
+ if (finalContent)
2220
+ this._emit("finalContent", finalContent);
2221
+ const finalFunctionCall = __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this);
2222
+ if (finalFunctionCall)
2223
+ this._emit("finalFunctionCall", finalFunctionCall);
2224
+ const finalFunctionCallResult = __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this);
2225
+ if (finalFunctionCallResult != null)
2226
+ this._emit("finalFunctionCallResult", finalFunctionCallResult);
2227
+ if (this._chatCompletions.some((c) => c.usage)) {
2228
+ this._emit("totalUsage", __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this));
2229
+ }
2230
+ }
2231
+ async _createChatCompletion(completions, params, options) {
2232
+ const signal = options == null ? void 0 : options.signal;
2233
+ if (signal) {
2234
+ if (signal.aborted)
2235
+ this.controller.abort();
2236
+ signal.addEventListener("abort", () => this.controller.abort());
2237
+ }
2238
+ __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params);
2239
+ const chatCompletion = await completions.create({ ...params, stream: false }, { ...options, signal: this.controller.signal });
2240
+ this._connected();
2241
+ return this._addChatCompletion(chatCompletion);
2242
+ }
2243
+ async _runChatCompletion(completions, params, options) {
2244
+ for (const message of params.messages) {
2245
+ this._addMessage(message, false);
2246
+ }
2247
+ return await this._createChatCompletion(completions, params, options);
2248
+ }
2249
+ async _runFunctions(completions, params, options) {
2250
+ var _a2;
2251
+ const role = "function";
2252
+ const { function_call = "auto", stream, ...restParams } = params;
2253
+ const singleFunctionToCall = typeof function_call !== "string" && (function_call == null ? void 0 : function_call.name);
2254
+ const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {};
2255
+ const functionsByName = {};
2256
+ for (const f of params.functions) {
2257
+ functionsByName[f.name || f.function.name] = f;
2258
+ }
2259
+ const functions = params.functions.map((f) => ({
2260
+ name: f.name || f.function.name,
2261
+ parameters: f.parameters,
2262
+ description: f.description
2263
+ }));
2264
+ for (const message of params.messages) {
2265
+ this._addMessage(message, false);
2266
+ }
2267
+ for (let i = 0; i < maxChatCompletions; ++i) {
2268
+ const chatCompletion = await this._createChatCompletion(completions, {
2269
+ ...restParams,
2270
+ function_call,
2271
+ functions,
2272
+ messages: [...this.messages]
2273
+ }, options);
2274
+ const message = (_a2 = chatCompletion.choices[0]) == null ? void 0 : _a2.message;
2275
+ if (!message) {
2276
+ throw new OpenAIError(`missing message in ChatCompletion response`);
2277
+ }
2278
+ if (!message.function_call)
2279
+ return;
2280
+ const { name, arguments: args } = message.function_call;
2281
+ const fn = functionsByName[name];
2282
+ if (!fn) {
2283
+ const content2 = `Invalid function_call: ${JSON.stringify(name)}. Available options are: ${functions.map((f) => JSON.stringify(f.name)).join(", ")}. Please try again`;
2284
+ this._addMessage({ role, name, content: content2 });
2285
+ continue;
2286
+ } else if (singleFunctionToCall && singleFunctionToCall !== name) {
2287
+ const content2 = `Invalid function_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`;
2288
+ this._addMessage({ role, name, content: content2 });
2289
+ continue;
2290
+ }
2291
+ let parsed;
2292
+ try {
2293
+ parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args;
2294
+ } catch (error) {
2295
+ this._addMessage({
2296
+ role,
2297
+ name,
2298
+ content: error instanceof Error ? error.message : String(error)
2299
+ });
2300
+ continue;
2301
+ }
2302
+ const rawContent = await fn.function(parsed, this);
2303
+ const content = __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent);
2304
+ this._addMessage({ role, name, content });
2305
+ if (singleFunctionToCall)
2306
+ return;
2307
+ }
2308
+ }
2309
+ async _runTools(completions, params, options) {
2310
+ var _a2, _b;
2311
+ const role = "tool";
2312
+ const { tool_choice = "auto", stream, ...restParams } = params;
2313
+ const singleFunctionToCall = typeof tool_choice !== "string" && ((_a2 = tool_choice == null ? void 0 : tool_choice.function) == null ? void 0 : _a2.name);
2314
+ const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {};
2315
+ const functionsByName = {};
2316
+ for (const f of params.tools) {
2317
+ if (f.type === "function") {
2318
+ functionsByName[f.function.name || f.function.function.name] = f.function;
2319
+ }
2320
+ }
2321
+ const tools = "tools" in params ? params.tools.map((t) => t.type === "function" ? {
2322
+ type: "function",
2323
+ function: {
2324
+ name: t.function.name || t.function.function.name,
2325
+ parameters: t.function.parameters,
2326
+ description: t.function.description
2327
+ }
2328
+ } : t) : void 0;
2329
+ for (const message of params.messages) {
2330
+ this._addMessage(message, false);
2331
+ }
2332
+ for (let i = 0; i < maxChatCompletions; ++i) {
2333
+ const chatCompletion = await this._createChatCompletion(completions, {
2334
+ ...restParams,
2335
+ tool_choice,
2336
+ tools,
2337
+ messages: [...this.messages]
2338
+ }, options);
2339
+ const message = (_b = chatCompletion.choices[0]) == null ? void 0 : _b.message;
2340
+ if (!message) {
2341
+ throw new OpenAIError(`missing message in ChatCompletion response`);
2342
+ }
2343
+ if (!message.tool_calls) {
2344
+ return;
2345
+ }
2346
+ for (const tool_call of message.tool_calls) {
2347
+ if (tool_call.type !== "function")
2348
+ continue;
2349
+ const tool_call_id = tool_call.id;
2350
+ const { name, arguments: args } = tool_call.function;
2351
+ const fn = functionsByName[name];
2352
+ if (!fn) {
2353
+ const content2 = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${tools.map((f) => JSON.stringify(f.function.name)).join(", ")}. Please try again`;
2354
+ this._addMessage({ role, tool_call_id, content: content2 });
2355
+ continue;
2356
+ } else if (singleFunctionToCall && singleFunctionToCall !== name) {
2357
+ const content2 = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`;
2358
+ this._addMessage({ role, tool_call_id, content: content2 });
2359
+ continue;
2360
+ }
2361
+ let parsed;
2362
+ try {
2363
+ parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args;
2364
+ } catch (error) {
2365
+ const content2 = error instanceof Error ? error.message : String(error);
2366
+ this._addMessage({ role, tool_call_id, content: content2 });
2367
+ continue;
2368
+ }
2369
+ const rawContent = await fn.function(parsed, this);
2370
+ const content = __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent);
2371
+ this._addMessage({ role, tool_call_id, content });
2372
+ if (singleFunctionToCall) {
2373
+ return;
2374
+ }
2375
+ }
2376
+ }
2377
+ return;
2378
+ }
2379
+ };
2380
+ _AbstractChatCompletionRunner_connectedPromise = /* @__PURE__ */ new WeakMap(), _AbstractChatCompletionRunner_resolveConnectedPromise = /* @__PURE__ */ new WeakMap(), _AbstractChatCompletionRunner_rejectConnectedPromise = /* @__PURE__ */ new WeakMap(), _AbstractChatCompletionRunner_endPromise = /* @__PURE__ */ new WeakMap(), _AbstractChatCompletionRunner_resolveEndPromise = /* @__PURE__ */ new WeakMap(), _AbstractChatCompletionRunner_rejectEndPromise = /* @__PURE__ */ new WeakMap(), _AbstractChatCompletionRunner_listeners = /* @__PURE__ */ new WeakMap(), _AbstractChatCompletionRunner_ended = /* @__PURE__ */ new WeakMap(), _AbstractChatCompletionRunner_errored = /* @__PURE__ */ new WeakMap(), _AbstractChatCompletionRunner_aborted = /* @__PURE__ */ new WeakMap(), _AbstractChatCompletionRunner_catchingPromiseCreated = /* @__PURE__ */ new WeakMap(), _AbstractChatCompletionRunner_handleError = /* @__PURE__ */ new WeakMap(), _AbstractChatCompletionRunner_instances = /* @__PURE__ */ new WeakSet(), _AbstractChatCompletionRunner_getFinalContent = function _AbstractChatCompletionRunner_getFinalContent2() {
2381
+ var _a2;
2382
+ return (_a2 = __classPrivateFieldGet4(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this).content) != null ? _a2 : null;
2383
+ }, _AbstractChatCompletionRunner_getFinalMessage = function _AbstractChatCompletionRunner_getFinalMessage2() {
2384
+ var _a2;
2385
+ let i = this.messages.length;
2386
+ while (i-- > 0) {
2387
+ const message = this.messages[i];
2388
+ if (isAssistantMessage(message)) {
2389
+ return { ...message, content: (_a2 = message.content) != null ? _a2 : null };
2390
+ }
2391
+ }
2392
+ throw new OpenAIError("stream ended without producing a ChatCompletionMessage with role=assistant");
2393
+ }, _AbstractChatCompletionRunner_getFinalFunctionCall = function _AbstractChatCompletionRunner_getFinalFunctionCall2() {
2394
+ var _a2, _b;
2395
+ for (let i = this.messages.length - 1; i >= 0; i--) {
2396
+ const message = this.messages[i];
2397
+ if (isAssistantMessage(message) && (message == null ? void 0 : message.function_call)) {
2398
+ return message.function_call;
2399
+ }
2400
+ if (isAssistantMessage(message) && ((_a2 = message == null ? void 0 : message.tool_calls) == null ? void 0 : _a2.length)) {
2401
+ return (_b = message.tool_calls.at(-1)) == null ? void 0 : _b.function;
2402
+ }
2403
+ }
2404
+ return;
2405
+ }, _AbstractChatCompletionRunner_getFinalFunctionCallResult = function _AbstractChatCompletionRunner_getFinalFunctionCallResult2() {
2406
+ for (let i = this.messages.length - 1; i >= 0; i--) {
2407
+ const message = this.messages[i];
2408
+ if (isFunctionMessage(message) && message.content != null) {
2409
+ return message.content;
2410
+ }
2411
+ if (isToolMessage(message) && message.content != null && this.messages.some((x) => {
2412
+ var _a2;
2413
+ return x.role === "assistant" && ((_a2 = x.tool_calls) == null ? void 0 : _a2.some((y) => y.type === "function" && y.id === message.tool_call_id));
2414
+ })) {
2415
+ return message.content;
2416
+ }
2417
+ }
2418
+ return;
2419
+ }, _AbstractChatCompletionRunner_calculateTotalUsage = function _AbstractChatCompletionRunner_calculateTotalUsage2() {
2420
+ const total = {
2421
+ completion_tokens: 0,
2422
+ prompt_tokens: 0,
2423
+ total_tokens: 0
2424
+ };
2425
+ for (const { usage } of this._chatCompletions) {
2426
+ if (usage) {
2427
+ total.completion_tokens += usage.completion_tokens;
2428
+ total.prompt_tokens += usage.prompt_tokens;
2429
+ total.total_tokens += usage.total_tokens;
2430
+ }
2431
+ }
2432
+ return total;
2433
+ }, _AbstractChatCompletionRunner_validateParams = function _AbstractChatCompletionRunner_validateParams2(params) {
2434
+ if (params.n != null && params.n > 1) {
2435
+ throw new OpenAIError("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.");
2436
+ }
2437
+ }, _AbstractChatCompletionRunner_stringifyFunctionCallResult = function _AbstractChatCompletionRunner_stringifyFunctionCallResult2(rawContent) {
2438
+ return typeof rawContent === "string" ? rawContent : rawContent === void 0 ? "undefined" : JSON.stringify(rawContent);
2439
+ };
2440
+
2441
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/lib/ChatCompletionRunner.mjs
2442
+ var ChatCompletionRunner = class _ChatCompletionRunner extends AbstractChatCompletionRunner {
2443
+ /** @deprecated - please use `runTools` instead. */
2444
+ static runFunctions(completions, params, options) {
2445
+ const runner = new _ChatCompletionRunner();
2446
+ const opts = {
2447
+ ...options,
2448
+ headers: { ...options == null ? void 0 : options.headers, "X-Stainless-Helper-Method": "runFunctions" }
2449
+ };
2450
+ runner._run(() => runner._runFunctions(completions, params, opts));
2451
+ return runner;
2452
+ }
2453
+ static runTools(completions, params, options) {
2454
+ const runner = new _ChatCompletionRunner();
2455
+ const opts = {
2456
+ ...options,
2457
+ headers: { ...options == null ? void 0 : options.headers, "X-Stainless-Helper-Method": "runTools" }
2458
+ };
2459
+ runner._run(() => runner._runTools(completions, params, opts));
2460
+ return runner;
2461
+ }
2462
+ _addMessage(message) {
2463
+ super._addMessage(message);
2464
+ if (isAssistantMessage(message) && message.content) {
2465
+ this._emit("content", message.content);
2466
+ }
2467
+ }
2468
+ };
2469
+
2470
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/lib/ChatCompletionStream.mjs
2471
+ var __classPrivateFieldGet5 = function(receiver, state, kind2, f) {
2472
+ if (kind2 === "a" && !f)
2473
+ throw new TypeError("Private accessor was defined without a getter");
2474
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
2475
+ throw new TypeError("Cannot read private member from an object whose class did not declare it");
2476
+ return kind2 === "m" ? f : kind2 === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
2477
+ };
2478
+ var __classPrivateFieldSet4 = function(receiver, state, value, kind2, f) {
2479
+ if (kind2 === "m")
2480
+ throw new TypeError("Private method is not writable");
2481
+ if (kind2 === "a" && !f)
2482
+ throw new TypeError("Private accessor was defined without a setter");
2483
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
2484
+ throw new TypeError("Cannot write private member to an object whose class did not declare it");
2485
+ return kind2 === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
2486
+ };
2487
+ var _ChatCompletionStream_instances;
2488
+ var _ChatCompletionStream_currentChatCompletionSnapshot;
2489
+ var _ChatCompletionStream_beginRequest;
2490
+ var _ChatCompletionStream_addChunk;
2491
+ var _ChatCompletionStream_endRequest;
2492
+ var _ChatCompletionStream_accumulateChatCompletion;
2493
+ var ChatCompletionStream = class _ChatCompletionStream extends AbstractChatCompletionRunner {
2494
+ constructor() {
2495
+ super(...arguments);
2496
+ _ChatCompletionStream_instances.add(this);
2497
+ _ChatCompletionStream_currentChatCompletionSnapshot.set(this, void 0);
2498
+ }
2499
+ get currentChatCompletionSnapshot() {
2500
+ return __classPrivateFieldGet5(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
2501
+ }
2502
+ /**
2503
+ * Intended for use on the frontend, consuming a stream produced with
2504
+ * `.toReadableStream()` on the backend.
2505
+ *
2506
+ * Note that messages sent to the model do not appear in `.on('message')`
2507
+ * in this context.
2508
+ */
2509
+ static fromReadableStream(stream) {
2510
+ const runner = new _ChatCompletionStream();
2511
+ runner._run(() => runner._fromReadableStream(stream));
2512
+ return runner;
2513
+ }
2514
+ static createChatCompletion(completions, params, options) {
2515
+ const runner = new _ChatCompletionStream();
2516
+ runner._run(() => runner._runChatCompletion(completions, { ...params, stream: true }, { ...options, headers: { ...options == null ? void 0 : options.headers, "X-Stainless-Helper-Method": "stream" } }));
2517
+ return runner;
2518
+ }
2519
+ async _createChatCompletion(completions, params, options) {
2520
+ var _a2;
2521
+ const signal = options == null ? void 0 : options.signal;
2522
+ if (signal) {
2523
+ if (signal.aborted)
2524
+ this.controller.abort();
2525
+ signal.addEventListener("abort", () => this.controller.abort());
2526
+ }
2527
+ __classPrivateFieldGet5(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
2528
+ const stream = await completions.create({ ...params, stream: true }, { ...options, signal: this.controller.signal });
2529
+ this._connected();
2530
+ for await (const chunk of stream) {
2531
+ __classPrivateFieldGet5(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
2532
+ }
2533
+ if ((_a2 = stream.controller.signal) == null ? void 0 : _a2.aborted) {
2534
+ throw new APIUserAbortError();
2535
+ }
2536
+ return this._addChatCompletion(__classPrivateFieldGet5(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
2537
+ }
2538
+ async _fromReadableStream(readableStream, options) {
2539
+ var _a2;
2540
+ const signal = options == null ? void 0 : options.signal;
2541
+ if (signal) {
2542
+ if (signal.aborted)
2543
+ this.controller.abort();
2544
+ signal.addEventListener("abort", () => this.controller.abort());
2545
+ }
2546
+ __classPrivateFieldGet5(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
2547
+ this._connected();
2548
+ const stream = Stream.fromReadableStream(readableStream, this.controller);
2549
+ let chatId;
2550
+ for await (const chunk of stream) {
2551
+ if (chatId && chatId !== chunk.id) {
2552
+ this._addChatCompletion(__classPrivateFieldGet5(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
2553
+ }
2554
+ __classPrivateFieldGet5(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
2555
+ chatId = chunk.id;
2556
+ }
2557
+ if ((_a2 = stream.controller.signal) == null ? void 0 : _a2.aborted) {
2558
+ throw new APIUserAbortError();
2559
+ }
2560
+ return this._addChatCompletion(__classPrivateFieldGet5(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
2561
+ }
2562
+ [(_ChatCompletionStream_currentChatCompletionSnapshot = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_instances = /* @__PURE__ */ new WeakSet(), _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest2() {
2563
+ if (this.ended)
2564
+ return;
2565
+ __classPrivateFieldSet4(this, _ChatCompletionStream_currentChatCompletionSnapshot, void 0, "f");
2566
+ }, _ChatCompletionStream_addChunk = function _ChatCompletionStream_addChunk2(chunk) {
2567
+ var _a2, _b, _c;
2568
+ if (this.ended)
2569
+ return;
2570
+ const completion = __classPrivateFieldGet5(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk);
2571
+ this._emit("chunk", chunk, completion);
2572
+ const delta = (_b = (_a2 = chunk.choices[0]) == null ? void 0 : _a2.delta) == null ? void 0 : _b.content;
2573
+ const snapshot = (_c = completion.choices[0]) == null ? void 0 : _c.message;
2574
+ if (delta != null && (snapshot == null ? void 0 : snapshot.role) === "assistant" && (snapshot == null ? void 0 : snapshot.content)) {
2575
+ this._emit("content", delta, snapshot.content);
2576
+ }
2577
+ }, _ChatCompletionStream_endRequest = function _ChatCompletionStream_endRequest2() {
2578
+ if (this.ended) {
2579
+ throw new OpenAIError(`stream has ended, this shouldn't happen`);
2580
+ }
2581
+ const snapshot = __classPrivateFieldGet5(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
2582
+ if (!snapshot) {
2583
+ throw new OpenAIError(`request ended without sending any chunks`);
2584
+ }
2585
+ __classPrivateFieldSet4(this, _ChatCompletionStream_currentChatCompletionSnapshot, void 0, "f");
2586
+ return finalizeChatCompletion(snapshot);
2587
+ }, _ChatCompletionStream_accumulateChatCompletion = function _ChatCompletionStream_accumulateChatCompletion2(chunk) {
2588
+ var _a3, _b2, _c2, _d;
2589
+ var _a2, _b, _c;
2590
+ let snapshot = __classPrivateFieldGet5(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
2591
+ const { choices, ...rest } = chunk;
2592
+ if (!snapshot) {
2593
+ snapshot = __classPrivateFieldSet4(this, _ChatCompletionStream_currentChatCompletionSnapshot, {
2594
+ ...rest,
2595
+ choices: []
2596
+ }, "f");
2597
+ } else {
2598
+ Object.assign(snapshot, rest);
2599
+ }
2600
+ for (const { delta, finish_reason, index, logprobs = null, ...other } of chunk.choices) {
2601
+ let choice = snapshot.choices[index];
2602
+ if (!choice) {
2603
+ choice = snapshot.choices[index] = { finish_reason, index, message: {}, logprobs, ...other };
2604
+ }
2605
+ if (logprobs) {
2606
+ if (!choice.logprobs) {
2607
+ choice.logprobs = Object.assign({}, logprobs);
2608
+ } else {
2609
+ const { content: content2, ...rest3 } = logprobs;
2610
+ Object.assign(choice.logprobs, rest3);
2611
+ if (content2) {
2612
+ (_a3 = (_a2 = choice.logprobs).content) != null ? _a3 : _a2.content = [];
2613
+ choice.logprobs.content.push(...content2);
2614
+ }
2615
+ }
2616
+ }
2617
+ if (finish_reason)
2618
+ choice.finish_reason = finish_reason;
2619
+ Object.assign(choice, other);
2620
+ if (!delta)
2621
+ continue;
2622
+ const { content, function_call, role, tool_calls, ...rest2 } = delta;
2623
+ Object.assign(choice.message, rest2);
2624
+ if (content)
2625
+ choice.message.content = (choice.message.content || "") + content;
2626
+ if (role)
2627
+ choice.message.role = role;
2628
+ if (function_call) {
2629
+ if (!choice.message.function_call) {
2630
+ choice.message.function_call = function_call;
2631
+ } else {
2632
+ if (function_call.name)
2633
+ choice.message.function_call.name = function_call.name;
2634
+ if (function_call.arguments) {
2635
+ (_b2 = (_b = choice.message.function_call).arguments) != null ? _b2 : _b.arguments = "";
2636
+ choice.message.function_call.arguments += function_call.arguments;
2637
+ }
2638
+ }
2639
+ }
2640
+ if (tool_calls) {
2641
+ if (!choice.message.tool_calls)
2642
+ choice.message.tool_calls = [];
2643
+ for (const { index: index2, id, type, function: fn, ...rest3 } of tool_calls) {
2644
+ const tool_call = (_c2 = (_c = choice.message.tool_calls)[index2]) != null ? _c2 : _c[index2] = {};
2645
+ Object.assign(tool_call, rest3);
2646
+ if (id)
2647
+ tool_call.id = id;
2648
+ if (type)
2649
+ tool_call.type = type;
2650
+ if (fn)
2651
+ (_d = tool_call.function) != null ? _d : tool_call.function = { arguments: "" };
2652
+ if (fn == null ? void 0 : fn.name)
2653
+ tool_call.function.name = fn.name;
2654
+ if (fn == null ? void 0 : fn.arguments)
2655
+ tool_call.function.arguments += fn.arguments;
2656
+ }
2657
+ }
2658
+ }
2659
+ return snapshot;
2660
+ }, Symbol.asyncIterator)]() {
2661
+ const pushQueue = [];
2662
+ const readQueue = [];
2663
+ let done = false;
2664
+ this.on("chunk", (chunk) => {
2665
+ const reader = readQueue.shift();
2666
+ if (reader) {
2667
+ reader(chunk);
2668
+ } else {
2669
+ pushQueue.push(chunk);
2670
+ }
2671
+ });
2672
+ this.on("end", () => {
2673
+ done = true;
2674
+ for (const reader of readQueue) {
2675
+ reader(void 0);
2676
+ }
2677
+ readQueue.length = 0;
2678
+ });
2679
+ return {
2680
+ next: async () => {
2681
+ if (!pushQueue.length) {
2682
+ if (done) {
2683
+ return { value: void 0, done: true };
2684
+ }
2685
+ return new Promise((resolve) => readQueue.push(resolve)).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
2686
+ }
2687
+ const chunk = pushQueue.shift();
2688
+ return { value: chunk, done: false };
2689
+ }
2690
+ };
2691
+ }
2692
+ toReadableStream() {
2693
+ const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);
2694
+ return stream.toReadableStream();
2695
+ }
2696
+ };
2697
+ function finalizeChatCompletion(snapshot) {
2698
+ const { id, choices, created, model, system_fingerprint, ...rest } = snapshot;
2699
+ return {
2700
+ ...rest,
2701
+ id,
2702
+ choices: choices.map(({ message, finish_reason, index, logprobs, ...choiceRest }) => {
2703
+ if (!finish_reason)
2704
+ throw new OpenAIError(`missing finish_reason for choice ${index}`);
2705
+ const { content = null, function_call, tool_calls, ...messageRest } = message;
2706
+ const role = message.role;
2707
+ if (!role)
2708
+ throw new OpenAIError(`missing role for choice ${index}`);
2709
+ if (function_call) {
2710
+ const { arguments: args, name } = function_call;
2711
+ if (args == null)
2712
+ throw new OpenAIError(`missing function_call.arguments for choice ${index}`);
2713
+ if (!name)
2714
+ throw new OpenAIError(`missing function_call.name for choice ${index}`);
2715
+ return {
2716
+ ...choiceRest,
2717
+ message: { content, function_call: { arguments: args, name }, role },
2718
+ finish_reason,
2719
+ index,
2720
+ logprobs
2721
+ };
2722
+ }
2723
+ if (tool_calls) {
2724
+ return {
2725
+ ...choiceRest,
2726
+ index,
2727
+ finish_reason,
2728
+ logprobs,
2729
+ message: {
2730
+ ...messageRest,
2731
+ role,
2732
+ content,
2733
+ tool_calls: tool_calls.map((tool_call, i) => {
2734
+ const { function: fn, type, id: id2, ...toolRest } = tool_call;
2735
+ const { arguments: args, name, ...fnRest } = fn || {};
2736
+ if (id2 == null)
2737
+ throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].id
2738
+ ${str(snapshot)}`);
2739
+ if (type == null)
2740
+ throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].type
2741
+ ${str(snapshot)}`);
2742
+ if (name == null)
2743
+ throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.name
2744
+ ${str(snapshot)}`);
2745
+ if (args == null)
2746
+ throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.arguments
2747
+ ${str(snapshot)}`);
2748
+ return { ...toolRest, id: id2, type, function: { ...fnRest, name, arguments: args } };
2749
+ })
2750
+ }
2751
+ };
2752
+ }
2753
+ return {
2754
+ ...choiceRest,
2755
+ message: { ...messageRest, content, role },
2756
+ finish_reason,
2757
+ index,
2758
+ logprobs
2759
+ };
2760
+ }),
2761
+ created,
2762
+ model,
2763
+ object: "chat.completion",
2764
+ ...system_fingerprint ? { system_fingerprint } : {}
2765
+ };
2766
+ }
2767
+ function str(x) {
2768
+ return JSON.stringify(x);
2769
+ }
2770
+
2771
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs
2772
+ var ChatCompletionStreamingRunner = class _ChatCompletionStreamingRunner extends ChatCompletionStream {
2773
+ static fromReadableStream(stream) {
2774
+ const runner = new _ChatCompletionStreamingRunner();
2775
+ runner._run(() => runner._fromReadableStream(stream));
2776
+ return runner;
2777
+ }
2778
+ /** @deprecated - please use `runTools` instead. */
2779
+ static runFunctions(completions, params, options) {
2780
+ const runner = new _ChatCompletionStreamingRunner();
2781
+ const opts = {
2782
+ ...options,
2783
+ headers: { ...options == null ? void 0 : options.headers, "X-Stainless-Helper-Method": "runFunctions" }
2784
+ };
2785
+ runner._run(() => runner._runFunctions(completions, params, opts));
2786
+ return runner;
2787
+ }
2788
+ static runTools(completions, params, options) {
2789
+ const runner = new _ChatCompletionStreamingRunner();
2790
+ const opts = {
2791
+ ...options,
2792
+ headers: { ...options == null ? void 0 : options.headers, "X-Stainless-Helper-Method": "runTools" }
2793
+ };
2794
+ runner._run(() => runner._runTools(completions, params, opts));
2795
+ return runner;
2796
+ }
2797
+ };
2798
+
2799
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/resources/beta/chat/completions.mjs
2800
+ var Completions2 = class extends APIResource {
2801
+ runFunctions(body, options) {
2802
+ if (body.stream) {
2803
+ return ChatCompletionStreamingRunner.runFunctions(this._client.chat.completions, body, options);
2804
+ }
2805
+ return ChatCompletionRunner.runFunctions(this._client.chat.completions, body, options);
2806
+ }
2807
+ runTools(body, options) {
2808
+ if (body.stream) {
2809
+ return ChatCompletionStreamingRunner.runTools(this._client.chat.completions, body, options);
2810
+ }
2811
+ return ChatCompletionRunner.runTools(this._client.chat.completions, body, options);
2812
+ }
2813
+ /**
2814
+ * Creates a chat completion stream
2815
+ */
2816
+ stream(body, options) {
2817
+ return ChatCompletionStream.createChatCompletion(this._client.chat.completions, body, options);
2818
+ }
2819
+ };
2820
+
2821
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/resources/beta/chat/chat.mjs
2822
+ var Chat2 = class extends APIResource {
2823
+ constructor() {
2824
+ super(...arguments);
2825
+ this.completions = new Completions2(this._client);
2826
+ }
2827
+ };
2828
+ (function(Chat3) {
2829
+ Chat3.Completions = Completions2;
2830
+ })(Chat2 || (Chat2 = {}));
2831
+
2832
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/resources/beta/threads/messages/files.mjs
2833
+ var Files2 = class extends APIResource {
2834
+ /**
2835
+ * Retrieves a message file.
2836
+ */
2837
+ retrieve(threadId, messageId, fileId, options) {
2838
+ return this._client.get(`/threads/${threadId}/messages/${messageId}/files/${fileId}`, {
2839
+ ...options,
2840
+ headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers }
2841
+ });
2842
+ }
2843
+ list(threadId, messageId, query = {}, options) {
2844
+ if (isRequestOptions(query)) {
2845
+ return this.list(threadId, messageId, {}, query);
2846
+ }
2847
+ return this._client.getAPIList(`/threads/${threadId}/messages/${messageId}/files`, MessageFilesPage, {
2848
+ query,
2849
+ ...options,
2850
+ headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers }
2851
+ });
2852
+ }
2853
+ };
2854
+ var MessageFilesPage = class extends CursorPage {
2855
+ };
2856
+ (function(Files4) {
2857
+ Files4.MessageFilesPage = MessageFilesPage;
2858
+ })(Files2 || (Files2 = {}));
2859
+
2860
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/resources/beta/threads/messages/messages.mjs
2861
+ var Messages = class extends APIResource {
2862
+ constructor() {
2863
+ super(...arguments);
2864
+ this.files = new Files2(this._client);
2865
+ }
2866
+ /**
2867
+ * Create a message.
2868
+ */
2869
+ create(threadId, body, options) {
2870
+ return this._client.post(`/threads/${threadId}/messages`, {
2871
+ body,
2872
+ ...options,
2873
+ headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers }
2874
+ });
2875
+ }
2876
+ /**
2877
+ * Retrieve a message.
2878
+ */
2879
+ retrieve(threadId, messageId, options) {
2880
+ return this._client.get(`/threads/${threadId}/messages/${messageId}`, {
2881
+ ...options,
2882
+ headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers }
2883
+ });
2884
+ }
2885
+ /**
2886
+ * Modifies a message.
2887
+ */
2888
+ update(threadId, messageId, body, options) {
2889
+ return this._client.post(`/threads/${threadId}/messages/${messageId}`, {
2890
+ body,
2891
+ ...options,
2892
+ headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers }
2893
+ });
2894
+ }
2895
+ list(threadId, query = {}, options) {
2896
+ if (isRequestOptions(query)) {
2897
+ return this.list(threadId, {}, query);
2898
+ }
2899
+ return this._client.getAPIList(`/threads/${threadId}/messages`, ThreadMessagesPage, {
2900
+ query,
2901
+ ...options,
2902
+ headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers }
2903
+ });
2904
+ }
2905
+ };
2906
+ var ThreadMessagesPage = class extends CursorPage {
2907
+ };
2908
+ (function(Messages2) {
2909
+ Messages2.ThreadMessagesPage = ThreadMessagesPage;
2910
+ Messages2.Files = Files2;
2911
+ Messages2.MessageFilesPage = MessageFilesPage;
2912
+ })(Messages || (Messages = {}));
2913
+
2914
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/resources/beta/threads/runs/steps.mjs
2915
+ var Steps = class extends APIResource {
2916
+ /**
2917
+ * Retrieves a run step.
2918
+ */
2919
+ retrieve(threadId, runId, stepId, options) {
2920
+ return this._client.get(`/threads/${threadId}/runs/${runId}/steps/${stepId}`, {
2921
+ ...options,
2922
+ headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers }
2923
+ });
2924
+ }
2925
+ list(threadId, runId, query = {}, options) {
2926
+ if (isRequestOptions(query)) {
2927
+ return this.list(threadId, runId, {}, query);
2928
+ }
2929
+ return this._client.getAPIList(`/threads/${threadId}/runs/${runId}/steps`, RunStepsPage, {
2930
+ query,
2931
+ ...options,
2932
+ headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers }
2933
+ });
2934
+ }
2935
+ };
2936
+ var RunStepsPage = class extends CursorPage {
2937
+ };
2938
+ (function(Steps2) {
2939
+ Steps2.RunStepsPage = RunStepsPage;
2940
+ })(Steps || (Steps = {}));
2941
+
2942
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/resources/beta/threads/runs/runs.mjs
2943
+ var Runs = class extends APIResource {
2944
+ constructor() {
2945
+ super(...arguments);
2946
+ this.steps = new Steps(this._client);
2947
+ }
2948
+ /**
2949
+ * Create a run.
2950
+ */
2951
+ create(threadId, body, options) {
2952
+ return this._client.post(`/threads/${threadId}/runs`, {
2953
+ body,
2954
+ ...options,
2955
+ headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers }
2956
+ });
2957
+ }
2958
+ /**
2959
+ * Retrieves a run.
2960
+ */
2961
+ retrieve(threadId, runId, options) {
2962
+ return this._client.get(`/threads/${threadId}/runs/${runId}`, {
2963
+ ...options,
2964
+ headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers }
2965
+ });
2966
+ }
2967
+ /**
2968
+ * Modifies a run.
2969
+ */
2970
+ update(threadId, runId, body, options) {
2971
+ return this._client.post(`/threads/${threadId}/runs/${runId}`, {
2972
+ body,
2973
+ ...options,
2974
+ headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers }
2975
+ });
2976
+ }
2977
+ list(threadId, query = {}, options) {
2978
+ if (isRequestOptions(query)) {
2979
+ return this.list(threadId, {}, query);
2980
+ }
2981
+ return this._client.getAPIList(`/threads/${threadId}/runs`, RunsPage, {
2982
+ query,
2983
+ ...options,
2984
+ headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers }
2985
+ });
2986
+ }
2987
+ /**
2988
+ * Cancels a run that is `in_progress`.
2989
+ */
2990
+ cancel(threadId, runId, options) {
2991
+ return this._client.post(`/threads/${threadId}/runs/${runId}/cancel`, {
2992
+ ...options,
2993
+ headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers }
2994
+ });
2995
+ }
2996
+ /**
2997
+ * When a run has the `status: "requires_action"` and `required_action.type` is
2998
+ * `submit_tool_outputs`, this endpoint can be used to submit the outputs from the
2999
+ * tool calls once they're all completed. All outputs must be submitted in a single
3000
+ * request.
3001
+ */
3002
+ submitToolOutputs(threadId, runId, body, options) {
3003
+ return this._client.post(`/threads/${threadId}/runs/${runId}/submit_tool_outputs`, {
3004
+ body,
3005
+ ...options,
3006
+ headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers }
3007
+ });
3008
+ }
3009
+ };
3010
+ var RunsPage = class extends CursorPage {
3011
+ };
3012
+ (function(Runs2) {
3013
+ Runs2.RunsPage = RunsPage;
3014
+ Runs2.Steps = Steps;
3015
+ Runs2.RunStepsPage = RunStepsPage;
3016
+ })(Runs || (Runs = {}));
3017
+
3018
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/resources/beta/threads/threads.mjs
3019
+ var Threads = class extends APIResource {
3020
+ constructor() {
3021
+ super(...arguments);
3022
+ this.runs = new Runs(this._client);
3023
+ this.messages = new Messages(this._client);
3024
+ }
3025
+ create(body = {}, options) {
3026
+ if (isRequestOptions(body)) {
3027
+ return this.create({}, body);
3028
+ }
3029
+ return this._client.post("/threads", {
3030
+ body,
3031
+ ...options,
3032
+ headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers }
3033
+ });
3034
+ }
3035
+ /**
3036
+ * Retrieves a thread.
3037
+ */
3038
+ retrieve(threadId, options) {
3039
+ return this._client.get(`/threads/${threadId}`, {
3040
+ ...options,
3041
+ headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers }
3042
+ });
3043
+ }
3044
+ /**
3045
+ * Modifies a thread.
3046
+ */
3047
+ update(threadId, body, options) {
3048
+ return this._client.post(`/threads/${threadId}`, {
3049
+ body,
3050
+ ...options,
3051
+ headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers }
3052
+ });
3053
+ }
3054
+ /**
3055
+ * Delete a thread.
3056
+ */
3057
+ del(threadId, options) {
3058
+ return this._client.delete(`/threads/${threadId}`, {
3059
+ ...options,
3060
+ headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers }
3061
+ });
3062
+ }
3063
+ /**
3064
+ * Create a thread and run it in one request.
3065
+ */
3066
+ createAndRun(body, options) {
3067
+ return this._client.post("/threads/runs", {
3068
+ body,
3069
+ ...options,
3070
+ headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers }
3071
+ });
3072
+ }
3073
+ };
3074
+ (function(Threads2) {
3075
+ Threads2.Runs = Runs;
3076
+ Threads2.RunsPage = RunsPage;
3077
+ Threads2.Messages = Messages;
3078
+ Threads2.ThreadMessagesPage = ThreadMessagesPage;
3079
+ })(Threads || (Threads = {}));
3080
+
3081
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/resources/beta/beta.mjs
3082
+ var Beta = class extends APIResource {
3083
+ constructor() {
3084
+ super(...arguments);
3085
+ this.chat = new Chat2(this._client);
3086
+ this.assistants = new Assistants(this._client);
3087
+ this.threads = new Threads(this._client);
3088
+ }
3089
+ };
3090
+ (function(Beta2) {
3091
+ Beta2.Chat = Chat2;
3092
+ Beta2.Assistants = Assistants;
3093
+ Beta2.AssistantsPage = AssistantsPage;
3094
+ Beta2.Threads = Threads;
3095
+ })(Beta || (Beta = {}));
3096
+
3097
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/resources/completions.mjs
3098
+ var Completions3 = class extends APIResource {
3099
+ create(body, options) {
3100
+ var _a2;
3101
+ return this._client.post("/completions", { body, ...options, stream: (_a2 = body.stream) != null ? _a2 : false });
3102
+ }
3103
+ };
3104
+ /* @__PURE__ */ (function(Completions4) {
3105
+ })(Completions3 || (Completions3 = {}));
3106
+
3107
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/resources/embeddings.mjs
3108
+ var Embeddings = class extends APIResource {
3109
+ /**
3110
+ * Creates an embedding vector representing the input text.
3111
+ */
3112
+ create(body, options) {
3113
+ return this._client.post("/embeddings", { body, ...options });
3114
+ }
3115
+ };
3116
+ /* @__PURE__ */ (function(Embeddings2) {
3117
+ })(Embeddings || (Embeddings = {}));
3118
+
3119
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/resources/files.mjs
3120
+ var Files3 = class extends APIResource {
3121
+ /**
3122
+ * Upload a file that can be used across various endpoints. The size of all the
3123
+ * files uploaded by one organization can be up to 100 GB.
3124
+ *
3125
+ * The size of individual files can be a maximum of 512 MB or 2 million tokens for
3126
+ * Assistants. See the
3127
+ * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) to
3128
+ * learn more about the types of files supported. The Fine-tuning API only supports
3129
+ * `.jsonl` files.
3130
+ *
3131
+ * Please [contact us](https://help.openai.com/) if you need to increase these
3132
+ * storage limits.
3133
+ */
3134
+ create(body, options) {
3135
+ return this._client.post("/files", multipartFormRequestOptions({ body, ...options }));
3136
+ }
3137
+ /**
3138
+ * Returns information about a specific file.
3139
+ */
3140
+ retrieve(fileId, options) {
3141
+ return this._client.get(`/files/${fileId}`, options);
3142
+ }
3143
+ list(query = {}, options) {
3144
+ if (isRequestOptions(query)) {
3145
+ return this.list({}, query);
3146
+ }
3147
+ return this._client.getAPIList("/files", FileObjectsPage, { query, ...options });
3148
+ }
3149
+ /**
3150
+ * Delete a file.
3151
+ */
3152
+ del(fileId, options) {
3153
+ return this._client.delete(`/files/${fileId}`, options);
3154
+ }
3155
+ /**
3156
+ * Returns the contents of the specified file.
3157
+ */
3158
+ content(fileId, options) {
3159
+ return this._client.get(`/files/${fileId}/content`, { ...options, __binaryResponse: true });
3160
+ }
3161
+ /**
3162
+ * Returns the contents of the specified file.
3163
+ *
3164
+ * @deprecated The `.content()` method should be used instead
3165
+ */
3166
+ retrieveContent(fileId, options) {
3167
+ return this._client.get(`/files/${fileId}/content`, {
3168
+ ...options,
3169
+ headers: { Accept: "application/json", ...options == null ? void 0 : options.headers }
3170
+ });
3171
+ }
3172
+ /**
3173
+ * Waits for the given file to be processed, default timeout is 30 mins.
3174
+ */
3175
+ async waitForProcessing(id, { pollInterval = 5e3, maxWait = 30 * 60 * 1e3 } = {}) {
3176
+ const TERMINAL_STATES = /* @__PURE__ */ new Set(["processed", "error", "deleted"]);
3177
+ const start = Date.now();
3178
+ let file = await this.retrieve(id);
3179
+ while (!file.status || !TERMINAL_STATES.has(file.status)) {
3180
+ await sleep(pollInterval);
3181
+ file = await this.retrieve(id);
3182
+ if (Date.now() - start > maxWait) {
3183
+ throw new APIConnectionTimeoutError({
3184
+ message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`
3185
+ });
3186
+ }
3187
+ }
3188
+ return file;
3189
+ }
3190
+ };
3191
+ var FileObjectsPage = class extends Page {
3192
+ };
3193
+ (function(Files4) {
3194
+ Files4.FileObjectsPage = FileObjectsPage;
3195
+ })(Files3 || (Files3 = {}));
3196
+
3197
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/resources/fine-tuning/jobs.mjs
3198
+ var Jobs = class extends APIResource {
3199
+ /**
3200
+ * Creates a fine-tuning job which begins the process of creating a new model from
3201
+ * a given dataset.
3202
+ *
3203
+ * Response includes details of the enqueued job including job status and the name
3204
+ * of the fine-tuned models once complete.
3205
+ *
3206
+ * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning)
3207
+ */
3208
+ create(body, options) {
3209
+ return this._client.post("/fine_tuning/jobs", { body, ...options });
3210
+ }
3211
+ /**
3212
+ * Get info about a fine-tuning job.
3213
+ *
3214
+ * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning)
3215
+ */
3216
+ retrieve(fineTuningJobId, options) {
3217
+ return this._client.get(`/fine_tuning/jobs/${fineTuningJobId}`, options);
3218
+ }
3219
+ list(query = {}, options) {
3220
+ if (isRequestOptions(query)) {
3221
+ return this.list({}, query);
3222
+ }
3223
+ return this._client.getAPIList("/fine_tuning/jobs", FineTuningJobsPage, { query, ...options });
3224
+ }
3225
+ /**
3226
+ * Immediately cancel a fine-tune job.
3227
+ */
3228
+ cancel(fineTuningJobId, options) {
3229
+ return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/cancel`, options);
3230
+ }
3231
+ listEvents(fineTuningJobId, query = {}, options) {
3232
+ if (isRequestOptions(query)) {
3233
+ return this.listEvents(fineTuningJobId, {}, query);
3234
+ }
3235
+ return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/events`, FineTuningJobEventsPage, {
3236
+ query,
3237
+ ...options
3238
+ });
3239
+ }
3240
+ };
3241
+ var FineTuningJobsPage = class extends CursorPage {
3242
+ };
3243
+ var FineTuningJobEventsPage = class extends CursorPage {
3244
+ };
3245
+ (function(Jobs2) {
3246
+ Jobs2.FineTuningJobsPage = FineTuningJobsPage;
3247
+ Jobs2.FineTuningJobEventsPage = FineTuningJobEventsPage;
3248
+ })(Jobs || (Jobs = {}));
3249
+
3250
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/resources/fine-tuning/fine-tuning.mjs
3251
+ var FineTuning = class extends APIResource {
3252
+ constructor() {
3253
+ super(...arguments);
3254
+ this.jobs = new Jobs(this._client);
3255
+ }
3256
+ };
3257
+ (function(FineTuning2) {
3258
+ FineTuning2.Jobs = Jobs;
3259
+ FineTuning2.FineTuningJobsPage = FineTuningJobsPage;
3260
+ FineTuning2.FineTuningJobEventsPage = FineTuningJobEventsPage;
3261
+ })(FineTuning || (FineTuning = {}));
3262
+
3263
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/resources/images.mjs
3264
+ var Images = class extends APIResource {
3265
+ /**
3266
+ * Creates a variation of a given image.
3267
+ */
3268
+ createVariation(body, options) {
3269
+ return this._client.post("/images/variations", multipartFormRequestOptions({ body, ...options }));
3270
+ }
3271
+ /**
3272
+ * Creates an edited or extended image given an original image and a prompt.
3273
+ */
3274
+ edit(body, options) {
3275
+ return this._client.post("/images/edits", multipartFormRequestOptions({ body, ...options }));
3276
+ }
3277
+ /**
3278
+ * Creates an image given a prompt.
3279
+ */
3280
+ generate(body, options) {
3281
+ return this._client.post("/images/generations", { body, ...options });
3282
+ }
3283
+ };
3284
+ /* @__PURE__ */ (function(Images2) {
3285
+ })(Images || (Images = {}));
3286
+
3287
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/resources/models.mjs
3288
+ var Models = class extends APIResource {
3289
+ /**
3290
+ * Retrieves a model instance, providing basic information about the model such as
3291
+ * the owner and permissioning.
3292
+ */
3293
+ retrieve(model, options) {
3294
+ return this._client.get(`/models/${model}`, options);
3295
+ }
3296
+ /**
3297
+ * Lists the currently available models, and provides basic information about each
3298
+ * one such as the owner and availability.
3299
+ */
3300
+ list(options) {
3301
+ return this._client.getAPIList("/models", ModelsPage, options);
3302
+ }
3303
+ /**
3304
+ * Delete a fine-tuned model. You must have the Owner role in your organization to
3305
+ * delete a model.
3306
+ */
3307
+ del(model, options) {
3308
+ return this._client.delete(`/models/${model}`, options);
3309
+ }
3310
+ };
3311
+ var ModelsPage = class extends Page {
3312
+ };
3313
+ (function(Models2) {
3314
+ Models2.ModelsPage = ModelsPage;
3315
+ })(Models || (Models = {}));
3316
+
3317
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/resources/moderations.mjs
3318
+ var Moderations = class extends APIResource {
3319
+ /**
3320
+ * Classifies if text violates OpenAI's Content Policy
3321
+ */
3322
+ create(body, options) {
3323
+ return this._client.post("/moderations", { body, ...options });
3324
+ }
3325
+ };
3326
+ /* @__PURE__ */ (function(Moderations2) {
3327
+ })(Moderations || (Moderations = {}));
3328
+
3329
+ // ../../node_modules/.pnpm/openai@4.28.4/node_modules/openai/index.mjs
3330
+ var _a;
3331
+ var OpenAI = class extends APIClient {
3332
+ /**
3333
+ * API Client for interfacing with the OpenAI API.
3334
+ *
3335
+ * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined]
3336
+ * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null]
3337
+ * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API.
3338
+ * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
3339
+ * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.
3340
+ * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
3341
+ * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
3342
+ * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.
3343
+ * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.
3344
+ * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.
3345
+ */
3346
+ constructor({ baseURL = readEnv("OPENAI_BASE_URL"), apiKey = readEnv("OPENAI_API_KEY"), organization = ((_a2) => (_a2 = readEnv("OPENAI_ORG_ID")) != null ? _a2 : null)(), ...opts } = {}) {
3347
+ var _a3;
3348
+ if (apiKey === void 0) {
3349
+ throw new OpenAIError("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");
3350
+ }
3351
+ const options = {
3352
+ apiKey,
3353
+ organization,
3354
+ ...opts,
3355
+ baseURL: baseURL || `https://api.openai.com/v1`
3356
+ };
3357
+ if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) {
3358
+ throw new OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");
3359
+ }
3360
+ super({
3361
+ baseURL: options.baseURL,
3362
+ timeout: (_a3 = options.timeout) != null ? _a3 : 6e5,
3363
+ httpAgent: options.httpAgent,
3364
+ maxRetries: options.maxRetries,
3365
+ fetch: options.fetch
3366
+ });
3367
+ this.completions = new Completions3(this);
3368
+ this.chat = new Chat(this);
3369
+ this.embeddings = new Embeddings(this);
3370
+ this.files = new Files3(this);
3371
+ this.images = new Images(this);
3372
+ this.audio = new Audio(this);
3373
+ this.moderations = new Moderations(this);
3374
+ this.models = new Models(this);
3375
+ this.fineTuning = new FineTuning(this);
3376
+ this.beta = new Beta(this);
3377
+ this._options = options;
3378
+ this.apiKey = apiKey;
3379
+ this.organization = organization;
3380
+ }
3381
+ defaultQuery() {
3382
+ return this._options.defaultQuery;
3383
+ }
3384
+ defaultHeaders(opts) {
3385
+ return {
3386
+ ...super.defaultHeaders(opts),
3387
+ "OpenAI-Organization": this.organization,
3388
+ ...this._options.defaultHeaders
3389
+ };
3390
+ }
3391
+ authHeaders(opts) {
3392
+ return { Authorization: `Bearer ${this.apiKey}` };
3393
+ }
3394
+ };
3395
+ _a = OpenAI;
3396
+ OpenAI.OpenAI = _a;
3397
+ OpenAI.OpenAIError = OpenAIError;
3398
+ OpenAI.APIError = APIError;
3399
+ OpenAI.APIConnectionError = APIConnectionError;
3400
+ OpenAI.APIConnectionTimeoutError = APIConnectionTimeoutError;
3401
+ OpenAI.APIUserAbortError = APIUserAbortError;
3402
+ OpenAI.NotFoundError = NotFoundError;
3403
+ OpenAI.ConflictError = ConflictError;
3404
+ OpenAI.RateLimitError = RateLimitError;
3405
+ OpenAI.BadRequestError = BadRequestError;
3406
+ OpenAI.AuthenticationError = AuthenticationError;
3407
+ OpenAI.InternalServerError = InternalServerError;
3408
+ OpenAI.PermissionDeniedError = PermissionDeniedError;
3409
+ OpenAI.UnprocessableEntityError = UnprocessableEntityError;
3410
+ var { OpenAIError: OpenAIError2, APIError: APIError2, APIConnectionError: APIConnectionError2, APIConnectionTimeoutError: APIConnectionTimeoutError2, APIUserAbortError: APIUserAbortError2, NotFoundError: NotFoundError2, ConflictError: ConflictError2, RateLimitError: RateLimitError2, BadRequestError: BadRequestError2, AuthenticationError: AuthenticationError2, InternalServerError: InternalServerError2, PermissionDeniedError: PermissionDeniedError2, UnprocessableEntityError: UnprocessableEntityError2 } = error_exports;
3411
+ var toFile2 = toFile;
3412
+ var fileFromPath3 = fileFromPath;
3413
+ (function(OpenAI2) {
3414
+ OpenAI2.toFile = toFile;
3415
+ OpenAI2.fileFromPath = fileFromPath;
3416
+ OpenAI2.Page = Page;
3417
+ OpenAI2.CursorPage = CursorPage;
3418
+ OpenAI2.Completions = Completions3;
3419
+ OpenAI2.Chat = Chat;
3420
+ OpenAI2.Embeddings = Embeddings;
3421
+ OpenAI2.Files = Files3;
3422
+ OpenAI2.FileObjectsPage = FileObjectsPage;
3423
+ OpenAI2.Images = Images;
3424
+ OpenAI2.Audio = Audio;
3425
+ OpenAI2.Moderations = Moderations;
3426
+ OpenAI2.Models = Models;
3427
+ OpenAI2.ModelsPage = ModelsPage;
3428
+ OpenAI2.FineTuning = FineTuning;
3429
+ OpenAI2.Beta = Beta;
3430
+ })(OpenAI || (OpenAI = {}));
3431
+ var openai_default = OpenAI;
3432
+ export {
3433
+ APIConnectionError2 as APIConnectionError,
3434
+ APIConnectionTimeoutError2 as APIConnectionTimeoutError,
3435
+ APIError2 as APIError,
3436
+ APIUserAbortError2 as APIUserAbortError,
3437
+ AuthenticationError2 as AuthenticationError,
3438
+ BadRequestError2 as BadRequestError,
3439
+ ConflictError2 as ConflictError,
3440
+ InternalServerError2 as InternalServerError,
3441
+ NotFoundError2 as NotFoundError,
3442
+ OpenAI,
3443
+ OpenAIError2 as OpenAIError,
3444
+ PermissionDeniedError2 as PermissionDeniedError,
3445
+ RateLimitError2 as RateLimitError,
3446
+ UnprocessableEntityError2 as UnprocessableEntityError,
3447
+ openai_default as default,
3448
+ fileFromPath3 as fileFromPath,
3449
+ toFile2 as toFile
3450
+ };
3451
+ //# sourceMappingURL=openai-3YL4AWLI.mjs.map