@postalsys/email-ai-tools 1.1.3 → 1.2.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.
@@ -1,9 +1,10 @@
1
1
  'use strict';
2
2
 
3
3
  const fs = require('fs').promises;
4
- const generateSummary = require('../lib/generate-summary');
4
+ const { generateSummary } = require('../lib/generate-summary');
5
5
  const simpleParser = require('mailparser').simpleParser;
6
6
  const libmime = require('libmime');
7
+ const util = require('util');
7
8
 
8
9
  async function main() {
9
10
  const eml = await fs.readFile(process.argv[2]);
@@ -19,13 +20,14 @@ async function main() {
19
20
  },
20
21
  process.env.OPENAI_API_KEY,
21
22
  {
22
- //gptModel: 'gpt-3.5-turbo'
23
+ //gptModel: 'gpt-3.5-turbo',
23
24
  gptModel: 'gpt-4',
24
- maxTokens: 6000
25
+ maxTokens: 6000,
26
+ verbose: true
25
27
  }
26
28
  );
27
29
 
28
- console.log(summary);
30
+ console.log(util.inspect(summary, false, 22, true));
29
31
  }
30
32
 
31
33
  main();
package/index.js CHANGED
@@ -1,9 +1,11 @@
1
1
  'use strict';
2
2
 
3
- const generateSummary = require('./lib/generate-summary');
3
+ const { generateSummary, DEFAULT_SYSTEM_PROMPT, DEFAULT_USER_PROMPT } = require('./lib/generate-summary');
4
4
  const riskAnalysis = require('./lib/risk-analysis');
5
5
 
6
6
  module.exports = {
7
7
  generateSummary,
8
- riskAnalysis
8
+ riskAnalysis,
9
+ DEFAULT_SYSTEM_PROMPT,
10
+ DEFAULT_USER_PROMPT
9
11
  };
@@ -3,7 +3,7 @@
3
3
  const packageData = require('../package.json');
4
4
  const { htmlToText } = require('@postalsys/email-text-tools');
5
5
  const GPT3Tokenizer = require('gpt3-tokenizer').default;
6
-
6
+ const util = require('util');
7
7
  const { fetch: fetchCmd, Agent } = require('undici');
8
8
  const fetchAgent = new Agent({ connect: { timeout: 90 * 1000 } });
9
9
 
@@ -13,14 +13,13 @@ const MAX_ALLOWED_TEXT_LENGTH = 32 * 1024;
13
13
  const MAX_ALLOWED_TOKENS = 4000;
14
14
  const OPENAI_API_URL = 'https://api.openai.com/v1/chat/completions';
15
15
 
16
- const SYSTEM_PROMPT = `
16
+ const DEFAULT_ALLOWED_HEADERS = ['from', 'to', 'cc', 'bcc', 'subject', 'mime-version', 'authentication-results', 'date', 'content-type', 'list-id'];
17
+
18
+ const DEFAULT_SYSTEM_PROMPT = `
17
19
  I want you to act as an email client that processes emails and highlights important parts.
18
- You do not comment or explain anything.
19
- `
20
- .replace(/\s+/g, ' ')
21
- .trim();
20
+ `.trim();
22
21
 
23
- const USER_PROMPT = `
22
+ const DEFAULT_USER_PROMPT = `
24
23
  Instructions:
25
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.
26
25
  - Your task is to monitor and analyze incoming emails, which consist of the message headers, a list of attachments, and text content
@@ -63,12 +62,10 @@ Instructions:
63
62
  - Does the sender's email look like it might be spoofed
64
63
  - Does the email contain attachments where the name of the attachment might be misleading and suggest a different file format than is actually used
65
64
  - Does the email contain attachments that might be executable files
66
- - Respond with a JSON formatted structure. Do not write any other explanations.
67
65
  - Always return the response in English
68
66
 
69
67
  Facts:
70
- - An email consists of message headers, an attachments list, and text content
71
- - The email to analyze is formatted in a JSON format
68
+
72
69
  - An email might contain an "authentication-results" result header that indicates if the message passed SPF, DKIM, ARC, and DMARC checks
73
70
  - Having a valid SPF, DKIM, and DMARC increases the chances that the sender domain name is not spoofed
74
71
  - For valid SPF, the "authentication-results" header must include "spf=pass"
@@ -84,18 +81,44 @@ Facts:
84
81
  - For timestamps without a timezone, use the "YYYY-MM-DD hh:mm:ss" format
85
82
  - For timestamps without known time, use the "YYYY-MM-DD" format
86
83
  - If the email uses relative dates, then use the date from the "date" header as the base value to calculate actual dates
87
- - Each header contains two properties, "key" as the header field key name and "value" as the header value without the key prefix
88
- - The email structure includes a property "attachments" that contains an array of attachments.
89
- - Each attachment includes a "filename" property that describes the file name, a "contentType" property that describes the Content-Type value of the attachment
90
- - The email includes a "text" property for the text content
91
- - The email includes a "subject" property for the email subject
92
-
93
- Analyze the following email:
94
84
  `.trim();
95
85
 
86
+ const SCHEMA_PROMPT = `
87
+
88
+ Input facts:
89
+
90
+ - An email consists of message headers, an attachments list, and text content
91
+ - The email to analyze is formatted in a JSON format using the following schema:
92
+
93
+ \`\`\`
94
+ {
95
+ "headers": [{"key": <Header-Name>, "value": <Header-Value>}],
96
+ "attachments": [{"filename": "<File-Name>", "contentType": "<File-Type>"}],
97
+ "subject": "<Subject>",
98
+ "text": "<Plaintext-Content>"
99
+ }
100
+ \`\`\`
101
+
102
+ - "<Header-Name>" defines the name part of a header line, e.g., "MIME-Version"
103
+ - "<Header-Value>" defines the value part of a header line, e.g., "1.0"
104
+ - "<File-Name>" defines the file name of the attachment, e.g., "document.pdf"
105
+ - "<File-Type>" defines the file content type of the attachment, e.g., "application/pdf"
106
+ - "<Subject>" defines the subject line of the email, e.g., "Sending documents."
107
+ - "<Plaintext-Content>" defines the email body formatted as plaintext, e.g., "Documents are attached."
108
+
109
+ Output facts:
110
+
111
+ - You do not comment or explain anything
112
+ - Respond with a JSON formatted structure. Do not write any other explanations
113
+
114
+ Analyze the following email:`.trim();
115
+
96
116
  async function generateSummary(message, apiToken, opts) {
97
117
  opts = opts || {};
98
118
 
119
+ let systemPrompt = (opts.systemPrompt || DEFAULT_SYSTEM_PROMPT).toString().trim();
120
+ let userPrompt = (opts.userPrompt || DEFAULT_USER_PROMPT).toString().trim();
121
+
99
122
  let maxAllowedTokens = opts.maxTokens || MAX_ALLOWED_TOKENS;
100
123
  let gptModel = opts.gptModel || 'gpt-3.5-turbo';
101
124
 
@@ -104,6 +127,18 @@ async function generateSummary(message, apiToken, opts) {
104
127
  text = htmlToText(message.html);
105
128
  }
106
129
 
130
+ const allowedHeaders = !opts.allowedHeaders
131
+ ? DEFAULT_ALLOWED_HEADERS
132
+ : Array.from(
133
+ new Set(
134
+ []
135
+ .concat(opts.allowedHeaders || [])
136
+ .concat(DEFAULT_ALLOWED_HEADERS)
137
+ .map(header => (header || '').toString().trim().toLowerCase())
138
+ .filter(header => header)
139
+ )
140
+ );
141
+
107
142
  let prompt;
108
143
  const headerSeen = new Set();
109
144
 
@@ -112,12 +147,11 @@ async function generateSummary(message, apiToken, opts) {
112
147
  .concat(message.headers || [])
113
148
  .filter(
114
149
  // use a whitelist
115
- header =>
116
- ['from', 'to', 'cc', 'bcc', 'subject', 'mime-version', 'authentication-results', 'date', 'content-type', 'list-id'].includes(header.key)
150
+ header => allowedHeaders.includes(header.key)
117
151
  )
118
152
  .filter(header => {
119
- // only keept the latest
120
- if (['authentication-results'].includes(header.key)) {
153
+ // only keept the latest authentication header
154
+ if (['authentication-results', 'arc-authentication-results', 'arc-message-signature', 'arc-seal'].includes(header.key)) {
121
155
  if (headerSeen.has(header.key)) {
122
156
  return false;
123
157
  }
@@ -125,7 +159,11 @@ async function generateSummary(message, apiToken, opts) {
125
159
  }
126
160
  return true;
127
161
  }),
128
- attachments: [].concat(message.attachments || []).map(attachment => ({ filename: attachment.filename, contentType: attachment.contentType }))
162
+ attachments: []
163
+ .concat(message.attachments || [])
164
+ .map(attachment =>
165
+ ({ filename: attachment.filename, contentType: attachment.contentType }.filter(attachment => attachment.filename || attachment.contentTyp))
166
+ )
129
167
  };
130
168
 
131
169
  let charactersRemoved = 0;
@@ -139,7 +177,8 @@ async function generateSummary(message, apiToken, opts) {
139
177
  // eslint-disable-next-line no-constant-condition
140
178
  while (true) {
141
179
  content.text = promptText;
142
- prompt = `${USER_PROMPT}
180
+ prompt = `${userPrompt}
181
+ ${SCHEMA_PROMPT}
143
182
 
144
183
  ${JSON.stringify(content)}`;
145
184
 
@@ -181,7 +220,7 @@ ${JSON.stringify(content)}`;
181
220
  messages: [
182
221
  {
183
222
  role: 'system',
184
- content: `${SYSTEM_PROMPT}`
223
+ content: `${systemPrompt}`
185
224
  },
186
225
  {
187
226
  role: 'user',
@@ -190,10 +229,22 @@ ${JSON.stringify(content)}`;
190
229
  ]
191
230
  };
192
231
 
232
+ if (opts.temperature && !isNaN(opts.temperature)) {
233
+ payload.temperature = Number(opts.temperature);
234
+ }
235
+
236
+ if (opts.topP && !isNaN(opts.topP)) {
237
+ payload.top_p = Number(opts.topP);
238
+ }
239
+
193
240
  let res;
194
241
  let data;
195
242
  let retries = 0;
196
243
 
244
+ if (opts.verbose) {
245
+ console.log(util.inspect(payload, false, 5, true));
246
+ }
247
+
197
248
  let run = async () => {
198
249
  res = await fetchCmd(OPENAI_API_URL, {
199
250
  method: 'post',
@@ -235,7 +286,7 @@ ${JSON.stringify(content)}`;
235
286
  const reqEndTime = Date.now();
236
287
 
237
288
  let values;
238
- const output =
289
+ let output =
239
290
  data &&
240
291
  data.choices &&
241
292
  data.choices
@@ -243,74 +294,51 @@ ${JSON.stringify(content)}`;
243
294
  .sort((a, b) => ((a && a.index) || 0) - ((b && b.index) || 0))
244
295
  .map(msg => msg.message.content)
245
296
  .join('\n')
246
- .trim()
247
- .replace(/^\s*"|"\s*$/g, '')
248
297
  .trim();
249
298
 
250
299
  try {
251
- values = JSON.parse(output);
252
- if (typeof values.shouldReply === 'string') {
253
- values.shouldReply = values.shouldReply === 'true';
300
+ let objStart = output.indexOf('{');
301
+ let objEnd = output.lastIndexOf('}');
302
+
303
+ if (objStart < 0 || objEnd < 0 || objEnd <= objStart) {
304
+ let error = new Error('Invalid JSON object');
305
+ error.objStart = objStart;
306
+ error.objEnd = objEnd;
307
+ throw error;
254
308
  }
255
- if (typeof values.shouldReply !== 'undefined' && typeof values.shouldReply !== 'boolean') {
256
- delete values.shouldReply;
309
+
310
+ // remove potential comments before and after the JSON output
311
+ if (objEnd < output.length - 1) {
312
+ output = output.substring(0, objEnd + 1);
257
313
  }
258
314
 
259
- if (values && values.events) {
260
- values.events = []
261
- .concat(values.events || [])
262
- .filter(event => event.startTime)
263
- .map(event => {
264
- let result = {};
265
- for (let key of Object.keys(event)) {
266
- switch (key) {
267
- case 'startTime':
268
- case 'endTime':
269
- {
270
- if (event[key]) {
271
- let parsedDate = new Date(event[key]);
272
- if (parsedDate.toString() === 'Invalid Date') {
273
- event[key] = '';
274
- }
275
- }
276
- }
277
- break;
278
- }
279
-
280
- if (event[key] !== '' && event[key] !== null) {
281
- result[key] = event[key];
282
- }
283
- }
284
- return result;
285
- });
315
+ if (objStart > 0) {
316
+ output = output.substring(objStart);
286
317
  }
287
318
 
288
- if (values && values.actions) {
289
- values.actions = [].concat(values.actions || []).map(action => {
290
- let result = {};
291
- for (let key of Object.keys(action)) {
292
- switch (key) {
293
- case 'dueDate':
294
- {
295
- if (action[key]) {
296
- let parsedDate = new Date(action[key]);
297
- if (parsedDate.toString() === 'Invalid Date') {
298
- action[key] = '';
299
- }
300
- }
301
- }
302
- break;
303
- }
319
+ values = JSON.parse(output);
304
320
 
305
- if (action[key] !== '' && action[key] !== null) {
306
- result[key] = action[key];
321
+ let walkAndRemoveNull = branch => {
322
+ if (typeof branch !== 'object' || !branch) {
323
+ return;
324
+ }
325
+ for (let key of Object.keys(branch)) {
326
+ let subBranch = branch[key];
327
+ if (Array.isArray(subBranch)) {
328
+ for (let entry of subBranch) {
329
+ walkAndRemoveNull(entry);
307
330
  }
331
+ } else if (subBranch && typeof subBranch === 'object') {
332
+ walkAndRemoveNull(subBranch);
333
+ } else if (!['boolean', 'string', 'number'].includes(typeof subBranch)) {
334
+ delete branch[key];
308
335
  }
309
- return result;
310
- });
311
- }
336
+ }
337
+ };
338
+
339
+ walkAndRemoveNull(values);
312
340
  } catch (err) {
313
- let error = new Error('Failed to parse output from OpenAI API');
341
+ let error = new Error('Failed to parse output from OpenAI API', { cause: err });
314
342
  error.textContent = output;
315
343
  throw error;
316
344
  }
@@ -318,14 +346,16 @@ ${JSON.stringify(content)}`;
318
346
  const response = Object.assign({ id: null, tokens: null, model: null }, values, {
319
347
  id: data && data.id,
320
348
  tokens: data && data.usage && data.usage.total_tokens,
321
- model: gptModel,
322
-
323
- _text: content.text,
324
- _time: reqEndTime - reqStartTime,
325
- _cr: charactersRemoved
349
+ model: gptModel
326
350
  });
327
351
 
352
+ if (opts.verbose) {
353
+ response._text = content.text;
354
+ response._time = reqEndTime - reqStartTime;
355
+ response._cr = charactersRemoved;
356
+ }
357
+
328
358
  return response;
329
359
  }
330
360
 
331
- module.exports = generateSummary;
361
+ module.exports = { generateSummary, DEFAULT_SYSTEM_PROMPT, DEFAULT_USER_PROMPT };
@@ -13,13 +13,13 @@ const MAX_ALLOWED_TEXT_LENGTH = 32 * 1024;
13
13
  const MAX_ALLOWED_TOKENS = 4000;
14
14
  const OPENAI_API_URL = 'https://api.openai.com/v1/chat/completions';
15
15
 
16
- const SYSTEM_PROMPT = `
16
+ const DEFAULT_SYSTEM_PROMPT = `
17
17
  I want you to act as are an IT security expert that monitors emails for suspicious and risky activity.
18
18
  `
19
19
  .replace(/\s+/g, ' ')
20
20
  .trim();
21
21
 
22
- const USER_PROMPT = `
22
+ const DEFAULT_USER_PROMPT = `
23
23
  Instructions:
24
24
  - You are an IT security expert scanning incoming emails to detect and block fraud attempts.
25
25
  - Your task is to monitor and analyze incoming emails, which consist of the message headers, a list of attachments, and text content
@@ -41,7 +41,7 @@ Instructions:
41
41
  - Respond with a JSON formatted structure with a numeric risk score as "risk" property and the assessment as the "assessment" property. Do not write any other explanations.
42
42
 
43
43
  Facts:
44
- - An email consists of message headers, an attachments list, and text content
44
+
45
45
  - An email might contain an "authentication-results" result header that indicates if the message passed SPF, DKIM, ARC, and DMARC checks
46
46
  - Having a valid SPF, DKIM, and DMARC increases the chances that the sender domain name is not spoofed
47
47
  - For valid SPF, the "authentication-results" header must include "spf=pass"
@@ -51,6 +51,8 @@ Facts:
51
51
  - Throwaway email addresses might contain a word or a name and more than one number in the username of the email address
52
52
  - Throwaway email addresses might use a randomly generated or hex text string as the username of the email address
53
53
  - Throwaway email addresses might use free email services like gmail.com, outlook.com, hotmail.com, yahoo.com, aol.com, etc
54
+
55
+ - An email consists of message headers, an attachments list, and text content
54
56
  - The email to analyze is formatted in a JSON format
55
57
  - The email structure includes a property "headers" that contains an array of header values.
56
58
  - Each header contains two properties, "key" as the header field key name and "value" as the header value without the key prefix
@@ -64,6 +66,9 @@ Analyze the following email:
64
66
  async function riskAnalysis(message, apiToken, opts) {
65
67
  opts = opts || {};
66
68
 
69
+ let systemPrompt = opts.systemPrompt || DEFAULT_SYSTEM_PROMPT;
70
+ let userPrompt = opts.userPrompt || DEFAULT_USER_PROMPT;
71
+
67
72
  let maxAllowedTokens = opts.maxTokens || MAX_ALLOWED_TOKENS;
68
73
  let gptModel = opts.gptModel || 'gpt-3.5-turbo';
69
74
 
@@ -106,7 +111,7 @@ async function riskAnalysis(message, apiToken, opts) {
106
111
 
107
112
  while (promptText.length) {
108
113
  content.text = promptText;
109
- prompt = `${USER_PROMPT}
114
+ prompt = `${userPrompt}
110
115
 
111
116
  ${JSON.stringify(content)}`;
112
117
 
@@ -148,7 +153,7 @@ ${JSON.stringify(content)}`;
148
153
  messages: [
149
154
  {
150
155
  role: 'system',
151
- content: `${SYSTEM_PROMPT}`
156
+ content: `${systemPrompt}`
152
157
  },
153
158
  {
154
159
  role: 'user',
@@ -157,6 +162,14 @@ ${JSON.stringify(content)}`;
157
162
  ]
158
163
  };
159
164
 
165
+ if (opts.temperature && !isNaN(opts.temperature)) {
166
+ payload.temperature = Number(opts.temperature);
167
+ }
168
+
169
+ if (opts.topP && !isNaN(opts.topP)) {
170
+ payload.top_p = Number(opts.topP);
171
+ }
172
+
160
173
  let res;
161
174
  let data;
162
175
  let retries = 0;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@postalsys/email-ai-tools",
3
- "version": "1.1.3",
3
+ "version": "1.2.0",
4
4
  "description": "Email AI tools",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -19,13 +19,13 @@
19
19
  "homepage": "https://github.com/postalsys/email-ai-tools#readme",
20
20
  "devDependencies": {
21
21
  "eslint-config-nodemailer": "1.2.0",
22
- "eslint-config-prettier": "8.8.0",
23
- "mailparser": "3.6.4"
22
+ "eslint-config-prettier": "9.0.0",
23
+ "mailparser": "3.6.5"
24
24
  },
25
25
  "dependencies": {
26
- "@postalsys/email-text-tools": "2.0.1",
26
+ "@postalsys/email-text-tools": "2.1.0",
27
27
  "gpt3-tokenizer": "1.1.5",
28
28
  "libmime": "5.2.1",
29
- "undici": "5.22.1"
29
+ "undici": "5.23.0"
30
30
  }
31
31
  }