@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.
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +14 -0
- package/CLAUDE.md +5 -1
- package/lib/api-request.js +194 -0
- package/lib/embeddings-query.js +27 -180
- package/lib/generate-embeddings.js +67 -90
- package/lib/generate-summary.js +24 -128
- package/lib/list-models.js +9 -63
- package/lib/risk-analysis.js +21 -103
- package/lib/token-estimate.js +186 -0
- package/package.json +5 -6
- package/test/api-request.test.js +162 -0
- package/test/dispatcher.test.js +15 -2
- package/test/generate-embeddings.test.js +131 -1
- package/test/helpers/mock-server.js +11 -3
- package/test/token-estimate.test.js +188 -0
|
@@ -3,7 +3,21 @@
|
|
|
3
3
|
const { describe, it, before, after, beforeEach } = require('node:test');
|
|
4
4
|
const assert = require('node:assert/strict');
|
|
5
5
|
const { createMockServer, embeddingResponse, errorResponse } = require('./helpers/mock-server');
|
|
6
|
-
const { getChunkEmbeddings } = require('../lib/generate-embeddings');
|
|
6
|
+
const { getChunkEmbeddings, generateEmbeddings } = require('../lib/generate-embeddings');
|
|
7
|
+
|
|
8
|
+
// Answers a single or batched embeddings request with one vector per input
|
|
9
|
+
function batchEmbeddingResponse(body) {
|
|
10
|
+
const inputs = [].concat(body.input);
|
|
11
|
+
return {
|
|
12
|
+
status: 200,
|
|
13
|
+
body: {
|
|
14
|
+
// reversed on purpose, entries carry their input position
|
|
15
|
+
data: inputs.map((input, index) => ({ index, embedding: [index, input.length] })).reverse()
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const cjkText = size => '\u6f22\u5b57\u4eee\u540d\u4e2d\u6587\u65e5\u672c\u8a9e\u6587\u5b57'.repeat(Math.ceil(size / 11)).substring(0, size);
|
|
7
21
|
|
|
8
22
|
describe('getChunkEmbeddings', () => {
|
|
9
23
|
let mock;
|
|
@@ -88,6 +102,12 @@ describe('getChunkEmbeddings', () => {
|
|
|
88
102
|
);
|
|
89
103
|
});
|
|
90
104
|
|
|
105
|
+
it('rejects a reply without embedding data instead of returning an undefined vector', async () => {
|
|
106
|
+
mock.setHandler(() => ({ status: 200, body: { object: 'list' } }));
|
|
107
|
+
|
|
108
|
+
await assert.rejects(() => getChunkEmbeddings('Test', 'test-token', { baseApiUrl: mock.url }), { code: 'InvalidResponse' });
|
|
109
|
+
});
|
|
110
|
+
|
|
91
111
|
it('throws generic error on failure without error details', async () => {
|
|
92
112
|
mock.setHandler(() => ({ status: 500, body: {} }));
|
|
93
113
|
|
|
@@ -101,3 +121,113 @@ describe('getChunkEmbeddings', () => {
|
|
|
101
121
|
);
|
|
102
122
|
});
|
|
103
123
|
});
|
|
124
|
+
|
|
125
|
+
describe('generateEmbeddings', () => {
|
|
126
|
+
let mock;
|
|
127
|
+
|
|
128
|
+
before(async () => {
|
|
129
|
+
mock = await createMockServer();
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
after(async () => {
|
|
133
|
+
await mock.close();
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
beforeEach(() => {
|
|
137
|
+
mock.clearRequests();
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
const headers = [
|
|
141
|
+
{ key: 'from', value: 'sender@example.com' },
|
|
142
|
+
{ key: 'subject', value: 'Hello' }
|
|
143
|
+
];
|
|
144
|
+
|
|
145
|
+
it('sends a short message as a single string input', async () => {
|
|
146
|
+
mock.setHandler((req, body) => batchEmbeddingResponse(body));
|
|
147
|
+
|
|
148
|
+
const result = await generateEmbeddings({ headers, text: 'Short message' }, 'token', { baseApiUrl: mock.url });
|
|
149
|
+
|
|
150
|
+
assert.equal(mock.requests.length, 1);
|
|
151
|
+
assert.equal(typeof mock.requests[0].body.input, 'string');
|
|
152
|
+
assert.equal(result.embeddings.length, 1);
|
|
153
|
+
assert.ok(result.embeddings[0].chunk.endsWith('Short message'));
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it('caps the input, batches chunks and never splits characters', { timeout: 5000 }, async () => {
|
|
157
|
+
mock.setHandler((req, body) => batchEmbeddingResponse(body));
|
|
158
|
+
|
|
159
|
+
const text = cjkText(1024 * 1024);
|
|
160
|
+
const result = await generateEmbeddings({ headers, text }, 'token', { baseApiUrl: mock.url });
|
|
161
|
+
|
|
162
|
+
const prefix = 'from: <sender@example.com>\nsubject: Hello\n\n';
|
|
163
|
+
const chunks = result.embeddings.map(entry => entry.chunk);
|
|
164
|
+
|
|
165
|
+
// capped at 64 KB instead of embedding the whole megabyte
|
|
166
|
+
const joined = chunks.map(chunk => chunk.substring(prefix.length)).join('');
|
|
167
|
+
assert.equal(joined, text.substring(0, 64 * 1024));
|
|
168
|
+
|
|
169
|
+
for (const chunk of chunks) {
|
|
170
|
+
assert.ok(chunk.startsWith(prefix));
|
|
171
|
+
assert.ok(!chunk.includes('\ufffd'));
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// one request per 16 chunks, not one per chunk
|
|
175
|
+
assert.equal(mock.requests.length, Math.ceil(chunks.length / 16));
|
|
176
|
+
assert.ok(Array.isArray(mock.requests[0].body.input));
|
|
177
|
+
|
|
178
|
+
// every chunk gets the vector answered for its own position
|
|
179
|
+
result.embeddings.forEach((entry, i) => {
|
|
180
|
+
assert.deepEqual(entry.embedding, [i % 16, entry.chunk.length]);
|
|
181
|
+
});
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
it('honours maxTextLength and chunksPerRequest', async () => {
|
|
185
|
+
mock.setHandler((req, body) => batchEmbeddingResponse(body));
|
|
186
|
+
|
|
187
|
+
const result = await generateEmbeddings({ headers, text: 'word '.repeat(10000) }, 'token', {
|
|
188
|
+
baseApiUrl: mock.url,
|
|
189
|
+
maxTextLength: 8000,
|
|
190
|
+
chunksPerRequest: 2
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
assert.ok(result.embeddings.length > 2);
|
|
194
|
+
assert.equal(mock.requests.length, Math.ceil(result.embeddings.length / 2));
|
|
195
|
+
for (const entry of result.embeddings) {
|
|
196
|
+
// chunks end at word boundaries
|
|
197
|
+
assert.ok(/(word |word)$/.test(entry.chunk));
|
|
198
|
+
}
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
it('caps the text without splitting a surrogate pair', async () => {
|
|
202
|
+
mock.setHandler((req, body) => batchEmbeddingResponse(body));
|
|
203
|
+
|
|
204
|
+
// the cap falls between the two halves of the emoji
|
|
205
|
+
const result = await generateEmbeddings({ headers, text: 'a'.repeat(99) + '\ud83d\ude00' + 'b'.repeat(100) }, 'token', {
|
|
206
|
+
baseApiUrl: mock.url,
|
|
207
|
+
maxTextLength: 100
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
const sent = result.embeddings.map(entry => entry.chunk).join('');
|
|
211
|
+
assert.ok(sent.endsWith('a'.repeat(99)), JSON.stringify(sent.slice(-5)));
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
it('stops sending requests once the signal is aborted', async () => {
|
|
215
|
+
const controller = new AbortController();
|
|
216
|
+
mock.setHandler((req, body) => {
|
|
217
|
+
controller.abort(new Error('stopped'));
|
|
218
|
+
return batchEmbeddingResponse(body);
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
await assert.rejects(() => generateEmbeddings({ headers, text: cjkText(64 * 1024) }, 'token', { baseApiUrl: mock.url, signal: controller.signal }), {
|
|
222
|
+
message: 'stopped'
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
assert.equal(mock.requests.length, 1);
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
it('rejects a batch response with the wrong number of entries', async () => {
|
|
229
|
+
mock.setHandler(() => embeddingResponse());
|
|
230
|
+
|
|
231
|
+
await assert.rejects(() => generateEmbeddings({ headers, text: cjkText(8000) }, 'token', { baseApiUrl: mock.url }), { code: 'InvalidResponse' });
|
|
232
|
+
});
|
|
233
|
+
});
|
|
@@ -7,11 +7,13 @@ async function createMockServer() {
|
|
|
7
7
|
const requests = [];
|
|
8
8
|
|
|
9
9
|
const server = http.createServer((req, res) => {
|
|
10
|
-
|
|
10
|
+
// collect Buffers, decoding chunk by chunk would split multi-byte characters
|
|
11
|
+
const chunks = [];
|
|
11
12
|
req.on('data', chunk => {
|
|
12
|
-
|
|
13
|
+
chunks.push(chunk);
|
|
13
14
|
});
|
|
14
15
|
req.on('end', () => {
|
|
16
|
+
const body = Buffer.concat(chunks).toString('utf-8');
|
|
15
17
|
let parsedBody = null;
|
|
16
18
|
try {
|
|
17
19
|
if (body) {
|
|
@@ -29,7 +31,13 @@ async function createMockServer() {
|
|
|
29
31
|
});
|
|
30
32
|
|
|
31
33
|
const response = requestHandler(req, parsedBody);
|
|
32
|
-
|
|
34
|
+
if (typeof response.raw === 'string') {
|
|
35
|
+
// a non-JSON body, for example an HTML error page from a proxy
|
|
36
|
+
res.writeHead(response.status || 200, Object.assign({ 'Content-Type': 'text/html' }, response.headers));
|
|
37
|
+
res.end(response.raw);
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
res.writeHead(response.status || 200, Object.assign({ 'Content-Type': 'application/json' }, response.headers));
|
|
33
41
|
res.end(JSON.stringify(response.body || {}));
|
|
34
42
|
});
|
|
35
43
|
});
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { describe, it, before, after, beforeEach } = require('node:test');
|
|
4
|
+
const assert = require('node:assert/strict');
|
|
5
|
+
const { createMockServer, chatResponse } = require('./helpers/mock-server');
|
|
6
|
+
const { estimateTokens, fitLength, fitPrompt, splitByTokens } = require('../lib/token-estimate');
|
|
7
|
+
const { generateSummary, embeddingsQuery, riskAnalysis } = require('..');
|
|
8
|
+
|
|
9
|
+
// 64 KB of CJK text with no whitespace or punctuation, the input that made the old tokenizer
|
|
10
|
+
// loop take 24 s per encode
|
|
11
|
+
const cjk = size => '\u6f22\u5b57\u4eee\u540d\u4e2d\u6587\u65e5\u672c\u8a9e\u6587\u5b57'.repeat(Math.ceil(size / 11)).substring(0, size);
|
|
12
|
+
|
|
13
|
+
function timeIt(fn, reps) {
|
|
14
|
+
const start = process.hrtime.bigint();
|
|
15
|
+
for (let i = 0; i < reps; i++) {
|
|
16
|
+
fn();
|
|
17
|
+
}
|
|
18
|
+
return Number(process.hrtime.bigint() - start) / 1e6;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
describe('token estimate', () => {
|
|
22
|
+
it('counts ASCII at 3 characters per token plus the margin', () => {
|
|
23
|
+
assert.equal(estimateTokens('a'.repeat(300)), 110);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it('counts every non-ASCII character as a token', () => {
|
|
27
|
+
assert.equal(estimateTokens(cjk(100)), 110);
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it('counts characters that JSON escaping doubles as two', () => {
|
|
31
|
+
assert.equal(estimateTokens('\n'.repeat(300)), 220);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it('fitLength returns a prefix whose estimate fits', () => {
|
|
35
|
+
const text = 'Hello world. ' + cjk(5000) + ' done';
|
|
36
|
+
const len = fitLength(text, 1000);
|
|
37
|
+
assert.ok(len > 0 && len < text.length);
|
|
38
|
+
assert.ok(estimateTokens(text.substring(0, len)) <= 1000);
|
|
39
|
+
assert.ok(estimateTokens(text.substring(0, len + 1)) > 1000);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('fitLength never cuts a surrogate pair in half', () => {
|
|
43
|
+
const text = '\u{1F600}'.repeat(100);
|
|
44
|
+
for (let tokens = 1; tokens < 50; tokens++) {
|
|
45
|
+
const len = fitLength(text, tokens);
|
|
46
|
+
assert.equal(len % 2, 0);
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it('splitByTokens keeps characters whole and loses nothing', () => {
|
|
51
|
+
const text = cjk(3000) + ' ' + 'word '.repeat(2000) + '\u{1F600}'.repeat(500);
|
|
52
|
+
const chunks = splitByTokens(text, 100);
|
|
53
|
+
assert.ok(chunks.length > 1);
|
|
54
|
+
assert.equal(chunks.join(''), text);
|
|
55
|
+
for (const chunk of chunks) {
|
|
56
|
+
assert.ok(!chunk.includes('\ufffd'));
|
|
57
|
+
assert.ok(!/^[\udc00-\udfff]/.test(chunk), 'chunk starts with a low surrogate');
|
|
58
|
+
assert.ok(!/[\ud800-\udbff]$/.test(chunk), 'chunk ends with a high surrogate');
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it('splitByTokens breaks ASCII text at whitespace', () => {
|
|
63
|
+
const chunks = splitByTokens('word '.repeat(2000), 100);
|
|
64
|
+
for (const chunk of chunks.slice(0, -1)) {
|
|
65
|
+
assert.ok(/ $/.test(chunk), JSON.stringify(chunk.slice(-10)));
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it('fits a 64 KB CJK body in well under 100 ms', () => {
|
|
70
|
+
const text = cjk(64 * 1024);
|
|
71
|
+
const ms = timeIt(() => fitLength(text, 18000), 1);
|
|
72
|
+
assert.ok(ms < 100, `took ${ms} ms`);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('scales linearly with the input size', () => {
|
|
76
|
+
const small = cjk(256 * 1024);
|
|
77
|
+
const large = cjk(512 * 1024);
|
|
78
|
+
// warm up
|
|
79
|
+
timeIt(() => estimateTokens(small) + fitLength(small, 1e9), 3);
|
|
80
|
+
const t1 = timeIt(() => estimateTokens(small) + fitLength(small, 1e9), 10);
|
|
81
|
+
const t2 = timeIt(() => estimateTokens(large) + fitLength(large, 1e9), 10);
|
|
82
|
+
assert.ok(t2 < t1 * 3 + 20, `256K: ${t1} ms, 512K: ${t2} ms`);
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
describe('prompt fitting', () => {
|
|
87
|
+
let mock;
|
|
88
|
+
|
|
89
|
+
before(async () => {
|
|
90
|
+
mock = await createMockServer();
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
after(async () => {
|
|
94
|
+
await mock.close();
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
beforeEach(() => {
|
|
98
|
+
mock.clearRequests();
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it('fitPrompt cuts only the text and reports what it removed', () => {
|
|
102
|
+
const build = text => `Prefix\n${text}`;
|
|
103
|
+
const result = fitPrompt({ text: 'word '.repeat(1000), maxTokens: 100, build });
|
|
104
|
+
|
|
105
|
+
assert.ok(estimateTokens(result.prompt) <= 100);
|
|
106
|
+
assert.equal(result.prompt, build(result.text));
|
|
107
|
+
assert.ok('word '.repeat(1000).startsWith(result.text));
|
|
108
|
+
assert.equal(result.charactersRemoved, 5000 - result.text.length);
|
|
109
|
+
assert.ok(result.charactersRemoved > 0);
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
it('fitPrompt applies the length cap without splitting a surrogate pair', () => {
|
|
113
|
+
const text = 'a'.repeat(9) + '\ud83d\ude00' + 'b'.repeat(10);
|
|
114
|
+
const result = fitPrompt({ text, maxLength: 10, maxTokens: 1000, build: t => t });
|
|
115
|
+
|
|
116
|
+
assert.equal(result.text, 'a'.repeat(9));
|
|
117
|
+
assert.equal(result.charactersRemoved, text.length - 9);
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
it('fitPrompt throws PROMPT_TOO_LONG when the prompt without text does not fit', () => {
|
|
121
|
+
assert.throws(
|
|
122
|
+
() => fitPrompt({ text: 'hello', maxTokens: 5, build: t => `${'x'.repeat(100)}${t}` }),
|
|
123
|
+
err => {
|
|
124
|
+
assert.equal(err.code, 'PROMPT_TOO_LONG');
|
|
125
|
+
assert.equal(err.originalLength, 5);
|
|
126
|
+
assert.equal(err.charactersRemoved, 5);
|
|
127
|
+
return true;
|
|
128
|
+
}
|
|
129
|
+
);
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
it('generateSummary prepares a 64 KB CJK body in one step and fits the limit', { timeout: 5000 }, async () => {
|
|
133
|
+
mock.setHandler(() => chatResponse({ sentiment: 'neutral', summary: 'ok', shouldReply: false, riskAssessment: { risk: 1 } }));
|
|
134
|
+
|
|
135
|
+
const text = cjk(64 * 1024);
|
|
136
|
+
// the old loop took minutes here, the test timeout is the regression catch
|
|
137
|
+
const result = await generateSummary({ headers: [], text }, 'token', { baseApiUrl: mock.url, maxTokens: 18000, verbose: false });
|
|
138
|
+
assert.equal(result.summary, 'ok');
|
|
139
|
+
|
|
140
|
+
const prompt = mock.requests[0].body.messages[1].content;
|
|
141
|
+
assert.ok(estimateTokens(prompt) <= 18000, `estimate ${estimateTokens(prompt)}`);
|
|
142
|
+
const sentText = JSON.parse(prompt.substring(prompt.lastIndexOf('\n{"headers"') + 1)).text;
|
|
143
|
+
assert.ok(sentText.length > 10000 && sentText.length < text.length);
|
|
144
|
+
assert.ok(text.startsWith(sentText));
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
it('generateSummary keeps short text intact', async () => {
|
|
148
|
+
mock.setHandler(() => chatResponse({ sentiment: 'neutral', summary: 'ok', shouldReply: false, riskAssessment: { risk: 1 } }));
|
|
149
|
+
|
|
150
|
+
const result = await generateSummary({ headers: [], text: 'Short message' }, 'token', { baseApiUrl: mock.url, verbose: true });
|
|
151
|
+
assert.equal(result._cr, 0);
|
|
152
|
+
assert.equal(result._text, 'Short message');
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
it('generateSummary throws PROMPT_TOO_LONG when the prompt alone exceeds the limit', async () => {
|
|
156
|
+
await assert.rejects(() => generateSummary({ headers: [], text: 'hello' }, 'token', { baseApiUrl: mock.url, maxTokens: 50 }), {
|
|
157
|
+
code: 'PROMPT_TOO_LONG'
|
|
158
|
+
});
|
|
159
|
+
assert.equal(mock.requests.length, 0);
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
it('embeddingsQuery fits a 64 KB CJK context in one step', { timeout: 5000 }, async () => {
|
|
163
|
+
mock.setHandler(() => chatResponse('Answer: yes\nMessage-ID: <id1>'));
|
|
164
|
+
|
|
165
|
+
await embeddingsQuery('token', { baseApiUrl: mock.url, question: 'What?', contextChunks: cjk(64 * 1024), maxTokens: 18000 });
|
|
166
|
+
|
|
167
|
+
const prompt = mock.requests[0].body.messages[1].content;
|
|
168
|
+
assert.ok(estimateTokens(prompt) <= 18000);
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
it('riskAnalysis fits a 64 KB CJK body in one step', { timeout: 5000 }, async () => {
|
|
172
|
+
mock.setHandler(() => chatResponse({ risk: 1, assessment: 'fine' }));
|
|
173
|
+
|
|
174
|
+
const result = await riskAnalysis({ headers: [], text: cjk(64 * 1024) }, 'token', { baseApiUrl: mock.url, maxTokens: 18000 });
|
|
175
|
+
assert.ok(result._cr > 0);
|
|
176
|
+
assert.ok(estimateTokens(mock.requests[0].body.messages[1].content) <= 18000);
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
it('riskAnalysis and embeddingsQuery throw the same PROMPT_TOO_LONG error', async () => {
|
|
180
|
+
await assert.rejects(() => riskAnalysis({ headers: [], text: 'hello' }, 'token', { baseApiUrl: mock.url, maxTokens: 50 }), {
|
|
181
|
+
code: 'PROMPT_TOO_LONG'
|
|
182
|
+
});
|
|
183
|
+
await assert.rejects(() => embeddingsQuery('token', { baseApiUrl: mock.url, question: 'What?', contextChunks: 'hello', maxTokens: 50 }), {
|
|
184
|
+
code: 'PROMPT_TOO_LONG'
|
|
185
|
+
});
|
|
186
|
+
assert.equal(mock.requests.length, 0);
|
|
187
|
+
});
|
|
188
|
+
});
|