@newses/plugin-digest-summary 0.2.0 → 0.3.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.
- package/README.md +115 -30
- package/dist/digest.d.ts +64 -15
- package/dist/digest.js +253 -80
- package/dist/index.d.ts +15 -3
- package/dist/index.js +43 -24
- package/dist/prompts.d.ts +23 -3
- package/dist/prompts.js +58 -20
- package/dist/{claude.d.ts → providers/anthropic.d.ts} +9 -1
- package/dist/providers/anthropic.js +108 -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 +11 -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 +25 -3
- package/dist/settings.js +45 -7
- package/dist/tokens.d.ts +2 -0
- package/dist/tokens.js +2 -0
- package/package.json +8 -5
- 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';
|
|
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';
|
|
5
4
|
import { costOf, dollars, 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))}. 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,17 @@
|
|
|
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 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
|
+
ollama: "ollama";
|
|
12
|
+
openai: "openai";
|
|
13
|
+
}>>;
|
|
14
|
+
apiKey: import("zod").ZodOptional<import("zod").ZodString>;
|
|
9
15
|
model: import("zod").ZodDefault<import("zod").ZodEnum<{
|
|
10
16
|
"claude-opus-5-5": "claude-opus-5-5";
|
|
11
17
|
"claude-sonnet-5-5": "claude-sonnet-5-5";
|
|
@@ -16,6 +22,12 @@ declare const _default: import("@newses/plugin-api").PluginDefinition<import("zo
|
|
|
16
22
|
medium: "medium";
|
|
17
23
|
high: "high";
|
|
18
24
|
}>>;
|
|
25
|
+
baseUrl: import("zod").ZodOptional<import("zod").ZodURL>;
|
|
26
|
+
localApiKey: import("zod").ZodOptional<import("zod").ZodString>;
|
|
27
|
+
localModel: import("zod").ZodDefault<import("zod").ZodString>;
|
|
28
|
+
contextTokens: import("zod").ZodDefault<import("zod").ZodNumber>;
|
|
29
|
+
parallelRequests: import("zod").ZodDefault<import("zod").ZodNumber>;
|
|
30
|
+
thinking: import("zod").ZodDefault<import("zod").ZodBoolean>;
|
|
19
31
|
monthlyTokens: import("zod").ZodDefault<import("zod").ZodNumber>;
|
|
20
32
|
userMonthlyTokens: import("zod").ZodDefault<import("zod").ZodNumber>;
|
|
21
33
|
allowInstructions: import("zod").ZodDefault<import("zod").ZodBoolean>;
|
package/dist/index.js
CHANGED
|
@@ -1,43 +1,64 @@
|
|
|
1
1
|
import { definePlugin, DIGEST_LIMITS } from '@newses/plugin-api';
|
|
2
|
-
import { API_HOST, clientFor, failureText } from './claude.js';
|
|
3
2
|
import { compose, estimate } from './digest.js';
|
|
3
|
+
import { providerFor } from './providers/index.js';
|
|
4
|
+
import { API_HOST } from './providers/anthropic.js';
|
|
4
5
|
import { instanceSettings, userSettings } from './settings.js';
|
|
5
6
|
import { usedThisMonth } from './usage.js';
|
|
6
7
|
/** Of the digest's time, what is left unused, for counting what came back. */
|
|
7
8
|
const MARGIN_MS = 3_000;
|
|
8
9
|
const formatted = (tokens) => new Intl.NumberFormat('en').format(tokens);
|
|
10
|
+
/** The host a self-hosted Ollama has on the Docker network of the plugin's compose example. */
|
|
11
|
+
const OLLAMA_HOST = 'ollama';
|
|
9
12
|
/**
|
|
10
13
|
* Opens each user's email digest with an overview of what their unread articles are about, in
|
|
11
14
|
* topic sections whose points link the articles they draw on, written by Claude through the
|
|
12
|
-
* Anthropic API
|
|
13
|
-
*
|
|
15
|
+
* Anthropic API or by a self-hosted model (Ollama, or a server with the OpenAI chat completions
|
|
16
|
+
* API) from the titles and excerpts of the unread articles the digest counts, of the feeds the
|
|
17
|
+
* user chooses, with the sections, length, style, and instructions the user chooses.
|
|
14
18
|
*/
|
|
15
19
|
export default definePlugin({
|
|
16
20
|
id: 'digest-summary',
|
|
17
21
|
// Keep in step with package.json; a test checks they match.
|
|
18
|
-
version: '0.
|
|
19
|
-
apiVersion: '^0.1.
|
|
22
|
+
version: '0.3.0',
|
|
23
|
+
apiVersion: '^0.1.3',
|
|
20
24
|
scopes: ['user'],
|
|
21
|
-
hosts: [API_HOST],
|
|
25
|
+
hosts: [API_HOST, OLLAMA_HOST],
|
|
22
26
|
settings: { instance: instanceSettings, user: userSettings },
|
|
23
27
|
messages: {
|
|
24
28
|
en: {
|
|
25
29
|
name: 'Digest summary',
|
|
26
|
-
description: 'Opens your email digest with an overview of what your unread articles are about, written by
|
|
30
|
+
description: 'Opens your email digest with an overview of what your unread articles are about, written by an AI model: a lead on their common themes, then topic sections whose points link the articles they draw on. The title, feed name, and first lines of the unread articles of the feeds you choose go, with your sections and instructions, to the model the server’s admin chose: Claude through Anthropic (api.anthropic.com), with the server’s API key under Anthropic’s commercial terms, or a model the server’s operator runs, at the address the admin set. Articles from feeds with a login, and pages you published, are never sent, nor are links.',
|
|
31
|
+
'settings.provider': 'Model from',
|
|
32
|
+
'settings.provider.hint': 'Anthropic bills each request to the API key. A self-hosted model runs on a server you run, such as the Ollama of the plugin’s Docker example, and needs its host approved above.',
|
|
33
|
+
'settings.provider.option.anthropic': 'Anthropic (Claude)',
|
|
34
|
+
'settings.provider.option.ollama': 'Ollama, self-hosted',
|
|
35
|
+
'settings.provider.option.openai': 'Self-hosted server with the OpenAI API (llama.cpp, vLLM, LM Studio…)',
|
|
27
36
|
'settings.apiKey': 'Anthropic API key',
|
|
28
|
-
'settings.apiKey.hint': 'From the Claude Console (platform.claude.com), under API keys
|
|
29
|
-
'settings.model': '
|
|
37
|
+
'settings.apiKey.hint': 'From the Claude Console (platform.claude.com), under API keys: every request is billed to it. Sent only to Anthropic. Stored as a secret.',
|
|
38
|
+
'settings.model': 'Claude model',
|
|
30
39
|
'settings.model.hint': 'Opus writes best, Haiku costs least.',
|
|
31
40
|
'settings.model.option.claude-opus-5-5': 'Claude Opus 5.5',
|
|
32
41
|
'settings.model.option.claude-sonnet-5-5': 'Claude Sonnet 5.5',
|
|
33
42
|
'settings.model.option.claude-haiku-5-5': 'Claude Haiku 5.5',
|
|
34
|
-
'settings.effort': '
|
|
35
|
-
'settings.effort.hint': 'How much
|
|
43
|
+
'settings.effort': 'Claude effort',
|
|
44
|
+
'settings.effort.hint': 'How much Claude thinks before it writes; more costs more tokens and takes longer, and a digest waits at most five minutes.',
|
|
36
45
|
'settings.effort.option.low': 'Low',
|
|
37
46
|
'settings.effort.option.medium': 'Medium',
|
|
38
47
|
'settings.effort.option.high': 'High',
|
|
48
|
+
'settings.baseUrl': 'Self-hosted server’s URL',
|
|
49
|
+
'settings.baseUrl.hint': 'Ollama’s, such as http://ollama:11434; or the OpenAI API’s, ending in /v1, such as http://llama:8080/v1. Its host must be approved above, and, on a private network, listed in the server’s PLUGIN_TRUSTED_HOSTS.',
|
|
50
|
+
'settings.localApiKey': 'Self-hosted server’s key',
|
|
51
|
+
'settings.localApiKey.hint': 'Only if the server asks for one, such as a server with the OpenAI API started with a key, or an Ollama behind a proxy that checks a bearer token. Sent as a bearer token. Stored as a secret.',
|
|
52
|
+
'settings.localModel': 'Self-hosted model',
|
|
53
|
+
'settings.localModel.hint': 'As the server names it, such as qwen3:8b on Ollama. Pull it there first; Send test checks it.',
|
|
54
|
+
'settings.contextTokens': 'Context, in tokens',
|
|
55
|
+
'settings.contextTokens.hint': 'What the model reads and writes in one request: the newest articles that fit are read, in up to 6 requests and one more for the overview. Sent to Ollama with each request; a server with the OpenAI API must be started with at least this much (llama.cpp’s -c). More reads more articles, takes more memory, and takes longer.',
|
|
56
|
+
'settings.parallelRequests': 'Requests at once',
|
|
57
|
+
'settings.parallelRequests.hint': 'Parts of a large digest read together. Keep to what the server runs at once (Ollama’s OLLAMA_NUM_PARALLEL), or they wait their turn.',
|
|
58
|
+
'settings.thinking': 'Let the self-hosted model think first',
|
|
59
|
+
'settings.thinking.hint': 'For Ollama models that think, such as Qwen 3: the model thinks before writing the overview (parts of a large digest are read without), from the answer’s room and time, so overviews take longer. Off by default, which writes faster.',
|
|
39
60
|
'settings.monthlyTokens': 'Tokens a month, for the server',
|
|
40
|
-
'settings.monthlyTokens.hint': 'Once used, no more overviews are written until the month ends (UTC). Send test shows how many are used.',
|
|
61
|
+
'settings.monthlyTokens.hint': 'Once used, no more overviews are written until the month ends (UTC). Self-hosted models count too. Send test shows how many are used.',
|
|
41
62
|
'settings.userMonthlyTokens': 'Tokens a month, for each user',
|
|
42
63
|
'settings.userMonthlyTokens.hint': 'A digest of 1,000 unread articles reads about 100,000 tokens.',
|
|
43
64
|
'settings.allowInstructions': 'Users may add their own instructions',
|
|
@@ -62,17 +83,18 @@ export default definePlugin({
|
|
|
62
83
|
'settings.style.option.bullets': 'Bullets',
|
|
63
84
|
'settings.lead': 'Open with a lead on the common themes',
|
|
64
85
|
'settings.instructions': 'Your instructions',
|
|
65
|
-
'settings.instructions.hint': 'What to focus on, leave out, or how to write, such as “Skip celebrity news; explain jargon.” Up to 1,000 characters, sent to
|
|
86
|
+
'settings.instructions.hint': 'What to focus on, leave out, or how to write, such as “Skip celebrity news; explain jargon.” Up to 1,000 characters, sent to the model with your articles. They cannot change what is sent or the overview’s format.',
|
|
66
87
|
'action.estimate': 'Estimate cost',
|
|
67
|
-
'action.estimate.hint': 'What the overview of a test digest of your unread articles from the last day would cost now, without sending it.',
|
|
88
|
+
'action.estimate.hint': 'What the overview of a test digest of your unread articles from the last day would read and cost now, and with a self-hosted model how long it would take, without sending it.',
|
|
68
89
|
},
|
|
69
90
|
},
|
|
70
91
|
hooks: {
|
|
71
92
|
'digest.compose': {
|
|
72
93
|
async run(input, context) {
|
|
73
94
|
const started = Date.now();
|
|
95
|
+
const provider = providerFor(context.settings, context.fetch);
|
|
74
96
|
const { overview, sections, outcome } = await compose({
|
|
75
|
-
|
|
97
|
+
provider,
|
|
76
98
|
settings: context.settings,
|
|
77
99
|
userSettings: context.userSettings ?? userSettings.parse({}),
|
|
78
100
|
input,
|
|
@@ -83,25 +105,21 @@ export default definePlugin({
|
|
|
83
105
|
deadline: started + DIGEST_LIMITS.timeoutSeconds * 1000 - MARGIN_MS,
|
|
84
106
|
now: () => new Date(),
|
|
85
107
|
});
|
|
86
|
-
context.logger.info('digest composed', { outcome });
|
|
108
|
+
context.logger.info('digest composed', { outcome, provider: provider.name });
|
|
87
109
|
return { overview, sections };
|
|
88
110
|
},
|
|
89
111
|
},
|
|
90
112
|
test: {
|
|
91
113
|
async run(context) {
|
|
92
|
-
const
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
}
|
|
96
|
-
catch (error) {
|
|
97
|
-
return { ok: false, message: failureText(error) };
|
|
98
|
-
}
|
|
114
|
+
const checked = await providerFor(context.settings, context.fetch).check(context.signal);
|
|
115
|
+
if (!checked.ok)
|
|
116
|
+
return checked;
|
|
99
117
|
const now = new Date();
|
|
100
118
|
const server = await usedThisMonth(context.storage, now);
|
|
101
119
|
const mine = context.userStorage ? await usedThisMonth(context.userStorage, now) : 0;
|
|
102
120
|
return {
|
|
103
121
|
ok: true,
|
|
104
|
-
message:
|
|
122
|
+
message: `${checked.message} Tokens this month: yours ${formatted(mine)} of ${formatted(context.settings.userMonthlyTokens)}, the server's ${formatted(server)} of ${formatted(context.settings.monthlyTokens)}.`,
|
|
105
123
|
};
|
|
106
124
|
},
|
|
107
125
|
},
|
|
@@ -114,6 +132,7 @@ export default definePlugin({
|
|
|
114
132
|
ok: true,
|
|
115
133
|
message: digest
|
|
116
134
|
? await estimate({
|
|
135
|
+
provider: providerFor(context.settings, context.fetch),
|
|
117
136
|
settings: context.settings,
|
|
118
137
|
userSettings: context.userSettings ?? userSettings.parse({}),
|
|
119
138
|
input: digest,
|