@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,187 @@
1
+ import { describe, it, expect, vi } from "vitest";
2
+ import {
3
+ IntentModelSelector,
4
+ IntentDetector,
5
+ cosineSimilarity,
6
+ dot,
7
+ norm,
8
+ } from "./intent";
9
+ import type { ModelPair } from "./router";
10
+
11
+ // ─── Math helpers ────────────────────────────────────────────────────────────
12
+
13
+ describe("dot", () => {
14
+ it("computes dot product", () => {
15
+ expect(dot([1, 2, 3], [4, 5, 6])).toBe(32);
16
+ });
17
+ });
18
+
19
+ describe("norm", () => {
20
+ it("computes L2 norm", () => {
21
+ expect(norm([3, 4])).toBe(5);
22
+ });
23
+ });
24
+
25
+ describe("cosineSimilarity", () => {
26
+ it("returns 1 for identical vectors", () => {
27
+ expect(cosineSimilarity([1, 0], [1, 0])).toBeCloseTo(1);
28
+ });
29
+
30
+ it("returns 0 for orthogonal vectors", () => {
31
+ expect(cosineSimilarity([1, 0], [0, 1])).toBeCloseTo(0);
32
+ });
33
+
34
+ it("returns 0 for zero vector", () => {
35
+ expect(cosineSimilarity([0, 0], [1, 0])).toBe(0);
36
+ });
37
+
38
+ it("returns -1 for opposite vectors", () => {
39
+ expect(cosineSimilarity([1, 0], [-1, 0])).toBeCloseTo(-1);
40
+ });
41
+ });
42
+
43
+ // ─── IntentModelSelector ─────────────────────────────────────────────────────
44
+
45
+ describe("IntentModelSelector", () => {
46
+ const codePair: ModelPair = { strong: "gpt-4", weak: "gpt-3.5" };
47
+ const writingPair: ModelPair = {
48
+ strong: "claude-3",
49
+ weak: "mixtral",
50
+ };
51
+ const defaultPair: ModelPair = {
52
+ strong: "default-s",
53
+ weak: "default-w",
54
+ };
55
+
56
+ it("returns matched model pair for detected intent", async () => {
57
+ const detect = vi.fn(async () => "coding");
58
+ const selector = new IntentModelSelector({
59
+ mappings: [
60
+ { intent: "coding", modelPair: codePair, description: "" },
61
+ { intent: "writing", modelPair: writingPair, description: "" },
62
+ ],
63
+ defaultPair,
64
+ detect,
65
+ });
66
+
67
+ const pair = await selector.getModelPair("write me code");
68
+ expect(pair).toEqual(codePair);
69
+ expect(detect).toHaveBeenCalledWith("write me code");
70
+ });
71
+
72
+ it("returns default pair for unknown intent", async () => {
73
+ const detect = vi.fn(async () => "unknown");
74
+ const selector = new IntentModelSelector({
75
+ mappings: [
76
+ { intent: "coding", modelPair: codePair, description: "" },
77
+ ],
78
+ defaultPair,
79
+ detect,
80
+ });
81
+
82
+ const pair = await selector.getModelPair("random question");
83
+ expect(pair).toEqual(defaultPair);
84
+ });
85
+
86
+ it("caches intent detection results", async () => {
87
+ const detect = vi.fn(async () => "coding");
88
+ const selector = new IntentModelSelector({
89
+ mappings: [
90
+ { intent: "coding", modelPair: codePair, description: "" },
91
+ ],
92
+ defaultPair,
93
+ detect,
94
+ });
95
+
96
+ await selector.getModelPair("same prompt");
97
+ await selector.getModelPair("same prompt");
98
+ expect(detect).toHaveBeenCalledTimes(1);
99
+ });
100
+
101
+ it("clearCache resets the cache", async () => {
102
+ const detect = vi.fn(async () => "coding");
103
+ const selector = new IntentModelSelector({
104
+ mappings: [
105
+ { intent: "coding", modelPair: codePair, description: "" },
106
+ ],
107
+ defaultPair,
108
+ detect,
109
+ });
110
+
111
+ await selector.getModelPair("prompt");
112
+ selector.clearCache();
113
+ await selector.getModelPair("prompt");
114
+ expect(detect).toHaveBeenCalledTimes(2);
115
+ });
116
+
117
+ it("intents() returns registered intent names", () => {
118
+ const selector = new IntentModelSelector({
119
+ mappings: [
120
+ { intent: "coding", modelPair: codePair, description: "" },
121
+ { intent: "writing", modelPair: writingPair, description: "" },
122
+ ],
123
+ defaultPair,
124
+ detect: async () => "coding",
125
+ });
126
+
127
+ expect(selector.intents()).toContain("coding");
128
+ expect(selector.intents()).toContain("writing");
129
+ });
130
+ });
131
+
132
+ // ─── IntentDetector ──────────────────────────────────────────────────────────
133
+
134
+ describe("IntentDetector", () => {
135
+ // Simple embeddings: coding=[1,0,0], writing=[0,1,0]
136
+ function mockEmbed(): (text: string) => Promise<number[]> {
137
+ return vi.fn(async (text: string) => {
138
+ if (text.includes("code") || text.includes("function")) {
139
+ return [1, 0, 0];
140
+ }
141
+ if (text.includes("write") || text.includes("essay")) {
142
+ return [0, 1, 0];
143
+ }
144
+ return [0.5, 0.5, 0];
145
+ });
146
+ }
147
+
148
+ it("returns 'general' with no examples", async () => {
149
+ const detector = new IntentDetector({ embed: mockEmbed() });
150
+ expect(await detector.detect("anything")).toBe("general");
151
+ });
152
+
153
+ it("detects intent matching closest examples", async () => {
154
+ const detector = new IntentDetector({ embed: mockEmbed() });
155
+ await detector.addExamples("coding", ["write a function"]);
156
+ await detector.addExamples("writing", ["write an essay"]);
157
+
158
+ expect(await detector.detect("code a function")).toBe("coding");
159
+ expect(await detector.detect("write my essay")).toBe("writing");
160
+ });
161
+
162
+ it("confidence returns normalized scores", async () => {
163
+ const detector = new IntentDetector({ embed: mockEmbed() });
164
+ await detector.addExamples("coding", ["code"]);
165
+ await detector.addExamples("writing", ["essay"]);
166
+
167
+ const conf = await detector.confidence("code something");
168
+ let total = 0;
169
+ for (const v of conf.values()) total += v;
170
+ expect(total).toBeCloseTo(1);
171
+ });
172
+
173
+ it("confidence returns empty map with no examples", async () => {
174
+ const detector = new IntentDetector({ embed: mockEmbed() });
175
+ const conf = await detector.confidence("anything");
176
+ expect(conf.size).toBe(0);
177
+ });
178
+
179
+ it("addExamples accumulates", async () => {
180
+ const detector = new IntentDetector({ embed: mockEmbed() });
181
+ await detector.addExamples("coding", ["code a"]);
182
+ await detector.addExamples("coding", ["code b"]);
183
+
184
+ // Should still detect coding.
185
+ expect(await detector.detect("code something")).toBe("coding");
186
+ });
187
+ });
@@ -0,0 +1,208 @@
1
+ /**
2
+ * Intent-based routing middleware.
3
+ *
4
+ * IntentModelSelector — detects prompt intent and overrides the model
5
+ * pair used for routing. IntentDetector — cosine-similarity-based
6
+ * intent detection using embeddings.
7
+ *
8
+ * Port of Python's intent_model_selector.py and domain_intent_detector.py.
9
+ */
10
+
11
+ import type { Middleware, ModelPair } from "./router";
12
+
13
+ // ─── Types ───────────────────────────────────────────────────────────────────
14
+
15
+ /** Maps an intent name to a specific model pair. */
16
+ export interface IntentModelMapping {
17
+ intent: string;
18
+ modelPair: ModelPair;
19
+ description: string;
20
+ }
21
+
22
+ /** Function that classifies a prompt into an intent string. */
23
+ export type IntentDetectFn = (prompt: string) => Promise<string>;
24
+
25
+ /** Function that returns an embedding vector for text. */
26
+ export type EmbedFn = (text: string) => Promise<number[]>;
27
+
28
+ // ─── IntentModelSelector (middleware) ────────────────────────────────────────
29
+
30
+ export interface IntentModelSelectorOptions {
31
+ /** Intent-to-model mappings. */
32
+ mappings: IntentModelMapping[];
33
+ /** Default model pair when no intent matches. */
34
+ defaultPair: ModelPair;
35
+ /** Intent detection function. */
36
+ detect: IntentDetectFn;
37
+ }
38
+
39
+ /**
40
+ * Middleware that selects a model pair based on detected intent.
41
+ *
42
+ * If the detected intent matches a mapping, returns that mapping's
43
+ * model pair. Otherwise returns the default pair.
44
+ */
45
+ export class IntentModelSelector implements Middleware {
46
+ private readonly _lookup: Map<string, ModelPair>;
47
+ private readonly _defaultPair: ModelPair;
48
+ private readonly _detect: IntentDetectFn;
49
+ private readonly _cache: Map<string, string>;
50
+
51
+ constructor(opts: IntentModelSelectorOptions) {
52
+ this._lookup = new Map(
53
+ opts.mappings.map((m) => [m.intent, m.modelPair]),
54
+ );
55
+ this._defaultPair = opts.defaultPair;
56
+ this._detect = opts.detect;
57
+ this._cache = new Map();
58
+ }
59
+
60
+ async getModelPair(prompt: string): Promise<ModelPair | null> {
61
+ let intent = this._cache.get(prompt);
62
+ if (intent === undefined) {
63
+ intent = await this._detect(prompt);
64
+ if (this._cache.size >= 10_000) this._cache.clear();
65
+ this._cache.set(prompt, intent);
66
+ }
67
+
68
+ return this._lookup.get(intent) ?? this._defaultPair;
69
+ }
70
+
71
+ /** Return all registered intent names. */
72
+ intents(): string[] {
73
+ return [...this._lookup.keys()];
74
+ }
75
+
76
+ /** Clear the detection cache. */
77
+ clearCache(): void {
78
+ this._cache.clear();
79
+ }
80
+ }
81
+
82
+ // ─── Cosine similarity helpers ───────────────────────────────────────────────
83
+
84
+ /** Dot product of two equal-length vectors. */
85
+ export function dot(a: number[], b: number[]): number {
86
+ let sum = 0;
87
+ for (let i = 0; i < a.length; i++) sum += a[i] * b[i];
88
+ return sum;
89
+ }
90
+
91
+ /** L2 norm of a vector. */
92
+ export function norm(v: number[]): number {
93
+ let sum = 0;
94
+ for (let i = 0; i < v.length; i++) sum += v[i] * v[i];
95
+ return Math.sqrt(sum);
96
+ }
97
+
98
+ /** Cosine similarity between two vectors. */
99
+ export function cosineSimilarity(a: number[], b: number[]): number {
100
+ const nA = norm(a);
101
+ const nB = norm(b);
102
+ if (nA === 0 || nB === 0) return 0;
103
+ return dot(a, b) / (nA * nB);
104
+ }
105
+
106
+ // ─── IntentDetector (embedding-based) ────────────────────────────────────────
107
+
108
+ export interface IntentDetectorOptions {
109
+ /** Function to get embedding vectors. */
110
+ embed: EmbedFn;
111
+ }
112
+
113
+ /**
114
+ * Embedding-based intent detector.
115
+ *
116
+ * Uses cosine similarity between the prompt embedding and stored
117
+ * example embeddings to find the best-matching intent.
118
+ */
119
+ export class IntentDetector {
120
+ private readonly _embed: EmbedFn;
121
+ private readonly _examples: Map<string, number[][]>;
122
+
123
+ constructor(opts: IntentDetectorOptions) {
124
+ this._embed = opts.embed;
125
+ this._examples = new Map();
126
+ }
127
+
128
+ /**
129
+ * Add example embeddings for an intent.
130
+ *
131
+ * Computes embeddings for the given texts and stores them.
132
+ */
133
+ async addExamples(intent: string, texts: string[]): Promise<void> {
134
+ const existing = this._examples.get(intent) ?? [];
135
+ const newEmbs = await Promise.all(texts.map((t) => this._embed(t)));
136
+ this._examples.set(intent, [...existing, ...newEmbs]);
137
+ }
138
+
139
+ /**
140
+ * Detect the intent of a prompt.
141
+ *
142
+ * Returns the intent with the highest average cosine similarity
143
+ * to the prompt. Returns "general" if no examples are stored.
144
+ */
145
+ async detect(prompt: string): Promise<string> {
146
+ if (this._examples.size === 0) return "general";
147
+
148
+ const promptEmb = await this._embed(prompt);
149
+ let bestIntent = "general";
150
+ let bestScore = -Infinity;
151
+
152
+ for (const [intent, embeddings] of this._examples) {
153
+ if (embeddings.length === 0) continue;
154
+
155
+ let sum = 0;
156
+ for (const emb of embeddings) {
157
+ sum += cosineSimilarity(promptEmb, emb);
158
+ }
159
+ const avg = sum / embeddings.length;
160
+
161
+ if (avg > bestScore) {
162
+ bestScore = avg;
163
+ bestIntent = intent;
164
+ }
165
+ }
166
+
167
+ return bestIntent;
168
+ }
169
+
170
+ /**
171
+ * Get confidence scores for all intents.
172
+ *
173
+ * Returns a map from intent to normalized confidence score.
174
+ */
175
+ async confidence(prompt: string): Promise<Map<string, number>> {
176
+ const result = new Map<string, number>();
177
+ if (this._examples.size === 0) return result;
178
+
179
+ const promptEmb = await this._embed(prompt);
180
+ let total = 0;
181
+
182
+ for (const [intent, embeddings] of this._examples) {
183
+ if (embeddings.length === 0) continue;
184
+
185
+ let sum = 0;
186
+ for (const emb of embeddings) {
187
+ sum += cosineSimilarity(promptEmb, emb);
188
+ }
189
+ const score = Math.max(0, sum / embeddings.length);
190
+ result.set(intent, score);
191
+ total += score;
192
+ }
193
+
194
+ // Normalize to proper confidence distribution.
195
+ if (total > 0) {
196
+ for (const [k, v] of result) {
197
+ result.set(k, v / total);
198
+ }
199
+ } else if (result.size > 0) {
200
+ const fallback = 1 / result.size;
201
+ for (const k of result.keys()) {
202
+ result.set(k, fallback);
203
+ }
204
+ }
205
+
206
+ return result;
207
+ }
208
+ }
@@ -0,0 +1,66 @@
1
+ import { describe, it, expect, vi } from "vitest";
2
+ import { MFRouter } from "./mf";
3
+ import type { TritonScorer } from "../triton/client";
4
+
5
+ function mockTriton(returnValue: number): TritonScorer {
6
+ return { score: vi.fn(async () => returnValue) };
7
+ }
8
+
9
+ function mockEmbed(dim = 4): (prompt: string) => Promise<Float32Array> {
10
+ return vi.fn(async () => new Float32Array(dim).fill(0.5));
11
+ }
12
+
13
+ describe("MFRouter", () => {
14
+ it("returns the win rate from Triton", async () => {
15
+ const triton = mockTriton(0.75);
16
+ const embed = mockEmbed();
17
+ const router = new MFRouter({ triton, embed });
18
+
19
+ const score = await router.score("hello world");
20
+ expect(score).toBe(0.75);
21
+ expect(embed).toHaveBeenCalledWith("hello world");
22
+ expect(triton.score).toHaveBeenCalled();
23
+ });
24
+
25
+ it("clamps values above 1 to 1", async () => {
26
+ const router = new MFRouter({
27
+ triton: mockTriton(1.5),
28
+ embed: mockEmbed(),
29
+ });
30
+ expect(await router.score("test")).toBe(1);
31
+ });
32
+
33
+ it("clamps values below 0 to 0", async () => {
34
+ const router = new MFRouter({
35
+ triton: mockTriton(-0.3),
36
+ embed: mockEmbed(),
37
+ });
38
+ expect(await router.score("test")).toBe(0);
39
+ });
40
+
41
+ it("passes the embedding to Triton scorer", async () => {
42
+ const triton = mockTriton(0.5);
43
+ const fixedEmb = new Float32Array([1, 2, 3]);
44
+ const embed = vi.fn(async () => fixedEmb);
45
+ const router = new MFRouter({ triton, embed });
46
+
47
+ await router.score("prompt");
48
+ expect(triton.score).toHaveBeenCalledWith(fixedEmb);
49
+ });
50
+
51
+ it("handles zero win rate", async () => {
52
+ const router = new MFRouter({
53
+ triton: mockTriton(0),
54
+ embed: mockEmbed(),
55
+ });
56
+ expect(await router.score("test")).toBe(0);
57
+ });
58
+
59
+ it("handles exact 1.0 win rate", async () => {
60
+ const router = new MFRouter({
61
+ triton: mockTriton(1.0),
62
+ embed: mockEmbed(),
63
+ });
64
+ expect(await router.score("test")).toBe(1);
65
+ });
66
+ });
@@ -0,0 +1,52 @@
1
+ /**
2
+ * MFRouter — Matrix Factorization router.
3
+ *
4
+ * Embeds the prompt (via an embedding function), sends the embedding
5
+ * to a Triton-hosted MF model, and returns the win rate as the score.
6
+ *
7
+ * Port of Python's MatrixFactorizationRouter.
8
+ */
9
+
10
+ import type { Router } from "./router";
11
+ import type { TritonScorer } from "../triton/client";
12
+
13
+ // ─── Types ───────────────────────────────────────────────────────────────────
14
+
15
+ /** Function that produces an embedding vector for a prompt. */
16
+ export type EmbedFn = (prompt: string) => Promise<Float32Array>;
17
+
18
+ export interface MFRouterOptions {
19
+ /** Triton scorer for the MF model. */
20
+ triton: TritonScorer;
21
+ /** Function to embed a prompt into a float vector. */
22
+ embed: EmbedFn;
23
+ }
24
+
25
+ // ─── Router ──────────────────────────────────────────────────────────────────
26
+
27
+ export class MFRouter implements Router {
28
+ private readonly _triton: TritonScorer;
29
+ private readonly _embed: EmbedFn;
30
+
31
+ constructor(opts: MFRouterOptions) {
32
+ this._triton = opts.triton;
33
+ this._embed = opts.embed;
34
+ }
35
+
36
+ /**
37
+ * Score a prompt by embedding it and sending to the Triton MF model.
38
+ *
39
+ * Returns the win rate of the strong model in [0, 1].
40
+ */
41
+ async score(prompt: string): Promise<number> {
42
+ const embedding = await this._embed(prompt);
43
+ const winRate = await this._triton.score(embedding);
44
+ return clamp01(winRate);
45
+ }
46
+ }
47
+
48
+ // ─── Helpers ─────────────────────────────────────────────────────────────────
49
+
50
+ function clamp01(v: number): number {
51
+ return Math.max(0, Math.min(1, v));
52
+ }
@@ -0,0 +1,23 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { RandomRouter } from "./random";
3
+
4
+ describe("RandomRouter", () => {
5
+ it("returns a number in [0, 1]", async () => {
6
+ const router = new RandomRouter();
7
+ for (let i = 0; i < 50; i++) {
8
+ const score = await router.score("anything");
9
+ expect(score).toBeGreaterThanOrEqual(0);
10
+ expect(score).toBeLessThanOrEqual(1);
11
+ }
12
+ });
13
+
14
+ it("ignores prompt content", async () => {
15
+ const router = new RandomRouter();
16
+ const a = await router.score("hello");
17
+ const b = await router.score("world");
18
+ // Both should be valid numbers (can't test inequality
19
+ // deterministically, but they should be finite).
20
+ expect(Number.isFinite(a)).toBe(true);
21
+ expect(Number.isFinite(b)).toBe(true);
22
+ });
23
+ });
@@ -0,0 +1,13 @@
1
+ /**
2
+ * RandomRouter — returns a uniform random score in [0, 1].
3
+ *
4
+ * Useful for A/B testing and baseline comparisons.
5
+ */
6
+
7
+ import type { Router } from "./router";
8
+
9
+ export class RandomRouter implements Router {
10
+ async score(_prompt: string): Promise<number> {
11
+ return Math.random();
12
+ }
13
+ }
@@ -0,0 +1,31 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { route, RoutingError } from "./router";
3
+ import type { ModelPair } from "./router";
4
+
5
+ const pair: ModelPair = { strong: "gpt-4", weak: "gpt-3.5" };
6
+
7
+ describe("route()", () => {
8
+ it("returns strong when score >= threshold", () => {
9
+ expect(route(0.7, 0.5, pair)).toBe("gpt-4");
10
+ expect(route(0.5, 0.5, pair)).toBe("gpt-4");
11
+ expect(route(1, 0, pair)).toBe("gpt-4");
12
+ });
13
+
14
+ it("returns weak when score < threshold", () => {
15
+ expect(route(0.3, 0.5, pair)).toBe("gpt-3.5");
16
+ expect(route(0, 0.5, pair)).toBe("gpt-3.5");
17
+ });
18
+
19
+ it("edge: score=0, threshold=0 returns strong", () => {
20
+ expect(route(0, 0, pair)).toBe("gpt-4");
21
+ });
22
+ });
23
+
24
+ describe("RoutingError", () => {
25
+ it("has correct name and message", () => {
26
+ const err = new RoutingError("test error");
27
+ expect(err.name).toBe("RoutingError");
28
+ expect(err.message).toBe("test error");
29
+ expect(err).toBeInstanceOf(Error);
30
+ });
31
+ });
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Core router interfaces and types for RouteLLM routing.
3
+ *
4
+ * Defines the Router interface (score-based routing), Middleware protocol,
5
+ * ModelPair type, and RoutingError.
6
+ */
7
+
8
+ // ─── Types ───────────────────────────────────────────────────────────────────
9
+
10
+ /** A pair of models: strong (high-quality) and weak (cost-effective). */
11
+ export interface ModelPair {
12
+ strong: string;
13
+ weak: string;
14
+ }
15
+
16
+ // ─── Errors ──────────────────────────────────────────────────────────────────
17
+
18
+ /** Error thrown when routing fails (bad config, missing router, etc.). */
19
+ export class RoutingError extends Error {
20
+ constructor(message: string) {
21
+ super(message);
22
+ this.name = "RoutingError";
23
+ }
24
+ }
25
+
26
+ // ─── Router interface ────────────────────────────────────────────────────────
27
+
28
+ /**
29
+ * A Router scores a prompt to decide which model to use.
30
+ *
31
+ * score() returns a value in [0, 1] representing the estimated win rate
32
+ * of the strong model. If score >= threshold, the controller routes to
33
+ * the strong model; otherwise, the weak model.
34
+ */
35
+ export interface Router {
36
+ /** Returns a score in [0, 1] — the strong-model win rate estimate. */
37
+ score(prompt: string): Promise<number>;
38
+ }
39
+
40
+ /**
41
+ * Route helper — applies the threshold decision to a score.
42
+ *
43
+ * If score >= threshold, returns pair.strong; otherwise pair.weak.
44
+ */
45
+ export function route(
46
+ score: number,
47
+ threshold: number,
48
+ pair: ModelPair,
49
+ ): string {
50
+ return score >= threshold ? pair.strong : pair.weak;
51
+ }
52
+
53
+ // ─── Middleware interface ────────────────────────────────────────────────────
54
+
55
+ /**
56
+ * Middleware can override the model pair before routing.
57
+ *
58
+ * Returns null to keep the default pair, or a ModelPair to override it.
59
+ */
60
+ export interface Middleware {
61
+ getModelPair(prompt: string): Promise<ModelPair | null>;
62
+ }