@postalsys/email-ai-tools 1.5.0 → 1.6.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.
- package/CHANGELOG.md +14 -0
- package/examples/question.js +18 -0
- package/index.js +2 -1
- package/lib/embeddings-query.js +330 -36
- package/lib/generate-embeddings.js +12 -1
- package/lib/generate-summary.js +12 -1
- package/lib/risk-analysis.js +4 -0
- package/package.json +4 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [1.6.0](https://github.com/postalsys/email-ai-tools/compare/v1.5.1...v1.6.0) (2023-10-02)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
### Features
|
|
7
|
+
|
|
8
|
+
* **chat:** Added question sorting method ([6b5ce50](https://github.com/postalsys/email-ai-tools/commit/6b5ce506f7d43e03b1dd9f6ae0142c976a4eb88e))
|
|
9
|
+
|
|
10
|
+
## [1.5.1](https://github.com/postalsys/email-ai-tools/compare/v1.5.0...v1.5.1) (2023-09-27)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
### Bug Fixes
|
|
14
|
+
|
|
15
|
+
* **package:** updated package-lock ([a892178](https://github.com/postalsys/email-ai-tools/commit/a89217801c7d05a281c031a9ac72593e29febc97))
|
|
16
|
+
|
|
3
17
|
## [1.5.0](https://github.com/postalsys/email-ai-tools/compare/v1.4.1...v1.5.0) (2023-09-27)
|
|
4
18
|
|
|
5
19
|
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { questionQuery } = require('../lib/embeddings-query');
|
|
4
|
+
const util = require('util');
|
|
5
|
+
|
|
6
|
+
async function main() {
|
|
7
|
+
const question = 'Kui suur on mu eelmise kuu Amazoni arve?';
|
|
8
|
+
|
|
9
|
+
const info = await questionQuery(question, process.env.OPENAI_API_KEY, {
|
|
10
|
+
//gptModel: 'gpt-3.5-turbo',
|
|
11
|
+
//gptModel: 'gpt-4',
|
|
12
|
+
verbose: true
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
console.log(util.inspect(info, false, 22, true));
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
main();
|
package/index.js
CHANGED
|
@@ -3,13 +3,14 @@
|
|
|
3
3
|
const { generateSummary, DEFAULT_SYSTEM_PROMPT, DEFAULT_USER_PROMPT } = require('./lib/generate-summary');
|
|
4
4
|
const riskAnalysis = require('./lib/risk-analysis');
|
|
5
5
|
const { generateEmbeddings, getChunkEmbeddings } = require('./lib/generate-embeddings');
|
|
6
|
-
const { embeddingsQuery } = require('./lib/embeddings-query');
|
|
6
|
+
const { embeddingsQuery, questionQuery } = require('./lib/embeddings-query');
|
|
7
7
|
|
|
8
8
|
module.exports = {
|
|
9
9
|
generateSummary,
|
|
10
10
|
generateEmbeddings,
|
|
11
11
|
getChunkEmbeddings,
|
|
12
12
|
embeddingsQuery,
|
|
13
|
+
questionQuery,
|
|
13
14
|
riskAnalysis,
|
|
14
15
|
DEFAULT_SYSTEM_PROMPT,
|
|
15
16
|
DEFAULT_USER_PROMPT
|
package/lib/embeddings-query.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
const packageData = require('../package.json');
|
|
4
4
|
const { default: GPT3Tokenizer } = require('gpt3-tokenizer');
|
|
5
5
|
const util = require('util');
|
|
6
|
+
const crypto = require('crypto');
|
|
6
7
|
const { fetch: fetchCmd, Agent } = require('undici');
|
|
7
8
|
const fetchAgent = new Agent({ connect: { timeout: 90 * 1000 } });
|
|
8
9
|
|
|
@@ -14,26 +15,94 @@ const OPENAI_API_URL_CHAT = 'https://api.openai.com/v1/chat/completions';
|
|
|
14
15
|
const OPENAI_API_URL_INSTRUCT = 'https://api.openai.com/v1/completions';
|
|
15
16
|
|
|
16
17
|
const DEFAULT_SYSTEM_PROMPT = `
|
|
17
|
-
You are
|
|
18
|
+
You are an automated system designed to extract and provide information based on stored emails.
|
|
18
19
|
`.trim();
|
|
19
20
|
|
|
20
21
|
const SCHEMA_PROMPT = `
|
|
21
|
-
Input
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
-
|
|
26
|
-
|
|
27
|
-
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
-
|
|
32
|
-
|
|
33
|
-
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
22
|
+
**Input Information:**
|
|
23
|
+
|
|
24
|
+
- **Question Format:** The query is presented using the JSON schema: \`{"question":"What was the date of our last meeting?"}\`
|
|
25
|
+
|
|
26
|
+
- **Email Context:** We are provided with a series of emails to analyze.
|
|
27
|
+
|
|
28
|
+
- **Email Structure:** Each email is divided into two sections: a header and its content. These sections are separated by an empty line.
|
|
29
|
+
|
|
30
|
+
- **Email Content:** This pertains exclusively to the plain text of the email. No attachments or their contents are provided.
|
|
31
|
+
|
|
32
|
+
- **Sample Header:**
|
|
33
|
+
\`\`\`
|
|
34
|
+
- EMAIL #1:
|
|
35
|
+
From: James <james@example.com>
|
|
36
|
+
To: Andris <andris@example.com>
|
|
37
|
+
Subject: Hello
|
|
38
|
+
Message-ID: <example@value>
|
|
39
|
+
Date: 1 Oct 2023 06:30:26 +0200
|
|
40
|
+
Attachments: image.png, invoice.pdf
|
|
41
|
+
\`\`\`
|
|
42
|
+
|
|
43
|
+
- Every header starts with the string \`- EMAIL #\` followed by the email sequence number
|
|
44
|
+
- **Mandatory Field:** Every email will contain a unique Message-ID.
|
|
45
|
+
- **Date Field:** Represents the timestamp when the email was sent.
|
|
46
|
+
- **Attachments:** This field, when present, lists the names of attachments included with the email, separated by commas.
|
|
47
|
+
|
|
48
|
+
**Output Guidelines:**
|
|
49
|
+
|
|
50
|
+
1. Your objective is to sift through the email context and pinpoint the answer that best addresses the given query.
|
|
51
|
+
2. If no email matches the query criteria, or if the match is ambiguous, refrain from providing an answer.
|
|
52
|
+
3. Limit your sources strictly to the provided email context. External references are not to be utilized.
|
|
53
|
+
4. Format your response as follows:
|
|
54
|
+
- Start with \`Answer:\` followed by the relevant information.
|
|
55
|
+
- On a new line, begin with \`Message-ID:\` and cite the unique Message-ID(s) of the emails you sourced your answer from.
|
|
56
|
+
5. Ensure that the Message-ID is never embedded within the main body of your response.
|
|
57
|
+
6. Avoid including any additional commentary or annotations.
|
|
58
|
+
`.trim();
|
|
59
|
+
|
|
60
|
+
const QUESTION_PROMPT = `
|
|
61
|
+
Instructions:
|
|
62
|
+
|
|
63
|
+
You are analyzing user questions regarding email retrieval from a database. From the user's query, determine:
|
|
64
|
+
|
|
65
|
+
1. **Order Preference**:
|
|
66
|
+
- Retrieve older emails first ('older_first').
|
|
67
|
+
- Retrieve newer emails first ('newer_first').
|
|
68
|
+
- If no specific order is discernible from the query, identify the most relevant email ('best_match'), based on keywords or subjects that closely align with the user's question.
|
|
69
|
+
|
|
70
|
+
2. **Time Constraints**:
|
|
71
|
+
- Identify the starting point for the query ('start_time').
|
|
72
|
+
- Identify when to stop the query ('end_time').
|
|
73
|
+
|
|
74
|
+
**Context**:
|
|
75
|
+
|
|
76
|
+
- The current time is '${new Date().toUTCString()}'.
|
|
77
|
+
|
|
78
|
+
**Output Guidelines**:
|
|
79
|
+
|
|
80
|
+
- For terms implying a near-future context (e.g., "next", "newest", "upcoming"), opt for the 'newer_first' ordering.
|
|
81
|
+
- For terms implying a distant past (e.g., "first", "oldest"), use the 'older_first' ordering.
|
|
82
|
+
- If the user's query does not provide a clear time frame, or if the system's confidence in deducing a timeframe is below 70%, exclude 'start_time' and 'end_time' from the output.
|
|
83
|
+
- If the deduced 'end_time' aligns with current time, omit the 'end_time'.
|
|
84
|
+
- For unspecified time zones, timestamps should follow the 'YYYY-MM-DD hh:mm:ss' format.
|
|
85
|
+
- If only the date is known, use the 'YYYY-MM-DD' format.
|
|
86
|
+
- Assume the week starts on Monday.
|
|
87
|
+
- Your response should be structured in JSON, strictly adhering to the schema:
|
|
88
|
+
\`\`\`
|
|
89
|
+
{
|
|
90
|
+
"ordering": "",
|
|
91
|
+
"start_time": "",
|
|
92
|
+
"end_time": ""
|
|
93
|
+
}
|
|
94
|
+
\`\`\`
|
|
95
|
+
- Example Queries and Responses:
|
|
96
|
+
- **Query**: "When is the next conference event?"
|
|
97
|
+
**Response**: \`{"ordering":"newer_first"}\`
|
|
98
|
+
- **Query**: "What did James write to me about last Friday?" (assuming that current time is "2023-10-02")
|
|
99
|
+
**Response**: \`{"ordering":"best_match", "start_time": "2023-09-29", "end_time": "2023-09-30"}\`
|
|
100
|
+
- **Query**: "When did I receive my first Amazon invoice?"
|
|
101
|
+
**Response**: \`{"ordering":"older_first"}\`
|
|
102
|
+
|
|
103
|
+
**User's Query**:
|
|
104
|
+
Process the user question:
|
|
105
|
+
`.trim();
|
|
37
106
|
|
|
38
107
|
async function embeddingsQuery(apiToken, opts) {
|
|
39
108
|
opts = opts || {};
|
|
@@ -104,6 +173,10 @@ ${promptText}
|
|
|
104
173
|
model: gptModel
|
|
105
174
|
};
|
|
106
175
|
|
|
176
|
+
if (opts.user) {
|
|
177
|
+
payload.user = opts.user;
|
|
178
|
+
}
|
|
179
|
+
|
|
107
180
|
if (opts.temperature && !isNaN(opts.temperature)) {
|
|
108
181
|
payload.temperature = Number(opts.temperature);
|
|
109
182
|
}
|
|
@@ -112,6 +185,8 @@ ${promptText}
|
|
|
112
185
|
payload.top_p = Number(opts.topP);
|
|
113
186
|
}
|
|
114
187
|
|
|
188
|
+
const requestId = crypto.randomBytes(8).toString('base64');
|
|
189
|
+
|
|
115
190
|
let res;
|
|
116
191
|
let data;
|
|
117
192
|
let retries = 0;
|
|
@@ -145,7 +220,7 @@ ${promptText}
|
|
|
145
220
|
}
|
|
146
221
|
|
|
147
222
|
if (opts.verbose) {
|
|
148
|
-
console.
|
|
223
|
+
console.error(util.inspect({ requestId, payload }, false, 8, true));
|
|
149
224
|
}
|
|
150
225
|
|
|
151
226
|
let run = async () => {
|
|
@@ -189,7 +264,6 @@ ${promptText}
|
|
|
189
264
|
await run();
|
|
190
265
|
const reqEndTime = Date.now();
|
|
191
266
|
|
|
192
|
-
let values;
|
|
193
267
|
let output =
|
|
194
268
|
data &&
|
|
195
269
|
data.choices &&
|
|
@@ -200,27 +274,49 @@ ${promptText}
|
|
|
200
274
|
.join('')
|
|
201
275
|
.trim();
|
|
202
276
|
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
output = output.substring(prefixMatch.index + prefixMatch[0].length).trim();
|
|
277
|
+
if (opts.verbose) {
|
|
278
|
+
console.error(util.inspect({ requestId, output: data }, false, 8, true));
|
|
206
279
|
}
|
|
207
280
|
|
|
208
|
-
|
|
281
|
+
let responseValues = { answer: '', 'message-id': '' };
|
|
282
|
+
let curKey;
|
|
283
|
+
output
|
|
209
284
|
.trim()
|
|
210
|
-
.replace(
|
|
211
|
-
.
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
285
|
+
.replace(/\r?\n/g, '\n')
|
|
286
|
+
.split(/(^|\n)(Answer:|Message-ID:)/gi)
|
|
287
|
+
.map(v => v.trim())
|
|
288
|
+
.filter(v => v)
|
|
289
|
+
.forEach(val => {
|
|
290
|
+
if (/^(answer|message-id):$/i.test(val)) {
|
|
291
|
+
curKey = val.replace(/:$/, '').trim().toLowerCase();
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
if (!curKey || !val) {
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
if (curKey === 'message-id') {
|
|
300
|
+
val = val
|
|
301
|
+
.split(/,/)
|
|
302
|
+
.map(v => v.trim())
|
|
303
|
+
.filter(v => v)
|
|
304
|
+
.join('\n');
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
if (!responseValues[curKey]) {
|
|
308
|
+
responseValues[curKey] = val;
|
|
309
|
+
} else {
|
|
310
|
+
responseValues[curKey] += '\n' + val;
|
|
311
|
+
}
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
if (responseValues['message-id']) {
|
|
315
|
+
responseValues.messageId = Array.from(new Set(responseValues['message-id'].split(/\n/)));
|
|
221
316
|
}
|
|
317
|
+
delete responseValues['message-id'];
|
|
222
318
|
|
|
223
|
-
const response = Object.assign({ id: null, tokens: null, model: null },
|
|
319
|
+
const response = Object.assign({ id: null, tokens: null, model: null }, responseValues, {
|
|
224
320
|
id: data && data.id,
|
|
225
321
|
tokens: data && data.usage && data.usage.total_tokens,
|
|
226
322
|
model: gptModel
|
|
@@ -229,9 +325,207 @@ ${promptText}
|
|
|
229
325
|
if (opts.verbose) {
|
|
230
326
|
response._time = reqEndTime - reqStartTime;
|
|
231
327
|
response._cr = charactersRemoved;
|
|
328
|
+
|
|
329
|
+
console.error(util.inspect({ requestId, response }, false, 8, true));
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
return response;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
async function questionQuery(question, apiToken, opts) {
|
|
336
|
+
opts = opts || {};
|
|
337
|
+
|
|
338
|
+
let systemPrompt = (opts.systemPrompt || DEFAULT_SYSTEM_PROMPT).toString().trim();
|
|
339
|
+
question = (question || '').toString().trim();
|
|
340
|
+
if (!question) {
|
|
341
|
+
let error = new Error('Question not provided');
|
|
342
|
+
error.code = 'EmptyInput';
|
|
343
|
+
throw error;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
let gptModel = opts.gptModel || 'gpt-3.5-turbo-instruct';
|
|
347
|
+
|
|
348
|
+
let prompt = `${QUESTION_PROMPT}
|
|
349
|
+
${question}
|
|
350
|
+
`;
|
|
351
|
+
|
|
352
|
+
let headers = {
|
|
353
|
+
'User-Agent': `${packageData.name}/${packageData.version}`,
|
|
354
|
+
Authorization: `Bearer ${apiToken}`,
|
|
355
|
+
'Content-Type': 'application/json'
|
|
356
|
+
};
|
|
357
|
+
|
|
358
|
+
let payload = {
|
|
359
|
+
model: gptModel
|
|
360
|
+
};
|
|
361
|
+
|
|
362
|
+
if (opts.user) {
|
|
363
|
+
payload.user = opts.user;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
if (opts.temperature && !isNaN(opts.temperature)) {
|
|
367
|
+
payload.temperature = Number(opts.temperature);
|
|
368
|
+
} else {
|
|
369
|
+
payload.temperature = 0.2;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
if (opts.topP && !isNaN(opts.topP)) {
|
|
373
|
+
payload.top_p = Number(opts.topP);
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
const requestId = crypto.randomBytes(8).toString('base64');
|
|
377
|
+
|
|
378
|
+
let res;
|
|
379
|
+
let data;
|
|
380
|
+
let retries = 0;
|
|
381
|
+
|
|
382
|
+
let openAiAPIURL;
|
|
383
|
+
switch (gptModel) {
|
|
384
|
+
case 'gpt-3.5-turbo-instruct':
|
|
385
|
+
{
|
|
386
|
+
openAiAPIURL = OPENAI_API_URL_INSTRUCT;
|
|
387
|
+
payload.prompt = `${systemPrompt}\n${prompt}`;
|
|
388
|
+
let tokens = tokenizer.encode(payload.prompt);
|
|
389
|
+
payload.max_tokens = 4000 - tokens.bpe.length;
|
|
390
|
+
}
|
|
391
|
+
break;
|
|
392
|
+
|
|
393
|
+
case 'gpt-3.5-turbo':
|
|
394
|
+
case 'gpt-4':
|
|
395
|
+
default:
|
|
396
|
+
openAiAPIURL = OPENAI_API_URL_CHAT;
|
|
397
|
+
payload.messages = [
|
|
398
|
+
{
|
|
399
|
+
role: 'system',
|
|
400
|
+
content: `${systemPrompt}`
|
|
401
|
+
},
|
|
402
|
+
{
|
|
403
|
+
role: 'user',
|
|
404
|
+
content: prompt
|
|
405
|
+
}
|
|
406
|
+
];
|
|
407
|
+
break;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
if (opts.verbose) {
|
|
411
|
+
console.error(util.inspect({ requestId, payload }, false, 8, true));
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
let run = async () => {
|
|
415
|
+
res = await fetchCmd(openAiAPIURL, {
|
|
416
|
+
method: 'post',
|
|
417
|
+
headers,
|
|
418
|
+
body: JSON.stringify(payload),
|
|
419
|
+
dispatcher: fetchAgent
|
|
420
|
+
});
|
|
421
|
+
|
|
422
|
+
data = await res.json();
|
|
423
|
+
|
|
424
|
+
if (!res.ok) {
|
|
425
|
+
if (res.status === 429 && ++retries < 5) {
|
|
426
|
+
// try again
|
|
427
|
+
await new Promise(r => setTimeout(r, 1000));
|
|
428
|
+
return await run();
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
if (data && data.error) {
|
|
432
|
+
let error = new Error(data.error.message || data.error);
|
|
433
|
+
if (data.error.code) {
|
|
434
|
+
error.code = data.error.code;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
error.statusCode = res.status;
|
|
438
|
+
throw error;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
let error = new Error('Failed to run API request');
|
|
442
|
+
error.statusCode = res.status;
|
|
443
|
+
throw error;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
if (!data) {
|
|
447
|
+
throw new Error(`Failed to POST API request`);
|
|
448
|
+
}
|
|
449
|
+
};
|
|
450
|
+
|
|
451
|
+
const reqStartTime = Date.now();
|
|
452
|
+
await run();
|
|
453
|
+
const reqEndTime = Date.now();
|
|
454
|
+
|
|
455
|
+
let values;
|
|
456
|
+
let output =
|
|
457
|
+
data &&
|
|
458
|
+
data.choices &&
|
|
459
|
+
data.choices
|
|
460
|
+
.filter(msg => msg && ((msg.message && msg.message.role === 'assistant' && msg.message.content) || msg.text))
|
|
461
|
+
.sort((a, b) => ((a && a.index) || 0) - ((b && b.index) || 0))
|
|
462
|
+
.map(msg => (msg.message && msg.message.content) || msg.text)
|
|
463
|
+
.join('')
|
|
464
|
+
.trim();
|
|
465
|
+
|
|
466
|
+
if (opts.verbose) {
|
|
467
|
+
console.error(util.inspect({ requestId, output: data }, false, 8, true));
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
try {
|
|
471
|
+
let objStart = output.indexOf('{');
|
|
472
|
+
let objEnd = output.lastIndexOf('}');
|
|
473
|
+
|
|
474
|
+
if (objStart < 0 || objEnd < 0 || objEnd <= objStart) {
|
|
475
|
+
let error = new Error('Invalid JSON object');
|
|
476
|
+
error.objStart = objStart;
|
|
477
|
+
error.objEnd = objEnd;
|
|
478
|
+
throw error;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// remove potential comments before and after the JSON output
|
|
482
|
+
if (objEnd < output.length - 1) {
|
|
483
|
+
output = output.substring(0, objEnd + 1);
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
if (objStart > 0) {
|
|
487
|
+
output = output.substring(objStart);
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
values = JSON.parse(output);
|
|
491
|
+
|
|
492
|
+
let walkAndRemoveNull = branch => {
|
|
493
|
+
if (typeof branch !== 'object' || !branch) {
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
for (let key of Object.keys(branch)) {
|
|
497
|
+
let subBranch = branch[key];
|
|
498
|
+
if (Array.isArray(subBranch)) {
|
|
499
|
+
for (let entry of subBranch) {
|
|
500
|
+
walkAndRemoveNull(entry);
|
|
501
|
+
}
|
|
502
|
+
} else if (subBranch && typeof subBranch === 'object') {
|
|
503
|
+
walkAndRemoveNull(subBranch);
|
|
504
|
+
} else if (!['boolean', 'string', 'number'].includes(typeof subBranch) || subBranch === '') {
|
|
505
|
+
delete branch[key];
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
};
|
|
509
|
+
|
|
510
|
+
walkAndRemoveNull(values);
|
|
511
|
+
} catch (err) {
|
|
512
|
+
let error = new Error('Failed to parse output from OpenAI API', { cause: err });
|
|
513
|
+
error.textContent = output;
|
|
514
|
+
error.code = 'OutputParseFailed';
|
|
515
|
+
throw error;
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
const response = Object.assign({ id: null, tokens: null, model: null }, values || {}, {
|
|
519
|
+
id: data && data.id,
|
|
520
|
+
tokens: data && data.usage && data.usage.total_tokens,
|
|
521
|
+
model: gptModel
|
|
522
|
+
});
|
|
523
|
+
|
|
524
|
+
if (opts.verbose) {
|
|
525
|
+
response._time = reqEndTime - reqStartTime;
|
|
232
526
|
}
|
|
233
527
|
|
|
234
528
|
return response;
|
|
235
529
|
}
|
|
236
530
|
|
|
237
|
-
module.exports = { embeddingsQuery };
|
|
531
|
+
module.exports = { embeddingsQuery, questionQuery };
|
|
@@ -11,6 +11,7 @@ const fetchAgent = new Agent({ connect: { timeout: 90 * 1000 } });
|
|
|
11
11
|
const util = require('util');
|
|
12
12
|
const linkifyIt = require('linkify-it');
|
|
13
13
|
const tlds = require('tlds');
|
|
14
|
+
const crypto = require('crypto');
|
|
14
15
|
|
|
15
16
|
const linkify = linkifyIt()
|
|
16
17
|
.tlds(tlds) // Reload with full tlds list
|
|
@@ -38,12 +39,18 @@ async function getChunkEmbeddings(chunk, apiToken, opts) {
|
|
|
38
39
|
input: chunk
|
|
39
40
|
};
|
|
40
41
|
|
|
42
|
+
if (opts.user) {
|
|
43
|
+
payload.user = opts.user;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
let requestId = crypto.randomBytes(8).toString('base64');
|
|
47
|
+
|
|
41
48
|
let res;
|
|
42
49
|
let data;
|
|
43
50
|
let retries = 0;
|
|
44
51
|
|
|
45
52
|
if (verbose) {
|
|
46
|
-
console.
|
|
53
|
+
console.error(util.inspect({ requestId, payload }, false, 8, true));
|
|
47
54
|
}
|
|
48
55
|
|
|
49
56
|
let run = async () => {
|
|
@@ -86,6 +93,10 @@ async function getChunkEmbeddings(chunk, apiToken, opts) {
|
|
|
86
93
|
await run();
|
|
87
94
|
const reqEndTime = Date.now();
|
|
88
95
|
|
|
96
|
+
if (opts.verbose) {
|
|
97
|
+
console.error(util.inspect({ requestId, output: data }, false, 8, true));
|
|
98
|
+
}
|
|
99
|
+
|
|
89
100
|
let embedding = data?.data?.[0]?.embedding;
|
|
90
101
|
return {
|
|
91
102
|
chunk,
|
package/lib/generate-summary.js
CHANGED
|
@@ -4,6 +4,7 @@ const packageData = require('../package.json');
|
|
|
4
4
|
const { htmlToText } = require('@postalsys/email-text-tools');
|
|
5
5
|
const { default: GPT3Tokenizer } = require('gpt3-tokenizer');
|
|
6
6
|
const util = require('util');
|
|
7
|
+
const crypto = require('crypto');
|
|
7
8
|
const { fetch: fetchCmd, Agent } = require('undici');
|
|
8
9
|
const fetchAgent = new Agent({ connect: { timeout: 90 * 1000 } });
|
|
9
10
|
|
|
@@ -218,6 +219,10 @@ ${JSON.stringify(content)}`;
|
|
|
218
219
|
model: gptModel
|
|
219
220
|
};
|
|
220
221
|
|
|
222
|
+
if (opts.user) {
|
|
223
|
+
payload.user = opts.user;
|
|
224
|
+
}
|
|
225
|
+
|
|
221
226
|
if (opts.temperature && !isNaN(opts.temperature)) {
|
|
222
227
|
payload.temperature = Number(opts.temperature);
|
|
223
228
|
}
|
|
@@ -226,6 +231,8 @@ ${JSON.stringify(content)}`;
|
|
|
226
231
|
payload.top_p = Number(opts.topP);
|
|
227
232
|
}
|
|
228
233
|
|
|
234
|
+
let requestId = crypto.randomBytes(8).toString('base64');
|
|
235
|
+
|
|
229
236
|
let res;
|
|
230
237
|
let data;
|
|
231
238
|
let retries = 0;
|
|
@@ -259,7 +266,7 @@ ${JSON.stringify(content)}`;
|
|
|
259
266
|
}
|
|
260
267
|
|
|
261
268
|
if (opts.verbose) {
|
|
262
|
-
console.
|
|
269
|
+
console.error(util.inspect({ requestId, payload }, false, 8, true));
|
|
263
270
|
}
|
|
264
271
|
|
|
265
272
|
let run = async () => {
|
|
@@ -314,6 +321,10 @@ ${JSON.stringify(content)}`;
|
|
|
314
321
|
.join('')
|
|
315
322
|
.trim();
|
|
316
323
|
|
|
324
|
+
if (opts.verbose) {
|
|
325
|
+
console.error(util.inspect({ output, data }, false, 8, true));
|
|
326
|
+
}
|
|
327
|
+
|
|
317
328
|
try {
|
|
318
329
|
let objStart = output.indexOf('{');
|
|
319
330
|
let objEnd = output.lastIndexOf('}');
|
package/lib/risk-analysis.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@postalsys/email-ai-tools",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.6.0",
|
|
4
4
|
"description": "Email AI tools",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"scripts": {
|
|
@@ -26,10 +26,10 @@
|
|
|
26
26
|
"@postalsys/email-text-tools": "2.1.1",
|
|
27
27
|
"gpt3-tokenizer": "1.1.5",
|
|
28
28
|
"libmime": "5.2.1",
|
|
29
|
-
"linkify-it": "
|
|
29
|
+
"linkify-it": "4.0.1",
|
|
30
30
|
"nodemailer": "6.9.5",
|
|
31
31
|
"punycode": "2.3.0",
|
|
32
|
-
"tlds": "
|
|
33
|
-
"undici": "5.
|
|
32
|
+
"tlds": "1.242.0",
|
|
33
|
+
"undici": "5.25.3"
|
|
34
34
|
}
|
|
35
35
|
}
|