Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 1x 1x | /**
* AgentKits — Provider Proxy Server
*
* Starts a local OpenAI-compatible proxy that routes to the cheapest/fastest provider.
*
* Usage:
* import { startProxy } from 'agentkits/proxy';
* await startProxy({ port: 3000, providers: [...] });
*
* CLI:
* npx agentkits serve --port 3000
*
* Then use as drop-in OpenAI replacement:
* const client = new OpenAI({ baseURL: 'http://localhost:3000/v1', apiKey: 'unused' });
*/
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { createChat, createEmbedding } from '../index.js';
import type { ChatConfig } from '../llm/index.js';
import type { EmbeddingConfig } from '../embedding/index.js';
// ── Types ──────────────────────────────────────────────────────────
export interface ProxyConfig {
port?: number;
host?: string;
/** Chat providers in priority order (first = primary) */
chatProviders?: ChatConfig[];
/** Embedding providers in priority order */
embeddingProviders?: EmbeddingConfig[];
/** Route strategy */
strategy?: 'priority' | 'round-robin' | 'random';
/** CORS enabled (default: true) */
cors?: boolean;
/** Log requests (default: true) */
log?: boolean;
}
// ── Server ─────────────────────────────────────────────────────────
export async function startProxy(config: ProxyConfig = {}): Promise<{ url: string; close: () => void }> {
const {
port = 3000,
host = '0.0.0.0',
chatProviders = [],
embeddingProviders = [],
strategy = 'priority',
cors = true,
log = true,
} = config;
// Auto-detect providers from env if not specified
const chatClients = chatProviders.length > 0
? chatProviders.map(p => createChat(p))
: autoDetectChat();
const embeddingClients = embeddingProviders.length > 0
? embeddingProviders.map(p => createEmbedding(p))
: autoDetectEmbedding();
let roundRobinIdx = 0;
function selectClient<T extends Array<any>>(clients: T): T[number] {
if (clients.length === 0) throw new Error('No providers configured');
switch (strategy) {
case 'round-robin':
return clients[roundRobinIdx++ % clients.length];
case 'random':
return clients[Math.floor(Math.random() * clients.length)];
case 'priority':
default:
return clients[0];
}
}
const server = createServer(async (req: IncomingMessage, res: ServerResponse) => {
// CORS
if (cors) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
}
const url = req.url ?? '';
try {
// Models list
if (url.endsWith('/models') && req.method === 'GET') {
const models = [
...chatClients.map(c => ({ id: `${c.config.provider}/${c.config.model}`, object: 'model', owned_by: c.config.provider })),
...embeddingClients.map(c => ({ id: `${c.config.provider}/${c.config.model}`, object: 'model', owned_by: c.config.provider })),
];
json(res, { object: 'list', data: models });
return;
}
// Chat completions
if (url.endsWith('/chat/completions') && req.method === 'POST') {
const body = await readBody(req);
const client = selectClient(chatClients);
if (log) console.log(`[agentkits-proxy] chat → ${client.config.provider}/${client.config.model}`);
const messages = body.messages ?? [];
if (body.stream) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
});
for await (const chunk of client.stream(messages, {
temperature: body.temperature,
maxTokens: body.max_tokens,
})) {
const data = {
id: `chatcmpl-${Date.now()}`,
object: 'chat.completion.chunk',
model: client.config.model,
choices: [{
index: 0,
delta: { content: chunk.content },
finish_reason: chunk.done ? 'stop' : null,
}],
};
res.write(`data: ${JSON.stringify(data)}\n\n`);
}
res.write('data: [DONE]\n\n');
res.end();
} else {
const response = await client.chat(messages, {
temperature: body.temperature,
maxTokens: body.max_tokens,
});
json(res, {
id: `chatcmpl-${Date.now()}`,
object: 'chat.completion',
model: client.config.model,
choices: [{
index: 0,
message: { role: 'assistant', content: response.content },
finish_reason: response.finishReason ?? 'stop',
}],
usage: response.usage ? {
prompt_tokens: response.usage.promptTokens,
completion_tokens: response.usage.completionTokens,
total_tokens: response.usage.totalTokens,
} : undefined,
});
}
return;
}
// Embeddings
if (url.endsWith('/embeddings') && req.method === 'POST') {
const body = await readBody(req);
const client = selectClient(embeddingClients);
if (log) console.log(`[agentkits-proxy] embed → ${client.config.provider}/${client.config.model}`);
const input = Array.isArray(body.input) ? body.input : [body.input];
const vectors = await client.embedBatch(input);
json(res, {
object: 'list',
model: client.config.model,
data: vectors.map((v, i) => ({
object: 'embedding',
index: i,
embedding: Array.from(v),
})),
usage: { prompt_tokens: 0, total_tokens: 0 },
});
return;
}
// Health check
if (url === '/' || url === '/health') {
json(res, {
status: 'ok',
name: 'agentkits-proxy',
chatProviders: chatClients.map(c => `${c.config.provider}/${c.config.model}`),
embeddingProviders: embeddingClients.map(c => `${c.config.provider}/${c.config.model}`),
strategy,
});
return;
}
res.writeHead(404);
json(res, { error: 'Not found' });
} catch (e: any) {
if (log) console.error(`[agentkits-proxy] Error:`, e.message);
res.writeHead(500);
json(res, { error: { message: e.message, type: 'proxy_error' } });
}
});
return new Promise((resolve) => {
server.listen(port, host, () => {
const url = `http://${host === '0.0.0.0' ? 'localhost' : host}:${port}`;
if (log) {
console.log(`\n🚀 AgentKits Proxy running at ${url}`);
console.log(` Chat: ${chatClients.map(c => c.config.provider).join(' → ')}`);
console.log(` Embedding: ${embeddingClients.map(c => c.config.provider).join(' → ')}`);
console.log(` Strategy: ${strategy}`);
console.log(`\n Use as OpenAI drop-in: baseURL="${url}/v1"\n`);
}
resolve({
url,
close: () => server.close(),
});
});
});
}
// ── Helpers ─────────────────────────────────────────────────────────
function json(res: ServerResponse, data: any) {
if (!res.headersSent) res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
}
function readBody(req: IncomingMessage): Promise<any> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
req.on('data', (chunk: Buffer) => chunks.push(chunk));
req.on('end', () => {
try { resolve(JSON.parse(Buffer.concat(chunks).toString())); }
catch { resolve({}); }
});
req.on('error', reject);
});
}
function autoDetectChat() {
const detected: ReturnType<typeof createChat>[] = [];
const providers = ['deepseek', 'dashscope', 'gemini', 'openai', 'zhipu', 'moonshot', 'ollama'] as const;
const envs: Record<string, string[]> = {
deepseek: ['DEEPSEEK_API_KEY'], dashscope: ['DASHSCOPE_API_KEY'],
gemini: ['GEMINI_API_KEY', 'GOOGLE_API_KEY'], openai: ['OPENAI_API_KEY'],
zhipu: ['ZHIPU_API_KEY'], moonshot: ['MOONSHOT_API_KEY'], ollama: [],
};
for (const p of providers) {
if (envs[p].length === 0 || envs[p].some(k => !!process.env[k])) {
try { detected.push(createChat({ provider: p })); } catch { /* skip */ }
}
}
return detected;
}
function autoDetectEmbedding() {
const detected: ReturnType<typeof createEmbedding>[] = [];
const providers = ['deepseek', 'dashscope', 'gemini', 'openai', 'zhipu', 'ollama'] as const;
const envs: Record<string, string[]> = {
deepseek: ['DEEPSEEK_API_KEY'], dashscope: ['DASHSCOPE_API_KEY'],
gemini: ['GEMINI_API_KEY', 'GOOGLE_API_KEY'], openai: ['OPENAI_API_KEY'],
zhipu: ['ZHIPU_API_KEY'], ollama: [],
};
for (const p of providers) {
if (envs[p].length === 0 || envs[p].some(k => !!process.env[k])) {
try { detected.push(createEmbedding({ provider: p })); } catch { /* skip */ }
}
}
return detected;
}
|