-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclaude-router.mjs
More file actions
303 lines (268 loc) · 9.75 KB
/
claude-router.mjs
File metadata and controls
303 lines (268 loc) · 9.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
#!/usr/bin/env node
// ~/bin/claude-router.mjs
import http from "http";
const CODER_MODEL = "qwen/qwen3-coder-next";
const VISION_MODEL = "mistralai/devstral-small-2-2512";
const PROXY_PORT = 3000;
const imageDescriptionCache = new Map();
function hashImage(imageBlock) {
const data = imageBlock?.source?.data ?? imageBlock?.image_url?.url ?? "";
return data.slice(0, 64);
}
function hasUncachedImagesInLastUserMessage(messages) {
const lastUser = [...messages].reverse().find(m => m.role === "user");
if (!lastUser || !Array.isArray(lastUser.content)) return false;
for (const block of lastUser.content) {
if (block.type === "image" || block.type === "image_url") {
if (!imageDescriptionCache.has(hashImage(block))) return true;
}
if (block.type === "tool_result" && Array.isArray(block.content)) {
for (const inner of block.content) {
if (inner.type === "image" && !imageDescriptionCache.has(hashImage(inner))) return true;
}
}
}
return false;
}
function hasImagesAnywhere(messages) {
return messages.some(msg => {
if (!Array.isArray(msg.content)) return false;
return msg.content.some(block => {
if (block.type === "image" || block.type === "image_url") return true;
if (block.type === "tool_result" && Array.isArray(block.content)) {
return block.content.some(b => b.type === "image" || b.type === "image_url");
}
return false;
});
});
}
function collectImages(messages) {
const images = [];
for (const msg of messages) {
if (!Array.isArray(msg.content)) continue;
for (const block of msg.content) {
if (block.type === "image" || block.type === "image_url") images.push(block);
if (block.type === "tool_result" && Array.isArray(block.content)) {
for (const inner of block.content) {
if (inner.type === "image") images.push(inner);
}
}
}
}
return images;
}
function imageToText(block) {
const key = hashImage(block);
const desc = imageDescriptionCache.get(key);
return desc ? `<<IMAGE DESCRIPTION: ${desc}>>` : "<<IMAGE: binary image file>>";
}
function flattenUserBlock(block) {
if (block.type === "image" || block.type === "image_url") {
return { type: "text", text: imageToText(block) };
}
if (block.type === "tool_result" && Array.isArray(block.content)) {
const textBlocks = block.content.filter(b => b.type === "text");
const imageBlocks = block.content.filter(b => b.type === "image");
const allText = [
...textBlocks.map(b => b.text),
...imageBlocks.map(imageToText),
].join("\n") || "[file content]";
return { ...block, content: allText };
}
return block;
}
function rewriteForVision(messages) {
let lastVisionIdx = -1;
for (let i = messages.length - 1; i >= 0; i--) {
const msg = messages[i];
if (msg.role !== "user" || !Array.isArray(msg.content)) continue;
const hasImg = msg.content.some(b => {
if (b.type === "image" || b.type === "image_url") return true;
if (b.type === "tool_result" && Array.isArray(b.content)) {
return b.content.some(inner => inner.type === "image");
}
return false;
});
if (hasImg) { lastVisionIdx = i; break; }
}
const result = [];
for (let i = 0; i < messages.length; i++) {
const msg = messages[i];
if (msg.role !== "user" || !Array.isArray(msg.content)) {
result.push(msg);
continue;
}
if (i < lastVisionIdx) {
result.push({ ...msg, content: msg.content.map(flattenUserBlock) });
continue;
}
const cleanContent = [];
const extractedImages = [];
for (const block of msg.content) {
if (block.type === "tool_result" && Array.isArray(block.content)) {
const textBlocks = block.content.filter(b => b.type === "text");
const imageBlocks = block.content.filter(b => b.type === "image");
cleanContent.push({
...block,
content: textBlocks.map(b => b.text).join("\n") || "[image file]",
});
extractedImages.push(...imageBlocks);
} else if (block.type === "image" || block.type === "image_url") {
extractedImages.push(block);
} else {
cleanContent.push(block);
}
}
result.push({ ...msg, content: cleanContent });
if (extractedImages.length > 0) {
result.push({
role: "assistant",
content: [{ type: "text", text: "I can see the images. Let me analyze them." }],
});
result.push({
role: "user",
content: extractedImages,
});
}
}
return result;
}
function substituteImagesWithDescriptions(messages) {
return messages.map(msg => {
if (!Array.isArray(msg.content)) return msg;
return { ...msg, content: msg.content.map(flattenUserBlock) };
});
}
function normalizeAssistantMessages(messages) {
return messages.map(msg => {
if (msg.role !== "assistant" || !Array.isArray(msg.content)) return msg;
const textBlocks = msg.content.filter(b => b.type === "text");
const toolUseBlocks = msg.content.filter(b => b.type === "tool_use");
const otherBlocks = msg.content.filter(b => b.type !== "text" && b.type !== "tool_use");
const mergedText = textBlocks.map(b => b.text).filter(Boolean).join("\n").trim();
const newContent = [];
if (mergedText) newContent.push({ type: "text", text: mergedText });
newContent.push(...toolUseBlocks);
newContent.push(...otherBlocks);
return { ...msg, content: newContent };
});
}
function ensureAssistantText(messages) {
return messages.map(msg => {
if (msg.role !== "assistant" || !Array.isArray(msg.content)) return msg;
const hasText = msg.content.some(b => b.type === "text");
if (hasText) return msg;
return { ...msg, content: [{ type: "text", text: "." }, ...msg.content] };
});
}
function splitMixedUserMessages(messages) {
const result = [];
for (const msg of messages) {
if (msg.role !== "user" || !Array.isArray(msg.content)) {
result.push(msg);
continue;
}
const toolResultBlocks = msg.content.filter(b => b.type === "tool_result");
const otherBlocks = msg.content.filter(b => b.type !== "tool_result");
if (toolResultBlocks.length > 0 && otherBlocks.length > 0) {
result.push({ role: "user", content: toolResultBlocks });
result.push({ role: "assistant", content: [{ type: "text", text: "Understood, continuing." }] });
result.push({ role: "user", content: otherBlocks });
} else {
result.push(msg);
}
}
return result;
}
function fixMessageAlternation(messages) {
if (!messages?.length) return messages;
const fixed = [{ ...messages[0] }];
for (let i = 1; i < messages.length; i++) {
const prev = fixed[fixed.length - 1];
const curr = messages[i];
if (curr.role === prev.role) {
const prevContent = Array.isArray(prev.content) ? prev.content : [{ type: "text", text: prev.content }];
const currContent = Array.isArray(curr.content) ? curr.content : [{ type: "text", text: curr.content }];
prev.content = [...prevContent, ...currContent];
} else {
fixed.push({ ...curr });
}
}
return fixed;
}
function prepareMessages(messages, isVision) {
const base = isVision
? rewriteForVision(messages)
: (hasImagesAnywhere(messages) ? substituteImagesWithDescriptions(messages) : messages);
return fixMessageAlternation(
splitMixedUserMessages(
ensureAssistantText(
normalizeAssistantMessages(base)
)
)
);
}
function forward(body, res, onResponse) {
let responseBody = "";
const proxyReq = http.request({
hostname: "127.0.0.1",
port: 1234,
path: "/v1/messages",
method: "POST",
headers: {
"Content-Type": "application/json",
"anthropic-version": "2023-06-01",
},
}, (proxyRes) => {
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.on("data", chunk => { responseBody += chunk; res.write(chunk); });
proxyRes.on("end", () => { res.end(); if (onResponse) onResponse(responseBody); });
});
proxyReq.on("error", (e) => {
console.error("Proxy error:", e.message);
res.writeHead(502);
res.end(JSON.stringify({ error: e.message }));
});
proxyReq.write(body);
proxyReq.end();
}
http.createServer((req, res) => {
if (req.method !== "POST") { res.writeHead(404); res.end(); return; }
let body = "";
req.on("data", chunk => body += chunk);
req.on("end", () => {
try {
const parsed = JSON.parse(body);
const messages = parsed.messages ?? [];
const isVision = hasUncachedImagesInLastUserMessage(messages);
parsed.model = isVision ? VISION_MODEL : CODER_MODEL;
parsed.messages = prepareMessages(messages, isVision);
delete parsed.thinking;
delete parsed.betas;
console.log(`→ ${isVision ? "vision " : "coder "} [${parsed.model}]`);
if (isVision) {
const imageBlocks = collectImages(messages);
forward(JSON.stringify(parsed), res, (responseBody) => {
try {
const resp = JSON.parse(responseBody);
const text = resp.content?.filter(b => b.type === "text").map(b => b.text).join("\n") ?? "";
if (text && imageBlocks.length > 0) {
for (const img of imageBlocks) imageDescriptionCache.set(hashImage(img), text);
console.log(` cached description for ${imageBlocks.length} image(s)`);
}
} catch { /* streaming, ignore */ }
});
} else {
forward(JSON.stringify(parsed), res, null);
}
} catch (e) {
console.error("Parse error:", e.message);
res.writeHead(400);
res.end(JSON.stringify({ error: "bad request" }));
}
});
}).listen(PROXY_PORT, () => {
console.log(`🔀 claude-router on :${PROXY_PORT}`);
console.log(` coder → ${CODER_MODEL}`);
console.log(` vision → ${VISION_MODEL}`);
});