@postalsys/email-ai-tools 1.14.10 → 1.14.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +14 -0
- package/CLAUDE.md +5 -1
- package/lib/api-request.js +194 -0
- package/lib/embeddings-query.js +27 -180
- package/lib/generate-embeddings.js +67 -90
- package/lib/generate-summary.js +24 -128
- package/lib/list-models.js +9 -63
- package/lib/risk-analysis.js +21 -103
- package/lib/token-estimate.js +186 -0
- package/package.json +5 -6
- package/test/api-request.test.js +162 -0
- package/test/dispatcher.test.js +15 -2
- package/test/generate-embeddings.test.js +131 -1
- package/test/helpers/mock-server.js +11 -3
- package/test/token-estimate.test.js +188 -0
|
@@ -1,17 +1,13 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
const packageData = require('../package.json');
|
|
4
3
|
const libmime = require('libmime');
|
|
5
4
|
const addressparser = require('nodemailer/lib/addressparser');
|
|
6
5
|
const { htmlToText } = require('@postalsys/email-text-tools');
|
|
7
6
|
const punycode = require('punycode.js');
|
|
8
|
-
const {
|
|
9
|
-
const {
|
|
10
|
-
const fetchAgent = new Agent({ connect: { timeout: 90 * 1000 } });
|
|
11
|
-
const util = require('util');
|
|
7
|
+
const { apiRequest } = require('./api-request');
|
|
8
|
+
const { estimateTokens, splitByTokens, keepSurrogatePair, CHUNK_ESTIMATE, MAX_ALLOWED_TEXT_LENGTH } = require('./token-estimate');
|
|
12
9
|
const linkifyIt = require('linkify-it');
|
|
13
10
|
const tlds = require('tlds');
|
|
14
|
-
const crypto = require('crypto');
|
|
15
11
|
|
|
16
12
|
const linkify = linkifyIt()
|
|
17
13
|
.tlds(tlds) // Reload with full tlds list
|
|
@@ -19,96 +15,67 @@ const linkify = linkifyIt()
|
|
|
19
15
|
.add('git:', 'http:') // Add `git:` protocol as "alias"
|
|
20
16
|
.set({ fuzzyIP: true });
|
|
21
17
|
|
|
22
|
-
const tokenizer = new GPT3Tokenizer({ type: 'gpt3' });
|
|
23
|
-
|
|
24
18
|
const { getApiUrl, OPENAI_API_BASE_URL } = require('./get-api-url');
|
|
25
19
|
|
|
26
20
|
const OPENAI_API_URL = '/v1/embeddings';
|
|
27
21
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
baseApiUrl = baseApiUrl || OPENAI_API_BASE_URL;
|
|
22
|
+
// Chunks sent in one embeddings request. OpenAI accepts far more, but some compatible services
|
|
23
|
+
// (older Azure OpenAI deployments) cap the input array at 16.
|
|
24
|
+
const DEFAULT_CHUNKS_PER_REQUEST = 16;
|
|
25
|
+
const MAX_CHUNKS_PER_REQUEST = 64;
|
|
33
26
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
};
|
|
27
|
+
// Sends one embeddings request for a string or an array of strings. Resolves with the
|
|
28
|
+
// embeddings in input order and the request time. The response must carry exactly one entry per
|
|
29
|
+
// input, so a reply without a `data` array is rejected with InvalidResponse even for a single
|
|
30
|
+
// string input (it used to resolve with an undefined embedding).
|
|
31
|
+
async function requestEmbeddings(input, apiToken, opts) {
|
|
32
|
+
opts = opts || {};
|
|
41
33
|
|
|
42
|
-
|
|
43
|
-
model: gptModel,
|
|
44
|
-
input
|
|
34
|
+
const payload = {
|
|
35
|
+
model: opts.gptModel || 'text-embedding-ada-002',
|
|
36
|
+
input
|
|
45
37
|
};
|
|
46
38
|
|
|
47
39
|
if (opts.user) {
|
|
48
40
|
payload.user = opts.user;
|
|
49
41
|
}
|
|
50
42
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
43
|
+
const { data, time } = await apiRequest(getApiUrl(opts.baseApiUrl || OPENAI_API_BASE_URL, OPENAI_API_URL), {
|
|
44
|
+
apiToken,
|
|
45
|
+
payload,
|
|
46
|
+
dispatcher: opts.dispatcher,
|
|
47
|
+
signal: opts.signal,
|
|
48
|
+
verbose: opts.verbose
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
const inputCount = [].concat(input).length;
|
|
52
|
+
const entries = Array.isArray(data.data) ? data.data.slice() : [];
|
|
53
|
+
if (entries.length !== inputCount) {
|
|
54
|
+
const error = new Error(`Embeddings response has ${entries.length} entries for ${inputCount} inputs`);
|
|
55
|
+
error.code = 'InvalidResponse';
|
|
56
|
+
throw error;
|
|
61
57
|
}
|
|
58
|
+
// entries carry their input position, do not rely on the array order
|
|
59
|
+
entries.sort((a, b) => ((a && a.index) || 0) - ((b && b.index) || 0));
|
|
62
60
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
method: 'post',
|
|
66
|
-
headers,
|
|
67
|
-
body: JSON.stringify(payload),
|
|
68
|
-
dispatcher: dispatcher || fetchAgent
|
|
69
|
-
});
|
|
70
|
-
|
|
71
|
-
data = await res.json();
|
|
72
|
-
if (!res.ok) {
|
|
73
|
-
if (res.status === 429 && ++retries < 5) {
|
|
74
|
-
// try again
|
|
75
|
-
await new Promise(r => setTimeout(r, 1000));
|
|
76
|
-
return await run();
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
if (data && data.error) {
|
|
80
|
-
let error = new Error(data.error.message || data.error);
|
|
81
|
-
if (data.error.code) {
|
|
82
|
-
error.code = data.error.code;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
error.statusCode = res.status;
|
|
86
|
-
throw error;
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
let error = new Error('Failed to run API request');
|
|
90
|
-
error.statusCode = res.status;
|
|
91
|
-
throw error;
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
if (!data) {
|
|
95
|
-
throw new Error(`Failed to POST API request`);
|
|
96
|
-
}
|
|
97
|
-
};
|
|
98
|
-
|
|
99
|
-
const reqStartTime = Date.now();
|
|
100
|
-
await run();
|
|
101
|
-
const reqEndTime = Date.now();
|
|
61
|
+
return { vectors: entries.map(entry => entry && entry.embedding), time };
|
|
62
|
+
}
|
|
102
63
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
64
|
+
/**
|
|
65
|
+
* Returns the embedding vector for a single chunk of text
|
|
66
|
+
*
|
|
67
|
+
* @throws {Error} InvalidResponse if the API reply does not carry exactly one embedding
|
|
68
|
+
*/
|
|
69
|
+
async function getChunkEmbeddings(chunk, apiToken, opts) {
|
|
70
|
+
const {
|
|
71
|
+
vectors: [embedding],
|
|
72
|
+
time
|
|
73
|
+
} = await requestEmbeddings(chunk, apiToken, opts);
|
|
106
74
|
|
|
107
|
-
let embedding = data?.data?.[0]?.embedding;
|
|
108
75
|
return {
|
|
109
76
|
chunk,
|
|
110
77
|
embedding,
|
|
111
|
-
_time:
|
|
78
|
+
_time: time
|
|
112
79
|
};
|
|
113
80
|
}
|
|
114
81
|
|
|
@@ -120,6 +87,9 @@ class Embedder {
|
|
|
120
87
|
opts = opts || {};
|
|
121
88
|
this.chunkSize = opts.chunkSize || 400;
|
|
122
89
|
this.gptModel = opts.gptModel || 'text-embedding-ada-002';
|
|
90
|
+
this.maxTextLength = opts.maxTextLength || MAX_ALLOWED_TEXT_LENGTH;
|
|
91
|
+
this.chunksPerRequest = Math.min(Math.max(Number(opts.chunksPerRequest) || DEFAULT_CHUNKS_PER_REQUEST, 1), MAX_CHUNKS_PER_REQUEST);
|
|
92
|
+
this.signal = opts.signal;
|
|
123
93
|
|
|
124
94
|
// Forwarded to every per-chunk embeddings request
|
|
125
95
|
this.requestOpts = {
|
|
@@ -127,6 +97,7 @@ class Embedder {
|
|
|
127
97
|
baseApiUrl: opts.baseApiUrl,
|
|
128
98
|
user: opts.user,
|
|
129
99
|
dispatcher: opts.dispatcher,
|
|
100
|
+
signal: opts.signal,
|
|
130
101
|
verbose: opts.verbose
|
|
131
102
|
};
|
|
132
103
|
|
|
@@ -201,6 +172,10 @@ class Embedder {
|
|
|
201
172
|
text = (htmlToText(message.html) || '').trim();
|
|
202
173
|
}
|
|
203
174
|
|
|
175
|
+
if (text.length > this.maxTextLength) {
|
|
176
|
+
text = text.substring(0, keepSurrogatePair(text, this.maxTextLength));
|
|
177
|
+
}
|
|
178
|
+
|
|
204
179
|
// replace links
|
|
205
180
|
|
|
206
181
|
this.text = this.prepareLinks(text);
|
|
@@ -320,28 +295,21 @@ class Embedder {
|
|
|
320
295
|
|
|
321
296
|
let prompt = `${headerLines.join('\n')}\n\n`;
|
|
322
297
|
|
|
323
|
-
let prefixTokens =
|
|
298
|
+
let prefixTokens = estimateTokens(prompt, CHUNK_ESTIMATE);
|
|
324
299
|
// If prefix is very large, then use larger chunks, so that each chunk contains at least 200 tokens of text
|
|
325
|
-
let allowedTokens = Math.max(prefixTokens
|
|
300
|
+
let allowedTokens = Math.max(prefixTokens + 200, this.chunkSize);
|
|
326
301
|
|
|
327
|
-
let textTokensChunkSize = allowedTokens - prefixTokens
|
|
302
|
+
let textTokensChunkSize = allowedTokens - prefixTokens;
|
|
328
303
|
|
|
329
304
|
let textChunks = [];
|
|
330
305
|
if (this.text) {
|
|
331
306
|
let preparedText = this.text
|
|
332
307
|
.replace(/\r?\n/g, '\n')
|
|
333
308
|
.replace(/^\s*>.*$/gm, '')
|
|
334
|
-
.replace(/^\s*>$/gm)
|
|
335
309
|
.replace(/^\s+$/gm, '')
|
|
336
310
|
.replace(/\n\n+/g, '\n\n');
|
|
337
311
|
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
let pos = 0;
|
|
341
|
-
while (pos < textTokens.bpe.length) {
|
|
342
|
-
textChunks.push(tokenizer.decode(textTokens.bpe.slice(pos, pos + textTokensChunkSize)));
|
|
343
|
-
pos += textTokensChunkSize;
|
|
344
|
-
}
|
|
312
|
+
textChunks = splitByTokens(preparedText, textTokensChunkSize);
|
|
345
313
|
} else {
|
|
346
314
|
textChunks.push('');
|
|
347
315
|
}
|
|
@@ -354,8 +322,17 @@ class Embedder {
|
|
|
354
322
|
|
|
355
323
|
let embeddings = [];
|
|
356
324
|
|
|
357
|
-
for (let
|
|
358
|
-
|
|
325
|
+
for (let i = 0; i < chunks.length; i += this.chunksPerRequest) {
|
|
326
|
+
this.signal?.throwIfAborted();
|
|
327
|
+
|
|
328
|
+
const batch = chunks.slice(i, i + this.chunksPerRequest);
|
|
329
|
+
|
|
330
|
+
// a single chunk goes out as a plain string, as it always did
|
|
331
|
+
const { vectors, time } = await requestEmbeddings(batch.length === 1 ? batch[0] : batch, this.apiToken, this.requestOpts);
|
|
332
|
+
|
|
333
|
+
batch.forEach((chunk, j) => {
|
|
334
|
+
embeddings.push({ chunk, embedding: vectors[j], _time: time });
|
|
335
|
+
});
|
|
359
336
|
}
|
|
360
337
|
|
|
361
338
|
return { model: this.gptModel, embeddings };
|
package/lib/generate-summary.js
CHANGED
|
@@ -1,20 +1,9 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
const packageData = require('../package.json');
|
|
4
3
|
const { htmlToText } = require('@postalsys/email-text-tools');
|
|
5
|
-
const {
|
|
6
|
-
const
|
|
7
|
-
const crypto = require('crypto');
|
|
8
|
-
const { fetch: fetchCmd, Agent } = require('undici');
|
|
9
|
-
const fetchAgent = new Agent({ connect: { timeout: 90 * 1000 } });
|
|
10
|
-
|
|
11
|
-
const tokenizer = new GPT3Tokenizer({ type: 'gpt3' });
|
|
12
|
-
|
|
13
|
-
const MAX_ALLOWED_TEXT_LENGTH = 64 * 1024;
|
|
14
|
-
const DEFAULT_MAX_ALLOWED_TOKENS = 30000;
|
|
4
|
+
const { apiRequest } = require('./api-request');
|
|
5
|
+
const { estimateTokens, fitPrompt, DEFAULT_MAX_ALLOWED_TOKENS } = require('./token-estimate');
|
|
15
6
|
const MAX_INSTRUCT_TOKENS = 4000;
|
|
16
|
-
const MAX_RETRIES = 5;
|
|
17
|
-
const RETRY_DELAY_MS = 1000;
|
|
18
7
|
|
|
19
8
|
const { getApiUrl, OPENAI_API_BASE_URL } = require('./get-api-url');
|
|
20
9
|
|
|
@@ -157,13 +146,14 @@ Analyze the following email:`.trim();
|
|
|
157
146
|
* @param {string} [opts.gptModel='gpt-5-mini'] - Model to use (gpt-3.5-turbo, gpt-4, etc.)
|
|
158
147
|
* @param {string} [opts.systemPrompt] - Override default system prompt
|
|
159
148
|
* @param {string} [opts.userPrompt] - Override default user prompt
|
|
160
|
-
* @param {number} [opts.maxTokens=
|
|
149
|
+
* @param {number} [opts.maxTokens=30000] - Maximum estimated tokens for the prompt (a character-based estimate that errs high)
|
|
161
150
|
* @param {number} [opts.temperature] - Sampling temperature (0-2)
|
|
162
151
|
* @param {number} [opts.topP] - Nucleus sampling parameter (0-1)
|
|
163
152
|
* @param {string} [opts.user] - OpenAI user identifier for tracking
|
|
164
153
|
* @param {Array<string>} [opts.allowedHeaders] - Additional headers to include (merged with defaults)
|
|
165
154
|
* @param {boolean} [opts.verbose=false] - Enable debug logging
|
|
166
155
|
* @param {Object} [opts.dispatcher] - undici Dispatcher (for example a ProxyAgent) the API request is sent through; the module's own keep-alive agent when omitted
|
|
156
|
+
* @param {AbortSignal} [opts.signal] - Aborts the API request and any rate limit retry wait
|
|
167
157
|
*
|
|
168
158
|
* @returns {Promise<Object>} Analysis result object
|
|
169
159
|
* @returns {string} return.sentiment - Email sentiment: 'positive', 'neutral', or 'negative'
|
|
@@ -223,7 +213,6 @@ async function generateSummary(message, apiToken, opts) {
|
|
|
223
213
|
)
|
|
224
214
|
);
|
|
225
215
|
|
|
226
|
-
let prompt;
|
|
227
216
|
const headerSeen = new Set();
|
|
228
217
|
|
|
229
218
|
const content = {
|
|
@@ -249,63 +238,18 @@ async function generateSummary(message, apiToken, opts) {
|
|
|
249
238
|
.filter(attachment => attachment.filename || attachment.contentType)
|
|
250
239
|
};
|
|
251
240
|
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
while (true) {
|
|
261
|
-
content.text = promptText;
|
|
262
|
-
prompt = `${userPrompt}
|
|
241
|
+
const {
|
|
242
|
+
prompt,
|
|
243
|
+
text: promptText,
|
|
244
|
+
charactersRemoved
|
|
245
|
+
} = fitPrompt({
|
|
246
|
+
text,
|
|
247
|
+
maxTokens: maxAllowedTokens,
|
|
248
|
+
build: bodyText => `${userPrompt}
|
|
263
249
|
${SCHEMA_PROMPT}
|
|
264
250
|
|
|
265
|
-
${JSON.stringify(content)}
|
|
266
|
-
|
|
267
|
-
let tokens = tokenizer.encode(prompt);
|
|
268
|
-
if (tokens.bpe.length <= maxAllowedTokens) {
|
|
269
|
-
break;
|
|
270
|
-
}
|
|
271
|
-
if (promptText.length > 2 * 1024 * 1024) {
|
|
272
|
-
promptText = promptText.substring(0, promptText.length - 1024 * 1024);
|
|
273
|
-
charactersRemoved += 1024 * 1024;
|
|
274
|
-
} else if (promptText.length > 2 * 1024) {
|
|
275
|
-
promptText = promptText.substring(0, promptText.length - 1024);
|
|
276
|
-
charactersRemoved += 1024;
|
|
277
|
-
} else if (promptText.length > 2 * 256) {
|
|
278
|
-
promptText = promptText.substring(0, promptText.length - 256);
|
|
279
|
-
charactersRemoved += 256;
|
|
280
|
-
} else if (promptText.length > 2 * 100) {
|
|
281
|
-
promptText = promptText.substring(0, promptText.length - 100);
|
|
282
|
-
charactersRemoved += 100;
|
|
283
|
-
} else if (promptText.length > 2 * 10) {
|
|
284
|
-
promptText = promptText.substring(0, promptText.length - 10);
|
|
285
|
-
charactersRemoved += 10;
|
|
286
|
-
} else if (promptText.length > 1) {
|
|
287
|
-
promptText = promptText.substring(0, promptText.length - 1);
|
|
288
|
-
charactersRemoved += 1;
|
|
289
|
-
} else {
|
|
290
|
-
const error = new Error(
|
|
291
|
-
`Unable to fit email content within token limit of ${maxAllowedTokens}. ` +
|
|
292
|
-
`Original text length: ${text.length} characters. ` +
|
|
293
|
-
`Removed ${charactersRemoved} characters but still exceeds limit. ` +
|
|
294
|
-
`Consider using a model with larger context window.`
|
|
295
|
-
);
|
|
296
|
-
error.code = 'PROMPT_TOO_LONG';
|
|
297
|
-
error.originalLength = text.length;
|
|
298
|
-
error.charactersRemoved = charactersRemoved;
|
|
299
|
-
error.maxAllowedTokens = maxAllowedTokens;
|
|
300
|
-
throw error;
|
|
301
|
-
}
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
let headers = {
|
|
305
|
-
'User-Agent': `${packageData.name}/${packageData.version}`,
|
|
306
|
-
Authorization: `Bearer ${apiToken}`,
|
|
307
|
-
'Content-Type': 'application/json'
|
|
308
|
-
};
|
|
251
|
+
${JSON.stringify(Object.assign({}, content, { text: bodyText }))}`
|
|
252
|
+
});
|
|
309
253
|
|
|
310
254
|
let payload = {
|
|
311
255
|
model: gptModel
|
|
@@ -323,20 +267,13 @@ ${JSON.stringify(content)}`;
|
|
|
323
267
|
payload.top_p = Number(opts.topP);
|
|
324
268
|
}
|
|
325
269
|
|
|
326
|
-
let requestId = crypto.randomBytes(8).toString('base64');
|
|
327
|
-
|
|
328
|
-
let res;
|
|
329
|
-
let data;
|
|
330
|
-
let retries = 0;
|
|
331
|
-
|
|
332
270
|
let openAiAPIURL;
|
|
333
271
|
switch (gptModel) {
|
|
334
272
|
case 'gpt-3.5-turbo-instruct':
|
|
335
273
|
{
|
|
336
274
|
openAiAPIURL = getApiUrl(baseApiUrl, OPENAI_API_URL_INSTRUCT);
|
|
337
275
|
payload.prompt = `${systemPrompt}\n${prompt}`;
|
|
338
|
-
|
|
339
|
-
payload.max_tokens = MAX_INSTRUCT_TOKENS - tokens.bpe.length;
|
|
276
|
+
payload.max_tokens = MAX_INSTRUCT_TOKENS - estimateTokens(payload.prompt);
|
|
340
277
|
}
|
|
341
278
|
break;
|
|
342
279
|
|
|
@@ -357,50 +294,13 @@ ${JSON.stringify(content)}`;
|
|
|
357
294
|
break;
|
|
358
295
|
}
|
|
359
296
|
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
headers,
|
|
368
|
-
body: JSON.stringify(payload),
|
|
369
|
-
dispatcher: opts.dispatcher || fetchAgent
|
|
370
|
-
});
|
|
371
|
-
|
|
372
|
-
data = await res.json();
|
|
373
|
-
|
|
374
|
-
if (!res.ok) {
|
|
375
|
-
if (res.status === 429 && ++retries < MAX_RETRIES) {
|
|
376
|
-
// try again
|
|
377
|
-
await new Promise(r => setTimeout(r, RETRY_DELAY_MS));
|
|
378
|
-
return await run();
|
|
379
|
-
}
|
|
380
|
-
|
|
381
|
-
if (data && data.error) {
|
|
382
|
-
let error = new Error(data.error.message || data.error);
|
|
383
|
-
if (data.error.code) {
|
|
384
|
-
error.code = data.error.code;
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
error.statusCode = res.status;
|
|
388
|
-
throw error;
|
|
389
|
-
}
|
|
390
|
-
|
|
391
|
-
let error = new Error('Failed to run API request');
|
|
392
|
-
error.statusCode = res.status;
|
|
393
|
-
throw error;
|
|
394
|
-
}
|
|
395
|
-
|
|
396
|
-
if (!data) {
|
|
397
|
-
throw new Error(`Failed to POST API request`);
|
|
398
|
-
}
|
|
399
|
-
};
|
|
400
|
-
|
|
401
|
-
const reqStartTime = Date.now();
|
|
402
|
-
await run();
|
|
403
|
-
const reqEndTime = Date.now();
|
|
297
|
+
const { data, time } = await apiRequest(openAiAPIURL, {
|
|
298
|
+
apiToken,
|
|
299
|
+
payload,
|
|
300
|
+
dispatcher: opts.dispatcher,
|
|
301
|
+
signal: opts.signal,
|
|
302
|
+
verbose: opts.verbose
|
|
303
|
+
});
|
|
404
304
|
|
|
405
305
|
let values;
|
|
406
306
|
let output =
|
|
@@ -413,10 +313,6 @@ ${JSON.stringify(content)}`;
|
|
|
413
313
|
.join('')
|
|
414
314
|
.trim();
|
|
415
315
|
|
|
416
|
-
if (opts.verbose) {
|
|
417
|
-
console.error(util.inspect({ requestId, output, data }, false, 8, true));
|
|
418
|
-
}
|
|
419
|
-
|
|
420
316
|
try {
|
|
421
317
|
let objStart = output.indexOf('{');
|
|
422
318
|
let objEnd = output.lastIndexOf('}');
|
|
@@ -471,8 +367,8 @@ ${JSON.stringify(content)}`;
|
|
|
471
367
|
});
|
|
472
368
|
|
|
473
369
|
if (opts.verbose) {
|
|
474
|
-
response._text =
|
|
475
|
-
response._time =
|
|
370
|
+
response._text = promptText;
|
|
371
|
+
response._time = time;
|
|
476
372
|
response._cr = charactersRemoved;
|
|
477
373
|
}
|
|
478
374
|
|
package/lib/list-models.js
CHANGED
|
@@ -1,10 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
const
|
|
4
|
-
const { fetch: fetchCmd, Agent } = require('undici');
|
|
5
|
-
const fetchAgent = new Agent({ connect: { timeout: 90 * 1000 } });
|
|
6
|
-
const util = require('util');
|
|
7
|
-
const crypto = require('crypto');
|
|
3
|
+
const { apiRequest } = require('./api-request');
|
|
8
4
|
|
|
9
5
|
const { getApiUrl, OPENAI_API_BASE_URL } = require('./get-api-url');
|
|
10
6
|
|
|
@@ -17,68 +13,18 @@ async function listModels(apiToken, opts) {
|
|
|
17
13
|
|
|
18
14
|
let openAiAPIURL = getApiUrl(baseApiUrl, OPENAI_API_MODELS);
|
|
19
15
|
|
|
20
|
-
|
|
21
|
-
'
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
let res;
|
|
29
|
-
let data;
|
|
30
|
-
let retries = 0;
|
|
31
|
-
|
|
32
|
-
if (opts.verbose) {
|
|
33
|
-
console.error(util.inspect({ requestId, apiUrl: openAiAPIURL }, false, 8, true));
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
let run = async () => {
|
|
37
|
-
res = await fetchCmd(openAiAPIURL, {
|
|
38
|
-
method: 'get',
|
|
39
|
-
headers,
|
|
40
|
-
dispatcher: opts.dispatcher || fetchAgent
|
|
41
|
-
});
|
|
42
|
-
|
|
43
|
-
data = await res.json();
|
|
44
|
-
|
|
45
|
-
if (!res.ok) {
|
|
46
|
-
if (res.status === 429 && ++retries < 5) {
|
|
47
|
-
// try again
|
|
48
|
-
await new Promise(r => setTimeout(r, 1000));
|
|
49
|
-
return await run();
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
if (data && data.error) {
|
|
53
|
-
let error = new Error(data.error.message || data.error);
|
|
54
|
-
if (data.error.code) {
|
|
55
|
-
error.code = data.error.code;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
error.statusCode = res.status;
|
|
59
|
-
throw error;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
let error = new Error('Failed to run API request');
|
|
63
|
-
error.statusCode = res.status;
|
|
64
|
-
throw error;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
if (!data) {
|
|
68
|
-
throw new Error(`Failed to POST API request`);
|
|
69
|
-
}
|
|
70
|
-
};
|
|
71
|
-
|
|
72
|
-
const reqStartTime = Date.now();
|
|
73
|
-
await run();
|
|
74
|
-
const reqEndTime = Date.now();
|
|
16
|
+
const { data, time } = await apiRequest(openAiAPIURL, {
|
|
17
|
+
method: 'get',
|
|
18
|
+
apiToken,
|
|
19
|
+
dispatcher: opts.dispatcher,
|
|
20
|
+
signal: opts.signal,
|
|
21
|
+
verbose: opts.verbose
|
|
22
|
+
});
|
|
75
23
|
|
|
76
24
|
const response = { models: [].concat((data && data.data) || []).filter(entry => !['openai-dev'].includes(entry.owned_by)) };
|
|
77
25
|
|
|
78
26
|
if (opts.verbose) {
|
|
79
|
-
response._time =
|
|
80
|
-
|
|
81
|
-
console.error(util.inspect({ requestId, response }, false, 8, true));
|
|
27
|
+
response._time = time;
|
|
82
28
|
}
|
|
83
29
|
|
|
84
30
|
response.models.sort((a, b) => {
|