-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbundle.js
More file actions
8682 lines (8271 loc) · 336 KB
/
Copy pathbundle.js
File metadata and controls
8682 lines (8271 loc) · 336 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
const { OpenAI } = require("openai");
const openai = new OpenAI({
apiKey: "1234567abcd",
baseURL: "https://api.aimlapi.com",
dangerouslyAllowBrowser: true
});
//mistralai/Mistral-7B-Instruct-v0.2
// vaihda malliksi gpt-4 testiä varter
//meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo
document.getElementById("button1").addEventListener("click", calculate);
const copying = document.getElementById("result-container");
// jos inputti ei toimi siirrä se function calculayte() sisään takaisin
function calculate () {
let results = document.getElementById("result");
let inputti = "Here's a problem for you, if my solution is wrong tell me what is wrong with my solution and then solve it for me step by step, I also might not have a solution of my own if you only see a problem then solve it" + document.getElementById("input").value;
input.addEventListener("keypress", (e) => {
if (e.key === "Enter") {
calculate()
}
})
let loadingAnimation = document.getElementById("loading-animation");
// Show the loading animation
loadingAnimation.style.display = 'block';
results.textContent = '';
(async () => {
const chatCompletion = await openai.chat.completions.create({
model: "gpt-4",
messages: [
{ role: "system", content: "You are a high school math teacher be helpful and accurate, give me step by step instructions on how to solve the problem I gave you, dont say anything unnessesary, asnwer to me in finnish. Use inline LaTeX for short equations and block LaTeX (using `$$ ... $$`) for larger equations. Ensure all LaTeX code is properly enclosed, and avoid splitting LaTeX across lines., if i give you solution that is wrong tell me what excactly what is with my answer before giving me the right answer. If answer is too long you can skip some steps and make it shorter but always give me result"},
{ role: "user", content: inputti}
],
temperature: 0.2,
max_tokens: 380,
});
// if innerhtml doesnt work try textcontent or console.log
// console.log(chatCompletion.choices[0].message.content);
results.textContent = chatCompletion.choices[0].message.content;
setTimeout(() => {
MathJax.typesetPromise([results]);
}, 5000);
loadingAnimation.style.display = 'none';
copying.addEventListener('click', function() {
const rawLatex = chatCompletion.choices[0].message.content;
try {
navigator.clipboard.writeText(rawLatex)
} catch (error) {
console.error('Failed to copy: ', err);
}
});
})();
}
// const input = document.getElementById("input");
// const nappi = document.getElementById("button1");
// nappi.addEventListener("click", function() {
// try {
// calculate()
// console.log("code run started")
// } catch (error) {
// console.error('Code run failed')
// }
// })
// calculate()
},{"openai":10}],2:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MultipartBody = void 0;
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/
class MultipartBody {
constructor(body) {
this.body = body;
}
get [Symbol.toStringTag]() {
return 'MultipartBody';
}
}
exports.MultipartBody = MultipartBody;
},{}],3:[function(require,module,exports){
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/
__exportStar(require("../web-runtime.js"), exports);
},{"../web-runtime.js":6}],4:[function(require,module,exports){
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/
const shims = require('./registry');
const auto = require('openai/_shims/auto/runtime');
if (!shims.kind) shims.setShims(auto.getRuntime(), { auto: true });
for (const property of Object.keys(shims)) {
Object.defineProperty(exports, property, {
get() {
return shims[property];
},
});
}
},{"./registry":5,"openai/_shims/auto/runtime":3}],5:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.setShims = exports.isFsReadStream = exports.fileFromPath = exports.getDefaultAgent = exports.getMultipartRequestOptions = exports.ReadableStream = exports.File = exports.Blob = exports.FormData = exports.Headers = exports.Response = exports.Request = exports.fetch = exports.kind = exports.auto = void 0;
exports.auto = false;
exports.kind = undefined;
exports.fetch = undefined;
exports.Request = undefined;
exports.Response = undefined;
exports.Headers = undefined;
exports.FormData = undefined;
exports.Blob = undefined;
exports.File = undefined;
exports.ReadableStream = undefined;
exports.getMultipartRequestOptions = undefined;
exports.getDefaultAgent = undefined;
exports.fileFromPath = undefined;
exports.isFsReadStream = undefined;
function setShims(shims, options = { auto: false }) {
if (exports.auto) {
throw new Error(`you must \`import 'openai/shims/${shims.kind}'\` before importing anything else from openai`);
}
if (exports.kind) {
throw new Error(`can't \`import 'openai/shims/${shims.kind}'\` after \`import 'openai/shims/${exports.kind}'\``);
}
exports.auto = options.auto;
exports.kind = shims.kind;
exports.fetch = shims.fetch;
exports.Request = shims.Request;
exports.Response = shims.Response;
exports.Headers = shims.Headers;
exports.FormData = shims.FormData;
exports.Blob = shims.Blob;
exports.File = shims.File;
exports.ReadableStream = shims.ReadableStream;
exports.getMultipartRequestOptions = shims.getMultipartRequestOptions;
exports.getDefaultAgent = shims.getDefaultAgent;
exports.fileFromPath = shims.fileFromPath;
exports.isFsReadStream = shims.isFsReadStream;
}
exports.setShims = setShims;
},{}],6:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getRuntime = void 0;
/**
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
*/
const MultipartBody_1 = require("./MultipartBody.js");
function getRuntime({ manuallyImported } = {}) {
const recommendation = manuallyImported ?
`You may need to use polyfills`
: `Add one of these imports before your first \`import … from 'openai'\`:
- \`import 'openai/shims/node'\` (if you're running on Node)
- \`import 'openai/shims/web'\` (otherwise)
`;
let _fetch, _Request, _Response, _Headers;
try {
// @ts-ignore
_fetch = fetch;
// @ts-ignore
_Request = Request;
// @ts-ignore
_Response = Response;
// @ts-ignore
_Headers = Headers;
}
catch (error) {
throw new Error(`this environment is missing the following Web Fetch API type: ${error.message}. ${recommendation}`);
}
return {
kind: 'web',
fetch: _fetch,
Request: _Request,
Response: _Response,
Headers: _Headers,
FormData:
// @ts-ignore
typeof FormData !== 'undefined' ? FormData : (class FormData {
// @ts-ignore
constructor() {
throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${recommendation}`);
}
}),
Blob: typeof Blob !== 'undefined' ? Blob : (class Blob {
constructor() {
throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${recommendation}`);
}
}),
File:
// @ts-ignore
typeof File !== 'undefined' ? File : (class File {
// @ts-ignore
constructor() {
throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${recommendation}`);
}
}),
ReadableStream:
// @ts-ignore
typeof ReadableStream !== 'undefined' ? ReadableStream : (class ReadableStream {
// @ts-ignore
constructor() {
throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${recommendation}`);
}
}),
getMultipartRequestOptions: async (
// @ts-ignore
form, opts) => ({
...opts,
body: new MultipartBody_1.MultipartBody(form),
}),
getDefaultAgent: (url) => undefined,
fileFromPath: () => {
throw new Error('The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads');
},
isFsReadStream: (value) => false,
};
}
exports.getRuntime = getRuntime;
},{"./MultipartBody.js":2}],7:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.partialParse = void 0;
const tokenize = (input) => {
let current = 0;
let tokens = [];
while (current < input.length) {
let char = input[current];
if (char === '\\') {
current++;
continue;
}
if (char === '{') {
tokens.push({
type: 'brace',
value: '{',
});
current++;
continue;
}
if (char === '}') {
tokens.push({
type: 'brace',
value: '}',
});
current++;
continue;
}
if (char === '[') {
tokens.push({
type: 'paren',
value: '[',
});
current++;
continue;
}
if (char === ']') {
tokens.push({
type: 'paren',
value: ']',
});
current++;
continue;
}
if (char === ':') {
tokens.push({
type: 'separator',
value: ':',
});
current++;
continue;
}
if (char === ',') {
tokens.push({
type: 'delimiter',
value: ',',
});
current++;
continue;
}
if (char === '"') {
let value = '';
let danglingQuote = false;
char = input[++current];
while (char !== '"') {
if (current === input.length) {
danglingQuote = true;
break;
}
if (char === '\\') {
current++;
if (current === input.length) {
danglingQuote = true;
break;
}
value += char + input[current];
char = input[++current];
}
else {
value += char;
char = input[++current];
}
}
char = input[++current];
if (!danglingQuote) {
tokens.push({
type: 'string',
value,
});
}
continue;
}
let WHITESPACE = /\s/;
if (char && WHITESPACE.test(char)) {
current++;
continue;
}
let NUMBERS = /[0-9]/;
if ((char && NUMBERS.test(char)) || char === '-' || char === '.') {
let value = '';
if (char === '-') {
value += char;
char = input[++current];
}
while ((char && NUMBERS.test(char)) || char === '.') {
value += char;
char = input[++current];
}
tokens.push({
type: 'number',
value,
});
continue;
}
let LETTERS = /[a-z]/i;
if (char && LETTERS.test(char)) {
let value = '';
while (char && LETTERS.test(char)) {
if (current === input.length) {
break;
}
value += char;
char = input[++current];
}
if (value == 'true' || value == 'false' || value === 'null') {
tokens.push({
type: 'name',
value,
});
}
else {
// unknown token, e.g. `nul` which isn't quite `null`
current++;
continue;
}
continue;
}
current++;
}
return tokens;
}, strip = (tokens) => {
if (tokens.length === 0) {
return tokens;
}
let lastToken = tokens[tokens.length - 1];
switch (lastToken.type) {
case 'separator':
tokens = tokens.slice(0, tokens.length - 1);
return strip(tokens);
break;
case 'number':
let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1];
if (lastCharacterOfLastToken === '.' || lastCharacterOfLastToken === '-') {
tokens = tokens.slice(0, tokens.length - 1);
return strip(tokens);
}
case 'string':
let tokenBeforeTheLastToken = tokens[tokens.length - 2];
if (tokenBeforeTheLastToken?.type === 'delimiter') {
tokens = tokens.slice(0, tokens.length - 1);
return strip(tokens);
}
else if (tokenBeforeTheLastToken?.type === 'brace' && tokenBeforeTheLastToken.value === '{') {
tokens = tokens.slice(0, tokens.length - 1);
return strip(tokens);
}
break;
case 'delimiter':
tokens = tokens.slice(0, tokens.length - 1);
return strip(tokens);
break;
}
return tokens;
}, unstrip = (tokens) => {
let tail = [];
tokens.map((token) => {
if (token.type === 'brace') {
if (token.value === '{') {
tail.push('}');
}
else {
tail.splice(tail.lastIndexOf('}'), 1);
}
}
if (token.type === 'paren') {
if (token.value === '[') {
tail.push(']');
}
else {
tail.splice(tail.lastIndexOf(']'), 1);
}
}
});
if (tail.length > 0) {
tail.reverse().map((item) => {
if (item === '}') {
tokens.push({
type: 'brace',
value: '}',
});
}
else if (item === ']') {
tokens.push({
type: 'paren',
value: ']',
});
}
});
}
return tokens;
}, generate = (tokens) => {
let output = '';
tokens.map((token) => {
switch (token.type) {
case 'string':
output += '"' + token.value + '"';
break;
default:
output += token.value;
break;
}
});
return output;
}, partialParse = (input) => JSON.parse(generate(unstrip(strip(tokenize(input)))));
exports.partialParse = partialParse;
},{}],8:[function(require,module,exports){
(function (process,Buffer){(function (){
"use strict";
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _AbstractPage_client;
Object.defineProperty(exports, "__esModule", { value: true });
exports.isObj = exports.toBase64 = exports.getRequiredHeader = exports.isHeadersProtocol = exports.isRunningInBrowser = exports.debug = exports.hasOwn = exports.isEmptyObj = exports.maybeCoerceBoolean = exports.maybeCoerceFloat = exports.maybeCoerceInteger = exports.coerceBoolean = exports.coerceFloat = exports.coerceInteger = exports.readEnv = exports.ensurePresent = exports.castToError = exports.sleep = exports.safeJSON = exports.isRequestOptions = exports.createResponseHeaders = exports.PagePromise = exports.AbstractPage = exports.APIClient = exports.APIPromise = exports.createForm = exports.multipartFormRequestOptions = exports.maybeMultipartFormRequestOptions = void 0;
const version_1 = require("./version.js");
const streaming_1 = require("./streaming.js");
const error_1 = require("./error.js");
const index_1 = require("./_shims/index.js");
const uploads_1 = require("./uploads.js");
var uploads_2 = require("./uploads.js");
Object.defineProperty(exports, "maybeMultipartFormRequestOptions", { enumerable: true, get: function () { return uploads_2.maybeMultipartFormRequestOptions; } });
Object.defineProperty(exports, "multipartFormRequestOptions", { enumerable: true, get: function () { return uploads_2.multipartFormRequestOptions; } });
Object.defineProperty(exports, "createForm", { enumerable: true, get: function () { return uploads_2.createForm; } });
async function defaultParseResponse(props) {
const { response } = props;
if (props.options.stream) {
debug('response', response.status, response.url, response.headers, response.body);
// Note: there is an invariant here that isn't represented in the type system
// that if you set `stream: true` the response type must also be `Stream<T>`
if (props.options.__streamClass) {
return props.options.__streamClass.fromSSEResponse(response, props.controller);
}
return streaming_1.Stream.fromSSEResponse(response, props.controller);
}
// fetch refuses to read the body when the status code is 204.
if (response.status === 204) {
return null;
}
if (props.options.__binaryResponse) {
return response;
}
const contentType = response.headers.get('content-type');
const isJSON = contentType?.includes('application/json') || contentType?.includes('application/vnd.api+json');
if (isJSON) {
const json = await response.json();
debug('response', response.status, response.url, response.headers, json);
return json;
}
const text = await response.text();
debug('response', response.status, response.url, response.headers, text);
// TODO handle blob, arraybuffer, other content types, etc.
return text;
}
/**
* A subclass of `Promise` providing additional helper methods
* for interacting with the SDK.
*/
class APIPromise extends Promise {
constructor(responsePromise, parseResponse = defaultParseResponse) {
super((resolve) => {
// this is maybe a bit weird but this has to be a no-op to not implicitly
// parse the response body; instead .then, .catch, .finally are overridden
// to parse the response
resolve(null);
});
this.responsePromise = responsePromise;
this.parseResponse = parseResponse;
}
_thenUnwrap(transform) {
return new APIPromise(this.responsePromise, async (props) => transform(await this.parseResponse(props)));
}
/**
* Gets the raw `Response` instance instead of parsing the response
* data.
*
* If you want to parse the response body but still get the `Response`
* instance, you can use {@link withResponse()}.
*
* 👋 Getting the wrong TypeScript type for `Response`?
* Try setting `"moduleResolution": "NodeNext"` if you can,
* or add one of these imports before your first `import … from 'openai'`:
* - `import 'openai/shims/node'` (if you're running on Node)
* - `import 'openai/shims/web'` (otherwise)
*/
asResponse() {
return this.responsePromise.then((p) => p.response);
}
/**
* Gets the parsed response data and the raw `Response` instance.
*
* If you just want to get the raw `Response` instance without parsing it,
* you can use {@link asResponse()}.
*
*
* 👋 Getting the wrong TypeScript type for `Response`?
* Try setting `"moduleResolution": "NodeNext"` if you can,
* or add one of these imports before your first `import … from 'openai'`:
* - `import 'openai/shims/node'` (if you're running on Node)
* - `import 'openai/shims/web'` (otherwise)
*/
async withResponse() {
const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
return { data, response };
}
parse() {
if (!this.parsedPromise) {
this.parsedPromise = this.responsePromise.then(this.parseResponse);
}
return this.parsedPromise;
}
then(onfulfilled, onrejected) {
return this.parse().then(onfulfilled, onrejected);
}
catch(onrejected) {
return this.parse().catch(onrejected);
}
finally(onfinally) {
return this.parse().finally(onfinally);
}
}
exports.APIPromise = APIPromise;
class APIClient {
constructor({ baseURL, maxRetries = 2, timeout = 600000, // 10 minutes
httpAgent, fetch: overridenFetch, }) {
this.baseURL = baseURL;
this.maxRetries = validatePositiveInteger('maxRetries', maxRetries);
this.timeout = validatePositiveInteger('timeout', timeout);
this.httpAgent = httpAgent;
this.fetch = overridenFetch ?? index_1.fetch;
}
authHeaders(opts) {
return {};
}
/**
* Override this to add your own default headers, for example:
*
* {
* ...super.defaultHeaders(),
* Authorization: 'Bearer 123',
* }
*/
defaultHeaders(opts) {
return {
Accept: 'application/json',
'Content-Type': 'application/json',
'User-Agent': this.getUserAgent(),
...getPlatformHeaders(),
...this.authHeaders(opts),
};
}
/**
* Override this to add your own headers validation:
*/
validateHeaders(headers, customHeaders) { }
defaultIdempotencyKey() {
return `stainless-node-retry-${uuid4()}`;
}
get(path, opts) {
return this.methodRequest('get', path, opts);
}
post(path, opts) {
return this.methodRequest('post', path, opts);
}
patch(path, opts) {
return this.methodRequest('patch', path, opts);
}
put(path, opts) {
return this.methodRequest('put', path, opts);
}
delete(path, opts) {
return this.methodRequest('delete', path, opts);
}
methodRequest(method, path, opts) {
return this.request(Promise.resolve(opts).then(async (opts) => {
const body = opts && (0, uploads_1.isBlobLike)(opts?.body) ? new DataView(await opts.body.arrayBuffer())
: opts?.body instanceof DataView ? opts.body
: opts?.body instanceof ArrayBuffer ? new DataView(opts.body)
: opts && ArrayBuffer.isView(opts?.body) ? new DataView(opts.body.buffer)
: opts?.body;
return { method, path, ...opts, body };
}));
}
getAPIList(path, Page, opts) {
return this.requestAPIList(Page, { method: 'get', path, ...opts });
}
calculateContentLength(body) {
if (typeof body === 'string') {
if (typeof Buffer !== 'undefined') {
return Buffer.byteLength(body, 'utf8').toString();
}
if (typeof TextEncoder !== 'undefined') {
const encoder = new TextEncoder();
const encoded = encoder.encode(body);
return encoded.length.toString();
}
}
else if (ArrayBuffer.isView(body)) {
return body.byteLength.toString();
}
return null;
}
buildRequest(options) {
const { method, path, query, headers: headers = {} } = options;
const body = ArrayBuffer.isView(options.body) || (options.__binaryRequest && typeof options.body === 'string') ?
options.body
: (0, uploads_1.isMultipartBody)(options.body) ? options.body.body
: options.body ? JSON.stringify(options.body, null, 2)
: null;
const contentLength = this.calculateContentLength(body);
const url = this.buildURL(path, query);
if ('timeout' in options)
validatePositiveInteger('timeout', options.timeout);
const timeout = options.timeout ?? this.timeout;
const httpAgent = options.httpAgent ?? this.httpAgent ?? (0, index_1.getDefaultAgent)(url);
const minAgentTimeout = timeout + 1000;
if (typeof httpAgent?.options?.timeout === 'number' &&
minAgentTimeout > (httpAgent.options.timeout ?? 0)) {
// Allow any given request to bump our agent active socket timeout.
// This may seem strange, but leaking active sockets should be rare and not particularly problematic,
// and without mutating agent we would need to create more of them.
// This tradeoff optimizes for performance.
httpAgent.options.timeout = minAgentTimeout;
}
if (this.idempotencyHeader && method !== 'get') {
if (!options.idempotencyKey)
options.idempotencyKey = this.defaultIdempotencyKey();
headers[this.idempotencyHeader] = options.idempotencyKey;
}
const reqHeaders = this.buildHeaders({ options, headers, contentLength });
const req = {
method,
...(body && { body: body }),
headers: reqHeaders,
...(httpAgent && { agent: httpAgent }),
// @ts-ignore node-fetch uses a custom AbortSignal type that is
// not compatible with standard web types
signal: options.signal ?? null,
};
return { req, url, timeout };
}
buildHeaders({ options, headers, contentLength, }) {
const reqHeaders = {};
if (contentLength) {
reqHeaders['content-length'] = contentLength;
}
const defaultHeaders = this.defaultHeaders(options);
applyHeadersMut(reqHeaders, defaultHeaders);
applyHeadersMut(reqHeaders, headers);
// let builtin fetch set the Content-Type for multipart bodies
if ((0, uploads_1.isMultipartBody)(options.body) && index_1.kind !== 'node') {
delete reqHeaders['content-type'];
}
this.validateHeaders(reqHeaders, headers);
return reqHeaders;
}
/**
* Used as a callback for mutating the given `FinalRequestOptions` object.
*/
async prepareOptions(options) { }
/**
* Used as a callback for mutating the given `RequestInit` object.
*
* This is useful for cases where you want to add certain headers based off of
* the request properties, e.g. `method` or `url`.
*/
async prepareRequest(request, { url, options }) { }
parseHeaders(headers) {
return (!headers ? {}
: Symbol.iterator in headers ?
Object.fromEntries(Array.from(headers).map((header) => [...header]))
: { ...headers });
}
makeStatusError(status, error, message, headers) {
return error_1.APIError.generate(status, error, message, headers);
}
request(options, remainingRetries = null) {
return new APIPromise(this.makeRequest(options, remainingRetries));
}
async makeRequest(optionsInput, retriesRemaining) {
const options = await optionsInput;
if (retriesRemaining == null) {
retriesRemaining = options.maxRetries ?? this.maxRetries;
}
await this.prepareOptions(options);
const { req, url, timeout } = this.buildRequest(options);
await this.prepareRequest(req, { url, options });
debug('request', url, options, req.headers);
if (options.signal?.aborted) {
throw new error_1.APIUserAbortError();
}
const controller = new AbortController();
const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(exports.castToError);
if (response instanceof Error) {
if (options.signal?.aborted) {
throw new error_1.APIUserAbortError();
}
if (retriesRemaining) {
return this.retryRequest(options, retriesRemaining);
}
if (response.name === 'AbortError') {
throw new error_1.APIConnectionTimeoutError();
}
throw new error_1.APIConnectionError({ cause: response });
}
const responseHeaders = (0, exports.createResponseHeaders)(response.headers);
if (!response.ok) {
if (retriesRemaining && this.shouldRetry(response)) {
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders);
return this.retryRequest(options, retriesRemaining, responseHeaders);
}
const errText = await response.text().catch((e) => (0, exports.castToError)(e).message);
const errJSON = (0, exports.safeJSON)(errText);
const errMessage = errJSON ? undefined : errText;
const retryMessage = retriesRemaining ? `(error; no more retries left)` : `(error; not retryable)`;
debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders, errMessage);
const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders);
throw err;
}
return { response, options, controller };
}
requestAPIList(Page, options) {
const request = this.makeRequest(options, null);
return new PagePromise(this, request, Page);
}
buildURL(path, query) {
const url = isAbsoluteURL(path) ?
new URL(path)
: new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
const defaultQuery = this.defaultQuery();
if (!isEmptyObj(defaultQuery)) {
query = { ...defaultQuery, ...query };
}
if (typeof query === 'object' && query && !Array.isArray(query)) {
url.search = this.stringifyQuery(query);
}
return url.toString();
}
stringifyQuery(query) {
return Object.entries(query)
.filter(([_, value]) => typeof value !== 'undefined')
.map(([key, value]) => {
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
}
if (value === null) {
return `${encodeURIComponent(key)}=`;
}
throw new error_1.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.`);
})
.join('&');
}
async fetchWithTimeout(url, init, ms, controller) {
const { signal, ...options } = init || {};
if (signal)
signal.addEventListener('abort', () => controller.abort());
const timeout = setTimeout(() => controller.abort(), ms);
return (this.getRequestClient()
// use undefined this binding; fetch errors if bound to something else in browser/cloudflare
.fetch.call(undefined, url, { signal: controller.signal, ...options })
.finally(() => {
clearTimeout(timeout);
}));
}
getRequestClient() {
return { fetch: this.fetch };
}
shouldRetry(response) {
// Note this is not a standard header.
const shouldRetryHeader = response.headers.get('x-should-retry');
// If the server explicitly says whether or not to retry, obey.
if (shouldRetryHeader === 'true')
return true;
if (shouldRetryHeader === 'false')
return false;
// Retry on request timeouts.
if (response.status === 408)
return true;
// Retry on lock timeouts.
if (response.status === 409)
return true;
// Retry on rate limits.
if (response.status === 429)
return true;
// Retry internal errors.
if (response.status >= 500)
return true;
return false;
}
async retryRequest(options, retriesRemaining, responseHeaders) {
let timeoutMillis;
// Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
const retryAfterMillisHeader = responseHeaders?.['retry-after-ms'];
if (retryAfterMillisHeader) {
const timeoutMs = parseFloat(retryAfterMillisHeader);
if (!Number.isNaN(timeoutMs)) {
timeoutMillis = timeoutMs;
}
}
// About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
const retryAfterHeader = responseHeaders?.['retry-after'];
if (retryAfterHeader && !timeoutMillis) {
const timeoutSeconds = parseFloat(retryAfterHeader);
if (!Number.isNaN(timeoutSeconds)) {
timeoutMillis = timeoutSeconds * 1000;
}
else {
timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
}
}
// If the API asks us to wait a certain amount of time (and it's a reasonable amount),
// just do what it says, but otherwise calculate a default
if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
const maxRetries = options.maxRetries ?? this.maxRetries;
timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
}
await (0, exports.sleep)(timeoutMillis);
return this.makeRequest(options, retriesRemaining - 1);
}
calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
const initialRetryDelay = 0.5;
const maxRetryDelay = 8.0;
const numRetries = maxRetries - retriesRemaining;
// Apply exponential backoff, but not more than the max.
const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
// Apply some jitter, take up to at most 25 percent of the retry time.
const jitter = 1 - Math.random() * 0.25;
return sleepSeconds * jitter * 1000;
}
getUserAgent() {
return `${this.constructor.name}/JS ${version_1.VERSION}`;
}
}
exports.APIClient = APIClient;
class AbstractPage {
constructor(client, response, body, options) {
_AbstractPage_client.set(this, void 0);
__classPrivateFieldSet(this, _AbstractPage_client, client, "f");
this.options = options;
this.response = response;
this.body = body;
}
hasNextPage() {
const items = this.getPaginatedItems();
if (!items.length)
return false;
return this.nextPageInfo() != null;
}
async getNextPage() {
const nextInfo = this.nextPageInfo();
if (!nextInfo) {
throw new error_1.OpenAIError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.');
}
const nextOptions = { ...this.options };
if ('params' in nextInfo && typeof nextOptions.query === 'object') {
nextOptions.query = { ...nextOptions.query, ...nextInfo.params };
}
else if ('url' in nextInfo) {
const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()];
for (const [key, value] of params) {
nextInfo.url.searchParams.set(key, value);
}
nextOptions.query = undefined;
nextOptions.path = nextInfo.url.toString();
}
return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
}
async *iterPages() {
// eslint-disable-next-line @typescript-eslint/no-this-alias
let page = this;
yield page;
while (page.hasNextPage()) {
page = await page.getNextPage();
yield page;
}
}
async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() {
for await (const page of this.iterPages()) {
for (const item of page.getPaginatedItems()) {
yield item;
}
}
}
}
exports.AbstractPage = AbstractPage;
/**
* This subclass of Promise will resolve to an instantiated Page once the request completes.
*
* It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg: