@postalsys/email-ai-tools 1.5.1 → 1.6.1

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