@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,193 @@
1
+ import { describe, it, expect, vi } from "vitest";
2
+ import { createApp } from "./server";
3
+ import { Controller } from "./controller";
4
+ import type { Router } from "./router";
5
+ import type {
6
+ ChatCompletionRequest,
7
+ ChatCompletionResponse,
8
+ UpstreamFn,
9
+ } from "./server";
10
+
11
+ // ─── Helpers ─────────────────────────────────────────────────────────────────
12
+
13
+ function fixedRouter(score: number): Router {
14
+ return { score: vi.fn(async () => score) };
15
+ }
16
+
17
+ function mockUpstream(): UpstreamFn {
18
+ return vi.fn(async (body: ChatCompletionRequest) => ({
19
+ id: "chatcmpl-test",
20
+ object: "chat.completion",
21
+ created: 1000,
22
+ model: body.model,
23
+ choices: [
24
+ {
25
+ index: 0,
26
+ message: { role: "assistant", content: `routed to ${body.model}` },
27
+ finish_reason: "stop",
28
+ },
29
+ ],
30
+ usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 },
31
+ }));
32
+ }
33
+
34
+ function makeApp(
35
+ score: number,
36
+ upstream?: UpstreamFn,
37
+ ) {
38
+ const controller = new Controller({
39
+ strongModel: "gpt-4",
40
+ weakModel: "gpt-3.5",
41
+ routers: { mf: fixedRouter(score) },
42
+ });
43
+ return createApp({
44
+ controller,
45
+ upstream: upstream ?? mockUpstream(),
46
+ });
47
+ }
48
+
49
+ // ─── Tests ───────────────────────────────────────────────────────────────────
50
+
51
+ describe("server /health", () => {
52
+ it("returns 200 with status online", async () => {
53
+ const app = makeApp(0.5);
54
+ const res = await app.request("/health");
55
+ expect(res.status).toBe(200);
56
+ const json = await res.json();
57
+ expect(json.status).toBe("online");
58
+ });
59
+ });
60
+
61
+ describe("server /v1/chat/completions", () => {
62
+ it("routes to strong model when score >= threshold", async () => {
63
+ const upstream = mockUpstream();
64
+ const app = makeApp(0.9, upstream); // score=0.9 >= threshold=0.5
65
+
66
+ const body: ChatCompletionRequest = {
67
+ model: "router-mf-0.5",
68
+ messages: [{ role: "user", content: "hello" }],
69
+ };
70
+
71
+ const res = await app.request("/v1/chat/completions", {
72
+ method: "POST",
73
+ headers: { "Content-Type": "application/json" },
74
+ body: JSON.stringify(body),
75
+ });
76
+
77
+ expect(res.status).toBe(200);
78
+ const json = (await res.json()) as ChatCompletionResponse;
79
+ expect(json.model).toBe("gpt-4");
80
+ expect(upstream).toHaveBeenCalled();
81
+ });
82
+
83
+ it("routes to weak model when score < threshold", async () => {
84
+ const upstream = mockUpstream();
85
+ const app = makeApp(0.1, upstream); // score=0.1 < threshold=0.5
86
+
87
+ const body: ChatCompletionRequest = {
88
+ model: "router-mf-0.5",
89
+ messages: [{ role: "user", content: "hello" }],
90
+ };
91
+
92
+ const res = await app.request("/v1/chat/completions", {
93
+ method: "POST",
94
+ headers: { "Content-Type": "application/json" },
95
+ body: JSON.stringify(body),
96
+ });
97
+
98
+ expect(res.status).toBe(200);
99
+ const json = (await res.json()) as ChatCompletionResponse;
100
+ expect(json.model).toBe("gpt-3.5");
101
+ });
102
+
103
+ it("returns 400 for invalid model format", async () => {
104
+ const app = makeApp(0.5);
105
+
106
+ const res = await app.request("/v1/chat/completions", {
107
+ method: "POST",
108
+ headers: { "Content-Type": "application/json" },
109
+ body: JSON.stringify({
110
+ model: "bad-model",
111
+ messages: [{ role: "user", content: "hi" }],
112
+ }),
113
+ });
114
+
115
+ expect(res.status).toBe(400);
116
+ const json = await res.json();
117
+ expect(json.object).toBe("error");
118
+ });
119
+
120
+ it("returns 400 for unknown router", async () => {
121
+ const app = makeApp(0.5);
122
+
123
+ const res = await app.request("/v1/chat/completions", {
124
+ method: "POST",
125
+ headers: { "Content-Type": "application/json" },
126
+ body: JSON.stringify({
127
+ model: "router-unknown-0.5",
128
+ messages: [{ role: "user", content: "hi" }],
129
+ }),
130
+ });
131
+
132
+ expect(res.status).toBe(400);
133
+ });
134
+
135
+ it("returns 400 for missing model/messages", async () => {
136
+ const app = makeApp(0.5);
137
+
138
+ const res = await app.request("/v1/chat/completions", {
139
+ method: "POST",
140
+ headers: { "Content-Type": "application/json" },
141
+ body: JSON.stringify({}),
142
+ });
143
+
144
+ expect(res.status).toBe(400);
145
+ const json = await res.json();
146
+ expect(json.message).toContain("required");
147
+ });
148
+
149
+ it("returns 400 for invalid JSON body", async () => {
150
+ const app = makeApp(0.5);
151
+
152
+ const res = await app.request("/v1/chat/completions", {
153
+ method: "POST",
154
+ headers: { "Content-Type": "application/json" },
155
+ body: "not json",
156
+ });
157
+
158
+ expect(res.status).toBe(400);
159
+ });
160
+
161
+ it("uses last message for routing", async () => {
162
+ const router: Router = {
163
+ score: vi.fn(async (prompt: string) => {
164
+ // Return high score only for "route me".
165
+ return prompt === "route me" ? 0.9 : 0.1;
166
+ }),
167
+ };
168
+ const upstream = mockUpstream();
169
+ const controller = new Controller({
170
+ strongModel: "gpt-4",
171
+ weakModel: "gpt-3.5",
172
+ routers: { mf: router },
173
+ });
174
+ const app = createApp({ controller, upstream });
175
+
176
+ const res = await app.request("/v1/chat/completions", {
177
+ method: "POST",
178
+ headers: { "Content-Type": "application/json" },
179
+ body: JSON.stringify({
180
+ model: "router-mf-0.5",
181
+ messages: [
182
+ { role: "user", content: "first" },
183
+ { role: "user", content: "route me" },
184
+ ],
185
+ }),
186
+ });
187
+
188
+ expect(res.status).toBe(200);
189
+ const json = (await res.json()) as ChatCompletionResponse;
190
+ expect(json.model).toBe("gpt-4");
191
+ expect(router.score).toHaveBeenCalledWith("route me");
192
+ });
193
+ });
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Hono HTTP handler for RouteLLM.
3
+ *
4
+ * Exposes /v1/chat/completions (routes + proxies to upstream LLM)
5
+ * and /health for liveness checks.
6
+ *
7
+ * Port of Python's openai_server.py.
8
+ */
9
+
10
+ import { Hono } from "hono";
11
+ import { Controller } from "./controller";
12
+ import { RoutingError } from "./router";
13
+
14
+ // ─── Request / response types (OpenAI-compatible) ────────────────────────────
15
+
16
+ export interface ChatMessage {
17
+ role: string;
18
+ content: string;
19
+ }
20
+
21
+ export interface ChatCompletionRequest {
22
+ model: string;
23
+ messages: ChatMessage[];
24
+ stream?: boolean;
25
+ temperature?: number;
26
+ max_tokens?: number;
27
+ top_p?: number;
28
+ stop?: string | string[];
29
+ n?: number;
30
+ [key: string]: unknown;
31
+ }
32
+
33
+ export interface ChatCompletionChoice {
34
+ index: number;
35
+ message: ChatMessage;
36
+ finish_reason: string | null;
37
+ }
38
+
39
+ export interface UsageInfo {
40
+ prompt_tokens: number;
41
+ completion_tokens: number;
42
+ total_tokens: number;
43
+ }
44
+
45
+ export interface ChatCompletionResponse {
46
+ id: string;
47
+ object: string;
48
+ created: number;
49
+ model: string;
50
+ choices: ChatCompletionChoice[];
51
+ usage: UsageInfo;
52
+ }
53
+
54
+ // ─── Upstream proxy type ─────────────────────────────────────────────────────
55
+
56
+ /**
57
+ * Function that forwards a completion request to the upstream LLM.
58
+ *
59
+ * Receives the request body with `model` already set to the routed
60
+ * model name. Returns the upstream response to relay to the client.
61
+ */
62
+ export type UpstreamFn = (
63
+ body: ChatCompletionRequest,
64
+ ) => Promise<ChatCompletionResponse>;
65
+
66
+ // ─── App factory ─────────────────────────────────────────────────────────────
67
+
68
+ export interface ServerOptions {
69
+ /** The controller with registered routers. */
70
+ controller: Controller;
71
+ /** Function to forward requests to the upstream LLM. */
72
+ upstream: UpstreamFn;
73
+ }
74
+
75
+ /**
76
+ * Create a Hono app with RouteLLM endpoints.
77
+ *
78
+ * Routes:
79
+ * POST /v1/chat/completions — route + proxy to upstream LLM.
80
+ * GET /health — liveness check.
81
+ */
82
+ export function createApp(opts: ServerOptions): Hono {
83
+ const app = new Hono();
84
+ const { controller, upstream } = opts;
85
+
86
+ // ── Health ──────────────────────────────────────────────────────
87
+ app.get("/health", (c) => {
88
+ return c.json({ status: "online" });
89
+ });
90
+
91
+ // ── Chat Completions ───────────────────────────────────────────
92
+ app.post("/v1/chat/completions", async (c) => {
93
+ let body: ChatCompletionRequest;
94
+ try {
95
+ body = await c.req.json<ChatCompletionRequest>();
96
+ } catch {
97
+ return c.json({ object: "error", message: "invalid JSON" }, 400);
98
+ }
99
+
100
+ if (!body.model || !body.messages?.length) {
101
+ return c.json(
102
+ { object: "error", message: "model and messages required" },
103
+ 400,
104
+ );
105
+ }
106
+
107
+ // Extract last user message for routing.
108
+ const userMsg = [...body.messages].reverse().find(
109
+ (m: { role: string }) => m.role === "user",
110
+ );
111
+ const prompt = userMsg?.content ?? body.messages[body.messages.length - 1]?.content ?? "";
112
+
113
+ let routedModel: string;
114
+ try {
115
+ routedModel = await controller.routeByModelName(prompt, body.model);
116
+ } catch (err) {
117
+ if (err instanceof RoutingError) {
118
+ return c.json({ object: "error", message: err.message }, 400);
119
+ }
120
+ throw err;
121
+ }
122
+
123
+ // Replace model with routed model and forward.
124
+ const upstreamBody: ChatCompletionRequest = {
125
+ ...body,
126
+ model: routedModel,
127
+ };
128
+
129
+ const result = await upstream(upstreamBody);
130
+ return c.json(result);
131
+ });
132
+
133
+ return app;
134
+ }
@@ -0,0 +1,199 @@
1
+ import { describe, it, expect, vi } from "vitest";
2
+ import {
3
+ dot,
4
+ norm,
5
+ cosineSimilarities,
6
+ getWeightings,
7
+ computeEloMle,
8
+ computeTiers,
9
+ SWRankingRouter,
10
+ } from "./sw";
11
+ import type { ArenaBattle, EmbeddingFn } from "./sw";
12
+
13
+ // ─── Math helpers ────────────────────────────────────────────────────────────
14
+
15
+ describe("dot", () => {
16
+ it("computes dot product", () => {
17
+ expect(dot([1, 2, 3], [4, 5, 6])).toBe(32);
18
+ });
19
+
20
+ it("returns 0 for zero vectors", () => {
21
+ expect(dot([0, 0], [1, 2])).toBe(0);
22
+ });
23
+ });
24
+
25
+ describe("norm", () => {
26
+ it("computes L2 norm", () => {
27
+ expect(norm([3, 4])).toBe(5);
28
+ });
29
+
30
+ it("returns 0 for zero vector", () => {
31
+ expect(norm([0, 0, 0])).toBe(0);
32
+ });
33
+ });
34
+
35
+ describe("cosineSimilarities", () => {
36
+ it("returns 1 for identical vectors", () => {
37
+ const sims = cosineSimilarities([[1, 0]], [1, 0]);
38
+ expect(sims[0]).toBeCloseTo(1);
39
+ });
40
+
41
+ it("returns 0 for orthogonal vectors", () => {
42
+ const sims = cosineSimilarities([[1, 0]], [0, 1]);
43
+ expect(sims[0]).toBeCloseTo(0);
44
+ });
45
+
46
+ it("handles zero vector input", () => {
47
+ const sims = cosineSimilarities([[1, 0]], [0, 0]);
48
+ expect(sims[0]).toBe(0);
49
+ });
50
+ });
51
+
52
+ describe("getWeightings", () => {
53
+ it("scales similarities into weightings", () => {
54
+ const w = getWeightings([0.5, 1.0, 0.0]);
55
+ expect(w.length).toBe(3);
56
+ // max similarity maps to 10 * 10^1 = 100
57
+ expect(w[1]).toBeCloseTo(100);
58
+ // 0 similarity maps to 10 * 10^0 = 10
59
+ expect(w[2]).toBeCloseTo(10);
60
+ });
61
+
62
+ it("handles all-zero similarities", () => {
63
+ const w = getWeightings([0, 0, 0]);
64
+ expect(w).toEqual([10, 10, 10]);
65
+ });
66
+ });
67
+
68
+ // ─── Elo ─────────────────────────────────────────────────────────────────────
69
+
70
+ describe("computeEloMle", () => {
71
+ it("stronger model gets higher rating", () => {
72
+ const battles: ArenaBattle[] = [];
73
+ for (let i = 0; i < 100; i++) {
74
+ battles.push({ modelA: "strong", modelB: "weak", winner: "model_a" });
75
+ }
76
+ const ratings = computeEloMle(battles);
77
+ expect(ratings.get("strong")!).toBeGreaterThan(ratings.get("weak")!);
78
+ });
79
+
80
+ it("handles ties", () => {
81
+ const battles: ArenaBattle[] = [];
82
+ for (let i = 0; i < 100; i++) {
83
+ battles.push({ modelA: "a", modelB: "b", winner: "tie" });
84
+ }
85
+ const ratings = computeEloMle(battles);
86
+ // With only ties, ratings should be roughly equal.
87
+ expect(
88
+ Math.abs(ratings.get("a")! - ratings.get("b")!),
89
+ ).toBeLessThan(10);
90
+ });
91
+
92
+ it("respects weights", () => {
93
+ const battles: ArenaBattle[] = [
94
+ { modelA: "a", modelB: "b", winner: "model_a" },
95
+ { modelA: "a", modelB: "b", winner: "model_b" },
96
+ ];
97
+ // Heavy weight on the first battle (a wins).
98
+ const ratings = computeEloMle(battles, [100, 1]);
99
+ expect(ratings.get("a")!).toBeGreaterThan(ratings.get("b")!);
100
+ });
101
+ });
102
+
103
+ describe("computeTiers", () => {
104
+ it("assigns tiers based on rating order", () => {
105
+ const ratings = new Map([
106
+ ["a", 800],
107
+ ["b", 1000],
108
+ ["c", 1200],
109
+ ["d", 1400],
110
+ ]);
111
+ const tiers = computeTiers(ratings, 2);
112
+ expect(tiers.get("a")).toBeLessThan(tiers.get("d")!);
113
+ });
114
+ });
115
+
116
+ // ─── SWRankingRouter ─────────────────────────────────────────────────────────
117
+
118
+ describe("SWRankingRouter", () => {
119
+ function makeBattles(): ArenaBattle[] {
120
+ const battles: ArenaBattle[] = [];
121
+ for (let i = 0; i < 20; i++) {
122
+ battles.push({
123
+ modelA: "gpt-4-1106-preview",
124
+ modelB: "mixtral-8x7b-instruct-v0.1",
125
+ winner: "model_a",
126
+ });
127
+ }
128
+ for (let i = 0; i < 5; i++) {
129
+ battles.push({
130
+ modelA: "gpt-4-1106-preview",
131
+ modelB: "mixtral-8x7b-instruct-v0.1",
132
+ winner: "model_b",
133
+ });
134
+ }
135
+ return battles;
136
+ }
137
+
138
+ function makeEmbeddings(n: number, dim = 4): number[][] {
139
+ return Array.from({ length: n }, (_, i) => {
140
+ const v = new Array(dim).fill(0);
141
+ v[i % dim] = 1;
142
+ return v;
143
+ });
144
+ }
145
+
146
+ it("returns a score in [0, 1]", async () => {
147
+ const battles = makeBattles();
148
+ const embs = makeEmbeddings(battles.length);
149
+ const embed: EmbeddingFn = vi.fn(async () => [1, 0, 0, 0]);
150
+
151
+ const router = new SWRankingRouter({
152
+ battles,
153
+ battleEmbeddings: embs,
154
+ embed,
155
+ });
156
+
157
+ const score = await router.score("test prompt");
158
+ expect(score).toBeGreaterThanOrEqual(0);
159
+ expect(score).toBeLessThanOrEqual(1);
160
+ expect(embed).toHaveBeenCalledWith("test prompt");
161
+ });
162
+
163
+ it("strong model dominance yields high score", async () => {
164
+ // All wins for strong model.
165
+ const battles: ArenaBattle[] = Array.from({ length: 50 }, () => ({
166
+ modelA: "gpt-4-1106-preview",
167
+ modelB: "mixtral-8x7b-instruct-v0.1",
168
+ winner: "model_a" as const,
169
+ }));
170
+ const embs = makeEmbeddings(50);
171
+ const embed: EmbeddingFn = async () => [1, 0, 0, 0];
172
+
173
+ const router = new SWRankingRouter({
174
+ battles,
175
+ battleEmbeddings: embs,
176
+ embed,
177
+ });
178
+
179
+ const score = await router.score("hi");
180
+ expect(score).toBeGreaterThan(0.5);
181
+ });
182
+
183
+ it("throws on mismatched lengths", () => {
184
+ expect(
185
+ () =>
186
+ new SWRankingRouter({
187
+ battles: [
188
+ {
189
+ modelA: "a",
190
+ modelB: "b",
191
+ winner: "model_a",
192
+ },
193
+ ],
194
+ battleEmbeddings: [],
195
+ embed: async () => [0],
196
+ }),
197
+ ).toThrow("same length");
198
+ });
199
+ });