@newses/plugin-digest-summary 0.2.0 → 0.3.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.
- package/README.md +195 -30
- package/dist/digest.d.ts +64 -15
- package/dist/digest.js +254 -81
- package/dist/index.d.ts +22 -3
- package/dist/index.js +54 -25
- package/dist/prices.d.ts +8 -2
- package/dist/prices.js +12 -4
- package/dist/prompts.d.ts +23 -3
- package/dist/prompts.js +58 -20
- package/dist/providers/anthropic.d.ts +47 -0
- package/dist/providers/anthropic.js +126 -0
- package/dist/providers/bedrock.d.ts +25 -0
- package/dist/providers/bedrock.js +112 -0
- package/dist/providers/http.d.ts +24 -0
- package/dist/providers/http.js +77 -0
- package/dist/providers/index.d.ts +5 -0
- package/dist/providers/index.js +14 -0
- package/dist/providers/ollama.d.ts +9 -0
- package/dist/providers/ollama.js +137 -0
- package/dist/providers/openai.d.ts +9 -0
- package/dist/providers/openai.js +116 -0
- package/dist/providers/types.d.ts +65 -0
- package/dist/providers/types.js +1 -0
- package/dist/settings.d.ts +70 -3
- package/dist/settings.js +130 -7
- package/dist/tokens.d.ts +2 -0
- package/dist/tokens.js +2 -0
- package/package.json +10 -5
- package/dist/claude.d.ts +0 -19
- package/dist/claude.js +0 -49
package/dist/digest.js
CHANGED
|
@@ -1,32 +1,53 @@
|
|
|
1
|
-
import Anthropic from '@anthropic-ai/sdk';
|
|
2
1
|
import { DIGEST_LIMITS, } from '@newses/plugin-api';
|
|
3
|
-
import {
|
|
4
|
-
import { MERGE_SYSTEM, mergePrompt, OVERVIEW_SYSTEM, overviewPrompt, PART_SYSTEM, partFormat, partPrompt, preferencesText, readPart, readSections, sectionsFormat, sectionsOf, } from './prompts.js';
|
|
5
|
-
import { costOf, dollars, tokensIn } from './prices.js';
|
|
2
|
+
import { PART_TOKENS } from './providers/anthropic.js';
|
|
3
|
+
import { MERGE_SYSTEM, mergePrompt, OVERVIEW_SYSTEM, overviewPrompt, PART_SYSTEM, partFormat, partPrompt, partThemes, preferencesText, readPart, readSections, sectionsFormat, sectionsOf, } from './prompts.js';
|
|
4
|
+
import { costOf, dollars, premiumOf, tokensIn } from './prices.js';
|
|
6
5
|
import { DEFAULT_SECTIONS, INSTRUCTIONS_LENGTH, } from './settings.js';
|
|
7
|
-
import {
|
|
8
|
-
|
|
9
|
-
export
|
|
10
|
-
/** Parts read
|
|
6
|
+
import { estimateTokens } from './tokens.js';
|
|
7
|
+
import { count, remaining } from './usage.js';
|
|
8
|
+
export { estimateTokens, PART_TOKENS };
|
|
9
|
+
/** Parts a digest is read in, at most; a larger one has larger parts, or reads the newest. */
|
|
11
10
|
export const MAX_PARTS = 6;
|
|
12
11
|
/** Of the time left, the share the parts may take, leaving the rest to the merge. */
|
|
13
12
|
const PARTS_SHARE = 0.6;
|
|
14
|
-
/** A request's `max_tokens`, thinking included. */
|
|
15
|
-
const MAX_TOKENS = 16_000;
|
|
16
13
|
/**
|
|
17
|
-
* Output tokens
|
|
14
|
+
* Output tokens Claude is expected to use, thinking included, for the budget check: a part's,
|
|
18
15
|
* and the overview's by length.
|
|
19
16
|
*/
|
|
20
17
|
const PART_OUTPUT_ESTIMATE = 3_000;
|
|
21
18
|
export const OUTPUT_ESTIMATE = { brief: 3_000, standard: 5_000, detailed: 8_000 };
|
|
19
|
+
/**
|
|
20
|
+
* Output tokens a self-hosted model may write, without thinking: a part's, and the overview's
|
|
21
|
+
* by length; thinking adds `THINKING_TOKENS` to the overview's, as parts never think. They are its `num_predict`/`max_tokens`,
|
|
22
|
+
* and are kept free of its context.
|
|
23
|
+
*/
|
|
24
|
+
const LOCAL_PART_OUTPUT = 3_000;
|
|
25
|
+
export const LOCAL_OUTPUT = { brief: 2_000, standard: 4_000, detailed: 7_000 };
|
|
26
|
+
const THINKING_TOKENS = 4_000;
|
|
27
|
+
/** Of a self-hosted model's context, the share planned for, as token counts are estimated. */
|
|
28
|
+
const CONTEXT_SHARE = 0.85;
|
|
22
29
|
/** Input tokens the parts' themes are expected to take in the request that merges them. */
|
|
23
30
|
const THEMES_ESTIMATE = 800;
|
|
31
|
+
/**
|
|
32
|
+
* Output tokens the requests are given (and expected to use): a part's, and the overview's; a
|
|
33
|
+
* self-hosted model's at most half its context, leaving the rest to the prompt.
|
|
34
|
+
*/
|
|
35
|
+
export function outputTokens(capacity, length) {
|
|
36
|
+
if (capacity.kind === 'grow')
|
|
37
|
+
return { part: PART_OUTPUT_ESTIMATE, overview: OUTPUT_ESTIMATE[length] };
|
|
38
|
+
const thinking = capacity.thinking ? THINKING_TOKENS : 0;
|
|
39
|
+
const half = Math.floor(capacity.contextTokens / 2);
|
|
40
|
+
return {
|
|
41
|
+
part: Math.min(half, LOCAL_PART_OUTPUT),
|
|
42
|
+
overview: Math.min(half, LOCAL_OUTPUT[length] + thinking),
|
|
43
|
+
};
|
|
44
|
+
}
|
|
24
45
|
/**
|
|
25
46
|
* The requests reading articles of `whole` tokens are expected to take: one, or parts and a
|
|
26
47
|
* merge; `preferences` is the tokens of the reader's preferences each request carries.
|
|
27
48
|
*/
|
|
28
49
|
export function plannedRequests(partTokens, whole, options) {
|
|
29
|
-
const request = (input, output =
|
|
50
|
+
const request = (input, output = options.output.overview) => ({
|
|
30
51
|
input: input + options.preferences,
|
|
31
52
|
cacheWrite: 0,
|
|
32
53
|
cacheRead: 0,
|
|
@@ -35,7 +56,7 @@ export function plannedRequests(partTokens, whole, options) {
|
|
|
35
56
|
if (!partTokens)
|
|
36
57
|
return [request(whole)];
|
|
37
58
|
return [
|
|
38
|
-
...partTokens.map((tokens) => request(estimateTokens(PART_SYSTEM) + tokens,
|
|
59
|
+
...partTokens.map((tokens) => request(estimateTokens(PART_SYSTEM) + tokens, options.output.part)),
|
|
39
60
|
request(estimateTokens(MERGE_SYSTEM) + THEMES_ESTIMATE * partTokens.length),
|
|
40
61
|
];
|
|
41
62
|
}
|
|
@@ -76,14 +97,22 @@ export function byFeed(entries) {
|
|
|
76
97
|
}
|
|
77
98
|
return { feeds: [...feeds.values()], ids };
|
|
78
99
|
}
|
|
79
|
-
/** Tokens a text is about, rounded up: some 3 characters each. */
|
|
80
|
-
export const estimateTokens = (text) => Math.ceil(text.length / 3);
|
|
81
100
|
const articleTokens = (article) => estimateTokens(`<article ref="${article.ref}"><title>${article.title}</title><start>${article.excerpt ?? ''}</start>`);
|
|
101
|
+
/** Of the share a part aims at, how far over it a feed may go to stay whole in the part. */
|
|
102
|
+
const PART_STRETCH = 1.1;
|
|
82
103
|
/**
|
|
83
|
-
* Feeds packed into parts of
|
|
84
|
-
*
|
|
104
|
+
* Feeds packed, in order, into as few parts of at most `limit` tokens as they take, each part
|
|
105
|
+
* about the same size: the articles' tokens shared evenly between them. A feed joins a part whole
|
|
106
|
+
* when that keeps it within `PART_STRETCH` of its share; otherwise its articles fill the part to
|
|
107
|
+
* its share and go on in the next. Every part but the last reaches its share, so there are never
|
|
108
|
+
* more parts than the fewest the articles take.
|
|
85
109
|
*/
|
|
86
110
|
export function partsOf(feeds, limit) {
|
|
111
|
+
const tokensOf = (articles) => articles.reduce((sum, article) => sum + articleTokens(article), 0);
|
|
112
|
+
const total = feeds.reduce((sum, feed) => sum + tokensOf(feed.articles), 0);
|
|
113
|
+
const count = Math.max(1, Math.ceil(total / limit));
|
|
114
|
+
const share = Math.ceil(total / count);
|
|
115
|
+
const stretch = Math.min(limit, Math.floor(share * PART_STRETCH));
|
|
87
116
|
const parts = [];
|
|
88
117
|
let part = [];
|
|
89
118
|
let size = 0;
|
|
@@ -94,12 +123,18 @@ export function partsOf(feeds, limit) {
|
|
|
94
123
|
size = 0;
|
|
95
124
|
};
|
|
96
125
|
for (const feed of feeds) {
|
|
97
|
-
const tokens = feed.articles
|
|
98
|
-
if (size
|
|
99
|
-
|
|
126
|
+
const tokens = tokensOf(feed.articles);
|
|
127
|
+
if (size + tokens <= stretch) {
|
|
128
|
+
part.push(feed);
|
|
129
|
+
size += tokens;
|
|
130
|
+
if (size >= share)
|
|
131
|
+
close();
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
100
134
|
let piece = { feed: feed.feed, articles: [] };
|
|
101
135
|
for (const article of feed.articles) {
|
|
102
136
|
const cost = articleTokens(article);
|
|
137
|
+
// One article larger than a part's room still goes in a part of its own.
|
|
103
138
|
if (size > 0 && size + cost > limit) {
|
|
104
139
|
if (piece.articles.length > 0)
|
|
105
140
|
part.push(piece);
|
|
@@ -108,6 +143,11 @@ export function partsOf(feeds, limit) {
|
|
|
108
143
|
}
|
|
109
144
|
piece.articles.push(article);
|
|
110
145
|
size += cost;
|
|
146
|
+
if (size >= share) {
|
|
147
|
+
part.push(piece);
|
|
148
|
+
close();
|
|
149
|
+
piece = { feed: feed.feed, articles: [] };
|
|
150
|
+
}
|
|
111
151
|
}
|
|
112
152
|
if (piece.articles.length > 0)
|
|
113
153
|
part.push(piece);
|
|
@@ -138,26 +178,106 @@ export function preferencesOf(settings, userSettings) {
|
|
|
138
178
|
};
|
|
139
179
|
}
|
|
140
180
|
/**
|
|
141
|
-
*
|
|
142
|
-
*
|
|
143
|
-
*
|
|
181
|
+
* Article tokens one request to a self-hosted model may carry: its context, less the output it
|
|
182
|
+
* may write, the longer system prompt, and the reader's preferences, of which `CONTEXT_SHARE`;
|
|
183
|
+
* at least one article's worth.
|
|
184
|
+
*/
|
|
185
|
+
export function contextLimit(capacity, output, preferences) {
|
|
186
|
+
const prompt = Math.max(estimateTokens(OVERVIEW_SYSTEM), estimateTokens(PART_SYSTEM));
|
|
187
|
+
const room = Math.floor((capacity.contextTokens - Math.max(output.part, output.overview)) * CONTEXT_SHARE) -
|
|
188
|
+
prompt -
|
|
189
|
+
estimateTokens(preferences) -
|
|
190
|
+
// The user turn's lines before the articles.
|
|
191
|
+
100;
|
|
192
|
+
return Math.max(room, 200);
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Parts a self-hosted model may read a digest in: at most `MAX_PARTS`, and no more than the
|
|
196
|
+
* request merging their themes holds in its context; one when it holds none.
|
|
197
|
+
*/
|
|
198
|
+
export function contextParts(capacity, output, preferences) {
|
|
199
|
+
const room = Math.floor((capacity.contextTokens - output.overview) * CONTEXT_SHARE) -
|
|
200
|
+
estimateTokens(MERGE_SYSTEM) -
|
|
201
|
+
estimateTokens(preferences) -
|
|
202
|
+
100;
|
|
203
|
+
return Math.max(1, Math.min(MAX_PARTS, Math.floor(room / THEMES_ESTIMATE)));
|
|
204
|
+
}
|
|
205
|
+
/** The newest entries whose articles take at most `limit` tokens, in their order; one at least. */
|
|
206
|
+
function newestWithin(entries, limit) {
|
|
207
|
+
let size = 0;
|
|
208
|
+
const kept = [];
|
|
209
|
+
for (const entry of entries) {
|
|
210
|
+
size += articleTokens({ ref: `a${String(kept.length + 1)}`, ...entry });
|
|
211
|
+
if (kept.length > 0 && size > limit)
|
|
212
|
+
break;
|
|
213
|
+
kept.push(entry);
|
|
214
|
+
}
|
|
215
|
+
return kept;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* How a digest's overview would be read: the user's chosen entries of those listed and unlisted
|
|
219
|
+
* (a self-hosted model's, the newest its parts hold), by feed with their refs, the reader's
|
|
220
|
+
* preferences, in one request or in parts, the requests' output tokens and expected tokens;
|
|
221
|
+
* null with none chosen. `total` is every unread article the digest counts.
|
|
144
222
|
*/
|
|
145
|
-
export function planOf(input, settings, userSettings) {
|
|
146
|
-
const
|
|
147
|
-
if (
|
|
223
|
+
export function planOf(input, settings, userSettings, capacity = { kind: 'grow', partTokens: PART_TOKENS }) {
|
|
224
|
+
const chosenEntries = chosen([...input.entries, ...input.unlisted], userSettings);
|
|
225
|
+
if (chosenEntries.length === 0)
|
|
148
226
|
return null;
|
|
149
|
-
const { feeds, ids } = byFeed(entries);
|
|
150
227
|
const preferences = preferencesOf(settings, userSettings);
|
|
151
|
-
const total =
|
|
228
|
+
const total = chosenEntries.length + Math.max(0, input.more - input.unlisted.length);
|
|
229
|
+
const output = outputTokens(capacity, userSettings.length);
|
|
230
|
+
let entries = chosenEntries;
|
|
231
|
+
let parts;
|
|
232
|
+
let byRef;
|
|
233
|
+
let maxParts = MAX_PARTS;
|
|
234
|
+
if (capacity.kind === 'grow') {
|
|
235
|
+
byRef = byFeed(entries);
|
|
236
|
+
const whole = estimateTokens(OVERVIEW_SYSTEM) + articlesTokens(byRef.feeds);
|
|
237
|
+
parts =
|
|
238
|
+
whole <= capacity.partTokens
|
|
239
|
+
? null
|
|
240
|
+
: partsOf(byRef.feeds, Math.max(capacity.partTokens, Math.ceil(whole / MAX_PARTS)));
|
|
241
|
+
}
|
|
242
|
+
else {
|
|
243
|
+
const limit = contextLimit(capacity, output, preferences.overview);
|
|
244
|
+
maxParts = contextParts(capacity, output, preferences.overview);
|
|
245
|
+
// Feeds packed into parts leave some room unused, so a little more than the parts hold is
|
|
246
|
+
// taken, and what does not fit in `maxParts` is left out.
|
|
247
|
+
entries = newestWithin(chosenEntries, Math.floor(limit * maxParts * 0.95));
|
|
248
|
+
byRef = byFeed(entries);
|
|
249
|
+
parts = articlesTokens(byRef.feeds) <= limit ? null : partsOf(byRef.feeds, limit);
|
|
250
|
+
// One part is one request: what it holds is all that is read.
|
|
251
|
+
if (maxParts === 1)
|
|
252
|
+
parts = null;
|
|
253
|
+
if (parts && parts.length > maxParts) {
|
|
254
|
+
parts = parts.slice(0, maxParts);
|
|
255
|
+
const read = new Set(parts.flat().flatMap((feed) => feed.articles.map((a) => a.ref)));
|
|
256
|
+
entries = entries.filter((_, index) => read.has(`a${String(index + 1)}`));
|
|
257
|
+
byRef = {
|
|
258
|
+
feeds: byRef.feeds,
|
|
259
|
+
ids: new Map([...byRef.ids].filter(([ref]) => read.has(ref))),
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
const { feeds, ids } = byRef;
|
|
152
264
|
const whole = estimateTokens(OVERVIEW_SYSTEM) + articlesTokens(feeds);
|
|
153
|
-
const parts = whole <= PART_TOKENS
|
|
154
|
-
? null
|
|
155
|
-
: partsOf(feeds, Math.max(PART_TOKENS, Math.ceil(whole / MAX_PARTS)));
|
|
156
265
|
const planned = plannedRequests(parts?.map(articlesTokens) ?? null, whole, {
|
|
157
266
|
preferences: estimateTokens(preferences.overview),
|
|
158
|
-
|
|
267
|
+
output,
|
|
159
268
|
});
|
|
160
|
-
return {
|
|
269
|
+
return {
|
|
270
|
+
entries,
|
|
271
|
+
chosen: chosenEntries.length,
|
|
272
|
+
feeds,
|
|
273
|
+
ids,
|
|
274
|
+
preferences,
|
|
275
|
+
total,
|
|
276
|
+
parts,
|
|
277
|
+
maxParts,
|
|
278
|
+
planned,
|
|
279
|
+
output,
|
|
280
|
+
};
|
|
161
281
|
}
|
|
162
282
|
/** The overview as the digest takes it: the lead as its overview, then its sections. */
|
|
163
283
|
export function additionsOf(overview, userSettings) {
|
|
@@ -170,13 +290,43 @@ export function additionsOf(overview, userSettings) {
|
|
|
170
290
|
})),
|
|
171
291
|
};
|
|
172
292
|
}
|
|
293
|
+
/** Where the speed a self-hosted model last read and wrote at is kept, in the instance's store. */
|
|
294
|
+
const SPEED_KEY = 'speed';
|
|
295
|
+
async function speedOf(storage) {
|
|
296
|
+
const value = (await storage.get(SPEED_KEY));
|
|
297
|
+
return typeof value?.prompt === 'number' && typeof value.output === 'number'
|
|
298
|
+
? { prompt: value.prompt, output: value.output }
|
|
299
|
+
: null;
|
|
300
|
+
}
|
|
301
|
+
/** Keeps the speed of an answer that read and wrote enough to measure it. */
|
|
302
|
+
async function keepSpeed(storage, timing) {
|
|
303
|
+
if (timing.promptMs <= 0 || timing.outputMs <= 0 || timing.outputTokens < 50)
|
|
304
|
+
return;
|
|
305
|
+
await storage.set(SPEED_KEY, {
|
|
306
|
+
prompt: (timing.promptTokens * 1000) / timing.promptMs,
|
|
307
|
+
output: (timing.outputTokens * 1000) / timing.outputMs,
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* Seconds the planned requests would take at a speed, at most: the parts `parallel` at a time,
|
|
312
|
+
* then the overview, each writing all the output it may.
|
|
313
|
+
*/
|
|
314
|
+
function secondsAt(speed, planned, parallel) {
|
|
315
|
+
const seconds = planned.map((r) => r.input / speed.prompt + r.output / speed.output);
|
|
316
|
+
if (seconds.length === 1)
|
|
317
|
+
return seconds[0] ?? 0;
|
|
318
|
+
const parts = seconds.slice(0, -1);
|
|
319
|
+
return (parts.reduce((sum, s) => sum + s, 0) / Math.min(parallel, parts.length) + (seconds.at(-1) ?? 0));
|
|
320
|
+
}
|
|
173
321
|
/**
|
|
174
322
|
* What the overview of a digest is expected to cost, making no request, as plain text: how it
|
|
175
|
-
* would be read, its tokens, and US dollars at list prices, or why it would add nothing.
|
|
323
|
+
* would be read, its tokens, and US dollars at list prices, or why it would add nothing. A
|
|
324
|
+
* self-hosted model's has no price, but how many articles its context holds, and how long it
|
|
325
|
+
* would take at the speed it last answered at.
|
|
176
326
|
*/
|
|
177
327
|
export async function estimate(options) {
|
|
178
|
-
const { settings } = options;
|
|
179
|
-
const plan = planOf(options.input, settings, options.userSettings);
|
|
328
|
+
const { settings, provider } = options;
|
|
329
|
+
const plan = planOf(options.input, settings, options.userSettings, provider.capacity);
|
|
180
330
|
if (!plan)
|
|
181
331
|
return "None of the test digest's articles are from feeds it reads, so it would add nothing.";
|
|
182
332
|
const tokens = tokensIn(plan.planned);
|
|
@@ -187,7 +337,22 @@ export async function estimate(options) {
|
|
|
187
337
|
const requests = `${String(plan.planned.length)} ${plan.planned.length === 1 ? 'request' : 'requests'}`;
|
|
188
338
|
if (left < tokens)
|
|
189
339
|
return `A test digest now: ${articles}, about ${formatted(tokens)} tokens, more than the ${formatted(left)} left of this month's budget, so it would add nothing.`;
|
|
190
|
-
|
|
340
|
+
const { capacity } = provider;
|
|
341
|
+
if (capacity.kind === 'grow')
|
|
342
|
+
return `A test digest now: ${articles} in ${requests} to ${provider.label}, about ${formatted(tokens)} tokens, ${dollars(costOf(settings.model, plan.planned, premiumOf(settings)))}. The output is estimated.`;
|
|
343
|
+
const held = count < plan.chosen
|
|
344
|
+
? `: the newest ${formatted(count)} of ${formatted(plan.chosen)}, as many as ${formatted(capacity.contextTokens)} tokens of context hold in ${String(plan.maxParts)} ${plan.maxParts === 1 ? 'request' : 'parts'}`
|
|
345
|
+
: '';
|
|
346
|
+
const speed = await speedOf(options.storage);
|
|
347
|
+
const minutes = speed
|
|
348
|
+
? Math.max(1, Math.round(secondsAt(speed, plan.planned, provider.parallel) / 60))
|
|
349
|
+
: null;
|
|
350
|
+
const time = minutes === null
|
|
351
|
+
? ''
|
|
352
|
+
: ` At the speed it last answered at, it would take up to about ${String(minutes)} ${minutes === 1 ? 'minute' : 'minutes'}${minutes * 60 > DIGEST_LIMITS.timeoutSeconds
|
|
353
|
+
? `, longer than the ${String(DIGEST_LIMITS.timeoutSeconds / 60)} minutes a digest waits, so parts would be left out`
|
|
354
|
+
: ''}.`;
|
|
355
|
+
return `A test digest now: ${articles} in ${requests} to ${provider.label}, about ${formatted(tokens)} tokens${held}. It runs on your own server, at no charge per token.${time}`;
|
|
191
356
|
}
|
|
192
357
|
const nothing = (outcome) => ({ overview: null, sections: null, outcome });
|
|
193
358
|
/**
|
|
@@ -197,11 +362,11 @@ const nothing = (outcome) => ({ overview: null, sections: null, outcome });
|
|
|
197
362
|
* unreadable, out of time), the digest goes out without it.
|
|
198
363
|
*/
|
|
199
364
|
export async function compose(options) {
|
|
200
|
-
const {
|
|
201
|
-
const plan = planOf(input, settings, userSettings);
|
|
365
|
+
const { provider, settings, userSettings, input, storage, userStorage, logger, signal } = options;
|
|
366
|
+
const plan = planOf(input, settings, userSettings, provider.capacity);
|
|
202
367
|
if (!plan)
|
|
203
368
|
return nothing('none');
|
|
204
|
-
const { entries, feeds, ids, preferences, total, parts, planned } = plan;
|
|
369
|
+
const { entries, feeds, ids, preferences, total, parts, planned, output } = plan;
|
|
205
370
|
const { names } = preferences;
|
|
206
371
|
const budgets = { instance: settings.monthlyTokens, user: settings.userMonthlyTokens };
|
|
207
372
|
if ((await remaining(budgets, { instance: storage, user: userStorage }, options.now())) <
|
|
@@ -217,51 +382,41 @@ export async function compose(options) {
|
|
|
217
382
|
});
|
|
218
383
|
return counting;
|
|
219
384
|
};
|
|
220
|
-
const ask = async (system, prompt, format, by) => {
|
|
221
|
-
let response;
|
|
385
|
+
const ask = async (system, prompt, format, maxTokens, by, thinking) => {
|
|
222
386
|
// Whole milliseconds: AbortSignal.timeout refuses fractions.
|
|
223
387
|
const left = Math.max(1, Math.floor(by - Date.now()));
|
|
224
388
|
const ownTime = AbortSignal.timeout(left);
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
timeout: left,
|
|
241
|
-
maxRetries: 0,
|
|
242
|
-
});
|
|
243
|
-
}
|
|
244
|
-
catch (error) {
|
|
245
|
-
// Out of its own time, rather than the digest's (which ends the digest too).
|
|
246
|
-
const timedOut = !signal.aborted &&
|
|
247
|
-
(ownTime.aborted || error instanceof Anthropic.APIConnectionTimeoutError);
|
|
248
|
-
logger.warn(timedOut ? 'digest request ran out of time' : 'digest request failed', {
|
|
249
|
-
error: String(error),
|
|
250
|
-
});
|
|
251
|
-
return { ok: false, outcome: timedOut ? 'timed out' : 'failed' };
|
|
389
|
+
const asked = await provider.ask({
|
|
390
|
+
system,
|
|
391
|
+
prompt,
|
|
392
|
+
format,
|
|
393
|
+
maxTokens,
|
|
394
|
+
thinking,
|
|
395
|
+
signal: AbortSignal.any([signal, ownTime]),
|
|
396
|
+
timeoutMs: left,
|
|
397
|
+
});
|
|
398
|
+
if (asked.tokens > 0)
|
|
399
|
+
await counted(asked.tokens);
|
|
400
|
+
if (asked.ok) {
|
|
401
|
+
if (asked.timing)
|
|
402
|
+
await keepSpeed(storage, asked.timing);
|
|
403
|
+
return { ok: true, text: asked.text };
|
|
252
404
|
}
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
405
|
+
if (asked.outcome !== 'failed' && asked.outcome !== 'timed out')
|
|
406
|
+
return { ok: false, outcome: asked.outcome };
|
|
407
|
+
// Out of its own time, rather than the digest's (which ends the digest too).
|
|
408
|
+
const timedOut = !signal.aborted && (ownTime.aborted || asked.outcome === 'timed out');
|
|
409
|
+
logger.warn(timedOut ? 'digest request ran out of time' : 'digest request failed', {
|
|
410
|
+
provider: provider.name,
|
|
411
|
+
error: String(asked.error),
|
|
412
|
+
});
|
|
413
|
+
return { ok: false, outcome: timedOut ? 'timed out' : 'failed' };
|
|
259
414
|
};
|
|
260
415
|
const language = input.language;
|
|
261
416
|
const frequency = input.frequency;
|
|
262
417
|
const read = (text) => readSections(text, { names, length: userSettings.length, ids });
|
|
263
418
|
if (!parts) {
|
|
264
|
-
const asked = await ask([OVERVIEW_SYSTEM, preferences.overview], overviewPrompt({ language, frequency, total, feeds }), sectionsFormat(names), options.deadline);
|
|
419
|
+
const asked = await ask([OVERVIEW_SYSTEM, preferences.overview], overviewPrompt({ language, frequency, total, feeds }), sectionsFormat(names), output.overview, options.deadline, true);
|
|
265
420
|
if (!asked.ok)
|
|
266
421
|
return nothing(asked.outcome);
|
|
267
422
|
const overview = read(asked.text);
|
|
@@ -270,12 +425,17 @@ export async function compose(options) {
|
|
|
270
425
|
: nothing('invalid');
|
|
271
426
|
}
|
|
272
427
|
const partsBy = Date.now() + Math.floor((options.deadline - Date.now()) * PARTS_SHARE);
|
|
273
|
-
|
|
274
|
-
|
|
428
|
+
// A part not started by then runs out of time without a request.
|
|
429
|
+
const found = await pooled(parts, provider.parallel, async (part) => {
|
|
430
|
+
if (Date.now() >= partsBy)
|
|
431
|
+
return 'timed out';
|
|
432
|
+
const asked = await ask([PART_SYSTEM, preferences.parts], partPrompt({ language, feeds: part }), partFormat(names), output.part, partsBy,
|
|
433
|
+
// Sorting articles into themes needs no thinking; writing the overview may.
|
|
434
|
+
false);
|
|
275
435
|
if (!asked.ok)
|
|
276
436
|
return asked.outcome;
|
|
277
|
-
return readPart(asked.text, { names, ids }) ?? 'invalid';
|
|
278
|
-
})
|
|
437
|
+
return (readPart(asked.text, { names, ids, themes: partThemes(userSettings.length) }) ?? 'invalid');
|
|
438
|
+
});
|
|
279
439
|
// A part that failed or ran out of time leaves the overview to the parts that answered.
|
|
280
440
|
const answered = parts.filter((_, index) => typeof found[index] !== 'string');
|
|
281
441
|
if (answered.length === 0)
|
|
@@ -287,7 +447,7 @@ export async function compose(options) {
|
|
|
287
447
|
read: answered.length < parts.length ? articleCount(answered.flat()) : entries.length,
|
|
288
448
|
total,
|
|
289
449
|
parts: found.filter((part) => typeof part !== 'string'),
|
|
290
|
-
}), sectionsFormat(names), options.deadline);
|
|
450
|
+
}), sectionsFormat(names), output.overview, options.deadline, true);
|
|
291
451
|
if (!asked.ok)
|
|
292
452
|
return nothing(asked.outcome);
|
|
293
453
|
const overview = read(asked.text);
|
|
@@ -310,6 +470,19 @@ export async function compose(options) {
|
|
|
310
470
|
outcome: 'partial',
|
|
311
471
|
};
|
|
312
472
|
}
|
|
473
|
+
/** Each item run, at most `size` at once, the results in the items' order. */
|
|
474
|
+
async function pooled(items, size, run) {
|
|
475
|
+
const results = [];
|
|
476
|
+
let next = 0;
|
|
477
|
+
const worker = async () => {
|
|
478
|
+
while (next < items.length) {
|
|
479
|
+
const index = next++;
|
|
480
|
+
results[index] = await run(items[index]);
|
|
481
|
+
}
|
|
482
|
+
};
|
|
483
|
+
await Promise.all(Array.from({ length: Math.max(1, Math.min(size, items.length)) }, worker));
|
|
484
|
+
return results;
|
|
485
|
+
}
|
|
313
486
|
/** What an overview written from only some parts says of the rest. */
|
|
314
487
|
export function missingNote(counts) {
|
|
315
488
|
const n = (count) => new Intl.NumberFormat('en').format(count);
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Opens each user's email digest with an overview of what their unread articles are about, in
|
|
3
3
|
* topic sections whose points link the articles they draw on, written by Claude through the
|
|
4
|
-
* Anthropic API
|
|
5
|
-
*
|
|
4
|
+
* Anthropic API or Amazon Bedrock, or by a self-hosted model (Ollama, or a server with the OpenAI chat completions
|
|
5
|
+
* API) from the titles and excerpts of the unread articles the digest counts, of the feeds the
|
|
6
|
+
* user chooses, with the sections, length, style, and instructions the user chooses.
|
|
6
7
|
*/
|
|
7
8
|
declare const _default: import("@newses/plugin-api").PluginDefinition<import("zod").ZodObject<{
|
|
8
|
-
|
|
9
|
+
provider: import("zod").ZodDefault<import("zod").ZodEnum<{
|
|
10
|
+
anthropic: "anthropic";
|
|
11
|
+
bedrock: "bedrock";
|
|
12
|
+
ollama: "ollama";
|
|
13
|
+
openai: "openai";
|
|
14
|
+
}>>;
|
|
15
|
+
apiKey: import("zod").ZodOptional<import("zod").ZodString>;
|
|
9
16
|
model: import("zod").ZodDefault<import("zod").ZodEnum<{
|
|
10
17
|
"claude-opus-5-5": "claude-opus-5-5";
|
|
11
18
|
"claude-sonnet-5-5": "claude-sonnet-5-5";
|
|
@@ -16,6 +23,18 @@ declare const _default: import("@newses/plugin-api").PluginDefinition<import("zo
|
|
|
16
23
|
medium: "medium";
|
|
17
24
|
high: "high";
|
|
18
25
|
}>>;
|
|
26
|
+
bedrockApiKey: import("zod").ZodOptional<import("zod").ZodString>;
|
|
27
|
+
bedrockRegion: import("zod").ZodDefault<import("zod").ZodString>;
|
|
28
|
+
bedrockRouting: import("zod").ZodDefault<import("zod").ZodEnum<{
|
|
29
|
+
global: "global";
|
|
30
|
+
geography: "geography";
|
|
31
|
+
}>>;
|
|
32
|
+
baseUrl: import("zod").ZodOptional<import("zod").ZodURL>;
|
|
33
|
+
localApiKey: import("zod").ZodOptional<import("zod").ZodString>;
|
|
34
|
+
localModel: import("zod").ZodDefault<import("zod").ZodString>;
|
|
35
|
+
contextTokens: import("zod").ZodDefault<import("zod").ZodNumber>;
|
|
36
|
+
parallelRequests: import("zod").ZodDefault<import("zod").ZodNumber>;
|
|
37
|
+
thinking: import("zod").ZodDefault<import("zod").ZodBoolean>;
|
|
19
38
|
monthlyTokens: import("zod").ZodDefault<import("zod").ZodNumber>;
|
|
20
39
|
userMonthlyTokens: import("zod").ZodDefault<import("zod").ZodNumber>;
|
|
21
40
|
allowInstructions: import("zod").ZodDefault<import("zod").ZodBoolean>;
|