forked from antonoly/claude-code-anymodel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathollama-proxy.mjs
More file actions
151 lines (138 loc) · 4.5 KB
/
ollama-proxy.mjs
File metadata and controls
151 lines (138 loc) · 4.5 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
// Direct Anthropic-to-Ollama proxy for Claude Code
// Routes /v1/messages → Ollama (format translation)
// Routes everything else → api.anthropic.com (passthrough)
import http from 'http';
import https from 'https';
const OLLAMA = 'http://localhost:11434';
const MODEL = 'qwen3-coder:30b';
const PORT = 9090;
function convertAnthropicToOllama(body) {
const messages = [];
// System prompt
if (body.system) {
const sysText = typeof body.system === 'string'
? body.system
: body.system.map(b => b.text || '').join('\n');
messages.push({ role: 'system', content: sysText });
}
// Messages
for (const msg of (body.messages || [])) {
let content = '';
if (typeof msg.content === 'string') {
content = msg.content;
} else if (Array.isArray(msg.content)) {
content = msg.content.map(b => b.text || '').filter(Boolean).join('\n');
}
if (content) {
messages.push({ role: msg.role, content });
}
}
return {
model: MODEL,
messages,
stream: false,
options: { num_predict: body.max_tokens || 4096 },
};
}
function convertOllamaToAnthropic(ollamaRes, requestModel) {
const text = ollamaRes.message?.content || '';
return {
id: 'msg_local_' + Date.now(),
type: 'message',
role: 'assistant',
content: [{ type: 'text', text }],
model: requestModel || 'claude-opus-4-6',
stop_reason: 'end_turn',
stop_sequence: null,
usage: {
input_tokens: ollamaRes.prompt_eval_count || 0,
output_tokens: ollamaRes.eval_count || 0,
cache_creation_input_tokens: 0,
cache_read_input_tokens: 0,
},
};
}
function proxyToAnthropic(req, res) {
let body = [];
req.on('data', c => body.push(c));
req.on('end', () => {
const opts = {
hostname: 'api.anthropic.com',
port: 443,
path: req.url,
method: req.method,
headers: { ...req.headers, host: 'api.anthropic.com' },
};
const pr = https.request(opts, pr2 => {
res.writeHead(pr2.statusCode, pr2.headers);
pr2.pipe(res);
});
pr.on('error', e => { res.writeHead(502); res.end(e.message); });
if (body.length) pr.write(Buffer.concat(body));
pr.end();
});
}
function handleMessages(req, res) {
let body = [];
req.on('data', c => body.push(c));
req.on('end', () => {
let parsed;
try {
parsed = JSON.parse(Buffer.concat(body).toString());
} catch {
res.writeHead(400);
res.end('Invalid JSON');
return;
}
const requestModel = parsed.model;
console.log(`\x1b[32m[OLLAMA]\x1b[0m ${req.method} ${req.url} model=${requestModel} stream=${parsed.stream}`);
// Force non-streaming (simpler translation)
const ollamaBody = convertAnthropicToOllama(parsed);
const payload = JSON.stringify(ollamaBody);
const ollamaReq = http.request(
`${OLLAMA}/api/chat`,
{ method: 'POST', headers: { 'Content-Type': 'application/json' } },
ollamaRes => {
let data = [];
ollamaRes.on('data', c => data.push(c));
ollamaRes.on('end', () => {
try {
const ollamaResult = JSON.parse(Buffer.concat(data).toString());
const anthropicResponse = convertOllamaToAnthropic(ollamaResult, requestModel);
const respBody = JSON.stringify(anthropicResponse);
console.log(`\x1b[32m[OLLAMA]\x1b[0m ← ${ollamaResult.eval_count || '?'} tokens, ${((ollamaResult.total_duration || 0) / 1e9).toFixed(1)}s`);
res.writeHead(200, {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(respBody),
});
res.end(respBody);
} catch (e) {
console.error('[OLLAMA] Parse error:', e.message);
res.writeHead(500);
res.end('Ollama response parse error');
}
});
},
);
ollamaReq.on('error', e => {
console.error('[OLLAMA] Connection error:', e.message);
res.writeHead(502);
res.end('Ollama connection error: ' + e.message);
});
ollamaReq.write(payload);
ollamaReq.end();
});
}
const server = http.createServer((req, res) => {
if (req.url?.startsWith('/v1/messages')) {
handleMessages(req, res);
} else {
console.log(`\x1b[33m[ANTHROPIC]\x1b[0m ${req.method} ${req.url}`);
proxyToAnthropic(req, res);
}
});
server.listen(PORT, () => {
console.log(`\n🔀 Ollama proxy on :${PORT}`);
console.log(` /v1/messages → Ollama ${MODEL} (Anthropic format translation)`);
console.log(` everything else → api.anthropic.com\n`);
});