@postalsys/email-ai-tools 1.14.13 → 2.0.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.
@@ -5,15 +5,79 @@ const { apiRequest } = require('./api-request');
5
5
  const { getApiUrl, OPENAI_API_BASE_URL } = require('./get-api-url');
6
6
 
7
7
  const OPENAI_API_MODELS = '/v1/models';
8
+ const OPENAI_API_HOST = new URL(OPENAI_API_BASE_URL).hostname;
9
+
10
+ // On OpenAI's own endpoint the names are known, and these are not chat models: embeddings,
11
+ // speech, images, video, moderation, the legacy completion models, and the chat models that are
12
+ // specialised for something else
13
+ const OPENAI_NON_CHAT_MODEL =
14
+ /embedding|tts|whisper|transcribe|dall-e|image|realtime|^gpt-live|audio|moderation|babbage|davinci|sora|instruct|codex|search|computer-use|cyber|daybreak|rosalind/i;
15
+
16
+ // Elsewhere the names are whatever the operator pulled ("Llama-3.1-8B-Instruct" is a chat model
17
+ // there), so only the unmistakable ones are left out
18
+ const GENERIC_NON_CHAT_MODEL = /embed|whisper|tts|rerank/i;
19
+
20
+ const DATED_SNAPSHOT = /-\d{4}-\d{2}-\d{2}$|-\d{4,}$/;
21
+
22
+ const collator = new Intl.Collator('en', { numeric: true });
23
+
24
+ /**
25
+ * The pattern of model names listModels() leaves out for an endpoint
26
+ *
27
+ * @param {string} [baseApiUrl] - Base API URL (default: OpenAI API)
28
+ * @returns {RegExp}
29
+ */
30
+ function nonChatModelPattern(baseApiUrl) {
31
+ return new URL(baseApiUrl || OPENAI_API_BASE_URL).hostname === OPENAI_API_HOST ? OPENAI_NON_CHAT_MODEL : GENERIC_NON_CHAT_MODEL;
32
+ }
33
+
34
+ // Sort key: GPT families first, newest first, then the o-series, then everything else; within a
35
+ // family the plain name before dated snapshots and previews
36
+ function decorate(entry) {
37
+ const match = /^(gpt-|o)(\d+(?:\.\d+)?)/i.exec(entry.id);
38
+ return {
39
+ entry,
40
+ group: match ? (match[1].toLowerCase() === 'o' ? 1 : 0) : 2,
41
+ version: match ? parseFloat(match[2]) : 0,
42
+ dated: DATED_SNAPSHOT.test(entry.id),
43
+ preview: /preview/i.test(entry.id)
44
+ };
45
+ }
46
+
47
+ function compare(a, b) {
48
+ return a.group - b.group || b.version - a.version || a.dated - b.dated || a.preview - b.preview || collator.compare(a.entry.id, b.entry.id);
49
+ }
8
50
 
51
+ function formatName(id) {
52
+ return id
53
+ .replace(/-/g, ' ')
54
+ .replace(/^.| ./g, c => c.toUpperCase())
55
+ .replace(/\bhd\b/gi, c => c.toUpperCase())
56
+ .replace(/\b\d+k\b/gi, c => c.toUpperCase())
57
+ .replace(/Dall E/g, 'Dall-E')
58
+ .replace(/^Whisper /g, 'Whisper-')
59
+ .replace(/(\d{4}) (\d{2}) (\d{2})/g, (o, y, m, d) => `${y}-${m}-${d}`)
60
+ .replace(/^(gpt|tts)\s/gi, (o, n) => `${n.toUpperCase()}-`);
61
+ }
62
+
63
+ /**
64
+ * Lists the models the API endpoint serves, newest family first, with a display name for each
65
+ *
66
+ * @param {string} apiToken - API authentication token
67
+ * @param {Object} [opts]
68
+ * @param {string} [opts.baseApiUrl] - Custom API base URL (default: OpenAI API)
69
+ * @param {boolean} [opts.chatOnly=true] - Leave out models that are not chat models
70
+ * @param {boolean} [opts.verbose] - Log the request and include the request time
71
+ * @param {Object} [opts.dispatcher] - undici Dispatcher the request is sent through
72
+ * @param {AbortSignal} [opts.signal] - Aborts the request
73
+ * @returns {Promise<{models: Array<{id: string, name: string}>}>}
74
+ */
9
75
  async function listModels(apiToken, opts) {
10
76
  opts = opts || {};
11
77
 
12
- let baseApiUrl = opts.baseApiUrl || OPENAI_API_BASE_URL;
13
-
14
- let openAiAPIURL = getApiUrl(baseApiUrl, OPENAI_API_MODELS);
78
+ const baseApiUrl = opts.baseApiUrl || OPENAI_API_BASE_URL;
15
79
 
16
- const { data, time } = await apiRequest(openAiAPIURL, {
80
+ const { data, time } = await apiRequest(getApiUrl(baseApiUrl, OPENAI_API_MODELS), {
17
81
  method: 'get',
18
82
  apiToken,
19
83
  dispatcher: opts.dispatcher,
@@ -21,53 +85,25 @@ async function listModels(apiToken, opts) {
21
85
  verbose: opts.verbose
22
86
  });
23
87
 
24
- const response = { models: [].concat((data && data.data) || []).filter(entry => !['openai-dev'].includes(entry.owned_by)) };
88
+ const nonChat = nonChatModelPattern(baseApiUrl);
89
+
90
+ const response = {
91
+ models: []
92
+ .concat((data && data.data) || [])
93
+ .filter(
94
+ entry =>
95
+ entry && typeof entry.id === 'string' && entry.id && entry.owned_by !== 'openai-dev' && (opts.chatOnly === false || !nonChat.test(entry.id))
96
+ )
97
+ .map(decorate)
98
+ .sort(compare)
99
+ .map(({ entry }) => Object.assign(entry, { name: formatName(entry.id) }))
100
+ };
25
101
 
26
102
  if (opts.verbose) {
27
103
  response._time = time;
28
104
  }
29
105
 
30
- response.models.sort((a, b) => {
31
- if (/^gpt/.test(a.id) && !/^gpt/.test(b.id)) {
32
- return -1;
33
- }
34
-
35
- if (/^gpt/.test(b.id) && !/^gpt/.test(a.id)) {
36
- return 1;
37
- }
38
-
39
- if (/-\d{4,}$/.test(b.id) && !/-\d{4,}$/.test(a.id)) {
40
- return -1;
41
- }
42
-
43
- if (/-\d{4,}$/.test(a.id) && !/-\d{4,}$/.test(b.id)) {
44
- return 1;
45
- }
46
-
47
- if (/-preview/.test(b.id) && !/-preview/.test(a.id)) {
48
- return -1;
49
- }
50
-
51
- if (/-preview/.test(a.id) && !/-preview/.test(b.id)) {
52
- return 1;
53
- }
54
-
55
- return a.id.localeCompare(b.id);
56
- });
57
-
58
- response.models.forEach(entry => {
59
- entry.name = entry.id
60
- .replace(/-/g, ' ')
61
- .replace(/^.| ./g, c => c.toUpperCase())
62
- .replace(/\bhd\b/gi, c => c.toUpperCase())
63
- .replace(/\b\d+k\b/gi, c => c.toUpperCase())
64
- .replace(/Dall E/g, 'Dall-E')
65
- .replace(/^Whisper /g, 'Whisper-')
66
- .replace(/(\d{4}) (\d{2}) (\d{2})/g, (o, y, m, d) => `${y}-${m}-${d}`)
67
- .replace(/^(gpt|tts)\s/gi, (o, n) => `${n.toUpperCase()}-`);
68
- });
69
-
70
106
  return response;
71
107
  }
72
108
 
73
- module.exports = { listModels };
109
+ module.exports = { listModels, nonChatModelPattern };
@@ -6,50 +6,44 @@
6
6
  // 25 s per encode). The estimate errs on the high side; the model's own context length error
7
7
  // stays the backstop for the rare input that tokenizes worse than this.
8
8
 
9
- // Prompt fitting: ASCII at 3 characters per token is below what English, code and base64-ish
10
- // runs actually reach, and every non-ASCII UTF-16 code unit counts as a whole token.
11
- const PROMPT_ESTIMATE = { charsPerToken: 3, margin: 1.1 };
9
+ // ASCII at 3 characters per token is below what English, code and base64-ish runs actually
10
+ // reach, every non-ASCII UTF-16 code unit counts as a whole token, and the margin goes on top
11
+ const CHARS_PER_TOKEN = 3;
12
+ const MARGIN = 1.1;
12
13
 
13
14
  // Input text beyond this many characters is never sent, whatever the token budget
14
15
  const MAX_ALLOWED_TEXT_LENGTH = 64 * 1024;
15
16
  // Default prompt budget when the caller does not set maxTokens
16
17
  const DEFAULT_MAX_ALLOWED_TOKENS = 30000;
17
18
 
18
- // Chunk sizing only needs to be roughly right, so it uses a typical English ratio instead.
19
- const CHUNK_ESTIMATE = { charsPerToken: 4, margin: 1 };
20
-
21
- // Cost of one UTF-16 code unit in "ASCII character" units
22
- function charUnits(code, charsPerToken) {
19
+ // Cost of one UTF-16 code unit in "ASCII character" units. The text travels JSON encoded, so the
20
+ // characters that encoding escapes count double
21
+ function charUnits(code) {
23
22
  if (code < 0x20 || code === 0x22 || code === 0x5c) {
24
- // control characters, quotes and backslashes are escaped when the text is JSON encoded
25
23
  return 2;
26
24
  }
27
25
  if (code < 0x80) {
28
26
  return 1;
29
27
  }
30
- return charsPerToken;
28
+ return CHARS_PER_TOKEN;
31
29
  }
32
30
 
33
31
  /**
34
32
  * Estimates how many tokens a string takes
35
33
  *
36
34
  * @param {string} str
37
- * @param {Object} [opts]
38
- * @param {number} [opts.charsPerToken=3] - ASCII characters per token
39
- * @param {number} [opts.margin=1.1] - Safety factor applied to the estimate
40
35
  * @returns {number} Estimated token count
41
36
  */
42
- function estimateTokens(str, opts) {
43
- const { charsPerToken, margin } = Object.assign({}, PROMPT_ESTIMATE, opts);
37
+ function estimateTokens(str) {
44
38
  str = (str || '').toString();
45
39
 
46
40
  let units = 0;
47
41
  for (let i = 0; i < str.length; i++) {
48
- units += charUnits(str.charCodeAt(i), charsPerToken);
42
+ units += charUnits(str.charCodeAt(i));
49
43
  }
50
44
 
51
45
  // the epsilon keeps float noise (100 * 1.1 = 110.00000000000001) from adding a token
52
- return Math.ceil((units / charsPerToken) * margin - 1e-9);
46
+ return Math.ceil((units / CHARS_PER_TOKEN) * MARGIN - 1e-9);
53
47
  }
54
48
 
55
49
  /**
@@ -58,23 +52,21 @@ function estimateTokens(str, opts) {
58
52
  *
59
53
  * @param {string} str
60
54
  * @param {number} maxTokens
61
- * @param {Object} [opts] - Same as for estimateTokens()
62
55
  * @returns {number} Prefix length in UTF-16 code units
63
56
  */
64
- function fitLength(str, maxTokens, opts) {
65
- const { charsPerToken, margin } = Object.assign({}, PROMPT_ESTIMATE, opts);
57
+ function fitLength(str, maxTokens) {
66
58
  str = (str || '').toString();
67
59
 
68
60
  if (!(maxTokens > 0)) {
69
61
  return 0;
70
62
  }
71
63
 
72
- const maxUnits = Math.floor((maxTokens * charsPerToken) / margin);
64
+ const maxUnits = Math.floor((maxTokens * CHARS_PER_TOKEN) / MARGIN);
73
65
 
74
66
  let units = 0;
75
67
  let i = 0;
76
68
  for (; i < str.length; i++) {
77
- const cost = charUnits(str.charCodeAt(i), charsPerToken);
69
+ const cost = charUnits(str.charCodeAt(i));
78
70
  if (units + cost > maxUnits) {
79
71
  break;
80
72
  }
@@ -96,65 +88,26 @@ function keepSurrogatePair(str, pos) {
96
88
  }
97
89
 
98
90
  /**
99
- * Splits text into chunks of at most `maxTokens` estimated tokens each, preferring to break at
100
- * whitespace. Characters are never split, unlike slicing BPE token arrays.
101
- *
102
- * @param {string} str
103
- * @param {number} maxTokens
104
- * @param {Object} [opts] - Same as for estimateTokens(), defaults to the chunk sizing ratio
105
- * @returns {string[]}
106
- */
107
- function splitByTokens(str, maxTokens, opts) {
108
- opts = Object.assign({}, CHUNK_ESTIMATE, opts);
109
- str = (str || '').toString();
110
-
111
- const chunks = [];
112
- let rest = str;
113
- while (rest.length) {
114
- let len = fitLength(rest, maxTokens, opts);
115
- if (len >= rest.length) {
116
- chunks.push(rest);
117
- break;
118
- }
119
-
120
- if (len < 1) {
121
- // a single character larger than the budget, take it (or its surrogate pair) anyway
122
- len = keepSurrogatePair(rest, 1) || 2;
123
- } else {
124
- // break at the last whitespace if it is not too far back, so words stay whole
125
- const ws = Math.max(rest.lastIndexOf(' ', len - 1), rest.lastIndexOf('\n', len - 1));
126
- if (ws >= len / 2) {
127
- len = ws + 1;
128
- }
129
- }
130
-
131
- chunks.push(rest.substring(0, len));
132
- rest = rest.substring(len);
133
- }
134
-
135
- return chunks;
136
- }
137
-
138
- /**
139
- * Cuts `text` so that the prompt built around it fits into `maxTokens` estimated tokens. The
140
- * text is sized in one step from an estimate of what the rest of the prompt takes.
91
+ * Cuts `text` so that it fits into `maxTokens` estimated tokens next to the fixed parts of the
92
+ * prompt
141
93
  *
142
94
  * @param {Object} opts
143
95
  * @param {string} opts.text - Variable part of the prompt, the only part that gets shortened
144
96
  * @param {number} [opts.maxLength=MAX_ALLOWED_TEXT_LENGTH] - Hard cap on the text length
145
97
  * @param {number} [opts.maxTokens=DEFAULT_MAX_ALLOWED_TOKENS] - Token budget for the whole prompt
146
- * @param {Function} opts.build - Returns the full prompt for a given text
147
- * @returns {{prompt: string, text: string, charactersRemoved: number}}
148
- * @throws {Error} PROMPT_TOO_LONG if the prompt does not fit even without any text
98
+ * @param {Array<string|number>|string|number} [opts.overhead] - The fixed parts, as strings to estimate or as token counts already estimated
99
+ * @returns {{text: string, charactersRemoved: number}}
100
+ * @throws {Error} PROMPT_TOO_LONG if the fixed parts alone do not fit
149
101
  */
150
- function fitPrompt({ text, maxLength, maxTokens, build }) {
102
+ function fitPrompt({ text, maxLength, maxTokens, overhead }) {
151
103
  text = (text || '').toString();
152
104
  maxLength = maxLength || MAX_ALLOWED_TEXT_LENGTH;
153
105
  maxTokens = maxTokens || DEFAULT_MAX_ALLOWED_TOKENS;
154
106
 
155
- let fitted = text.length > maxLength ? text.substring(0, keepSurrogatePair(text, maxLength)) : text;
107
+ const overheadTokens = []
108
+ .concat(overhead === undefined ? [] : overhead)
109
+ .reduce((sum, part) => sum + (typeof part === 'number' ? part : estimateTokens(part)), 0);
156
110
 
157
- const overheadTokens = estimateTokens(build(''));
158
111
  if (overheadTokens > maxTokens) {
159
112
  const error = new Error(
160
113
  `Unable to fit email content within token limit of ${maxTokens}. ` +
@@ -169,18 +122,10 @@ function fitPrompt({ text, maxLength, maxTokens, build }) {
169
122
  throw error;
170
123
  }
171
124
 
125
+ let fitted = text.length > maxLength ? text.substring(0, keepSurrogatePair(text, maxLength)) : text;
172
126
  fitted = fitted.substring(0, fitLength(fitted, maxTokens - overheadTokens));
173
127
 
174
- return { prompt: build(fitted), text: fitted, charactersRemoved: text.length - fitted.length };
128
+ return { text: fitted, charactersRemoved: text.length - fitted.length };
175
129
  }
176
130
 
177
- module.exports = {
178
- estimateTokens,
179
- fitLength,
180
- fitPrompt,
181
- keepSurrogatePair,
182
- splitByTokens,
183
- CHUNK_ESTIMATE,
184
- MAX_ALLOWED_TEXT_LENGTH,
185
- DEFAULT_MAX_ALLOWED_TOKENS
186
- };
131
+ module.exports = { estimateTokens, fitLength, fitPrompt };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@postalsys/email-ai-tools",
3
- "version": "1.14.13",
4
- "description": "Email AI tools",
3
+ "version": "2.0.0",
4
+ "description": "Summarize and risk-score email messages with an OpenAI-compatible chat model",
5
5
  "main": "index.js",
6
6
  "scripts": {
7
7
  "test": "node --test test/*.test.js",
@@ -26,16 +26,12 @@
26
26
  "eslint": "10.11.0",
27
27
  "eslint-config-nodemailer": "1.2.0",
28
28
  "eslint-config-prettier": "10.1.8",
29
- "mailparser": "3.9.31",
29
+ "mailparser": "3.9.32",
30
30
  "prettier": "3.9.9"
31
31
  },
32
32
  "dependencies": {
33
33
  "@postalsys/email-text-tools": "2.4.18",
34
34
  "libmime": "5.4.6",
35
- "linkify-it": "5.0.2",
36
- "nodemailer": "10.0.12",
37
- "punycode.js": "2.3.1",
38
- "tlds": "1.261.0",
39
35
  "undici": "7.30.0"
40
36
  },
41
37
  "engines": {
@@ -3,8 +3,8 @@
3
3
  const { describe, it, before, after, beforeEach } = require('node:test');
4
4
  const assert = require('node:assert/strict');
5
5
  const { Agent } = require('undici');
6
- const { createMockServer, chatResponse, embeddingResponse, modelsResponse } = require('./helpers/mock-server');
7
- const { generateSummary, generateEmbeddings, getChunkEmbeddings, embeddingsQuery, questionQuery, riskAnalysis, listModels } = require('..');
6
+ const { createMockServer, chatResponse, modelsResponse } = require('./helpers/mock-server');
7
+ const { generateSummary, listModels } = require('..');
8
8
 
9
9
  // A real undici Agent that counts what was dispatched through it, so a test can tell the request
10
10
  // used the dispatcher it was given and not the module's own agent.
@@ -54,31 +54,6 @@ describe('request option pass-through', () => {
54
54
  response: () => chatResponse({ sentiment: 'neutral', summary: 'ok', shouldReply: false, riskAssessment: { risk: 1 } }),
55
55
  run: opts => generateSummary(message, 'token', opts)
56
56
  },
57
- {
58
- name: 'riskAnalysis',
59
- response: () => chatResponse({ risk: 1, assessment: 'fine' }),
60
- run: opts => riskAnalysis(message, 'token', opts)
61
- },
62
- {
63
- name: 'getChunkEmbeddings',
64
- response: () => embeddingResponse(),
65
- run: opts => getChunkEmbeddings('chunk', 'token', opts)
66
- },
67
- {
68
- name: 'generateEmbeddings',
69
- response: () => embeddingResponse(),
70
- run: opts => generateEmbeddings(message, 'token', opts)
71
- },
72
- {
73
- name: 'embeddingsQuery',
74
- response: () => chatResponse('Answer.\n\nMessage IDs: id1'),
75
- run: opts => embeddingsQuery('token', Object.assign({ question: 'What?', contextChunks: 'id1: hello' }, opts))
76
- },
77
- {
78
- name: 'questionQuery',
79
- response: () => chatResponse({ ordering: 'best_match', topic: 'conference' }),
80
- run: opts => questionQuery('When is the next conference?', 'token', opts)
81
- },
82
57
  {
83
58
  name: 'listModels',
84
59
  response: () => modelsResponse(),
@@ -108,25 +83,6 @@ describe('request option pass-through', () => {
108
83
  });
109
84
  }
110
85
 
111
- it('generateEmbeddings forwards the request options to every chunk request', async () => {
112
- mock.setHandler(() => embeddingResponse());
113
-
114
- const result = await generateEmbeddings(message, 'token', {
115
- baseApiUrl: mock.url,
116
- dispatcher,
117
- gptModel: 'text-embedding-3-small',
118
- user: 'user-1'
119
- });
120
-
121
- assert.equal(result.model, 'text-embedding-3-small');
122
- assert.ok(mock.requests.length >= 1);
123
- for (const req of mock.requests) {
124
- assert.equal(req.url, '/v1/embeddings');
125
- assert.equal(req.body.model, 'text-embedding-3-small');
126
- assert.equal(req.body.user, 'user-1');
127
- }
128
- });
129
-
130
86
  it('falls back to the built-in agent when no dispatcher is given', async () => {
131
87
  mock.setHandler(() => modelsResponse());
132
88