@hop-top/kit 0.4.0-alpha.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.
Files changed (174) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/LICENSE +25 -0
  3. package/README.md +189 -0
  4. package/dist/aim.d.ts +116 -0
  5. package/dist/aim.js +417 -0
  6. package/dist/alias.d.ts +73 -0
  7. package/dist/alias.js +207 -0
  8. package/dist/api.d.ts +62 -0
  9. package/dist/api.js +165 -0
  10. package/dist/auth.d.ts +26 -0
  11. package/dist/auth.js +41 -0
  12. package/dist/cli.d.ts +309 -0
  13. package/dist/cli.js +885 -0
  14. package/dist/config.d.ts +97 -0
  15. package/dist/config.js +79 -0
  16. package/dist/errcorrect.d.ts +37 -0
  17. package/dist/errcorrect.js +69 -0
  18. package/dist/llm.d.ts +188 -0
  19. package/dist/llm.js +356 -0
  20. package/dist/output.d.ts +213 -0
  21. package/dist/output.js +447 -0
  22. package/dist/progress.d.ts +30 -0
  23. package/dist/progress.js +56 -0
  24. package/dist/provenance.d.ts +24 -0
  25. package/dist/provenance.js +32 -0
  26. package/dist/routellm.d.ts +64 -0
  27. package/dist/routellm.js +258 -0
  28. package/dist/rpc.d.ts +25 -0
  29. package/dist/rpc.js +101 -0
  30. package/dist/safety.d.ts +24 -0
  31. package/dist/safety.js +44 -0
  32. package/dist/scope.d.ts +121 -0
  33. package/dist/scope.js +380 -0
  34. package/dist/sqlstore.d.ts +84 -0
  35. package/dist/sqlstore.js +85 -0
  36. package/dist/stream.d.ts +35 -0
  37. package/dist/stream.js +52 -0
  38. package/dist/tui/index.d.ts +300 -0
  39. package/dist/tui/index.js +332 -0
  40. package/dist/upgrade.d.ts +95 -0
  41. package/dist/upgrade.js +115 -0
  42. package/dist/xdg.d.ts +169 -0
  43. package/dist/xdg.js +129 -0
  44. package/eslint.config.mjs +17 -0
  45. package/package.json +133 -0
  46. package/src/README.md +3 -0
  47. package/src/aim.test.ts +331 -0
  48. package/src/aim.ts +388 -0
  49. package/src/alias.test.ts +423 -0
  50. package/src/alias.ts +256 -0
  51. package/src/api.test.ts +190 -0
  52. package/src/api.ts +214 -0
  53. package/src/auth.test.ts +24 -0
  54. package/src/auth.ts +37 -0
  55. package/src/bus.test.ts +178 -0
  56. package/src/bus.ts +114 -0
  57. package/src/cli.test.ts +690 -0
  58. package/src/cli.ts +741 -0
  59. package/src/completion-values.test.ts +202 -0
  60. package/src/completion-values.ts +173 -0
  61. package/src/completion.test.ts +212 -0
  62. package/src/completion.ts +158 -0
  63. package/src/compliance.test.ts +134 -0
  64. package/src/compliance.ts +669 -0
  65. package/src/config.test.ts +110 -0
  66. package/src/config.ts +164 -0
  67. package/src/errcorrect.test.ts +134 -0
  68. package/src/errcorrect.ts +84 -0
  69. package/src/flagregister.test.ts +103 -0
  70. package/src/flagregister.ts +78 -0
  71. package/src/gen/crud_connect.ts +76 -0
  72. package/src/gen/crud_pb.ts +269 -0
  73. package/src/hint.test.ts +315 -0
  74. package/src/hint.ts +178 -0
  75. package/src/llm.test.ts +612 -0
  76. package/src/llm.ts +577 -0
  77. package/src/log.test.ts +145 -0
  78. package/src/log.ts +155 -0
  79. package/src/output/builtins.ts +34 -0
  80. package/src/output/dispatch.ts +195 -0
  81. package/src/output/flags.ts +151 -0
  82. package/src/output/format_help.ts +80 -0
  83. package/src/output/formatter.ts +167 -0
  84. package/src/output/formatters/csv.ts +72 -0
  85. package/src/output/formatters/json.ts +44 -0
  86. package/src/output/formatters/table.ts +44 -0
  87. package/src/output/formatters/text.ts +109 -0
  88. package/src/output/formatters/yaml.ts +47 -0
  89. package/src/output/projection.ts +126 -0
  90. package/src/output/registry.ts +88 -0
  91. package/src/output/template.ts +63 -0
  92. package/src/output.test.ts +117 -0
  93. package/src/output.ts +90 -0
  94. package/src/progress.test.ts +93 -0
  95. package/src/progress.ts +58 -0
  96. package/src/provenance.test.ts +59 -0
  97. package/src/provenance.ts +26 -0
  98. package/src/routellm.test.ts +179 -0
  99. package/src/routellm.ts +365 -0
  100. package/src/router/bert.test.ts +180 -0
  101. package/src/router/bert.ts +145 -0
  102. package/src/router/controller.test.ts +183 -0
  103. package/src/router/controller.ts +165 -0
  104. package/src/router/integration.test.ts +309 -0
  105. package/src/router/intent.test.ts +187 -0
  106. package/src/router/intent.ts +208 -0
  107. package/src/router/mf.test.ts +66 -0
  108. package/src/router/mf.ts +52 -0
  109. package/src/router/random.test.ts +23 -0
  110. package/src/router/random.ts +13 -0
  111. package/src/router/router.test.ts +31 -0
  112. package/src/router/router.ts +62 -0
  113. package/src/router/server.test.ts +193 -0
  114. package/src/router/server.ts +134 -0
  115. package/src/router/sw.test.ts +199 -0
  116. package/src/router/sw.ts +232 -0
  117. package/src/rpc.test.ts +47 -0
  118. package/src/rpc.ts +91 -0
  119. package/src/safety.test.ts +53 -0
  120. package/src/safety.ts +42 -0
  121. package/src/scope-defaults.json +72 -0
  122. package/src/scope.test.ts +177 -0
  123. package/src/scope.ts +382 -0
  124. package/src/setflag.test.ts +110 -0
  125. package/src/setflag.ts +102 -0
  126. package/src/sqlstore.test.ts +110 -0
  127. package/src/sqlstore.ts +144 -0
  128. package/src/stream.test.ts +69 -0
  129. package/src/stream.ts +47 -0
  130. package/src/textflag.test.ts +105 -0
  131. package/src/textflag.ts +68 -0
  132. package/src/toolspec.test.ts +187 -0
  133. package/src/toolspec.ts +279 -0
  134. package/src/triton/client.test.ts +205 -0
  135. package/src/triton/client.ts +261 -0
  136. package/src/tui/anim.test.ts +146 -0
  137. package/src/tui/anim.ts +134 -0
  138. package/src/tui/badge.test.ts +41 -0
  139. package/src/tui/badge.ts +55 -0
  140. package/src/tui/confirm.test.ts +68 -0
  141. package/src/tui/confirm.ts +49 -0
  142. package/src/tui/index.ts +29 -0
  143. package/src/tui/list.test.ts +84 -0
  144. package/src/tui/list.ts +72 -0
  145. package/src/tui/parity.ts +41 -0
  146. package/src/tui/pills.test.ts +40 -0
  147. package/src/tui/pills.ts +43 -0
  148. package/src/tui/progress.test.ts +164 -0
  149. package/src/tui/progress.ts +120 -0
  150. package/src/tui/spinner.test.ts +111 -0
  151. package/src/tui/spinner.ts +96 -0
  152. package/src/tui/status.test.ts +68 -0
  153. package/src/tui/status.ts +66 -0
  154. package/src/upgrade.test.ts +298 -0
  155. package/src/upgrade.ts +205 -0
  156. package/src/uri.ts +199 -0
  157. package/src/wizard.test.ts +441 -0
  158. package/src/wizard.ts +662 -0
  159. package/src/xdg.test.ts +202 -0
  160. package/src/xdg.ts +280 -0
  161. package/test/output/cols.test.ts +148 -0
  162. package/test/output/csv.test.ts +129 -0
  163. package/test/output/dispatch.test.ts +194 -0
  164. package/test/output/format_help.test.ts +131 -0
  165. package/test/output/formatter.test.ts +137 -0
  166. package/test/output/output_flag.test.ts +124 -0
  167. package/test/output/registry.test.ts +127 -0
  168. package/test/output/smoke-capture.ts +83 -0
  169. package/test/output/smoke.test.ts +142 -0
  170. package/test/output/template.test.ts +95 -0
  171. package/test/output/text.test.ts +75 -0
  172. package/test/testdata/api-fixture.json +115 -0
  173. package/test/testdata/query-vectors.json +187 -0
  174. package/tsconfig.json +12 -0
@@ -0,0 +1,365 @@
1
+ /**
2
+ * @packageDocumentation
3
+ *
4
+ * RouteLLM adapter — registers the `routellm` URI scheme.
5
+ *
6
+ * URI format: `routellm://router_name:threshold` (e.g. `routellm://mf:0.7`).
7
+ *
8
+ * Delegates HTTP completions to an OpenAI-compatible endpoint on the
9
+ * RouteLLM server, translating the model field into the server's
10
+ * expected `router-[name]-[threshold]` format.
11
+ */
12
+
13
+ import {
14
+ type Completer,
15
+ type Streamer,
16
+ type Request,
17
+ type Response,
18
+ type Token,
19
+ type ResolvedConfig,
20
+ type Provider,
21
+ LLMError,
22
+ register,
23
+ } from "./llm";
24
+
25
+ // ─── RouterConfig ─────────────────────────────────────────────────────────────
26
+
27
+ export interface EvaConfig {
28
+ contracts: string[];
29
+ enforce: boolean;
30
+ }
31
+
32
+ export interface RouterConfig {
33
+ baseUrl: string;
34
+ grpcPort: number;
35
+ strongModel: string;
36
+ weakModel: string;
37
+ routers: string[];
38
+ routerConfig: Record<string, unknown>;
39
+ eva: EvaConfig;
40
+ autostart: boolean;
41
+ }
42
+
43
+ function defaultRouterConfig(): RouterConfig {
44
+ return {
45
+ baseUrl: "http://localhost:6060",
46
+ grpcPort: 6061,
47
+ strongModel: "",
48
+ weakModel: "",
49
+ routers: [],
50
+ routerConfig: {},
51
+ eva: { contracts: [], enforce: false },
52
+ autostart: false,
53
+ };
54
+ }
55
+
56
+ /**
57
+ * Extract and validate RouteLLM configuration from provider extras.
58
+ * Environment variables override all other sources.
59
+ */
60
+ export function parseRouterConfig(
61
+ extras?: Record<string, unknown>
62
+ ): RouterConfig {
63
+ const cfg = defaultRouterConfig();
64
+
65
+ if (extras) {
66
+ const raw = extras["routellm"];
67
+ if (raw !== undefined) {
68
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
69
+ throw new LLMError(
70
+ `routellm: expected map, got ${typeof raw}`
71
+ );
72
+ }
73
+ const sub = raw as Record<string, unknown>;
74
+
75
+ if (typeof sub["base_url"] === "string") cfg.baseUrl = sub["base_url"];
76
+ if (typeof sub["grpc_port"] === "number") cfg.grpcPort = sub["grpc_port"];
77
+ if (typeof sub["strong_model"] === "string") {
78
+ cfg.strongModel = sub["strong_model"];
79
+ }
80
+ if (typeof sub["weak_model"] === "string") {
81
+ cfg.weakModel = sub["weak_model"];
82
+ }
83
+ if (Array.isArray(sub["routers"])) {
84
+ cfg.routers = sub["routers"].filter(
85
+ (r): r is string => typeof r === "string"
86
+ );
87
+ }
88
+ if (
89
+ typeof sub["router_config"] === "object" &&
90
+ sub["router_config"] !== null &&
91
+ !Array.isArray(sub["router_config"])
92
+ ) {
93
+ cfg.routerConfig = sub["router_config"] as Record<string, unknown>;
94
+ }
95
+ if (typeof sub["eva"] === "object" && sub["eva"] !== null) {
96
+ const e = sub["eva"] as Record<string, unknown>;
97
+ if (Array.isArray(e["contracts"])) {
98
+ cfg.eva.contracts = e["contracts"].filter(
99
+ (c): c is string => typeof c === "string"
100
+ );
101
+ }
102
+ if (typeof e["enforce"] === "boolean") cfg.eva.enforce = e["enforce"];
103
+ }
104
+ if (typeof sub["autostart"] === "boolean") {
105
+ cfg.autostart = sub["autostart"];
106
+ }
107
+ }
108
+ }
109
+
110
+ // Environment variable overrides (highest precedence).
111
+ const envBaseUrl = process.env["ROUTELLM_BASE_URL"];
112
+ if (envBaseUrl) cfg.baseUrl = envBaseUrl;
113
+
114
+ const envStrong = process.env["ROUTELLM_STRONG_MODEL"];
115
+ if (envStrong) cfg.strongModel = envStrong;
116
+
117
+ const envWeak = process.env["ROUTELLM_WEAK_MODEL"];
118
+ if (envWeak) cfg.weakModel = envWeak;
119
+
120
+ const envRouters = process.env["ROUTELLM_ROUTERS"];
121
+ if (envRouters) {
122
+ cfg.routers = envRouters
123
+ .split(",")
124
+ .map((r) => r.trim())
125
+ .filter(Boolean);
126
+ }
127
+
128
+ return cfg;
129
+ }
130
+
131
+ // ─── Model field parsing ──────────────────────────────────────────────────────
132
+
133
+ export interface ParsedModel {
134
+ routerName: string;
135
+ threshold: number;
136
+ }
137
+
138
+ /**
139
+ * Split a model string of the form `router_name:threshold` into its
140
+ * components.
141
+ */
142
+ export function parseModelField(model: string): ParsedModel {
143
+ if (!model) {
144
+ throw new LLMError(
145
+ "model field is required (format: router_name:threshold)"
146
+ );
147
+ }
148
+
149
+ const idx = model.indexOf(":");
150
+ if (idx < 0) {
151
+ throw new LLMError(
152
+ `invalid model "${model}": expected format ` +
153
+ "router_name:threshold (e.g. mf:0.7)"
154
+ );
155
+ }
156
+
157
+ const routerName = model.slice(0, idx);
158
+ const rawThreshold = model.slice(idx + 1);
159
+
160
+ if (!routerName || !rawThreshold) {
161
+ throw new LLMError(
162
+ `invalid model "${model}": expected format ` +
163
+ "router_name:threshold (e.g. mf:0.7)"
164
+ );
165
+ }
166
+
167
+ const threshold = Number(rawThreshold);
168
+ if (Number.isNaN(threshold)) {
169
+ throw new LLMError(`invalid threshold "${rawThreshold}": not a number`);
170
+ }
171
+
172
+ return { routerName, threshold };
173
+ }
174
+
175
+ // ─── Adapter ──────────────────────────────────────────────────────────────────
176
+
177
+ /**
178
+ * RouteLLM adapter implementing Completer and Streamer.
179
+ *
180
+ * Delegates to an OpenAI-compatible HTTP endpoint on the RouteLLM
181
+ * server using the standard fetch API.
182
+ */
183
+ export class RouteLLMAdapter implements Completer, Streamer {
184
+ readonly config: RouterConfig;
185
+ readonly routerName: string;
186
+ readonly threshold: number;
187
+
188
+ private readonly _baseUrl: string;
189
+ private readonly _serverModel: string;
190
+ private readonly _apiKey: string;
191
+
192
+ constructor(cfg: ResolvedConfig) {
193
+ this.config = parseRouterConfig(cfg.provider.extras);
194
+
195
+ const model = cfg.provider.model || cfg.uri.model;
196
+ const parsed = parseModelField(model);
197
+ this.routerName = parsed.routerName;
198
+ this.threshold = parsed.threshold;
199
+
200
+ if (this.threshold < 0 || this.threshold > 1) {
201
+ throw new LLMError(
202
+ `routellm: threshold ${this.threshold} out of range [0, 1]`
203
+ );
204
+ }
205
+
206
+ // Build server model name: router-[name]-[threshold]
207
+ this._serverModel = `router-${this.routerName}-${this.threshold}`;
208
+
209
+ // Resolve base URL: config > provider > default.
210
+ let baseUrl = this.config.baseUrl;
211
+ if (baseUrl === "http://localhost:6060" && cfg.provider.baseURL) {
212
+ baseUrl = cfg.provider.baseURL;
213
+ }
214
+ this._baseUrl = baseUrl;
215
+ this._apiKey = cfg.provider.apiKey ?? "";
216
+ }
217
+
218
+ async complete(req: Request): Promise<Response> {
219
+ const body = this._buildBody(req, false);
220
+ const resp = await this._post("/v1/chat/completions", body);
221
+
222
+ const data = (await resp.json()) as OpenAIChatResponse;
223
+ const choice = data.choices?.[0];
224
+ const content = choice?.message?.content ?? "";
225
+ const finishReason = choice?.finish_reason ?? "";
226
+
227
+ const usage = data.usage
228
+ ? {
229
+ promptTokens: data.usage.prompt_tokens ?? 0,
230
+ completionTokens: data.usage.completion_tokens ?? 0,
231
+ totalTokens: data.usage.total_tokens ?? 0,
232
+ }
233
+ : undefined;
234
+
235
+ return { content, role: "assistant", usage, finishReason };
236
+ }
237
+
238
+ async *stream(req: Request): AsyncGenerator<Token> {
239
+ const body = this._buildBody(req, true);
240
+ const resp = await this._post("/v1/chat/completions", body);
241
+
242
+ if (!resp.body) {
243
+ throw new LLMError("routellm: streaming response has no body");
244
+ }
245
+
246
+ const reader = resp.body.getReader();
247
+ const decoder = new TextDecoder();
248
+ let buf = "";
249
+
250
+ try {
251
+ for (;;) {
252
+ const { done, value } = await reader.read();
253
+ if (done) break;
254
+
255
+ buf += decoder.decode(value, { stream: true });
256
+ const lines = buf.split("\n");
257
+ buf = lines.pop() ?? "";
258
+
259
+ for (const line of lines) {
260
+ const trimmed = line.trim();
261
+ if (!trimmed || !trimmed.startsWith("data: ")) continue;
262
+ const payload = trimmed.slice(6);
263
+ if (payload === "[DONE]") {
264
+ yield { content: "", done: true };
265
+ return;
266
+ }
267
+
268
+ const chunk = JSON.parse(payload) as OpenAIStreamChunk;
269
+ const delta = chunk.choices?.[0]?.delta;
270
+ const content = delta?.content ?? "";
271
+ const isDone = chunk.choices?.[0]?.finish_reason != null;
272
+ yield { content, done: isDone };
273
+ }
274
+ }
275
+ } finally {
276
+ reader.releaseLock();
277
+ }
278
+ }
279
+
280
+ close(): void {
281
+ // No persistent resources to release.
282
+ }
283
+
284
+ // ── private ────────────────────────────────────────────────────
285
+
286
+ private _buildBody(
287
+ req: Request,
288
+ stream: boolean
289
+ ): Record<string, unknown> {
290
+ const body: Record<string, unknown> = {
291
+ model: this._serverModel,
292
+ messages: req.messages.map((m) => ({
293
+ role: m.role,
294
+ content: m.content,
295
+ })),
296
+ stream,
297
+ };
298
+ if (req.temperature !== undefined) body["temperature"] = req.temperature;
299
+ if (req.maxTokens !== undefined) body["max_tokens"] = req.maxTokens;
300
+ if (req.stopSequences?.length) body["stop"] = req.stopSequences;
301
+ return body;
302
+ }
303
+
304
+ private async _post(
305
+ path: string,
306
+ body: Record<string, unknown>
307
+ ): Promise<globalThis.Response> {
308
+ const url = `${this._baseUrl}${path}`;
309
+ const headers: Record<string, string> = {
310
+ "Content-Type": "application/json",
311
+ };
312
+ if (this._apiKey) {
313
+ headers["Authorization"] = `Bearer ${this._apiKey}`;
314
+ }
315
+
316
+ const resp = await fetch(url, {
317
+ method: "POST",
318
+ headers,
319
+ body: JSON.stringify(body),
320
+ });
321
+
322
+ if (!resp.ok) {
323
+ const text = await resp.text().catch(() => "");
324
+ throw new LLMError(
325
+ `routellm: HTTP ${resp.status} from ${url}: ${text}`
326
+ );
327
+ }
328
+
329
+ return resp;
330
+ }
331
+ }
332
+
333
+ // ─── OpenAI-compatible response types (internal) ──────────────────────────────
334
+
335
+ interface OpenAIChatResponse {
336
+ choices?: {
337
+ message?: { content?: string; role?: string };
338
+ finish_reason?: string;
339
+ }[];
340
+ usage?: {
341
+ prompt_tokens?: number;
342
+ completion_tokens?: number;
343
+ total_tokens?: number;
344
+ };
345
+ }
346
+
347
+ interface OpenAIStreamChunk {
348
+ choices?: {
349
+ delta?: { content?: string; role?: string };
350
+ finish_reason?: string | null;
351
+ }[];
352
+ }
353
+
354
+ // ─── Registration ─────────────────────────────────────────────────────────────
355
+
356
+ function routellmFactory(cfg: ResolvedConfig): Provider {
357
+ const adapter = new RouteLLMAdapter(cfg);
358
+ return {
359
+ complete: (req) => adapter.complete(req),
360
+ stream: (req) => adapter.stream(req),
361
+ close: () => adapter.close(),
362
+ };
363
+ }
364
+
365
+ register("routellm", routellmFactory);
@@ -0,0 +1,180 @@
1
+ import { describe, it, expect, vi } from "vitest";
2
+ import { BERTRouter, softmax } from "./bert";
3
+ import type { Tokenizer, TritonInfer } from "./bert";
4
+ import type { InferRequest, InferResponse } from "../triton/client";
5
+
6
+ // ─── softmax ─────────────────────────────────────────────────────────────────
7
+
8
+ describe("softmax", () => {
9
+ it("sums to 1", () => {
10
+ const probs = softmax([1, 2, 3]);
11
+ const sum = probs.reduce((a, b) => a + b, 0);
12
+ expect(sum).toBeCloseTo(1);
13
+ });
14
+
15
+ it("highest logit gets highest probability", () => {
16
+ const probs = softmax([1, 5, 2]);
17
+ expect(probs[1]).toBeGreaterThan(probs[0]);
18
+ expect(probs[1]).toBeGreaterThan(probs[2]);
19
+ });
20
+
21
+ it("equal logits give uniform distribution", () => {
22
+ const probs = softmax([3, 3, 3]);
23
+ expect(probs[0]).toBeCloseTo(1 / 3);
24
+ expect(probs[1]).toBeCloseTo(1 / 3);
25
+ expect(probs[2]).toBeCloseTo(1 / 3);
26
+ });
27
+
28
+ it("handles large logits without overflow", () => {
29
+ const probs = softmax([1000, 1001, 1002]);
30
+ const sum = probs.reduce((a, b) => a + b, 0);
31
+ expect(sum).toBeCloseTo(1);
32
+ });
33
+
34
+ it("handles negative logits", () => {
35
+ const probs = softmax([-5, -3, -1]);
36
+ const sum = probs.reduce((a, b) => a + b, 0);
37
+ expect(sum).toBeCloseTo(1);
38
+ expect(probs[2]).toBeGreaterThan(probs[0]);
39
+ });
40
+ });
41
+
42
+ // ─── BERTRouter ──────────────────────────────────────────────────────────────
43
+
44
+ function stubTokenizer(): Tokenizer {
45
+ return {
46
+ encode: vi.fn((_text: string) => ({
47
+ inputIds: [101, 2023, 2003, 1037, 3231, 102],
48
+ attentionMask: [1, 1, 1, 1, 1, 1],
49
+ })),
50
+ };
51
+ }
52
+
53
+ function mockTritonInfer(logits: number[]): TritonInfer {
54
+ return {
55
+ infer: vi.fn(async (_req: InferRequest): Promise<InferResponse> => ({
56
+ model_name: "bert",
57
+ outputs: [
58
+ {
59
+ name: "logits",
60
+ shape: [1, logits.length],
61
+ datatype: "FP32",
62
+ data: logits,
63
+ },
64
+ ],
65
+ })),
66
+ };
67
+ }
68
+
69
+ describe("BERTRouter", () => {
70
+ it("high strong-win logit yields high score", async () => {
71
+ // logits: [strong_wins=10, tie=0, weak_wins=0]
72
+ const triton = mockTritonInfer([10, 0, 0]);
73
+ const router = new BERTRouter({
74
+ triton,
75
+ tokenizer: stubTokenizer(),
76
+ });
77
+
78
+ const score = await router.score("test prompt");
79
+ // softmax([10,0,0]) ~ [0.9999, ~0, ~0]
80
+ // binaryProb = ~0 + ~0 ~ 0, score = 1 - ~0 ~ 1
81
+ expect(score).toBeGreaterThan(0.95);
82
+ });
83
+
84
+ it("high weak-win logit yields low score", async () => {
85
+ // logits: [strong_wins=0, tie=0, weak_wins=10]
86
+ const triton = mockTritonInfer([0, 0, 10]);
87
+ const router = new BERTRouter({
88
+ triton,
89
+ tokenizer: stubTokenizer(),
90
+ });
91
+
92
+ const score = await router.score("test prompt");
93
+ // binaryProb = softmax[1] + softmax[2] ~ 0 + ~1 ~ 1
94
+ // score = 1 - 1 ~ 0
95
+ expect(score).toBeLessThan(0.05);
96
+ });
97
+
98
+ it("equal logits yield moderate score", async () => {
99
+ const triton = mockTritonInfer([1, 1, 1]);
100
+ const router = new BERTRouter({
101
+ triton,
102
+ tokenizer: stubTokenizer(),
103
+ });
104
+
105
+ const score = await router.score("test");
106
+ // binaryProb = 1/3 + 1/3 = 2/3, score = 1/3
107
+ expect(score).toBeCloseTo(1 / 3, 2);
108
+ });
109
+
110
+ it("sends correct input tensor names", async () => {
111
+ const triton = mockTritonInfer([1, 1, 1]);
112
+ const router = new BERTRouter({
113
+ triton,
114
+ tokenizer: stubTokenizer(),
115
+ });
116
+
117
+ await router.score("test");
118
+ const call = (triton.infer as ReturnType<typeof vi.fn>).mock.calls[0];
119
+ const req = call[0] as InferRequest;
120
+ expect(req.inputs[0].name).toBe("input_ids");
121
+ expect(req.inputs[1].name).toBe("attention_mask");
122
+ expect(req.outputs![0].name).toBe("logits");
123
+ });
124
+
125
+ it("uses custom tensor names", async () => {
126
+ const triton: TritonInfer = {
127
+ infer: vi.fn(async () => ({
128
+ model_name: "bert",
129
+ outputs: [
130
+ {
131
+ name: "custom_out",
132
+ shape: [1, 3],
133
+ datatype: "FP32" as const,
134
+ data: [1, 1, 1],
135
+ },
136
+ ],
137
+ })),
138
+ };
139
+
140
+ const router = new BERTRouter({
141
+ triton,
142
+ tokenizer: stubTokenizer(),
143
+ inputIdsName: "ids",
144
+ attentionMaskName: "mask",
145
+ outputName: "custom_out",
146
+ });
147
+
148
+ await router.score("test");
149
+ const req = (triton.infer as ReturnType<typeof vi.fn>).mock
150
+ .calls[0][0] as InferRequest;
151
+ expect(req.inputs[0].name).toBe("ids");
152
+ expect(req.inputs[1].name).toBe("mask");
153
+ });
154
+
155
+ it("returns 1 when output is empty (defaults to strong)", async () => {
156
+ const triton: TritonInfer = {
157
+ infer: vi.fn(async () => ({
158
+ model_name: "bert",
159
+ outputs: [],
160
+ })),
161
+ };
162
+
163
+ const router = new BERTRouter({
164
+ triton,
165
+ tokenizer: stubTokenizer(),
166
+ });
167
+
168
+ const score = await router.score("test");
169
+ expect(score).toBe(1);
170
+ });
171
+
172
+ it("tokenizer receives the prompt text", async () => {
173
+ const tokenizer = stubTokenizer();
174
+ const triton = mockTritonInfer([1, 1, 1]);
175
+ const router = new BERTRouter({ triton, tokenizer });
176
+
177
+ await router.score("my special prompt");
178
+ expect(tokenizer.encode).toHaveBeenCalledWith("my special prompt");
179
+ });
180
+ });
@@ -0,0 +1,145 @@
1
+ /**
2
+ * BERTRouter — BERT-based sequence classification router.
3
+ *
4
+ * Tokenizes the prompt, sends token IDs and attention mask to a
5
+ * Triton-hosted BERT model, applies softmax to logits, and returns
6
+ * the strong-model win rate.
7
+ *
8
+ * Port of Python's BERTRouter from routellm/routers/routers.py.
9
+ */
10
+
11
+ import type { Router } from "./router";
12
+ import type { InferRequest, InferResponse } from "../triton/client";
13
+
14
+ // ─── Tokenizer interface (stubbed) ──────────────────────────────────────────
15
+
16
+ /** Tokenizer output — mirrors HuggingFace tokenizer output shape. */
17
+ export interface TokenizerOutput {
18
+ inputIds: number[];
19
+ attentionMask: number[];
20
+ }
21
+
22
+ /**
23
+ * Tokenizer interface for BERT.
24
+ *
25
+ * Implementations should handle padding, truncation, and special tokens
26
+ * (CLS, SEP, etc.) internally.
27
+ */
28
+ export interface Tokenizer {
29
+ encode(text: string): TokenizerOutput;
30
+ }
31
+
32
+ // ─── Triton caller interface ─────────────────────────────────────────────────
33
+
34
+ /**
35
+ * Sends raw inference requests to Triton.
36
+ * Separated from TritonClient so tests can inject a mock.
37
+ */
38
+ export interface TritonInfer {
39
+ infer(request: InferRequest): Promise<InferResponse>;
40
+ }
41
+
42
+ // ─── Math helpers ────────────────────────────────────────────────────────────
43
+
44
+ /**
45
+ * Softmax over an array of logits.
46
+ *
47
+ * Subtracts max for numerical stability, then normalizes.
48
+ */
49
+ export function softmax(logits: number[]): number[] {
50
+ const maxVal = Math.max(...logits);
51
+ const exps = logits.map((v) => Math.exp(v - maxVal));
52
+ const sum = exps.reduce((a, b) => a + b, 0);
53
+ return exps.map((e) => e / sum);
54
+ }
55
+
56
+ // ─── Options ─────────────────────────────────────────────────────────────────
57
+
58
+ export interface BERTRouterOptions {
59
+ /** Triton inference caller for the BERT model. */
60
+ triton: TritonInfer;
61
+ /** Tokenizer for the BERT model. */
62
+ tokenizer: Tokenizer;
63
+ /** Number of output labels (default: 3). */
64
+ numLabels?: number;
65
+ /** Name for the input_ids tensor (default: "input_ids"). */
66
+ inputIdsName?: string;
67
+ /** Name for the attention_mask tensor (default: "attention_mask"). */
68
+ attentionMaskName?: string;
69
+ /** Name for the output logits tensor (default: "logits"). */
70
+ outputName?: string;
71
+ }
72
+
73
+ // ─── Router ──────────────────────────────────────────────────────────────────
74
+
75
+ export class BERTRouter implements Router {
76
+ private readonly _triton: TritonInfer;
77
+ private readonly _tokenizer: Tokenizer;
78
+ private readonly _numLabels: number;
79
+ private readonly _inputIdsName: string;
80
+ private readonly _attentionMaskName: string;
81
+ private readonly _outputName: string;
82
+
83
+ constructor(opts: BERTRouterOptions) {
84
+ this._triton = opts.triton;
85
+ this._tokenizer = opts.tokenizer;
86
+ this._numLabels = opts.numLabels ?? 3;
87
+ this._inputIdsName = opts.inputIdsName ?? "input_ids";
88
+ this._attentionMaskName = opts.attentionMaskName ?? "attention_mask";
89
+ this._outputName = opts.outputName ?? "logits";
90
+ }
91
+
92
+ /**
93
+ * Score a prompt using BERT classification.
94
+ *
95
+ * 1. Tokenize the prompt.
96
+ * 2. Send input_ids + attention_mask to Triton.
97
+ * 3. Apply softmax to logits.
98
+ * 4. Compute strong-model win rate as 1 - P(tie or weak wins).
99
+ *
100
+ * The Python code uses the last two softmax classes as the
101
+ * "binary probability" of tie + weak winning.
102
+ */
103
+ async score(prompt: string): Promise<number> {
104
+ const { inputIds, attentionMask } = this._tokenizer.encode(prompt);
105
+
106
+ const request: InferRequest = {
107
+ inputs: [
108
+ {
109
+ name: this._inputIdsName,
110
+ shape: [1, inputIds.length],
111
+ datatype: "INT64",
112
+ data: inputIds,
113
+ },
114
+ {
115
+ name: this._attentionMaskName,
116
+ shape: [1, attentionMask.length],
117
+ datatype: "INT64",
118
+ data: attentionMask,
119
+ },
120
+ ],
121
+ outputs: [{ name: this._outputName }],
122
+ };
123
+
124
+ const response = await this._triton.infer(request);
125
+ const logitsOutput = response.outputs.find(
126
+ (o) => o.name === this._outputName,
127
+ );
128
+
129
+ if (!logitsOutput || !logitsOutput.data.length) {
130
+ // Default to strong model on error.
131
+ return 1;
132
+ }
133
+
134
+ const logits = logitsOutput.data.slice(0, this._numLabels) as number[];
135
+ const probs = softmax(logits);
136
+
137
+ // binaryProb = sum of last 2 classes (tie + weak wins).
138
+ const binaryProb =
139
+ probs.length >= 2
140
+ ? probs[probs.length - 2] + probs[probs.length - 1]
141
+ : 0;
142
+
143
+ return 1 - binaryProb;
144
+ }
145
+ }