@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
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import Anthropic from '@anthropic-ai/sdk';
|
|
2
|
+
import { BEDROCK_GEOGRAPHIES, geographyOf } from '../settings.js';
|
|
3
|
+
import { clientFor, messagesProvider } from './anthropic.js';
|
|
4
|
+
import { reachText } from './http.js';
|
|
5
|
+
/**
|
|
6
|
+
* The regions whose hosts the plugin asks for, the most used with Claude, so an admin can pick
|
|
7
|
+
* theirs among them; an admin may approve any other region's host too.
|
|
8
|
+
*/
|
|
9
|
+
export const BEDROCK_HOST_REGIONS = [
|
|
10
|
+
'us-east-1',
|
|
11
|
+
'us-east-2',
|
|
12
|
+
'us-west-2',
|
|
13
|
+
'ca-central-1',
|
|
14
|
+
'eu-central-1',
|
|
15
|
+
'eu-west-1',
|
|
16
|
+
'eu-west-2',
|
|
17
|
+
'eu-west-3',
|
|
18
|
+
'ap-northeast-1',
|
|
19
|
+
'ap-southeast-2',
|
|
20
|
+
];
|
|
21
|
+
/** The host of Bedrock's runtime in a region, which an admin approves for the plugin. */
|
|
22
|
+
export const bedrockHost = (region) => `bedrock-runtime.${region}.amazonaws.com`;
|
|
23
|
+
/**
|
|
24
|
+
* The inference profile a request names: `global.anthropic.claude-opus-5-5`, or, routed within
|
|
25
|
+
* the region's geography, `eu.anthropic.claude-opus-5-5`. The settings refuse a geography the
|
|
26
|
+
* region or model does not have.
|
|
27
|
+
*/
|
|
28
|
+
export function bedrockModel(settings) {
|
|
29
|
+
const geography = settings.bedrockRouting === 'geography' ? geographyOf(settings.bedrockRegion) : null;
|
|
30
|
+
return `${geography ?? 'global'}.anthropic.${settings.model}`;
|
|
31
|
+
}
|
|
32
|
+
/** Where requests may run, for the messages: `in us-east-1`, `in eu-west-1, within the EU`. */
|
|
33
|
+
function whereOf(settings) {
|
|
34
|
+
const geography = settings.bedrockRouting === 'geography' ? geographyOf(settings.bedrockRegion) : null;
|
|
35
|
+
return geography
|
|
36
|
+
? `in ${settings.bedrockRegion}, within ${BEDROCK_GEOGRAPHIES[geography].name}`
|
|
37
|
+
: `in ${settings.bedrockRegion}`;
|
|
38
|
+
}
|
|
39
|
+
/** The message in an error's body: AWS's `{message}`, or the Messages API's `{error: {message}}`. */
|
|
40
|
+
function detailOf(body) {
|
|
41
|
+
if (typeof body !== 'object' || body === null)
|
|
42
|
+
return null;
|
|
43
|
+
const record = body;
|
|
44
|
+
const nested = record.error;
|
|
45
|
+
const message = record.message ??
|
|
46
|
+
record.Message ??
|
|
47
|
+
(typeof nested === 'object' && nested !== null
|
|
48
|
+
? nested.message
|
|
49
|
+
: null);
|
|
50
|
+
return typeof message === 'string' && message ? message.slice(0, 200) : null;
|
|
51
|
+
}
|
|
52
|
+
/** A Bedrock failure as people read it, saying what to change, without anything from the request. */
|
|
53
|
+
export function bedrockFailureText(error, settings) {
|
|
54
|
+
const host = bedrockHost(settings.bedrockRegion);
|
|
55
|
+
const where = whereOf(settings);
|
|
56
|
+
if (error instanceof Anthropic.APIConnectionTimeoutError)
|
|
57
|
+
return `${host} did not answer in time`;
|
|
58
|
+
if (error instanceof Anthropic.APIConnectionError)
|
|
59
|
+
return reachText(error.cause ?? error, host);
|
|
60
|
+
if (error instanceof Anthropic.APIError && error.status !== undefined) {
|
|
61
|
+
const detail = detailOf(error.error);
|
|
62
|
+
const said = detail ? `: ${detail}` : '';
|
|
63
|
+
if (error.status === 401)
|
|
64
|
+
return 'Bedrock refused the API key (HTTP 401): check it in the server’s settings';
|
|
65
|
+
if (error.status === 403)
|
|
66
|
+
return `The Bedrock API key may not use ${settings.model} ${where} (HTTP 403): its IAM user needs bedrock:InvokeModel and bedrock:CallWithBearerToken, and the AWS account access to the model${said}`;
|
|
67
|
+
if (error.status === 404)
|
|
68
|
+
return `Bedrock has no ${settings.model} ${where} (HTTP 404)${said}`;
|
|
69
|
+
if (error.status === 429)
|
|
70
|
+
return `Rate limited by Bedrock (HTTP 429): the account’s quota for ${settings.model} ${where} is used up for now`;
|
|
71
|
+
return `Bedrock answered HTTP ${String(error.status)}${said}`;
|
|
72
|
+
}
|
|
73
|
+
return error instanceof Error ? error.message : String(error);
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Claude through Amazon Bedrock's Messages API, at its runtime in the region set, with the server's
|
|
77
|
+
* Bedrock API key in `x-api-key`. As with Anthropic, the fixed prompt is cached and answers are
|
|
78
|
+
* held to the format; Bedrock has no server-side fallback, so a refusal is the answer.
|
|
79
|
+
*/
|
|
80
|
+
export function bedrockProvider(settings, fetch) {
|
|
81
|
+
const client = clientFor({
|
|
82
|
+
baseURL: `https://${bedrockHost(settings.bedrockRegion)}/anthropic`,
|
|
83
|
+
apiKey: settings.bedrockApiKey,
|
|
84
|
+
header: 'x-api-key',
|
|
85
|
+
}, fetch);
|
|
86
|
+
const model = bedrockModel(settings);
|
|
87
|
+
const where = whereOf(settings);
|
|
88
|
+
return messagesProvider({
|
|
89
|
+
name: 'bedrock',
|
|
90
|
+
label: `${settings.model} at ${settings.effort} effort on Bedrock ${where}`,
|
|
91
|
+
client,
|
|
92
|
+
model,
|
|
93
|
+
effort: settings.effort,
|
|
94
|
+
fallback: false,
|
|
95
|
+
// Bedrock's runtime neither lists models nor counts tokens for these, so a request of a few
|
|
96
|
+
// tokens checks the key, its permissions, and the model.
|
|
97
|
+
async check(signal) {
|
|
98
|
+
try {
|
|
99
|
+
await client.beta.messages.create({
|
|
100
|
+
model,
|
|
101
|
+
max_tokens: 16,
|
|
102
|
+
output_config: { effort: 'low' },
|
|
103
|
+
messages: [{ role: 'user', content: 'Hello' }],
|
|
104
|
+
}, { signal, timeout: 20_000, maxRetries: 0 });
|
|
105
|
+
}
|
|
106
|
+
catch (error) {
|
|
107
|
+
return { ok: false, message: bedrockFailureText(error, settings) };
|
|
108
|
+
}
|
|
109
|
+
return { ok: true, message: `The Bedrock API key works with ${model} ${where}.` };
|
|
110
|
+
},
|
|
111
|
+
});
|
|
112
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** A server's answer: its status, and its body as JSON when it is JSON. */
|
|
2
|
+
export interface JsonAnswer {
|
|
3
|
+
status: number;
|
|
4
|
+
body: unknown;
|
|
5
|
+
}
|
|
6
|
+
/** A model server's answer that was not a success, for the log and the test. */
|
|
7
|
+
export declare class ServerError extends Error {
|
|
8
|
+
readonly status: number;
|
|
9
|
+
constructor(status: number, detail: string | null);
|
|
10
|
+
}
|
|
11
|
+
/** A URL without its trailing slashes, to append paths to. */
|
|
12
|
+
export declare const trimmed: (base: string) => string;
|
|
13
|
+
/** Sends JSON (or nothing, for GET) and reads JSON back; throws as `fetch` does, and on bad JSON. */
|
|
14
|
+
export declare function requestJson(fetch: typeof globalThis.fetch, url: string, options: {
|
|
15
|
+
body?: unknown;
|
|
16
|
+
headers?: Record<string, string>;
|
|
17
|
+
signal: AbortSignal;
|
|
18
|
+
}): Promise<JsonAnswer>;
|
|
19
|
+
/** The error message a server sent: Ollama's `{error}`, or OpenAI's `{error: {message}}`. */
|
|
20
|
+
export declare function errorDetail(body: unknown): string | null;
|
|
21
|
+
/** Whether a failure was the request's own time running out. */
|
|
22
|
+
export declare const isTimeout: (error: unknown) => boolean;
|
|
23
|
+
/** A failure reaching `host` as people read it, saying what to change where they can. */
|
|
24
|
+
export declare function reachText(error: unknown, host: string): string;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Requests to a self-hosted model server through the hook's `fetch`, and their failures as
|
|
3
|
+
* people read them. The server's `fetch` refuses hosts an admin has not approved, and private
|
|
4
|
+
* addresses unless the operator trusts the host (`PLUGIN_TRUSTED_HOSTS`), with a `TypeError`.
|
|
5
|
+
*/
|
|
6
|
+
/** A model server's answer that was not a success, for the log and the test. */
|
|
7
|
+
export class ServerError extends Error {
|
|
8
|
+
status;
|
|
9
|
+
constructor(status, detail) {
|
|
10
|
+
super(detail
|
|
11
|
+
? `The server answered HTTP ${String(status)}: ${detail}`
|
|
12
|
+
: `The server answered HTTP ${String(status)}`);
|
|
13
|
+
this.name = 'ServerError';
|
|
14
|
+
this.status = status;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/** A URL without its trailing slashes, to append paths to. */
|
|
18
|
+
export const trimmed = (base) => base.replace(/\/+$/, '');
|
|
19
|
+
/** Sends JSON (or nothing, for GET) and reads JSON back; throws as `fetch` does, and on bad JSON. */
|
|
20
|
+
export async function requestJson(fetch, url, options) {
|
|
21
|
+
const response = await fetch(url, {
|
|
22
|
+
method: options.body === undefined ? 'GET' : 'POST',
|
|
23
|
+
headers: {
|
|
24
|
+
accept: 'application/json',
|
|
25
|
+
...(options.body !== undefined && { 'content-type': 'application/json' }),
|
|
26
|
+
...options.headers,
|
|
27
|
+
},
|
|
28
|
+
...(options.body !== undefined && { body: JSON.stringify(options.body) }),
|
|
29
|
+
signal: options.signal,
|
|
30
|
+
});
|
|
31
|
+
const text = await response.text();
|
|
32
|
+
return { status: response.status, body: parsedJson(text) };
|
|
33
|
+
}
|
|
34
|
+
/** Text as JSON, or null when it is empty or not JSON. */
|
|
35
|
+
function parsedJson(text) {
|
|
36
|
+
if (!text)
|
|
37
|
+
return null;
|
|
38
|
+
try {
|
|
39
|
+
return JSON.parse(text);
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/** The error message a server sent: Ollama's `{error}`, or OpenAI's `{error: {message}}`. */
|
|
46
|
+
export function errorDetail(body) {
|
|
47
|
+
if (typeof body !== 'object' || body === null || !('error' in body))
|
|
48
|
+
return null;
|
|
49
|
+
const { error } = body;
|
|
50
|
+
const message = typeof error === 'string'
|
|
51
|
+
? error
|
|
52
|
+
: typeof error === 'object' && error !== null && 'message' in error
|
|
53
|
+
? String(error.message)
|
|
54
|
+
: null;
|
|
55
|
+
return message ? message.slice(0, 200) : null;
|
|
56
|
+
}
|
|
57
|
+
/** Whether a failure was the request's own time running out. */
|
|
58
|
+
export const isTimeout = (error) => error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError');
|
|
59
|
+
/** A failure reaching `host` as people read it, saying what to change where they can. */
|
|
60
|
+
export function reachText(error, host) {
|
|
61
|
+
if (error instanceof ServerError)
|
|
62
|
+
return error.message;
|
|
63
|
+
if (isTimeout(error))
|
|
64
|
+
return `${host} did not answer in time`;
|
|
65
|
+
if (error instanceof TypeError) {
|
|
66
|
+
if (/not (an )?approved/.test(error.message))
|
|
67
|
+
return `${host} is not approved for this plugin: add it under Approved hosts`;
|
|
68
|
+
const cause = error.cause;
|
|
69
|
+
const code = typeof cause === 'object' && cause !== null && 'code' in cause ? String(cause.code) : null;
|
|
70
|
+
if (/private address/.test(error.message) || code === 'blocked_address')
|
|
71
|
+
return `${host} is on a private network: the server's operator must add it to PLUGIN_TRUSTED_HOSTS`;
|
|
72
|
+
if (cause instanceof Error)
|
|
73
|
+
return `${host} could not be reached: ${cause.message}`;
|
|
74
|
+
return `${host} could not be reached: ${error.message}`;
|
|
75
|
+
}
|
|
76
|
+
return error instanceof Error ? error.message : String(error);
|
|
77
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { InstanceSettings } from '../settings.js';
|
|
2
|
+
import type { Provider } from './types.js';
|
|
3
|
+
export type { Asked, AskOutcome, AskRequest, Capacity, Provider, Timing } from './types.js';
|
|
4
|
+
/** The model the settings choose, sending its requests through the hook's `fetch`. */
|
|
5
|
+
export declare function providerFor(settings: InstanceSettings, fetch: typeof globalThis.fetch): Provider;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { anthropicProvider } from './anthropic.js';
|
|
2
|
+
import { bedrockProvider } from './bedrock.js';
|
|
3
|
+
import { ollamaProvider } from './ollama.js';
|
|
4
|
+
import { openaiProvider } from './openai.js';
|
|
5
|
+
/** The model the settings choose, sending its requests through the hook's `fetch`. */
|
|
6
|
+
export function providerFor(settings, fetch) {
|
|
7
|
+
if (settings.provider === 'bedrock')
|
|
8
|
+
return bedrockProvider(settings, fetch);
|
|
9
|
+
if (settings.provider === 'ollama')
|
|
10
|
+
return ollamaProvider(settings, fetch);
|
|
11
|
+
if (settings.provider === 'openai')
|
|
12
|
+
return openaiProvider(settings, fetch);
|
|
13
|
+
return anthropicProvider(settings, fetch);
|
|
14
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { InstanceSettings } from '../settings.js';
|
|
2
|
+
import type { Provider } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* A model on an Ollama server, through its own API (`/api/chat`): the context set with each
|
|
5
|
+
* request (`num_ctx`), so a prompt is never cut to Ollama's default; the answer held to the
|
|
6
|
+
* format's JSON schema; thinking on or off as the admin chose. The key, when set, is sent as a
|
|
7
|
+
* bearer token, for an Ollama behind a proxy that asks for one (Ollama itself has no keys).
|
|
8
|
+
*/
|
|
9
|
+
export declare function ollamaProvider(settings: Pick<InstanceSettings, 'baseUrl' | 'localApiKey' | 'localModel' | 'contextTokens' | 'parallelRequests' | 'thinking'>, fetch: typeof globalThis.fetch): Provider;
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { errorDetail, isTimeout, reachText, requestJson, ServerError, trimmed } from './http.js';
|
|
3
|
+
/** Low, so the overview keeps to the articles; not zero, which repeats itself on small models. */
|
|
4
|
+
const TEMPERATURE = 0.2;
|
|
5
|
+
const chatAnswer = z.object({
|
|
6
|
+
message: z.object({ content: z.string() }),
|
|
7
|
+
done_reason: z.string().optional(),
|
|
8
|
+
prompt_eval_count: z.number().optional(),
|
|
9
|
+
prompt_eval_duration: z.number().optional(),
|
|
10
|
+
eval_count: z.number().optional(),
|
|
11
|
+
eval_duration: z.number().optional(),
|
|
12
|
+
});
|
|
13
|
+
const showAnswer = z.object({
|
|
14
|
+
model_info: z.record(z.string(), z.unknown()).optional(),
|
|
15
|
+
capabilities: z.array(z.string()).optional(),
|
|
16
|
+
});
|
|
17
|
+
const formatted = (n) => new Intl.NumberFormat('en').format(n);
|
|
18
|
+
/** The longest context a model was trained for, from `/api/show`'s `<architecture>.context_length`. */
|
|
19
|
+
function trainedContext(info) {
|
|
20
|
+
const entry = Object.entries(info ?? {}).find(([key]) => key.endsWith('.context_length'));
|
|
21
|
+
return typeof entry?.[1] === 'number' ? entry[1] : null;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* A model on an Ollama server, through its own API (`/api/chat`): the context set with each
|
|
25
|
+
* request (`num_ctx`), so a prompt is never cut to Ollama's default; the answer held to the
|
|
26
|
+
* format's JSON schema; thinking on or off as the admin chose. The key, when set, is sent as a
|
|
27
|
+
* bearer token, for an Ollama behind a proxy that asks for one (Ollama itself has no keys).
|
|
28
|
+
*/
|
|
29
|
+
export function ollamaProvider(settings, fetch) {
|
|
30
|
+
const base = trimmed(settings.baseUrl ?? '');
|
|
31
|
+
const host = base ? new URL(base).host : 'the Ollama server';
|
|
32
|
+
const model = settings.localModel;
|
|
33
|
+
const headers = settings.localApiKey
|
|
34
|
+
? { authorization: `Bearer ${settings.localApiKey}` }
|
|
35
|
+
: {};
|
|
36
|
+
return {
|
|
37
|
+
name: 'ollama',
|
|
38
|
+
label: `${model} on Ollama`,
|
|
39
|
+
capacity: {
|
|
40
|
+
kind: 'context',
|
|
41
|
+
contextTokens: settings.contextTokens,
|
|
42
|
+
thinking: settings.thinking,
|
|
43
|
+
},
|
|
44
|
+
parallel: settings.parallelRequests,
|
|
45
|
+
async ask(request) {
|
|
46
|
+
let answer;
|
|
47
|
+
try {
|
|
48
|
+
const { status, body } = await requestJson(fetch, `${base}/api/chat`, {
|
|
49
|
+
body: {
|
|
50
|
+
model,
|
|
51
|
+
// One system message, the fixed prompt first, so Ollama reuses what it read of it.
|
|
52
|
+
messages: [
|
|
53
|
+
{ role: 'system', content: `${request.system[0]}\n\n${request.system[1]}` },
|
|
54
|
+
{ role: 'user', content: request.prompt },
|
|
55
|
+
],
|
|
56
|
+
stream: false,
|
|
57
|
+
format: request.format.schema,
|
|
58
|
+
think: settings.thinking && request.thinking,
|
|
59
|
+
// An error, rather than a prompt cut short, when it does not fit.
|
|
60
|
+
truncate: false,
|
|
61
|
+
shift: false,
|
|
62
|
+
options: {
|
|
63
|
+
num_ctx: settings.contextTokens,
|
|
64
|
+
num_predict: request.maxTokens,
|
|
65
|
+
temperature: TEMPERATURE,
|
|
66
|
+
},
|
|
67
|
+
},
|
|
68
|
+
headers,
|
|
69
|
+
signal: request.signal,
|
|
70
|
+
});
|
|
71
|
+
if (status !== 200)
|
|
72
|
+
throw new ServerError(status, errorDetail(body));
|
|
73
|
+
const parsed = chatAnswer.safeParse(body);
|
|
74
|
+
if (!parsed.success)
|
|
75
|
+
throw new Error('The Ollama server answered with something else');
|
|
76
|
+
answer = parsed.data;
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
return { ok: false, outcome: isTimeout(error) ? 'timed out' : 'failed', tokens: 0, error };
|
|
80
|
+
}
|
|
81
|
+
const promptTokens = answer.prompt_eval_count ?? 0;
|
|
82
|
+
const outputTokens = answer.eval_count ?? 0;
|
|
83
|
+
const tokens = promptTokens + outputTokens;
|
|
84
|
+
if (answer.done_reason !== undefined && answer.done_reason !== 'stop')
|
|
85
|
+
return { ok: false, outcome: 'invalid', tokens };
|
|
86
|
+
return {
|
|
87
|
+
ok: true,
|
|
88
|
+
text: answer.message.content,
|
|
89
|
+
tokens,
|
|
90
|
+
...(answer.prompt_eval_duration !== undefined &&
|
|
91
|
+
answer.eval_duration !== undefined && {
|
|
92
|
+
timing: {
|
|
93
|
+
promptTokens,
|
|
94
|
+
promptMs: answer.prompt_eval_duration / 1e6,
|
|
95
|
+
outputTokens,
|
|
96
|
+
outputMs: answer.eval_duration / 1e6,
|
|
97
|
+
},
|
|
98
|
+
}),
|
|
99
|
+
};
|
|
100
|
+
},
|
|
101
|
+
async check(signal) {
|
|
102
|
+
if (!base)
|
|
103
|
+
return { ok: false, message: 'Set the URL of the Ollama server.' };
|
|
104
|
+
let shown;
|
|
105
|
+
try {
|
|
106
|
+
const { status, body } = await requestJson(fetch, `${base}/api/show`, {
|
|
107
|
+
body: { model },
|
|
108
|
+
headers,
|
|
109
|
+
signal,
|
|
110
|
+
});
|
|
111
|
+
if (status === 404)
|
|
112
|
+
return {
|
|
113
|
+
ok: false,
|
|
114
|
+
message: `${model} is not on the Ollama server at ${host}: pull it there with \`ollama pull ${model}\`.`,
|
|
115
|
+
};
|
|
116
|
+
if (status !== 200)
|
|
117
|
+
throw new ServerError(status, errorDetail(body));
|
|
118
|
+
shown = showAnswer.parse(body);
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
return { ok: false, message: reachText(error, host) };
|
|
122
|
+
}
|
|
123
|
+
const trained = trainedContext(shown.model_info);
|
|
124
|
+
if (trained !== null && settings.contextTokens > trained)
|
|
125
|
+
return {
|
|
126
|
+
ok: false,
|
|
127
|
+
message: `${model} takes at most ${formatted(trained)} tokens of context, fewer than the ${formatted(settings.contextTokens)} set: lower Context.`,
|
|
128
|
+
};
|
|
129
|
+
if (settings.thinking && shown.capabilities && !shown.capabilities.includes('thinking'))
|
|
130
|
+
return { ok: false, message: `${model} does not think: turn Thinking off.` };
|
|
131
|
+
return {
|
|
132
|
+
ok: true,
|
|
133
|
+
message: `Ollama at ${host} has ${model}, with ${formatted(settings.contextTokens)} tokens of context.`,
|
|
134
|
+
};
|
|
135
|
+
},
|
|
136
|
+
};
|
|
137
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { InstanceSettings } from '../settings.js';
|
|
2
|
+
import type { Provider } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* A model on a server speaking the OpenAI chat completions API (`/chat/completions` under the
|
|
5
|
+
* URL set, which ends in `/v1`): llama.cpp's server, vLLM, LM Studio, LocalAI, Ollama's `/v1`.
|
|
6
|
+
* The answer is held to the format's JSON schema (`response_format`); the key, when set, is
|
|
7
|
+
* sent as a bearer token. The server's own context must be at least `contextTokens`.
|
|
8
|
+
*/
|
|
9
|
+
export declare function openaiProvider(settings: Pick<InstanceSettings, 'baseUrl' | 'localApiKey' | 'localModel' | 'contextTokens' | 'parallelRequests'>, fetch: typeof globalThis.fetch): Provider;
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { estimateTokens } from '../tokens.js';
|
|
3
|
+
import { errorDetail, isTimeout, reachText, requestJson, ServerError, trimmed } from './http.js';
|
|
4
|
+
/** Low, so the overview keeps to the articles; not zero, which repeats itself on small models. */
|
|
5
|
+
const TEMPERATURE = 0.2;
|
|
6
|
+
const completion = z.object({
|
|
7
|
+
choices: z
|
|
8
|
+
.array(z.object({
|
|
9
|
+
message: z.object({
|
|
10
|
+
content: z.string().nullable().optional(),
|
|
11
|
+
refusal: z.string().nullable().optional(),
|
|
12
|
+
}),
|
|
13
|
+
finish_reason: z.string().nullable().optional(),
|
|
14
|
+
}))
|
|
15
|
+
.min(1),
|
|
16
|
+
usage: z
|
|
17
|
+
.object({ prompt_tokens: z.number(), completion_tokens: z.number() })
|
|
18
|
+
.nullable()
|
|
19
|
+
.optional(),
|
|
20
|
+
});
|
|
21
|
+
const models = z.object({ data: z.array(z.object({ id: z.string() })) });
|
|
22
|
+
/**
|
|
23
|
+
* A model on a server speaking the OpenAI chat completions API (`/chat/completions` under the
|
|
24
|
+
* URL set, which ends in `/v1`): llama.cpp's server, vLLM, LM Studio, LocalAI, Ollama's `/v1`.
|
|
25
|
+
* The answer is held to the format's JSON schema (`response_format`); the key, when set, is
|
|
26
|
+
* sent as a bearer token. The server's own context must be at least `contextTokens`.
|
|
27
|
+
*/
|
|
28
|
+
export function openaiProvider(settings, fetch) {
|
|
29
|
+
const base = trimmed(settings.baseUrl ?? '');
|
|
30
|
+
const host = base ? new URL(base).host : 'the server';
|
|
31
|
+
const model = settings.localModel;
|
|
32
|
+
const headers = settings.localApiKey
|
|
33
|
+
? { authorization: `Bearer ${settings.localApiKey}` }
|
|
34
|
+
: {};
|
|
35
|
+
return {
|
|
36
|
+
name: 'openai',
|
|
37
|
+
label: `${model} at ${host}`,
|
|
38
|
+
capacity: { kind: 'context', contextTokens: settings.contextTokens, thinking: false },
|
|
39
|
+
parallel: settings.parallelRequests,
|
|
40
|
+
async ask(request) {
|
|
41
|
+
let answer;
|
|
42
|
+
try {
|
|
43
|
+
const { status, body } = await requestJson(fetch, `${base}/chat/completions`, {
|
|
44
|
+
body: {
|
|
45
|
+
model,
|
|
46
|
+
messages: [
|
|
47
|
+
{ role: 'system', content: `${request.system[0]}\n\n${request.system[1]}` },
|
|
48
|
+
{ role: 'user', content: request.prompt },
|
|
49
|
+
],
|
|
50
|
+
response_format: {
|
|
51
|
+
type: 'json_schema',
|
|
52
|
+
json_schema: { name: 'digest', strict: true, schema: request.format.schema },
|
|
53
|
+
},
|
|
54
|
+
max_tokens: request.maxTokens,
|
|
55
|
+
temperature: TEMPERATURE,
|
|
56
|
+
stream: false,
|
|
57
|
+
},
|
|
58
|
+
headers,
|
|
59
|
+
signal: request.signal,
|
|
60
|
+
});
|
|
61
|
+
if (status !== 200)
|
|
62
|
+
throw new ServerError(status, errorDetail(body));
|
|
63
|
+
const parsed = completion.safeParse(body);
|
|
64
|
+
if (!parsed.success)
|
|
65
|
+
throw new Error('The server answered with something else');
|
|
66
|
+
answer = parsed.data;
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
return { ok: false, outcome: isTimeout(error) ? 'timed out' : 'failed', tokens: 0, error };
|
|
70
|
+
}
|
|
71
|
+
const [choice] = answer.choices;
|
|
72
|
+
const text = choice?.message.content ?? '';
|
|
73
|
+
// Servers that leave usage out are counted by estimate, so the budgets still hold.
|
|
74
|
+
const tokens = answer.usage
|
|
75
|
+
? answer.usage.prompt_tokens + answer.usage.completion_tokens
|
|
76
|
+
: estimateTokens(request.system.join('') + request.prompt + text);
|
|
77
|
+
if (choice?.message.refusal || choice?.finish_reason === 'content_filter')
|
|
78
|
+
return { ok: false, outcome: 'refused', tokens };
|
|
79
|
+
if (choice?.finish_reason && choice.finish_reason !== 'stop')
|
|
80
|
+
return { ok: false, outcome: 'invalid', tokens };
|
|
81
|
+
return { ok: true, text, tokens };
|
|
82
|
+
},
|
|
83
|
+
async check(signal) {
|
|
84
|
+
if (!base)
|
|
85
|
+
return { ok: false, message: 'Set the URL of the server, ending in /v1.' };
|
|
86
|
+
let listed;
|
|
87
|
+
try {
|
|
88
|
+
const { status, body } = await requestJson(fetch, `${base}/models`, { headers, signal });
|
|
89
|
+
if (status === 401 || status === 403)
|
|
90
|
+
return {
|
|
91
|
+
ok: false,
|
|
92
|
+
message: `${host} refused the API key (HTTP ${String(status)}): check it in the server’s settings.`,
|
|
93
|
+
};
|
|
94
|
+
if (status !== 200)
|
|
95
|
+
throw new ServerError(status, errorDetail(body));
|
|
96
|
+
const parsed = models.safeParse(body);
|
|
97
|
+
if (!parsed.success)
|
|
98
|
+
return {
|
|
99
|
+
ok: false,
|
|
100
|
+
message: `${host} did not list its models: check that the URL ends in /v1.`,
|
|
101
|
+
};
|
|
102
|
+
listed = parsed.data;
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
return { ok: false, message: reachText(error, host) };
|
|
106
|
+
}
|
|
107
|
+
const ids = listed.data.map((entry) => entry.id);
|
|
108
|
+
if (!ids.includes(model))
|
|
109
|
+
return {
|
|
110
|
+
ok: false,
|
|
111
|
+
message: `${host} has no model ${model}${ids.length ? `; it has ${ids.slice(0, 5).join(', ')}` : ''}.`,
|
|
112
|
+
};
|
|
113
|
+
return { ok: true, message: `${host} has ${model}.` };
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { OutputFormat } from '../prompts.js';
|
|
2
|
+
import type { InstanceSettings } from '../settings.js';
|
|
3
|
+
/** Why a request has no answer to read. */
|
|
4
|
+
export type AskOutcome = 'refused' | 'invalid' | 'failed' | 'timed out';
|
|
5
|
+
/** One request for an overview, or for a part's themes. */
|
|
6
|
+
export interface AskRequest {
|
|
7
|
+
/** The fixed system prompt, then the reader's preferences. */
|
|
8
|
+
system: readonly [string, string];
|
|
9
|
+
prompt: string;
|
|
10
|
+
format: OutputFormat;
|
|
11
|
+
/** Output tokens the answer may take, thinking included. */
|
|
12
|
+
maxTokens: number;
|
|
13
|
+
/** The model may think first, when the admin lets it: the overview's request; parts never do. */
|
|
14
|
+
thinking: boolean;
|
|
15
|
+
/** Ends the request: the hook's signal and the request's own time together. */
|
|
16
|
+
signal: AbortSignal;
|
|
17
|
+
/** Milliseconds the request may take. */
|
|
18
|
+
timeoutMs: number;
|
|
19
|
+
}
|
|
20
|
+
/** How long a self-hosted model took to read a prompt and write an answer. */
|
|
21
|
+
export interface Timing {
|
|
22
|
+
promptTokens: number;
|
|
23
|
+
promptMs: number;
|
|
24
|
+
outputTokens: number;
|
|
25
|
+
outputMs: number;
|
|
26
|
+
}
|
|
27
|
+
/** How one request ended: its text, or why it has none; and the tokens it used either way. */
|
|
28
|
+
export type Asked = {
|
|
29
|
+
ok: true;
|
|
30
|
+
text: string;
|
|
31
|
+
tokens: number;
|
|
32
|
+
timing?: Timing;
|
|
33
|
+
} | {
|
|
34
|
+
ok: false;
|
|
35
|
+
outcome: AskOutcome;
|
|
36
|
+
tokens: number;
|
|
37
|
+
error?: unknown;
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* How much one request may read: Claude's parts grow past `partTokens` for a digest larger than
|
|
41
|
+
* the parts hold; a self-hosted model's context is fixed, so it reads the newest articles that fit.
|
|
42
|
+
*/
|
|
43
|
+
export type Capacity = {
|
|
44
|
+
kind: 'grow';
|
|
45
|
+
partTokens: number;
|
|
46
|
+
} | {
|
|
47
|
+
kind: 'context';
|
|
48
|
+
contextTokens: number;
|
|
49
|
+
thinking: boolean;
|
|
50
|
+
};
|
|
51
|
+
/** A model the plugin writes with, whoever serves it. */
|
|
52
|
+
export interface Provider {
|
|
53
|
+
readonly name: InstanceSettings['provider'];
|
|
54
|
+
/** What the messages call it: `claude-opus-5-5 at low effort`, `qwen3:8b on Ollama`. */
|
|
55
|
+
readonly label: string;
|
|
56
|
+
readonly capacity: Capacity;
|
|
57
|
+
/** Parts read at once, at most. */
|
|
58
|
+
readonly parallel: number;
|
|
59
|
+
ask(request: AskRequest): Promise<Asked>;
|
|
60
|
+
/** Whether the model can be reached, for the test hook, as people read it. */
|
|
61
|
+
check(signal: AbortSignal): Promise<{
|
|
62
|
+
ok: boolean;
|
|
63
|
+
message: string;
|
|
64
|
+
}>;
|
|
65
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|