opencode-model-router 2.1.0 → 2.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/CHANGELOG.md +86 -0
- package/README.md +44 -5
- package/package.json +4 -1
- package/src/commands/output.ts +4 -1
- package/src/compat/child-session.ts +43 -0
- package/src/compat/v2-client.ts +107 -7
- package/src/compat/v2-hooks.ts +174 -47
- package/src/escalate/attempt-recorder.ts +263 -0
- package/src/escalate/ladder.ts +484 -10
- package/src/escalate/resume.ts +208 -0
- package/src/escalate/variants.ts +391 -0
- package/src/index.ts +557 -61
- package/src/router/build-info.ts +151 -0
- package/src/router/config.ts +1691 -67
- package/src/router/protocol.ts +47 -0
- package/src/router/sessions.ts +441 -9
- package/src/routing/advisor/findings.ts +706 -0
- package/src/routing/advisor/index.ts +606 -0
- package/src/routing/classify/backends/host.ts +163 -0
- package/src/routing/classify/backends/openai-compatible.ts +275 -0
- package/src/routing/classify/backends/shared.ts +741 -0
- package/src/routing/classify/backends/typesafe.ts +315 -0
- package/src/routing/classify/fences.ts +96 -0
- package/src/routing/classify/index.ts +576 -0
- package/src/routing/classify/route-line.ts +298 -0
- package/src/routing/classify/rules.ts +607 -0
- package/src/routing/classify/scrub.ts +214 -0
- package/src/routing/classify/state.ts +148 -0
- package/src/routing/classify/text.ts +20 -0
- package/src/routing/classify/types.ts +1280 -0
- package/src/routing/commands/annotate-plan.ts +652 -0
- package/src/routing/commands/stats.ts +131 -0
- package/src/routing/commands/v1-roles.ts +64 -0
- package/src/routing/engine/index.ts +32 -0
- package/src/routing/engine/kernel.ts +597 -0
- package/src/routing/engine/ladders.ts +561 -0
- package/src/routing/engine/plan.ts +404 -0
- package/src/routing/engine/protocol-line.ts +133 -0
- package/src/routing/engine/simulate.ts +167 -0
- package/src/routing/engine/types.ts +270 -0
- package/src/routing/file-lock.ts +53 -0
- package/src/routing/outcomes/beta.ts +141 -0
- package/src/routing/outcomes/cost.ts +313 -0
- package/src/routing/outcomes/index.ts +172 -0
- package/src/routing/outcomes/ingest.ts +812 -0
- package/src/routing/outcomes/persist.ts +1058 -0
- package/src/routing/outcomes/stats.ts +602 -0
- package/src/routing/outcomes/store.ts +653 -0
- package/src/routing/outcomes/types.ts +954 -0
- package/src/routing/wire/dispatch.ts +799 -0
- package/src/routing/wire/hint.ts +208 -0
- package/src/routing/wire/host-info.ts +256 -0
- package/src/routing/wire/runtime.ts +259 -0
- package/src/v2.ts +15 -1
- package/tiers.json +43 -0
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `host` backend (amendment A4): classifies through the host's own
|
|
3
|
+
* `ctx.generate.text`. The model is passed as the object `{ providerID, id,
|
|
4
|
+
* variant? }` — never the `provider/model` string, never the raw
|
|
5
|
+
* `/api/experimental/generate` HTTP route, never `fetch`.
|
|
6
|
+
*
|
|
7
|
+
* Contract: never throws, never retries, settles within `timeoutMs` (the timer
|
|
8
|
+
* races the host call; an abandoned call may still complete and bill).
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import {
|
|
12
|
+
CLASS_OPTIONS,
|
|
13
|
+
type BackendCallOptions,
|
|
14
|
+
type BackendResult,
|
|
15
|
+
type ClassifierBackend,
|
|
16
|
+
type ClassifierLogger,
|
|
17
|
+
type ClassifierSettings,
|
|
18
|
+
type ClassifierState,
|
|
19
|
+
type HostGenerate,
|
|
20
|
+
type TaskClass,
|
|
21
|
+
} from "../types";
|
|
22
|
+
import {
|
|
23
|
+
createRuntime,
|
|
24
|
+
cutRaw,
|
|
25
|
+
disabled,
|
|
26
|
+
disabledMany,
|
|
27
|
+
finish,
|
|
28
|
+
finishMany,
|
|
29
|
+
backendUnavailable,
|
|
30
|
+
gatherSamples,
|
|
31
|
+
guarded,
|
|
32
|
+
guardedMany,
|
|
33
|
+
parseBatchLabels,
|
|
34
|
+
parseLabel,
|
|
35
|
+
parseModelRef,
|
|
36
|
+
renderBatchPrompt,
|
|
37
|
+
renderSinglePrompt,
|
|
38
|
+
resolveOutcome,
|
|
39
|
+
type SampleAnswer,
|
|
40
|
+
type Settled,
|
|
41
|
+
} from "./shared";
|
|
42
|
+
|
|
43
|
+
export interface HostBackendDeps {
|
|
44
|
+
readonly generate: HostGenerate;
|
|
45
|
+
readonly settings: ClassifierSettings;
|
|
46
|
+
readonly logger: ClassifierLogger;
|
|
47
|
+
readonly now?: () => number;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const BAD_MODEL = "classifier.model is not provider/model[#variant]";
|
|
51
|
+
|
|
52
|
+
interface BatchAnswer {
|
|
53
|
+
readonly labels: readonly (TaskClass | null)[];
|
|
54
|
+
readonly raw: string | null;
|
|
55
|
+
readonly reason?: string;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function createHostBackend(deps: HostBackendDeps): ClassifierBackend {
|
|
59
|
+
const rt = createRuntime("host", deps.logger, deps.now);
|
|
60
|
+
const { generate, settings } = deps;
|
|
61
|
+
|
|
62
|
+
const hostModel = () => {
|
|
63
|
+
const ref = parseModelRef(settings.model ?? "");
|
|
64
|
+
return ref === null
|
|
65
|
+
? null
|
|
66
|
+
: {
|
|
67
|
+
providerID: ref.providerID,
|
|
68
|
+
id: ref.id,
|
|
69
|
+
...(ref.variant ? { variant: ref.variant } : {}),
|
|
70
|
+
};
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
async function callHost(
|
|
74
|
+
prompt: string,
|
|
75
|
+
model: NonNullable<ReturnType<typeof hostModel>>,
|
|
76
|
+
signal: AbortSignal,
|
|
77
|
+
): Promise<string | null> {
|
|
78
|
+
const result = await generate.text({ prompt, model }, { signal });
|
|
79
|
+
return typeof result?.text === "string" ? result.text : null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return {
|
|
83
|
+
id: "host",
|
|
84
|
+
|
|
85
|
+
async classify(state: ClassifierState, options: BackendCallOptions): Promise<BackendResult> {
|
|
86
|
+
const startedAt = rt.now();
|
|
87
|
+
return guarded(rt, startedAt, async () => {
|
|
88
|
+
const model = hostModel();
|
|
89
|
+
if (model === null) return disabled(rt, BAD_MODEL, startedAt);
|
|
90
|
+
const blocked = backendUnavailable(rt);
|
|
91
|
+
if (blocked !== null) return disabled(rt, blocked, startedAt);
|
|
92
|
+
const samples = settings.samples;
|
|
93
|
+
const choices = options.choices.length > 0 ? options.choices : CLASS_OPTIONS;
|
|
94
|
+
const rendered = Array.from({ length: samples }, () =>
|
|
95
|
+
renderSinglePrompt(state, choices, options.random),
|
|
96
|
+
);
|
|
97
|
+
const gathered = await gatherSamples<SampleAnswer>(
|
|
98
|
+
rt,
|
|
99
|
+
samples,
|
|
100
|
+
settings.timeoutMs,
|
|
101
|
+
new AbortController(),
|
|
102
|
+
async (index, signal) => {
|
|
103
|
+
const text = await callHost(rendered[index]!.prompt, model, signal);
|
|
104
|
+
if (text === null) return { label: null, raw: null, reason: "host returned no text" };
|
|
105
|
+
const label = parseLabel(text, rendered[index]!.labels);
|
|
106
|
+
return { label, raw: cutRaw(text) };
|
|
107
|
+
},
|
|
108
|
+
(answer) => answer.label,
|
|
109
|
+
);
|
|
110
|
+
const labels = gathered.settled.map((s) => (s.kind === "value" ? s.v.label : null));
|
|
111
|
+
const outcome = resolveOutcome(labels, gathered.settled, samples, gathered.timedOut, settings.timeoutMs);
|
|
112
|
+
return finish(rt, outcome, samples, startedAt);
|
|
113
|
+
});
|
|
114
|
+
},
|
|
115
|
+
|
|
116
|
+
async classifyMany(
|
|
117
|
+
states: readonly ClassifierState[],
|
|
118
|
+
options: BackendCallOptions,
|
|
119
|
+
): Promise<BackendResult[]> {
|
|
120
|
+
if (states.length === 0) return [];
|
|
121
|
+
const startedAt = rt.now();
|
|
122
|
+
return guardedMany(rt, states.length, startedAt, async () => {
|
|
123
|
+
const model = hostModel();
|
|
124
|
+
if (model === null) return disabledMany(rt, states.length, BAD_MODEL, startedAt);
|
|
125
|
+
const blocked = backendUnavailable(rt);
|
|
126
|
+
if (blocked !== null) return disabledMany(rt, states.length, blocked, startedAt);
|
|
127
|
+
const samples = settings.samples;
|
|
128
|
+
const count = states.length;
|
|
129
|
+
const choices = options.choices.length > 0 ? options.choices : CLASS_OPTIONS;
|
|
130
|
+
const rendered = Array.from({ length: samples }, () => renderBatchPrompt(states, choices, options.random));
|
|
131
|
+
const gathered = await gatherSamples<BatchAnswer>(
|
|
132
|
+
rt,
|
|
133
|
+
samples,
|
|
134
|
+
settings.timeoutMs,
|
|
135
|
+
new AbortController(),
|
|
136
|
+
async (index, signal) => {
|
|
137
|
+
const batch = rendered[index]!;
|
|
138
|
+
const text = await callHost(batch.prompt, model, signal);
|
|
139
|
+
if (text === null) {
|
|
140
|
+
return { labels: [], raw: null, reason: "host returned no text" };
|
|
141
|
+
}
|
|
142
|
+
return {
|
|
143
|
+
labels: parseBatchLabels(text, count, batch.labels),
|
|
144
|
+
raw: cutRaw(text),
|
|
145
|
+
};
|
|
146
|
+
},
|
|
147
|
+
(answer) => (answer.labels.length > 0 ? answer.labels.join("|") : null),
|
|
148
|
+
);
|
|
149
|
+
const settled: Array<Settled<BatchAnswer>> = gathered.settled;
|
|
150
|
+
const outcomes = states.map((_, item) =>
|
|
151
|
+
resolveOutcome(
|
|
152
|
+
settled.map((s) => (s.kind === "value" ? (s.v.labels[item] ?? null) : null)),
|
|
153
|
+
settled,
|
|
154
|
+
samples,
|
|
155
|
+
gathered.timedOut,
|
|
156
|
+
settings.timeoutMs,
|
|
157
|
+
),
|
|
158
|
+
);
|
|
159
|
+
return finishMany(rt, outcomes, samples, startedAt);
|
|
160
|
+
});
|
|
161
|
+
},
|
|
162
|
+
};
|
|
163
|
+
}
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `openai-compatible` backend: POST `<baseUrl>/chat/completions` on any server
|
|
3
|
+
* that speaks the OpenAI chat protocol (Ollama, vLLM, LM Studio, OpenRouter…).
|
|
4
|
+
*
|
|
5
|
+
* Users point `baseUrl` at the `/v1` root. The API key is read from the
|
|
6
|
+
* environment variable named by `apiKeyEnv` at EACH call, so setting it later
|
|
7
|
+
* enables the backend without a reload; `apiKeyEnv: null` sends no
|
|
8
|
+
* `Authorization` header (local servers). `response_format` json_schema is sent
|
|
9
|
+
* first and dropped for later calls when the server rejects it.
|
|
10
|
+
*
|
|
11
|
+
* Contract: never throws, never retries, `timeoutMs` enforced by racing a timer
|
|
12
|
+
* and aborting the `fetch` signal.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import {
|
|
16
|
+
CLASS_OPTIONS,
|
|
17
|
+
type BackendCallOptions,
|
|
18
|
+
type BackendResult,
|
|
19
|
+
type ClassifierBackend,
|
|
20
|
+
type ClassifierLogger,
|
|
21
|
+
type ClassifierSettings,
|
|
22
|
+
type ClassifierState,
|
|
23
|
+
type EnvLike,
|
|
24
|
+
type FetchLike,
|
|
25
|
+
type TaskClass,
|
|
26
|
+
} from "../types";
|
|
27
|
+
import {
|
|
28
|
+
checkBaseUrl,
|
|
29
|
+
createRuntime,
|
|
30
|
+
cutRaw,
|
|
31
|
+
disabled,
|
|
32
|
+
disabledMany,
|
|
33
|
+
finish,
|
|
34
|
+
finishMany,
|
|
35
|
+
backendUnavailable,
|
|
36
|
+
gatherSamples,
|
|
37
|
+
guarded,
|
|
38
|
+
guardedMany,
|
|
39
|
+
logEffectiveHost,
|
|
40
|
+
parseBatchLabels,
|
|
41
|
+
parseLabel,
|
|
42
|
+
parseModelRef,
|
|
43
|
+
renderBatchPrompt,
|
|
44
|
+
renderSinglePrompt,
|
|
45
|
+
resolveOutcome,
|
|
46
|
+
safeWarn,
|
|
47
|
+
type SampleAnswer,
|
|
48
|
+
type Settled,
|
|
49
|
+
} from "./shared";
|
|
50
|
+
|
|
51
|
+
export interface OpenAICompatibleBackendDeps {
|
|
52
|
+
readonly fetch: FetchLike;
|
|
53
|
+
readonly env: EnvLike;
|
|
54
|
+
readonly settings: ClassifierSettings;
|
|
55
|
+
readonly logger: ClassifierLogger;
|
|
56
|
+
readonly now?: () => number;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const BAD_MODEL = "classifier.model is not provider/model[#variant]";
|
|
60
|
+
const NO_BASE_URL = "classifier.baseUrl is not set";
|
|
61
|
+
|
|
62
|
+
interface Endpoint {
|
|
63
|
+
readonly url: string;
|
|
64
|
+
readonly model: string;
|
|
65
|
+
readonly headers: Record<string, string>;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
interface ChatContent {
|
|
69
|
+
readonly content: string | null;
|
|
70
|
+
readonly reason?: string;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
interface BatchAnswer {
|
|
74
|
+
readonly labels: readonly (TaskClass | null)[];
|
|
75
|
+
readonly raw: string | null;
|
|
76
|
+
readonly reason?: string;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function createOpenAICompatibleBackend(deps: OpenAICompatibleBackendDeps): ClassifierBackend {
|
|
80
|
+
const rt = createRuntime("openai-compatible", deps.logger, deps.now);
|
|
81
|
+
const { settings } = deps;
|
|
82
|
+
logEffectiveHost(rt, settings.baseUrl);
|
|
83
|
+
/** Instance memo: false once the server rejected `response_format`. */
|
|
84
|
+
let jsonSchema = true;
|
|
85
|
+
|
|
86
|
+
/** Resolve URL, model and headers at call time; a string is the `disabled` reason. */
|
|
87
|
+
function endpoint(): Endpoint | string {
|
|
88
|
+
const baseUrl = settings.baseUrl?.trim() ?? "";
|
|
89
|
+
if (baseUrl === "") return NO_BASE_URL;
|
|
90
|
+
const ref = parseModelRef(settings.model ?? "");
|
|
91
|
+
if (ref === null) return BAD_MODEL;
|
|
92
|
+
const headers: Record<string, string> = { "Content-Type": "application/json" };
|
|
93
|
+
let key: string | null = null;
|
|
94
|
+
if (settings.apiKeyEnv) {
|
|
95
|
+
const value = deps.env[settings.apiKeyEnv];
|
|
96
|
+
if (value === undefined || value.trim() === "") return `apiKeyEnv ${settings.apiKeyEnv} is not set`;
|
|
97
|
+
key = value;
|
|
98
|
+
headers.Authorization = `Bearer ${value}`;
|
|
99
|
+
}
|
|
100
|
+
const safe = checkBaseUrl(baseUrl, key !== null);
|
|
101
|
+
if (!safe.ok) return safe.reason;
|
|
102
|
+
return { url: baseUrl.replace(/\/+$/, "") + "/chat/completions", model: ref.id, headers };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function requestBody(
|
|
106
|
+
target: Endpoint,
|
|
107
|
+
system: string,
|
|
108
|
+
user: string,
|
|
109
|
+
labels: readonly string[],
|
|
110
|
+
batchCount: number | null,
|
|
111
|
+
withSchema: boolean,
|
|
112
|
+
): string {
|
|
113
|
+
const schema =
|
|
114
|
+
batchCount === null
|
|
115
|
+
? {
|
|
116
|
+
type: "object",
|
|
117
|
+
properties: { label: { type: "string", enum: labels } },
|
|
118
|
+
required: ["label"],
|
|
119
|
+
additionalProperties: false,
|
|
120
|
+
}
|
|
121
|
+
: {
|
|
122
|
+
type: "object",
|
|
123
|
+
properties: {
|
|
124
|
+
labels: {
|
|
125
|
+
type: "array",
|
|
126
|
+
items: { type: "string", enum: labels },
|
|
127
|
+
minItems: batchCount,
|
|
128
|
+
maxItems: batchCount,
|
|
129
|
+
},
|
|
130
|
+
},
|
|
131
|
+
required: ["labels"],
|
|
132
|
+
additionalProperties: false,
|
|
133
|
+
};
|
|
134
|
+
return JSON.stringify({
|
|
135
|
+
model: target.model,
|
|
136
|
+
temperature: 0,
|
|
137
|
+
max_tokens: batchCount === null ? 20 : 12 * batchCount + 20,
|
|
138
|
+
messages: [
|
|
139
|
+
{ role: "system", content: system },
|
|
140
|
+
{ role: "user", content: user },
|
|
141
|
+
],
|
|
142
|
+
...(withSchema
|
|
143
|
+
? {
|
|
144
|
+
response_format: {
|
|
145
|
+
type: "json_schema",
|
|
146
|
+
json_schema: {
|
|
147
|
+
name: batchCount === null ? "task_class" : "task_classes",
|
|
148
|
+
strict: true,
|
|
149
|
+
schema,
|
|
150
|
+
},
|
|
151
|
+
},
|
|
152
|
+
}
|
|
153
|
+
: {}),
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** One chat request. HTTP failures throw (→ `error`); malformed bodies return a reason (→ `invalid`). */
|
|
158
|
+
async function chat(
|
|
159
|
+
target: Endpoint,
|
|
160
|
+
system: string,
|
|
161
|
+
user: string,
|
|
162
|
+
labels: readonly string[],
|
|
163
|
+
batchCount: number | null,
|
|
164
|
+
signal: AbortSignal,
|
|
165
|
+
): Promise<ChatContent> {
|
|
166
|
+
const withSchema = jsonSchema;
|
|
167
|
+
const response = await deps.fetch(target.url, {
|
|
168
|
+
method: "POST",
|
|
169
|
+
headers: target.headers,
|
|
170
|
+
body: requestBody(target, system, user, labels, batchCount, withSchema),
|
|
171
|
+
signal,
|
|
172
|
+
redirect: "error",
|
|
173
|
+
});
|
|
174
|
+
if (!response.ok) {
|
|
175
|
+
// The status below is the reported failure; the body is read only to detect `response_format` rejection.
|
|
176
|
+
const detail = await response.text().catch(() => "");
|
|
177
|
+
if (withSchema && jsonSchema && (response.status === 400 || response.status === 422) && /response_format/i.test(detail)) {
|
|
178
|
+
jsonSchema = false;
|
|
179
|
+
safeWarn(
|
|
180
|
+
rt.logger,
|
|
181
|
+
"classifier openai-compatible: server rejected response_format json_schema; later calls omit it",
|
|
182
|
+
{ status: response.status },
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
throw new Error(`HTTP ${response.status}`);
|
|
186
|
+
}
|
|
187
|
+
const text = await response.text();
|
|
188
|
+
let parsed: unknown;
|
|
189
|
+
try {
|
|
190
|
+
parsed = JSON.parse(text);
|
|
191
|
+
} catch {
|
|
192
|
+
return { content: null, reason: "non-JSON response" };
|
|
193
|
+
}
|
|
194
|
+
const choices = (parsed as { choices?: unknown } | null)?.choices;
|
|
195
|
+
const first: unknown = Array.isArray(choices) ? choices[0] : undefined;
|
|
196
|
+
const content = (first as { message?: { content?: unknown } } | undefined)?.message?.content;
|
|
197
|
+
if (typeof content !== "string") return { content: null, reason: "missing message content" };
|
|
198
|
+
return { content };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
return {
|
|
202
|
+
id: "openai-compatible",
|
|
203
|
+
|
|
204
|
+
async classify(state: ClassifierState, options: BackendCallOptions): Promise<BackendResult> {
|
|
205
|
+
const startedAt = rt.now();
|
|
206
|
+
return guarded(rt, startedAt, async () => {
|
|
207
|
+
const target = endpoint();
|
|
208
|
+
if (typeof target === "string") return disabled(rt, target, startedAt);
|
|
209
|
+
const blocked = backendUnavailable(rt);
|
|
210
|
+
if (blocked !== null) return disabled(rt, blocked, startedAt);
|
|
211
|
+
const samples = settings.samples;
|
|
212
|
+
const choices = options.choices.length > 0 ? options.choices : CLASS_OPTIONS;
|
|
213
|
+
const rendered = Array.from({ length: samples }, () => renderSinglePrompt(state, choices, options.random));
|
|
214
|
+
const gathered = await gatherSamples<SampleAnswer>(
|
|
215
|
+
rt,
|
|
216
|
+
samples,
|
|
217
|
+
settings.timeoutMs,
|
|
218
|
+
new AbortController(),
|
|
219
|
+
async (index, signal) => {
|
|
220
|
+
const r = rendered[index]!;
|
|
221
|
+
const answer = await chat(target, r.system, r.user, r.labels, null, signal);
|
|
222
|
+
if (answer.content === null) return { label: null, raw: null, reason: answer.reason };
|
|
223
|
+
return { label: parseLabel(answer.content, r.labels), raw: cutRaw(answer.content) };
|
|
224
|
+
},
|
|
225
|
+
(answer) => answer.label,
|
|
226
|
+
);
|
|
227
|
+
const labels = gathered.settled.map((s) => (s.kind === "value" ? s.v.label : null));
|
|
228
|
+
const outcome = resolveOutcome(labels, gathered.settled, samples, gathered.timedOut, settings.timeoutMs);
|
|
229
|
+
return finish(rt, outcome, samples, startedAt);
|
|
230
|
+
});
|
|
231
|
+
},
|
|
232
|
+
|
|
233
|
+
async classifyMany(
|
|
234
|
+
states: readonly ClassifierState[],
|
|
235
|
+
options: BackendCallOptions,
|
|
236
|
+
): Promise<BackendResult[]> {
|
|
237
|
+
if (states.length === 0) return [];
|
|
238
|
+
const startedAt = rt.now();
|
|
239
|
+
return guardedMany(rt, states.length, startedAt, async () => {
|
|
240
|
+
const target = endpoint();
|
|
241
|
+
if (typeof target === "string") return disabledMany(rt, states.length, target, startedAt);
|
|
242
|
+
const blocked = backendUnavailable(rt);
|
|
243
|
+
if (blocked !== null) return disabledMany(rt, states.length, blocked, startedAt);
|
|
244
|
+
const samples = settings.samples;
|
|
245
|
+
const count = states.length;
|
|
246
|
+
const choices = options.choices.length > 0 ? options.choices : CLASS_OPTIONS;
|
|
247
|
+
const rendered = Array.from({ length: samples }, () => renderBatchPrompt(states, choices, options.random));
|
|
248
|
+
const gathered = await gatherSamples<BatchAnswer>(
|
|
249
|
+
rt,
|
|
250
|
+
samples,
|
|
251
|
+
settings.timeoutMs,
|
|
252
|
+
new AbortController(),
|
|
253
|
+
async (index, signal) => {
|
|
254
|
+
const r = rendered[index]!;
|
|
255
|
+
const answer = await chat(target, r.system, r.user, r.labels, count, signal);
|
|
256
|
+
if (answer.content === null) return { labels: [], raw: null, reason: answer.reason };
|
|
257
|
+
return { labels: parseBatchLabels(answer.content, count, r.labels), raw: cutRaw(answer.content) };
|
|
258
|
+
},
|
|
259
|
+
(answer) => (answer.labels.length > 0 ? answer.labels.join("|") : null),
|
|
260
|
+
);
|
|
261
|
+
const settled: Array<Settled<BatchAnswer>> = gathered.settled;
|
|
262
|
+
const outcomes = states.map((_, item) =>
|
|
263
|
+
resolveOutcome(
|
|
264
|
+
settled.map((s) => (s.kind === "value" ? (s.v.labels[item] ?? null) : null)),
|
|
265
|
+
settled,
|
|
266
|
+
samples,
|
|
267
|
+
gathered.timedOut,
|
|
268
|
+
settings.timeoutMs,
|
|
269
|
+
),
|
|
270
|
+
);
|
|
271
|
+
return finishMany(rt, outcomes, samples, startedAt);
|
|
272
|
+
});
|
|
273
|
+
},
|
|
274
|
+
};
|
|
275
|
+
}
|