@postalsys/email-ai-tools 1.14.10 → 1.14.12

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,3 +1,3 @@
1
1
  {
2
- ".": "1.14.10"
2
+ ".": "1.14.12"
3
3
  }
package/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # Changelog
2
2
 
3
+ ## [1.14.12](https://github.com/postalsys/email-ai-tools/compare/v1.14.11...v1.14.12) (2026-09-28)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * **deps:** pick up email-text-tools 2.4.18 ([436201e](https://github.com/postalsys/email-ai-tools/commit/436201ee41b37dd0e4a1cab85a3a2a6b77c87a13))
9
+
10
+ ## [1.14.11](https://github.com/postalsys/email-ai-tools/compare/v1.14.10...v1.14.11) (2026-09-28)
11
+
12
+
13
+ ### Bug Fixes
14
+
15
+ * estimate tokens without gpt3-tokenizer, cap and batch embeddings input, handle non-JSON API errors ([f08c565](https://github.com/postalsys/email-ai-tools/commit/f08c565355768023c0b0d5645c552704fd1bd1fe))
16
+
3
17
  ## [1.14.10](https://github.com/postalsys/email-ai-tools/compare/v1.14.9...v1.14.10) (2026-09-27)
4
18
 
5
19
 
package/CLAUDE.md CHANGED
@@ -30,13 +30,17 @@ which dependencies this library may use.
30
30
  - `lib/embeddings-query.js` - `embeddingsQuery()` / `questionQuery()`; answers
31
31
  questions over a set of emails using embeddings and chat completions.
32
32
  - `lib/list-models.js` - `listModels()`; lists models exposed by the API endpoint.
33
+ - `lib/api-request.js` - shared HTTP request helper (size cap, JSON parsing, 429
34
+ retry with Retry-After, error shaping) used by every API call.
35
+ - `lib/token-estimate.js` - character-based token estimate, prompt fitting and chunking.
33
36
 
34
37
  ## Technology Stack
35
38
 
36
39
  - **Runtime**: Node.js (CI tests on 22 and 24). No build step - plain CommonJS.
37
40
  - **Module system**: CommonJS (`'use strict';`, `require`/`module.exports`).
38
41
  - **HTTP**: `undici` (`fetch` + `Agent`) for all outbound API calls.
39
- - **Tokenizing**: `gpt3-tokenizer` for token-count budgeting.
42
+ - **Token budgeting**: a character-based estimate in `lib/token-estimate.js` (no
43
+ tokenizer dependency); the model's own context-length error is the backstop.
40
44
  - **Email/text helpers**: `@postalsys/email-text-tools`, `libmime`,
41
45
  `nodemailer/lib/addressparser`, `linkify-it`, `tlds`, `punycode.js`.
42
46
 
@@ -0,0 +1,194 @@
1
+ 'use strict';
2
+
3
+ const { fetch: fetchCmd, Agent } = require('undici');
4
+ const { setTimeout: delay } = require('timers/promises');
5
+ const crypto = require('crypto');
6
+ const util = require('util');
7
+ const packageData = require('../package.json');
8
+
9
+ const fetchAgent = new Agent({ connect: { timeout: 90 * 1000 } });
10
+
11
+ const MAX_RETRIES = 5;
12
+ const RETRY_DELAY_MS = 1000;
13
+ // A 429 asking for a longer pause than this fails right away instead of holding the caller
14
+ const MAX_RETRY_DELAY_MS = 20 * 1000;
15
+ // Large enough for a batch of 3072-dimension embeddings, small enough to not buffer anything
16
+ const MAX_RESPONSE_SIZE = 8 * 1024 * 1024;
17
+ const RESPONSE_SNIPPET_LENGTH = 512;
18
+
19
+ async function sleep(ms, signal) {
20
+ try {
21
+ await delay(ms, undefined, { signal });
22
+ } catch (err) {
23
+ // report the caller's own abort reason, not the generic AbortError of the timer
24
+ if (err.name === 'AbortError' && signal && signal.aborted) {
25
+ throw signal.reason;
26
+ }
27
+ throw err;
28
+ }
29
+ }
30
+
31
+ // Returns the requested delay in milliseconds, or null if the response does not name one
32
+ function getRetryAfter(headers) {
33
+ // Azure OpenAI sends the millisecond variant
34
+ const retryAfterMs = (headers.get('retry-after-ms') || '').trim();
35
+ if (/^\d+(\.\d+)?$/.test(retryAfterMs)) {
36
+ return Number(retryAfterMs);
37
+ }
38
+
39
+ const retryAfter = (headers.get('retry-after') || '').trim();
40
+ if (!retryAfter) {
41
+ return null;
42
+ }
43
+ if (/^\d+(\.\d+)?$/.test(retryAfter)) {
44
+ return Number(retryAfter) * 1000;
45
+ }
46
+ const date = Date.parse(retryAfter);
47
+ if (!isNaN(date)) {
48
+ return Math.max(date - Date.now(), 0);
49
+ }
50
+ return null;
51
+ }
52
+
53
+ async function readBody(res, maxSize) {
54
+ const declared = Number(res.headers.get('content-length'));
55
+ if (declared > maxSize) {
56
+ await res.body?.cancel().catch(() => false);
57
+ throw responseTooLarge(res, maxSize);
58
+ }
59
+
60
+ const chunks = [];
61
+ let size = 0;
62
+ if (res.body) {
63
+ for await (const chunk of res.body) {
64
+ size += chunk.length;
65
+ if (size > maxSize) {
66
+ // leaving the loop cancels the stream
67
+ throw responseTooLarge(res, maxSize);
68
+ }
69
+ chunks.push(chunk);
70
+ }
71
+ }
72
+ return Buffer.concat(chunks).toString('utf-8');
73
+ }
74
+
75
+ function responseTooLarge(res, maxSize) {
76
+ const error = new Error(`API response exceeds the maximum allowed size of ${maxSize} bytes`);
77
+ error.code = 'ResponseTooLarge';
78
+ error.statusCode = res.status;
79
+ return error;
80
+ }
81
+
82
+ function errorMessage(apiError) {
83
+ if (typeof apiError === 'string') {
84
+ return apiError;
85
+ }
86
+ if (apiError && typeof apiError.message === 'string' && apiError.message) {
87
+ return apiError.message;
88
+ }
89
+ try {
90
+ return JSON.stringify(apiError);
91
+ } catch {
92
+ return 'Failed to run API request';
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Sends a request to an OpenAI-compatible API and returns the parsed JSON response body
98
+ *
99
+ * @param {string} url - Request URL
100
+ * @param {Object} opts
101
+ * @param {string} [opts.method='post']
102
+ * @param {string} opts.apiToken - Sent as a Bearer token
103
+ * @param {Object} [opts.payload] - JSON request body
104
+ * @param {Object} [opts.dispatcher] - undici Dispatcher, the module's own agent when omitted
105
+ * @param {AbortSignal} [opts.signal] - Aborts the request and any retry wait
106
+ * @param {boolean} [opts.verbose] - Logs the request and the response to stderr
107
+ * @returns {Promise<{data: Object, time: number}>} Parsed response body and the time the request took in milliseconds
108
+ */
109
+ async function apiRequest(url, opts) {
110
+ const { method, apiToken, payload, dispatcher, signal, verbose } = opts;
111
+
112
+ const headers = {
113
+ 'User-Agent': `${packageData.name}/${packageData.version}`,
114
+ Authorization: `Bearer ${apiToken}`,
115
+ 'Content-Type': 'application/json'
116
+ };
117
+
118
+ const requestId = crypto.randomBytes(8).toString('base64');
119
+ if (verbose) {
120
+ console.error(util.inspect({ requestId, apiUrl: url, payload }, false, 8, true));
121
+ }
122
+
123
+ const startTime = Date.now();
124
+
125
+ for (let attempt = 1; ; attempt++) {
126
+ const res = await fetchCmd(url, {
127
+ method: method || 'post',
128
+ headers,
129
+ body: payload ? JSON.stringify(payload) : undefined,
130
+ dispatcher: dispatcher || fetchAgent,
131
+ signal
132
+ });
133
+
134
+ const text = await readBody(res, MAX_RESPONSE_SIZE);
135
+
136
+ let data = null;
137
+ try {
138
+ data = JSON.parse(text);
139
+ } catch {
140
+ // handled below, an HTML error page from a proxy is the usual case
141
+ }
142
+
143
+ if (!res.ok) {
144
+ const retryAfter = res.status === 429 ? getRetryAfter(res.headers) : null;
145
+
146
+ if (res.status === 429 && attempt < MAX_RETRIES) {
147
+ const wait = retryAfter !== null ? retryAfter : RETRY_DELAY_MS * 2 ** (attempt - 1);
148
+ if (wait <= MAX_RETRY_DELAY_MS) {
149
+ await sleep(wait, signal);
150
+ continue;
151
+ }
152
+ }
153
+
154
+ let error;
155
+ if (data && data.error) {
156
+ error = new Error(errorMessage(data.error));
157
+ if (data.error.code) {
158
+ error.code = data.error.code;
159
+ }
160
+ } else {
161
+ error = new Error('Failed to run API request');
162
+ }
163
+ error.statusCode = res.status;
164
+
165
+ if (retryAfter !== null) {
166
+ error.retryAfter = Math.ceil(retryAfter / 1000);
167
+ }
168
+
169
+ if (!data && text) {
170
+ error.responseText = text.substring(0, RESPONSE_SNIPPET_LENGTH);
171
+ }
172
+ throw error;
173
+ }
174
+
175
+ if (!data) {
176
+ // not JSON at all, or a JSON null
177
+ const error = new Error('Invalid JSON in API response');
178
+ error.code = 'InvalidResponse';
179
+ error.statusCode = res.status;
180
+ error.responseText = text.substring(0, RESPONSE_SNIPPET_LENGTH);
181
+ throw error;
182
+ }
183
+
184
+ const time = Date.now() - startTime;
185
+
186
+ if (verbose) {
187
+ console.error(util.inspect({ requestId, output: data }, false, 8, true));
188
+ }
189
+
190
+ return { data, time };
191
+ }
192
+ }
193
+
194
+ module.exports = { apiRequest, MAX_RESPONSE_SIZE };
@@ -1,16 +1,7 @@
1
1
  'use strict';
2
2
 
3
- const packageData = require('../package.json');
4
- const { default: GPT3Tokenizer } = require('gpt3-tokenizer');
5
- const util = require('util');
6
- const crypto = require('crypto');
7
- const { fetch: fetchCmd, Agent } = require('undici');
8
- const fetchAgent = new Agent({ connect: { timeout: 90 * 1000 } });
9
-
10
- const tokenizer = new GPT3Tokenizer({ type: 'gpt3' });
11
-
12
- const MAX_ALLOWED_TEXT_LENGTH = 64 * 1024;
13
- const DEFAULT_MAX_ALLOWED_TOKENS = 30000;
3
+ const { apiRequest } = require('./api-request');
4
+ const { estimateTokens, fitPrompt, DEFAULT_MAX_ALLOWED_TOKENS } = require('./token-estimate');
14
5
 
15
6
  const { getApiUrl, OPENAI_API_BASE_URL } = require('./get-api-url');
16
7
 
@@ -135,59 +126,19 @@ async function embeddingsQuery(apiToken, opts) {
135
126
  let maxAllowedTokens = opts.maxTokens || DEFAULT_MAX_ALLOWED_TOKENS;
136
127
  let gptModel = opts.gptModel || 'gpt-5-mini';
137
128
 
138
- let prompt;
139
-
140
- let charactersRemoved = 0;
141
- let promptText = contextChunks;
142
-
143
- if (promptText.length > MAX_ALLOWED_TEXT_LENGTH) {
144
- charactersRemoved += promptText.length - MAX_ALLOWED_TEXT_LENGTH;
145
- promptText = promptText.substr(0, MAX_ALLOWED_TEXT_LENGTH);
146
- }
147
-
148
- while (true) {
149
- prompt = `${SCHEMA_PROMPT}
129
+ const { prompt, charactersRemoved } = fitPrompt({
130
+ text: contextChunks,
131
+ maxTokens: maxAllowedTokens,
132
+ build: contextText => `${SCHEMA_PROMPT}
150
133
 
151
134
  **Input**:
152
135
  ${JSON.stringify({ name: opts?.userData?.name, email: opts?.userData?.email, question })}
153
136
 
154
137
  **Context emails**:
155
138
 
156
- ${promptText}
157
- `;
158
-
159
- let tokens = tokenizer.encode(prompt);
160
- if (tokens.bpe.length <= maxAllowedTokens) {
161
- break;
162
- }
163
- if (promptText.length > 2 * 1024 * 1024) {
164
- promptText = promptText.substring(0, promptText.length - 1024 * 1024);
165
- charactersRemoved += 1024 * 1024;
166
- } else if (promptText.length > 2 * 1024) {
167
- promptText = promptText.substring(0, promptText.length - 1024);
168
- charactersRemoved += 1024;
169
- } else if (promptText.length > 2 * 256) {
170
- promptText = promptText.substring(0, promptText.length - 256);
171
- charactersRemoved += 255;
172
- } else if (promptText.length > 2 * 100) {
173
- promptText = promptText.substring(0, promptText.length - 100);
174
- charactersRemoved += 100;
175
- } else if (promptText.length > 2 * 10) {
176
- promptText = promptText.substring(0, promptText.length - 10);
177
- charactersRemoved += 10;
178
- } else if (promptText.length > 1) {
179
- promptText = promptText.substring(0, promptText.length - 1);
180
- charactersRemoved += 1;
181
- } else {
182
- throw new Error(`Prompt too long. Removed ${charactersRemoved} characters.`);
183
- }
184
- }
185
-
186
- let headers = {
187
- 'User-Agent': `${packageData.name}/${packageData.version}`,
188
- Authorization: `Bearer ${apiToken}`,
189
- 'Content-Type': 'application/json'
190
- };
139
+ ${contextText}
140
+ `
141
+ });
191
142
 
192
143
  let payload = {
193
144
  model: gptModel
@@ -205,20 +156,13 @@ ${promptText}
205
156
  payload.top_p = Number(opts.topP);
206
157
  }
207
158
 
208
- const requestId = crypto.randomBytes(8).toString('base64');
209
-
210
- let res;
211
- let data;
212
- let retries = 0;
213
-
214
159
  let openAiAPIURL;
215
160
  switch (gptModel) {
216
161
  case 'gpt-3.5-turbo-instruct':
217
162
  {
218
163
  openAiAPIURL = getApiUrl(baseApiUrl, OPENAI_API_URL_INSTRUCT);
219
164
  payload.prompt = `${systemPrompt}\n${prompt}`;
220
- let tokens = tokenizer.encode(payload.prompt);
221
- payload.max_tokens = 4000 - tokens.bpe.length;
165
+ payload.max_tokens = 4000 - estimateTokens(payload.prompt);
222
166
  }
223
167
  break;
224
168
 
@@ -239,50 +183,13 @@ ${promptText}
239
183
  break;
240
184
  }
241
185
 
242
- if (opts.verbose) {
243
- console.error(util.inspect({ requestId, apiUrl: openAiAPIURL, payload }, false, 8, true));
244
- }
245
-
246
- let run = async () => {
247
- res = await fetchCmd(openAiAPIURL, {
248
- method: 'post',
249
- headers,
250
- body: JSON.stringify(payload),
251
- dispatcher: opts.dispatcher || fetchAgent
252
- });
253
-
254
- data = await res.json();
255
-
256
- if (!res.ok) {
257
- if (res.status === 429 && ++retries < 5) {
258
- // try again
259
- await new Promise(r => setTimeout(r, 1000));
260
- return await run();
261
- }
262
-
263
- if (data && data.error) {
264
- let error = new Error(data.error.message || data.error);
265
- if (data.error.code) {
266
- error.code = data.error.code;
267
- }
268
-
269
- error.statusCode = res.status;
270
- throw error;
271
- }
272
-
273
- let error = new Error('Failed to run API request');
274
- error.statusCode = res.status;
275
- throw error;
276
- }
277
-
278
- if (!data) {
279
- throw new Error(`Failed to POST API request`);
280
- }
281
- };
282
-
283
- const reqStartTime = Date.now();
284
- await run();
285
- const reqEndTime = Date.now();
186
+ const { data, time } = await apiRequest(openAiAPIURL, {
187
+ apiToken,
188
+ payload,
189
+ dispatcher: opts.dispatcher,
190
+ signal: opts.signal,
191
+ verbose: opts.verbose
192
+ });
286
193
 
287
194
  let output =
288
195
  data &&
@@ -294,10 +201,6 @@ ${promptText}
294
201
  .join('')
295
202
  .trim();
296
203
 
297
- if (opts.verbose) {
298
- console.error(util.inspect({ requestId, output: data }, false, 8, true));
299
- }
300
-
301
204
  let responseValues = { answer: '', 'message-id': '' };
302
205
  let curKey;
303
206
  output
@@ -343,10 +246,8 @@ ${promptText}
343
246
  });
344
247
 
345
248
  if (opts.verbose) {
346
- response._time = reqEndTime - reqStartTime;
249
+ response._time = time;
347
250
  response._cr = charactersRemoved;
348
-
349
- console.error(util.inspect({ requestId, response }, false, 8, true));
350
251
  }
351
252
 
352
253
  return response;
@@ -371,12 +272,6 @@ async function questionQuery(question, apiToken, opts) {
371
272
  ${question}
372
273
  `;
373
274
 
374
- let headers = {
375
- 'User-Agent': `${packageData.name}/${packageData.version}`,
376
- Authorization: `Bearer ${apiToken}`,
377
- 'Content-Type': 'application/json'
378
- };
379
-
380
275
  let payload = {
381
276
  model: gptModel
382
277
  };
@@ -395,20 +290,13 @@ ${question}
395
290
  payload.top_p = Number(opts.topP);
396
291
  }
397
292
 
398
- const requestId = crypto.randomBytes(8).toString('base64');
399
-
400
- let res;
401
- let data;
402
- let retries = 0;
403
-
404
293
  let openAiAPIURL;
405
294
  switch (gptModel) {
406
295
  case 'gpt-3.5-turbo-instruct':
407
296
  {
408
297
  openAiAPIURL = getApiUrl(baseApiUrl, OPENAI_API_URL_INSTRUCT);
409
298
  payload.prompt = `${systemPrompt}\n${prompt}`;
410
- let tokens = tokenizer.encode(payload.prompt);
411
- payload.max_tokens = 4000 - tokens.bpe.length;
299
+ payload.max_tokens = 4000 - estimateTokens(payload.prompt);
412
300
  }
413
301
  break;
414
302
 
@@ -429,50 +317,13 @@ ${question}
429
317
  break;
430
318
  }
431
319
 
432
- if (opts.verbose) {
433
- console.error(util.inspect({ requestId, apiUrl: openAiAPIURL, payload }, false, 8, true));
434
- }
435
-
436
- let run = async () => {
437
- res = await fetchCmd(openAiAPIURL, {
438
- method: 'post',
439
- headers,
440
- body: JSON.stringify(payload),
441
- dispatcher: opts.dispatcher || fetchAgent
442
- });
443
-
444
- data = await res.json();
445
-
446
- if (!res.ok) {
447
- if (res.status === 429 && ++retries < 5) {
448
- // try again
449
- await new Promise(r => setTimeout(r, 1000));
450
- return await run();
451
- }
452
-
453
- if (data && data.error) {
454
- let error = new Error(data.error.message || data.error);
455
- if (data.error.code) {
456
- error.code = data.error.code;
457
- }
458
-
459
- error.statusCode = res.status;
460
- throw error;
461
- }
462
-
463
- let error = new Error('Failed to run API request');
464
- error.statusCode = res.status;
465
- throw error;
466
- }
467
-
468
- if (!data) {
469
- throw new Error(`Failed to POST API request`);
470
- }
471
- };
472
-
473
- const reqStartTime = Date.now();
474
- await run();
475
- const reqEndTime = Date.now();
320
+ const { data, time } = await apiRequest(openAiAPIURL, {
321
+ apiToken,
322
+ payload,
323
+ dispatcher: opts.dispatcher,
324
+ signal: opts.signal,
325
+ verbose: opts.verbose
326
+ });
476
327
 
477
328
  let values;
478
329
  let output =
@@ -485,10 +336,6 @@ ${question}
485
336
  .join('')
486
337
  .trim();
487
338
 
488
- if (opts.verbose) {
489
- console.error(util.inspect({ requestId, output: data }, false, 8, true));
490
- }
491
-
492
339
  try {
493
340
  let objStart = output.indexOf('{');
494
341
  let objEnd = output.lastIndexOf('}');
@@ -544,7 +391,7 @@ ${question}
544
391
  });
545
392
 
546
393
  if (opts.verbose) {
547
- response._time = reqEndTime - reqStartTime;
394
+ response._time = time;
548
395
  }
549
396
 
550
397
  return response;