@postalsys/email-ai-tools 1.4.0 → 1.5.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 CHANGED
@@ -1,5 +1,19 @@
1
1
  # Changelog
2
2
 
3
+ ## [1.5.0](https://github.com/postalsys/email-ai-tools/compare/v1.4.1...v1.5.0) (2023-09-27)
4
+
5
+
6
+ ### Features
7
+
8
+ * **embeddings:** Support for embeddings query ([5c40f15](https://github.com/postalsys/email-ai-tools/commit/5c40f1504f969cb39270edf28e06e2ea65681fc1))
9
+
10
+ ## [1.4.1](https://github.com/postalsys/email-ai-tools/compare/v1.4.0...v1.4.1) (2023-09-23)
11
+
12
+
13
+ ### Bug Fixes
14
+
15
+ * **embeddings:** remove quoted lines ([fb5dd92](https://github.com/postalsys/email-ai-tools/commit/fb5dd92b834249a0290113df4c42b2f01eb22e84))
16
+
3
17
  ## [1.4.0](https://github.com/postalsys/email-ai-tools/compare/v1.3.4...v1.4.0) (2023-09-20)
4
18
 
5
19
 
@@ -28,6 +28,11 @@ async function main() {
28
28
  );
29
29
 
30
30
  console.log(util.inspect(result, false, 22, true));
31
+
32
+ for (let e of result?.embeddings || []) {
33
+ console.log('CHUNK');
34
+ console.log(e.chunk);
35
+ }
31
36
  }
32
37
 
33
38
  main();
package/index.js CHANGED
@@ -2,11 +2,14 @@
2
2
 
3
3
  const { generateSummary, DEFAULT_SYSTEM_PROMPT, DEFAULT_USER_PROMPT } = require('./lib/generate-summary');
4
4
  const riskAnalysis = require('./lib/risk-analysis');
5
- const { generateEmbeddings } = require('./lib/generate-embeddings');
5
+ const { generateEmbeddings, getChunkEmbeddings } = require('./lib/generate-embeddings');
6
+ const { embeddingsQuery } = require('./lib/embeddings-query');
6
7
 
7
8
  module.exports = {
8
9
  generateSummary,
9
10
  generateEmbeddings,
11
+ getChunkEmbeddings,
12
+ embeddingsQuery,
10
13
  riskAnalysis,
11
14
  DEFAULT_SYSTEM_PROMPT,
12
15
  DEFAULT_USER_PROMPT
@@ -0,0 +1,237 @@
1
+ 'use strict';
2
+
3
+ const packageData = require('../package.json');
4
+ const { default: GPT3Tokenizer } = require('gpt3-tokenizer');
5
+ const util = require('util');
6
+ const { fetch: fetchCmd, Agent } = require('undici');
7
+ const fetchAgent = new Agent({ connect: { timeout: 90 * 1000 } });
8
+
9
+ const tokenizer = new GPT3Tokenizer({ type: 'gpt3' });
10
+
11
+ const MAX_ALLOWED_TEXT_LENGTH = 32 * 1024;
12
+ const MAX_ALLOWED_TOKENS = 4000;
13
+ const OPENAI_API_URL_CHAT = 'https://api.openai.com/v1/chat/completions';
14
+ const OPENAI_API_URL_INSTRUCT = 'https://api.openai.com/v1/completions';
15
+
16
+ const DEFAULT_SYSTEM_PROMPT = `
17
+ You are a helpful executive assistant that looks for requested information from stored emails.
18
+ `.trim();
19
+
20
+ 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();
37
+
38
+ async function embeddingsQuery(apiToken, opts) {
39
+ opts = opts || {};
40
+
41
+ let systemPrompt = (opts.systemPrompt || DEFAULT_SYSTEM_PROMPT).toString().trim();
42
+ let question = (opts.question || '').toString().trim();
43
+ let contextChunks = (opts.contextChunks || '').toString().trim();
44
+
45
+ let maxAllowedTokens = opts.maxTokens || MAX_ALLOWED_TOKENS;
46
+ let gptModel = opts.gptModel || 'gpt-3.5-turbo';
47
+
48
+ let prompt;
49
+
50
+ let charactersRemoved = 0;
51
+ let promptText = contextChunks;
52
+
53
+ if (promptText.length > MAX_ALLOWED_TEXT_LENGTH) {
54
+ charactersRemoved += promptText.length - MAX_ALLOWED_TEXT_LENGTH;
55
+ promptText = promptText.substr(0, MAX_ALLOWED_TEXT_LENGTH);
56
+ }
57
+
58
+ // eslint-disable-next-line no-constant-condition
59
+ while (true) {
60
+ prompt = `${SCHEMA_PROMPT}
61
+
62
+ Input:
63
+ ${JSON.stringify({ question })}
64
+
65
+ Context emails:
66
+
67
+ ${promptText}
68
+ `;
69
+
70
+ let tokens = tokenizer.encode(prompt);
71
+ if (tokens.bpe.length <= maxAllowedTokens) {
72
+ break;
73
+ }
74
+ if (promptText.length > 2 * 1024 * 1024) {
75
+ promptText = promptText.substring(0, promptText.length - 1024 * 1024);
76
+ charactersRemoved += 1024 * 1024;
77
+ } else if (promptText.length > 2 * 1024) {
78
+ promptText = promptText.substring(0, promptText.length - 1024);
79
+ charactersRemoved += 1024;
80
+ } else if (promptText.length > 2 * 256) {
81
+ promptText = promptText.substring(0, promptText.length - 256);
82
+ charactersRemoved += 255;
83
+ } else if (promptText.length > 2 * 100) {
84
+ promptText = promptText.substring(0, promptText.length - 100);
85
+ charactersRemoved += 100;
86
+ } else if (promptText.length > 2 * 10) {
87
+ promptText = promptText.substring(0, promptText.length - 10);
88
+ charactersRemoved += 10;
89
+ } else if (promptText.length > 1) {
90
+ promptText = promptText.substring(0, promptText.length - 1);
91
+ charactersRemoved += 1;
92
+ } else {
93
+ throw new Error(`Prompt too long. Removed ${charactersRemoved} characters.`);
94
+ }
95
+ }
96
+
97
+ let headers = {
98
+ 'User-Agent': `${packageData.name}/${packageData.version}`,
99
+ Authorization: `Bearer ${apiToken}`,
100
+ 'Content-Type': 'application/json'
101
+ };
102
+
103
+ let payload = {
104
+ model: gptModel
105
+ };
106
+
107
+ if (opts.temperature && !isNaN(opts.temperature)) {
108
+ payload.temperature = Number(opts.temperature);
109
+ }
110
+
111
+ if (opts.topP && !isNaN(opts.topP)) {
112
+ payload.top_p = Number(opts.topP);
113
+ }
114
+
115
+ let res;
116
+ let data;
117
+ let retries = 0;
118
+
119
+ let openAiAPIURL;
120
+ switch (gptModel) {
121
+ case 'gpt-3.5-turbo-instruct':
122
+ {
123
+ openAiAPIURL = OPENAI_API_URL_INSTRUCT;
124
+ payload.prompt = `${systemPrompt}\n${prompt}`;
125
+ let tokens = tokenizer.encode(payload.prompt);
126
+ payload.max_tokens = 4000 - tokens.bpe.length;
127
+ }
128
+ break;
129
+
130
+ case 'gpt-3.5-turbo':
131
+ case 'gpt-4':
132
+ default:
133
+ openAiAPIURL = OPENAI_API_URL_CHAT;
134
+ payload.messages = [
135
+ {
136
+ role: 'system',
137
+ content: `${systemPrompt}`
138
+ },
139
+ {
140
+ role: 'user',
141
+ content: prompt
142
+ }
143
+ ];
144
+ break;
145
+ }
146
+
147
+ if (opts.verbose) {
148
+ console.log(util.inspect(payload, false, 5, true));
149
+ }
150
+
151
+ let run = async () => {
152
+ res = await fetchCmd(openAiAPIURL, {
153
+ method: 'post',
154
+ headers,
155
+ body: JSON.stringify(payload),
156
+ dispatcher: fetchAgent
157
+ });
158
+
159
+ data = await res.json();
160
+
161
+ if (!res.ok) {
162
+ if (res.status === 429 && ++retries < 5) {
163
+ // try again
164
+ await new Promise(r => setTimeout(r, 1000));
165
+ return await run();
166
+ }
167
+
168
+ if (data && data.error) {
169
+ let error = new Error(data.error.message || data.error);
170
+ if (data.error.code) {
171
+ error.code = data.error.code;
172
+ }
173
+
174
+ error.statusCode = res.status;
175
+ throw error;
176
+ }
177
+
178
+ let error = new Error('Failed to run API request');
179
+ error.statusCode = res.status;
180
+ throw error;
181
+ }
182
+
183
+ if (!data) {
184
+ throw new Error(`Failed to POST API request`);
185
+ }
186
+ };
187
+
188
+ const reqStartTime = Date.now();
189
+ await run();
190
+ const reqEndTime = Date.now();
191
+
192
+ let values;
193
+ let output =
194
+ data &&
195
+ data.choices &&
196
+ data.choices
197
+ .filter(msg => msg && ((msg.message && msg.message.role === 'assistant' && msg.message.content) || msg.text))
198
+ .sort((a, b) => ((a && a.index) || 0) - ((b && b.index) || 0))
199
+ .map(msg => (msg.message && msg.message.content) || msg.text)
200
+ .join('')
201
+ .trim();
202
+
203
+ let prefixMatch = output.match(/Message[-_]ID:?/i);
204
+ if (prefixMatch) {
205
+ output = output.substring(prefixMatch.index + prefixMatch[0].length).trim();
206
+ }
207
+
208
+ output = output
209
+ .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
+ };
221
+ }
222
+
223
+ const response = Object.assign({ id: null, tokens: null, model: null }, values, {
224
+ id: data && data.id,
225
+ tokens: data && data.usage && data.usage.total_tokens,
226
+ model: gptModel
227
+ });
228
+
229
+ if (opts.verbose) {
230
+ response._time = reqEndTime - reqStartTime;
231
+ response._cr = charactersRemoved;
232
+ }
233
+
234
+ return response;
235
+ }
236
+
237
+ module.exports = { embeddingsQuery };
@@ -9,18 +9,98 @@ const { default: GPT3Tokenizer } = require('gpt3-tokenizer');
9
9
  const { fetch: fetchCmd, Agent } = require('undici');
10
10
  const fetchAgent = new Agent({ connect: { timeout: 90 * 1000 } });
11
11
  const util = require('util');
12
+ const linkifyIt = require('linkify-it');
13
+ const tlds = require('tlds');
14
+
15
+ const linkify = linkifyIt()
16
+ .tlds(tlds) // Reload with full tlds list
17
+ .tlds('onion', true) // Add unofficial `.onion` domain
18
+ .add('git:', 'http:') // Add `git:` protocol as "alias"
19
+ .set({ fuzzyIP: true });
12
20
 
13
21
  const tokenizer = new GPT3Tokenizer({ type: 'gpt3' });
14
22
 
15
23
  const OPENAI_API_URL = 'https://api.openai.com/v1/embeddings';
16
24
 
25
+ async function getChunkEmbeddings(chunk, apiToken, opts) {
26
+ let { gptModel, verbose } = opts || {};
27
+
28
+ gptModel = gptModel || 'text-embedding-ada-002';
29
+
30
+ let headers = {
31
+ 'User-Agent': `${packageData.name}/${packageData.version}`,
32
+ Authorization: `Bearer ${apiToken}`,
33
+ 'Content-Type': 'application/json'
34
+ };
35
+
36
+ let payload = {
37
+ model: gptModel,
38
+ input: chunk
39
+ };
40
+
41
+ let res;
42
+ let data;
43
+ let retries = 0;
44
+
45
+ if (verbose) {
46
+ console.log(util.inspect(payload, false, 5, true));
47
+ }
48
+
49
+ let run = async () => {
50
+ res = await fetchCmd(OPENAI_API_URL, {
51
+ method: 'post',
52
+ headers,
53
+ body: JSON.stringify(payload),
54
+ dispatcher: fetchAgent
55
+ });
56
+
57
+ data = await res.json();
58
+ if (!res.ok) {
59
+ if (res.status === 429 && ++retries < 5) {
60
+ // try again
61
+ await new Promise(r => setTimeout(r, 1000));
62
+ return await run();
63
+ }
64
+
65
+ if (data && data.error) {
66
+ let error = new Error(data.error.message || data.error);
67
+ if (data.error.code) {
68
+ error.code = data.error.code;
69
+ }
70
+
71
+ error.statusCode = res.status;
72
+ throw error;
73
+ }
74
+
75
+ let error = new Error('Failed to run API request');
76
+ error.statusCode = res.status;
77
+ throw error;
78
+ }
79
+
80
+ if (!data) {
81
+ throw new Error(`Failed to POST API request`);
82
+ }
83
+ };
84
+
85
+ const reqStartTime = Date.now();
86
+ await run();
87
+ const reqEndTime = Date.now();
88
+
89
+ let embedding = data?.data?.[0]?.embedding;
90
+ return {
91
+ chunk,
92
+ embedding,
93
+ _time: reqEndTime - reqStartTime
94
+ };
95
+ }
96
+
17
97
  class Embedder {
18
98
  constructor(message, apiToken, opts) {
19
99
  this.message = message;
20
100
  this.apiToken = apiToken;
21
101
 
22
102
  opts = opts || {};
23
- this.chunkSize = opts.chunkSize || 600;
103
+ this.chunkSize = opts.chunkSize || 400;
24
104
  this.gptModel = opts.gptModel || 'text-embedding-ada-002';
25
105
 
26
106
  this.addressHeaders = new Map();
@@ -49,6 +129,7 @@ class Embedder {
49
129
  addressList.push(...this.formatAddresses(addressparser(value, { flatten: true })));
50
130
  }
51
131
  break;
132
+
52
133
  case 'subject': {
53
134
  subject = (value || '').toString().trim();
54
135
  try {
@@ -59,6 +140,20 @@ class Embedder {
59
140
  if (subject) {
60
141
  this.subject = subject;
61
142
  }
143
+ break;
144
+ }
145
+
146
+ case 'date': {
147
+ let date;
148
+ try {
149
+ date = new Date((value || '').toString().trim());
150
+ if (date && date.toString() !== 'Invalid Date') {
151
+ this.date = date.toUTCString();
152
+ }
153
+ } catch {
154
+ // ignore?
155
+ }
156
+ break;
62
157
  }
63
158
  }
64
159
  }
@@ -79,9 +174,62 @@ class Embedder {
79
174
  text = (htmlToText(message.html) || '').trim();
80
175
  }
81
176
 
82
- this.text = text;
177
+ // replace links
178
+
179
+ this.text = this.prepareLinks(text);
180
+ }
181
+
182
+ prepareLinks(text) {
183
+ try {
184
+ let links = linkify.match(text);
185
+ if (links && links.length) {
186
+ let parts = [];
187
+ let cursor = 0;
188
+ for (let link of links) {
189
+ if (cursor < link.index) {
190
+ parts.push({
191
+ type: 'text',
192
+ content: text.substring(cursor, link.index)
193
+ });
194
+ cursor = link.index;
195
+ }
196
+ parts.push(Object.assign({ type: 'link' }, link));
197
+ cursor = link.lastIndex;
198
+ }
199
+
200
+ if (cursor < text.length) {
201
+ parts.push({
202
+ type: 'text',
203
+ content: text.substr(cursor)
204
+ });
205
+ }
206
+
207
+ return parts
208
+ .map(part => {
209
+ switch (part.type) {
210
+ case 'text': {
211
+ // normal text, escape HTML
212
+ return part.content;
213
+ }
214
+ case 'link':
215
+ // URL with html escaped text content and URL
216
+ try {
217
+ const parsedUrl = new URL(part.url);
218
+ return `${parsedUrl.protocol}//${parsedUrl.host}`;
219
+ } catch (err) {
220
+ return ' ';
221
+ }
222
+ }
223
+ return '';
224
+ })
225
+ .join('');
226
+ }
227
+ } catch (err) {
228
+ // ignore?
229
+ }
83
230
 
84
- this.remainingText = text;
231
+ // No links or exception, so HTML escape everything
232
+ return text;
85
233
  }
86
234
 
87
235
  formatAddresses(addresses) {
@@ -133,7 +281,9 @@ class Embedder {
133
281
  if (this.subject) {
134
282
  headerLines.push(`subject: ${this.subject}`);
135
283
  }
136
-
284
+ if (this.date) {
285
+ headerLines.push(`date: ${this.date}`);
286
+ }
137
287
  if (this.message.attachments?.length) {
138
288
  let attachments = this.message.attachments.map(attachment => attachment.filename?.replace(/\s/g, ' ').trim()).filter(val => val);
139
289
  if (attachments.length) {
@@ -151,7 +301,14 @@ class Embedder {
151
301
 
152
302
  let textChunks = [];
153
303
  if (this.text) {
154
- let textTokens = tokenizer.encode(this.text.replace(/[\r\n]+/g, '\n'));
304
+ let preparedText = this.text
305
+ .replace(/\r?\n/g, '\n')
306
+ .replace(/^\s*>.*$/gm, '')
307
+ .replace(/^\s*>$/gm)
308
+ .replace(/^\s+$/gm, '')
309
+ .replace(/\n\n+/g, '\n\n');
310
+
311
+ let textTokens = tokenizer.encode(preparedText);
155
312
 
156
313
  let pos = 0;
157
314
  while (pos < textTokens.bpe.length) {
@@ -165,88 +322,26 @@ class Embedder {
165
322
  return textChunks.map(value => `${prompt}${value}`);
166
323
  }
167
324
 
168
- async getChunkEmbeddings(chunk) {
169
- let headers = {
170
- 'User-Agent': `${packageData.name}/${packageData.version}`,
171
- Authorization: `Bearer ${this.apiToken}`,
172
- 'Content-Type': 'application/json'
173
- };
174
-
175
- let payload = {
176
- model: this.gptModel,
177
- input: chunk
178
- };
179
-
180
- let res;
181
- let data;
182
- let retries = 0;
183
-
184
- if (this.verbose) {
185
- console.log(util.inspect(payload, false, 5, true));
186
- }
187
-
188
- let run = async () => {
189
- res = await fetchCmd(OPENAI_API_URL, {
190
- method: 'post',
191
- headers,
192
- body: JSON.stringify(payload),
193
- dispatcher: fetchAgent
194
- });
195
-
196
- data = await res.json();
197
- if (!res.ok) {
198
- if (res.status === 429 && ++retries < 5) {
199
- // try again
200
- await new Promise(r => setTimeout(r, 1000));
201
- return await run();
202
- }
203
-
204
- if (data && data.error) {
205
- let error = new Error(data.error.message || data.error);
206
- if (data.error.code) {
207
- error.code = data.error.code;
208
- }
209
-
210
- error.statusCode = res.status;
211
- throw error;
212
- }
213
-
214
- let error = new Error('Failed to run API request');
215
- error.statusCode = res.status;
216
- throw error;
217
- }
218
-
219
- if (!data) {
220
- throw new Error(`Failed to POST API request`);
221
- }
222
- };
223
-
224
- const reqStartTime = Date.now();
225
- await run();
226
- const reqEndTime = Date.now();
227
-
228
- let embedding = data?.data?.[0]?.embedding;
229
- return {
230
- chunk,
231
- embedding,
232
- _time: reqEndTime - reqStartTime
233
- };
234
- }
235
-
236
325
  async getEmbeddings() {
237
326
  let chunks = this.getChunks();
238
327
 
239
328
  let embeddings = [];
240
329
 
241
330
  for (let chunk of chunks) {
242
- embeddings.push(await this.getChunkEmbeddings(chunk));
331
+ embeddings.push(
332
+ await getChunkEmbeddings(chunk, this.apiToken, {
333
+ gptModel: this.gptModel,
334
+ verbose: this.verbose
335
+ })
336
+ );
243
337
  }
244
338
 
245
339
  return { model: this.gptModel, embeddings };
246
340
  }
247
341
  }
248
342
 
343
+ module.exports.getChunkEmbeddings = getChunkEmbeddings;
249
344
  module.exports.generateEmbeddings = async (message, apiToken) => {
250
345
  let embedder = new Embedder(message, apiToken);
251
- return embedder.getEmbeddings();
346
+ return await embedder.getEmbeddings();
252
347
  };
@@ -348,7 +348,7 @@ ${JSON.stringify(content)}`;
348
348
  }
349
349
  } else if (subBranch && typeof subBranch === 'object') {
350
350
  walkAndRemoveNull(subBranch);
351
- } else if (!['boolean', 'string', 'number'].includes(typeof subBranch)) {
351
+ } else if (!['boolean', 'string', 'number'].includes(typeof subBranch) || subBranch === '') {
352
352
  delete branch[key];
353
353
  }
354
354
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@postalsys/email-ai-tools",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "description": "Email AI tools",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -26,8 +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": "^4.0.1",
29
30
  "nodemailer": "6.9.5",
30
31
  "punycode": "2.3.0",
32
+ "tlds": "^1.242.0",
31
33
  "undici": "5.24.0"
32
34
  }
33
35
  }