@postalsys/email-ai-tools 1.1.3 → 1.2.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.
@@ -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,17 +13,15 @@ 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 = `
17
- 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();
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 = `
19
+ I want you to act as an executive assistant that processes emails for reporting.
20
+ `.trim();
22
21
 
23
- const USER_PROMPT = `
22
+ const DEFAULT_USER_PROMPT = `
24
23
  Instructions:
25
- - 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
- - 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.
27
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.
28
26
  - Generate a one-sentence summary of the email. Include this value in the response as a "summary" property.
29
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.
@@ -63,12 +61,10 @@ Instructions:
63
61
  - Does the sender's email look like it might be spoofed
64
62
  - 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
63
  - Does the email contain attachments that might be executable files
66
- - Respond with a JSON formatted structure. Do not write any other explanations.
67
64
  - Always return the response in English
68
65
 
69
66
  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
67
+
72
68
  - An email might contain an "authentication-results" result header that indicates if the message passed SPF, DKIM, ARC, and DMARC checks
73
69
  - Having a valid SPF, DKIM, and DMARC increases the chances that the sender domain name is not spoofed
74
70
  - For valid SPF, the "authentication-results" header must include "spf=pass"
@@ -84,18 +80,44 @@ Facts:
84
80
  - For timestamps without a timezone, use the "YYYY-MM-DD hh:mm:ss" format
85
81
  - For timestamps without known time, use the "YYYY-MM-DD" format
86
82
  - 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
83
  `.trim();
95
84
 
85
+ const SCHEMA_PROMPT = `
86
+
87
+ Input facts:
88
+
89
+ - An email consists of message headers, an attachments list, and text content
90
+ - The email to analyze is formatted in a JSON format using the following schema:
91
+
92
+ \`\`\`
93
+ {
94
+ "headers": [{"key": <Header-Name>, "value": <Header-Value>}],
95
+ "attachments": [{"filename": "<File-Name>", "contentType": "<File-Type>"}],
96
+ "subject": "<Subject>",
97
+ "text": "<Plaintext-Content>"
98
+ }
99
+ \`\`\`
100
+
101
+ - "<Header-Name>" defines the name part of a header line, e.g., "MIME-Version"
102
+ - "<Header-Value>" defines the value part of a header line, e.g., "1.0"
103
+ - "<File-Name>" defines the file name of the attachment, e.g., "document.pdf"
104
+ - "<File-Type>" defines the file content type of the attachment, e.g., "application/pdf"
105
+ - "<Subject>" defines the subject line of the email, e.g., "Sending documents."
106
+ - "<Plaintext-Content>" defines the email body formatted as plaintext, e.g., "Documents are attached."
107
+
108
+ Output facts:
109
+
110
+ - You do not comment or explain anything
111
+ - Respond with a JSON formatted structure. Do not write any other explanations
112
+
113
+ Analyze the following email:`.trim();
114
+
96
115
  async function generateSummary(message, apiToken, opts) {
97
116
  opts = opts || {};
98
117
 
118
+ let systemPrompt = (opts.systemPrompt || DEFAULT_SYSTEM_PROMPT).toString().trim();
119
+ let userPrompt = (opts.userPrompt || DEFAULT_USER_PROMPT).toString().trim();
120
+
99
121
  let maxAllowedTokens = opts.maxTokens || MAX_ALLOWED_TOKENS;
100
122
  let gptModel = opts.gptModel || 'gpt-3.5-turbo';
101
123
 
@@ -104,6 +126,18 @@ async function generateSummary(message, apiToken, opts) {
104
126
  text = htmlToText(message.html);
105
127
  }
106
128
 
129
+ const allowedHeaders = !opts.allowedHeaders
130
+ ? DEFAULT_ALLOWED_HEADERS
131
+ : Array.from(
132
+ new Set(
133
+ []
134
+ .concat(opts.allowedHeaders || [])
135
+ .concat(DEFAULT_ALLOWED_HEADERS)
136
+ .map(header => (header || '').toString().trim().toLowerCase())
137
+ .filter(header => header)
138
+ )
139
+ );
140
+
107
141
  let prompt;
108
142
  const headerSeen = new Set();
109
143
 
@@ -112,12 +146,11 @@ async function generateSummary(message, apiToken, opts) {
112
146
  .concat(message.headers || [])
113
147
  .filter(
114
148
  // use a whitelist
115
- header =>
116
- ['from', 'to', 'cc', 'bcc', 'subject', 'mime-version', 'authentication-results', 'date', 'content-type', 'list-id'].includes(header.key)
149
+ header => allowedHeaders.includes(header.key)
117
150
  )
118
151
  .filter(header => {
119
- // only keept the latest
120
- if (['authentication-results'].includes(header.key)) {
152
+ // only keept the latest authentication header
153
+ if (['authentication-results', 'arc-authentication-results', 'arc-message-signature', 'arc-seal'].includes(header.key)) {
121
154
  if (headerSeen.has(header.key)) {
122
155
  return false;
123
156
  }
@@ -125,7 +158,10 @@ async function generateSummary(message, apiToken, opts) {
125
158
  }
126
159
  return true;
127
160
  }),
128
- attachments: [].concat(message.attachments || []).map(attachment => ({ filename: attachment.filename, contentType: attachment.contentType }))
161
+ attachments: []
162
+ .concat(message.attachments || [])
163
+ .map(attachment => ({ filename: attachment.filename, contentType: attachment.contentType }))
164
+ .filter(attachment => attachment.filename || attachment.contentType)
129
165
  };
130
166
 
131
167
  let charactersRemoved = 0;
@@ -139,7 +175,8 @@ async function generateSummary(message, apiToken, opts) {
139
175
  // eslint-disable-next-line no-constant-condition
140
176
  while (true) {
141
177
  content.text = promptText;
142
- prompt = `${USER_PROMPT}
178
+ prompt = `${userPrompt}
179
+ ${SCHEMA_PROMPT}
143
180
 
144
181
  ${JSON.stringify(content)}`;
145
182
 
@@ -181,7 +218,7 @@ ${JSON.stringify(content)}`;
181
218
  messages: [
182
219
  {
183
220
  role: 'system',
184
- content: `${SYSTEM_PROMPT}`
221
+ content: `${systemPrompt}`
185
222
  },
186
223
  {
187
224
  role: 'user',
@@ -190,10 +227,22 @@ ${JSON.stringify(content)}`;
190
227
  ]
191
228
  };
192
229
 
230
+ if (opts.temperature && !isNaN(opts.temperature)) {
231
+ payload.temperature = Number(opts.temperature);
232
+ }
233
+
234
+ if (opts.topP && !isNaN(opts.topP)) {
235
+ payload.top_p = Number(opts.topP);
236
+ }
237
+
193
238
  let res;
194
239
  let data;
195
240
  let retries = 0;
196
241
 
242
+ if (opts.verbose) {
243
+ console.log(util.inspect(payload, false, 5, true));
244
+ }
245
+
197
246
  let run = async () => {
198
247
  res = await fetchCmd(OPENAI_API_URL, {
199
248
  method: 'post',
@@ -235,7 +284,7 @@ ${JSON.stringify(content)}`;
235
284
  const reqEndTime = Date.now();
236
285
 
237
286
  let values;
238
- const output =
287
+ let output =
239
288
  data &&
240
289
  data.choices &&
241
290
  data.choices
@@ -243,74 +292,51 @@ ${JSON.stringify(content)}`;
243
292
  .sort((a, b) => ((a && a.index) || 0) - ((b && b.index) || 0))
244
293
  .map(msg => msg.message.content)
245
294
  .join('\n')
246
- .trim()
247
- .replace(/^\s*"|"\s*$/g, '')
248
295
  .trim();
249
296
 
250
297
  try {
251
- values = JSON.parse(output);
252
- if (typeof values.shouldReply === 'string') {
253
- values.shouldReply = values.shouldReply === 'true';
298
+ let objStart = output.indexOf('{');
299
+ let objEnd = output.lastIndexOf('}');
300
+
301
+ if (objStart < 0 || objEnd < 0 || objEnd <= objStart) {
302
+ let error = new Error('Invalid JSON object');
303
+ error.objStart = objStart;
304
+ error.objEnd = objEnd;
305
+ throw error;
254
306
  }
255
- if (typeof values.shouldReply !== 'undefined' && typeof values.shouldReply !== 'boolean') {
256
- delete values.shouldReply;
307
+
308
+ // remove potential comments before and after the JSON output
309
+ if (objEnd < output.length - 1) {
310
+ output = output.substring(0, objEnd + 1);
257
311
  }
258
312
 
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
- });
313
+ if (objStart > 0) {
314
+ output = output.substring(objStart);
286
315
  }
287
316
 
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
- }
317
+ values = JSON.parse(output);
304
318
 
305
- if (action[key] !== '' && action[key] !== null) {
306
- result[key] = action[key];
319
+ let walkAndRemoveNull = branch => {
320
+ if (typeof branch !== 'object' || !branch) {
321
+ return;
322
+ }
323
+ for (let key of Object.keys(branch)) {
324
+ let subBranch = branch[key];
325
+ if (Array.isArray(subBranch)) {
326
+ for (let entry of subBranch) {
327
+ walkAndRemoveNull(entry);
307
328
  }
329
+ } else if (subBranch && typeof subBranch === 'object') {
330
+ walkAndRemoveNull(subBranch);
331
+ } else if (!['boolean', 'string', 'number'].includes(typeof subBranch)) {
332
+ delete branch[key];
308
333
  }
309
- return result;
310
- });
311
- }
334
+ }
335
+ };
336
+
337
+ walkAndRemoveNull(values);
312
338
  } catch (err) {
313
- let error = new Error('Failed to parse output from OpenAI API');
339
+ let error = new Error('Failed to parse output from OpenAI API', { cause: err });
314
340
  error.textContent = output;
315
341
  throw error;
316
342
  }
@@ -318,14 +344,16 @@ ${JSON.stringify(content)}`;
318
344
  const response = Object.assign({ id: null, tokens: null, model: null }, values, {
319
345
  id: data && data.id,
320
346
  tokens: data && data.usage && data.usage.total_tokens,
321
- model: gptModel,
322
-
323
- _text: content.text,
324
- _time: reqEndTime - reqStartTime,
325
- _cr: charactersRemoved
347
+ model: gptModel
326
348
  });
327
349
 
350
+ if (opts.verbose) {
351
+ response._text = content.text;
352
+ response._time = reqEndTime - reqStartTime;
353
+ response._cr = charactersRemoved;
354
+ }
355
+
328
356
  return response;
329
357
  }
330
358
 
331
- module.exports = generateSummary;
359
+ 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.1",
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.1",
27
27
  "gpt3-tokenizer": "1.1.5",
28
28
  "libmime": "5.2.1",
29
- "undici": "5.22.1"
29
+ "undici": "5.24.0"
30
30
  }
31
31
  }