@postalsys/email-ai-tools 1.2.0 → 1.3.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/.eslintrc CHANGED
@@ -9,7 +9,7 @@
9
9
  },
10
10
  "extends": ["nodemailer", "prettier"],
11
11
  "parserOptions": {
12
- "ecmaVersion": 2018,
12
+ "ecmaVersion": 2020,
13
13
  "sourceType": "script"
14
14
  }
15
15
  }
@@ -0,0 +1,33 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs').promises;
4
+ const { generateEmbeddings } = require('../lib/generate-embeddings');
5
+ const simpleParser = require('mailparser').simpleParser;
6
+ const libmime = require('libmime');
7
+ const util = require('util');
8
+
9
+ async function main() {
10
+ const eml = await fs.readFile(process.argv[2]);
11
+
12
+ const parsed = await simpleParser(eml);
13
+
14
+ const result = await generateEmbeddings(
15
+ {
16
+ headers: parsed.headerLines.map(header => libmime.decodeHeader(header.line)),
17
+ attachments: parsed.attachments,
18
+ html: parsed.html,
19
+ text: parsed.text
20
+ },
21
+ process.env.OPENAI_API_KEY,
22
+ {
23
+ //gptModel: 'gpt-3.5-turbo',
24
+ gptModel: 'gpt-4',
25
+ maxTokens: 6000,
26
+ verbose: true
27
+ }
28
+ );
29
+
30
+ console.log(util.inspect(result, false, 22, true));
31
+ }
32
+
33
+ main();
@@ -16,7 +16,8 @@ async function main() {
16
16
  headers: parsed.headerLines.map(header => libmime.decodeHeader(header.line)),
17
17
  attachments: parsed.attachments,
18
18
  html: parsed.html,
19
- text: parsed.text
19
+ text: parsed.text,
20
+ subject: parsed.subject
20
21
  },
21
22
  process.env.OPENAI_API_KEY,
22
23
  {
@@ -0,0 +1,245 @@
1
+ 'use strict';
2
+
3
+ const packageData = require('../package.json');
4
+ const libmime = require('libmime');
5
+ const addressparser = require('nodemailer/lib/addressparser');
6
+ const { htmlToText } = require('@postalsys/email-text-tools');
7
+ const punycode = require('punycode/');
8
+ const { default: GPT3Tokenizer } = require('gpt3-tokenizer');
9
+ const { fetch: fetchCmd, Agent } = require('undici');
10
+ const fetchAgent = new Agent({ connect: { timeout: 90 * 1000 } });
11
+ const util = require('util');
12
+
13
+ const tokenizer = new GPT3Tokenizer({ type: 'gpt3' });
14
+
15
+ const OPENAI_API_URL = 'https://api.openai.com/v1/embeddings';
16
+
17
+ class Embedder {
18
+ constructor(message, apiToken, opts) {
19
+ this.message = message;
20
+ this.apiToken = apiToken;
21
+
22
+ opts = opts || {};
23
+ this.chunkSize = opts.chunkSize || 600;
24
+ this.gptModel = opts.gptModel || 'text-embedding-ada-002';
25
+
26
+ this.addressHeaders = new Map();
27
+
28
+ let subject;
29
+
30
+ for (const { key: headerKey, value } of message.headers || []) {
31
+ switch (headerKey) {
32
+ case 'from':
33
+ case 'to':
34
+ case 'cc':
35
+ case 'bcc':
36
+ {
37
+ // join to, cc, and bcc entries
38
+ let key = headerKey === 'from' ? headerKey : 'to';
39
+
40
+ let addressList;
41
+
42
+ if (this.addressHeaders.has(key)) {
43
+ addressList = this.addressHeaders.get(key);
44
+ } else {
45
+ addressList = [];
46
+ this.addressHeaders.set(key, addressList);
47
+ }
48
+
49
+ addressList.push(...this.formatAddresses(addressparser(value, { flatten: true })));
50
+ }
51
+ break;
52
+ case 'subject': {
53
+ subject = (value || '').toString().trim();
54
+ try {
55
+ subject = libmime.decodeWords(subject);
56
+ } catch (err) {
57
+ // ignore?
58
+ }
59
+ if (subject) {
60
+ this.subject = subject;
61
+ }
62
+ }
63
+ }
64
+ }
65
+
66
+ for (let key of ['from', 'to']) {
67
+ if (this.addressHeaders.has(key)) {
68
+ const addressList = this.addressHeaders.get(key);
69
+ if (!addressList || !addressList.length) {
70
+ this.addressHeaders.delete(key);
71
+ continue;
72
+ }
73
+ this.addressHeaders.set(key, this.getAddressString(addressList));
74
+ }
75
+ }
76
+
77
+ let text = (message.text || '').toString().trim();
78
+ if (message.html && (!text || message.html.length >= text.length)) {
79
+ text = (htmlToText(message.html) || '').trim();
80
+ }
81
+
82
+ this.text = text;
83
+
84
+ this.remainingText = text;
85
+ }
86
+
87
+ formatAddresses(addresses) {
88
+ let result = [];
89
+ for (let address of [].concat(addresses || [])) {
90
+ if (address.group) {
91
+ result = result.concat(this.formatAddresses(address.group));
92
+ } else {
93
+ let name = address.name || '';
94
+ let addr = address.address || '';
95
+ try {
96
+ name = libmime.decodeWords(name);
97
+ } catch (err) {
98
+ // ignore?
99
+ }
100
+
101
+ if (/@xn--/.test(addr)) {
102
+ addr = addr.substr(0, addr.lastIndexOf('@') + 1) + punycode.toUnicode(addr.substr(addr.lastIndexOf('@') + 1));
103
+ }
104
+
105
+ result.push({ name, address: addr });
106
+ }
107
+ }
108
+ return result;
109
+ }
110
+
111
+ getAddressString(addresses) {
112
+ return []
113
+ .concat(addresses)
114
+ .map(address => {
115
+ let res = [];
116
+ if (address.name) {
117
+ res.push(address.name);
118
+ }
119
+ if (address.address) {
120
+ res.push(`<${address.address}>`);
121
+ }
122
+ return res.join(' ');
123
+ })
124
+ .filter(val => val)
125
+ .join(', ');
126
+ }
127
+
128
+ getChunks() {
129
+ let headerLines = [];
130
+ for (let [key, value] of this.addressHeaders.entries()) {
131
+ headerLines.push(`${key}: ${value}`);
132
+ }
133
+ if (this.subject) {
134
+ headerLines.push(`subject: ${this.subject}`);
135
+ }
136
+
137
+ let prompt = `${headerLines.join('\n')}\n`;
138
+
139
+ let prefixTokens = tokenizer.encode(prompt);
140
+ // If prefix is very large, then use larger chunks, so that each chunk contains at least 200 tokens of text
141
+ let allowedTokens = Math.max(prefixTokens.text.length + 200, this.chunkSize);
142
+
143
+ let textTokensChunkSize = allowedTokens - prefixTokens.text.length;
144
+
145
+ let textChunks = [];
146
+ if (this.text) {
147
+ let textTokens = tokenizer.encode(this.text);
148
+
149
+ let pos = 0;
150
+ while (pos < textTokens.bpe.length) {
151
+ textChunks.push(tokenizer.decode(textTokens.bpe.slice(pos, pos + textTokensChunkSize)));
152
+ pos += textTokensChunkSize;
153
+ }
154
+ } else {
155
+ textChunks.push('');
156
+ }
157
+
158
+ return textChunks.map(value => `${prompt}${value}`);
159
+ }
160
+
161
+ async getChunkEmbeddings(chunk) {
162
+ let headers = {
163
+ 'User-Agent': `${packageData.name}/${packageData.version}`,
164
+ Authorization: `Bearer ${this.apiToken}`,
165
+ 'Content-Type': 'application/json'
166
+ };
167
+
168
+ let payload = {
169
+ model: this.gptModel,
170
+ input: chunk
171
+ };
172
+
173
+ let res;
174
+ let data;
175
+ let retries = 0;
176
+
177
+ if (this.verbose) {
178
+ console.log(util.inspect(payload, false, 5, true));
179
+ }
180
+
181
+ let run = async () => {
182
+ res = await fetchCmd(OPENAI_API_URL, {
183
+ method: 'post',
184
+ headers,
185
+ body: JSON.stringify(payload),
186
+ dispatcher: fetchAgent
187
+ });
188
+
189
+ data = await res.json();
190
+ if (!res.ok) {
191
+ if (res.status === 429 && ++retries < 5) {
192
+ // try again
193
+ await new Promise(r => setTimeout(r, 1000));
194
+ return await run();
195
+ }
196
+
197
+ if (data && data.error) {
198
+ let error = new Error(data.error.message || data.error);
199
+ if (data.error.code) {
200
+ error.code = data.error.code;
201
+ }
202
+
203
+ error.statusCode = res.status;
204
+ throw error;
205
+ }
206
+
207
+ let error = new Error('Failed to run API request');
208
+ error.statusCode = res.status;
209
+ throw error;
210
+ }
211
+
212
+ if (!data) {
213
+ throw new Error(`Failed to POST API request`);
214
+ }
215
+ };
216
+
217
+ const reqStartTime = Date.now();
218
+ await run();
219
+ const reqEndTime = Date.now();
220
+
221
+ let embedding = data?.data?.[0]?.embedding;
222
+ return {
223
+ chunk,
224
+ embedding,
225
+ time: reqEndTime - reqStartTime
226
+ };
227
+ }
228
+
229
+ async getEmbeddings() {
230
+ let chunks = this.getChunks();
231
+
232
+ let result = [];
233
+
234
+ for (let chunk of chunks) {
235
+ result.push(await this.getChunkEmbeddings(chunk));
236
+ }
237
+
238
+ return result;
239
+ }
240
+ }
241
+
242
+ module.exports.generateEmbeddings = async (message, apiToken) => {
243
+ let embedder = new Embedder(message, apiToken);
244
+ return embedder.getEmbeddings();
245
+ };
@@ -2,7 +2,7 @@
2
2
 
3
3
  const packageData = require('../package.json');
4
4
  const { htmlToText } = require('@postalsys/email-text-tools');
5
- const GPT3Tokenizer = require('gpt3-tokenizer').default;
5
+ const { default: GPT3Tokenizer } = require('gpt3-tokenizer');
6
6
  const util = require('util');
7
7
  const { fetch: fetchCmd, Agent } = require('undici');
8
8
  const fetchAgent = new Agent({ connect: { timeout: 90 * 1000 } });
@@ -16,13 +16,12 @@ const OPENAI_API_URL = 'https://api.openai.com/v1/chat/completions';
16
16
  const DEFAULT_ALLOWED_HEADERS = ['from', 'to', 'cc', 'bcc', 'subject', 'mime-version', 'authentication-results', 'date', 'content-type', 'list-id'];
17
17
 
18
18
  const DEFAULT_SYSTEM_PROMPT = `
19
- I want you to act as an email client that processes emails and highlights important parts.
19
+ I want you to act as an executive assistant that processes emails for reporting.
20
20
  `.trim();
21
21
 
22
22
  const DEFAULT_USER_PROMPT = `
23
23
  Instructions:
24
- - You are an executive assistant scanning incoming emails to inform your superiors about what is important and what is not, and also to inform about obvious fraud attempts.
25
- - Your task is to monitor and analyze incoming emails, which consist of the message headers, a list of attachments, and text content
24
+ - You are an executive assistant scanning incoming emails to report what is important and what is not, and also to inform about obvious fraud attempts.
26
25
  - Describe the sentiment of the email using one word. Use either "positive", "neutral", or "negative". Include this value in the response as a "sentiment" property.
27
26
  - Generate a one-sentence summary of the email. Include this value in the response as a "summary" property.
28
27
  - Does it seem like the sender of the email would expect a reply to this email? Include this information in the response as a "shouldReply" property with the value "true" if they expect it and "false" if not.
@@ -161,9 +160,8 @@ async function generateSummary(message, apiToken, opts) {
161
160
  }),
162
161
  attachments: []
163
162
  .concat(message.attachments || [])
164
- .map(attachment =>
165
- ({ filename: attachment.filename, contentType: attachment.contentType }.filter(attachment => attachment.filename || attachment.contentTyp))
166
- )
163
+ .map(attachment => ({ filename: attachment.filename, contentType: attachment.contentType }))
164
+ .filter(attachment => attachment.filename || attachment.contentType)
167
165
  };
168
166
 
169
167
  let charactersRemoved = 0;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@postalsys/email-ai-tools",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "description": "Email AI tools",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -23,9 +23,11 @@
23
23
  "mailparser": "3.6.5"
24
24
  },
25
25
  "dependencies": {
26
- "@postalsys/email-text-tools": "2.1.0",
26
+ "@postalsys/email-text-tools": "2.1.1",
27
27
  "gpt3-tokenizer": "1.1.5",
28
28
  "libmime": "5.2.1",
29
- "undici": "5.23.0"
29
+ "nodemailer": "6.9.5",
30
+ "punycode": "2.3.0",
31
+ "undici": "5.24.0"
30
32
  }
31
33
  }