Skip to content

7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.

TypeScript

feat: add legacy completions endpoint (#340)

Stanislav Luchanskiy0b4e2a1b7c88
diff --git a/README.md b/README.md
index 4b848aa2..d5239bc6 100644
--- a/README.md
+++ b/README.md
@@ -86,6 +86,7 @@ Plus a **custom** provider — point chat, embedding, image, or audio models at
- **OpenAI-compatible** — `POST /v1/chat/completions` and `GET /v1/models` work with the official OpenAI SDKs and any OpenAI-compatible client (LangChain, LlamaIndex, Continue, Hermes, etc.). Just change `base_url`.
- **Responses API** — `POST /v1/responses` (the wire format current Codex CLI versions require) is implemented as a translating shim over the same router, with full streaming events and tool calls.
+- **Editor autocomplete** — `POST /v1/completions` translates legacy prompt/suffix requests into the same router, so VS Code ghost-text clients such as Continue can use FreeLLMAPI for inline suggestions.
- **Anthropic Messages API** — `POST /v1/messages` (plus `/v1/messages/count_tokens`) speaks Anthropic's wire format over the same router, so **Claude Code** and the official Anthropic SDKs run against your free pool. `GET /v1/models` is content-negotiated (Anthropic shape when the client sends `anthropic-version`, OpenAI shape otherwise), and Claude families (`opus` / `sonnet` / `haiku` / `default`) map to `auto` or a pinned model on the Keys page. See [Anthropic / Claude clients](#anthropic--claude-clients).
- **Image generation & text-to-speech** — `POST /v1/images/generations` and `POST /v1/audio/speech` route across the providers that serve media models, including custom OpenAI-compatible media endpoints. Browse and toggle them on the dashboard's **Models → Image / Audio** tabs.
- **Streaming and non-streaming** — Server-Sent Events for `stream: true`, JSON response otherwise. Every provider adapter implements both.
@@ -107,7 +108,6 @@ Plus a **custom** provider — point chat, embedding, image, or audio models at
The scope is deliberately narrow. If a feature isn't on this list and isn't below, assume it isn't there yet.
-- **Legacy completions** (`/v1/completions`) — only the chat endpoint is implemented
- **Moderation** (`/v1/moderations`)
- **`n > 1`** (multiple completions per request)
- **Per-user billing / multi-tenant auth** — single-user by design
@@ -313,6 +313,22 @@ for chunk in stream:
print(chunk.choices[0].delta.content or "", end="", flush=True)
```
+**VS Code ghost-text autocomplete (Continue)**
+
+FreeLLMAPI exposes `/v1/completions` for editor autocomplete clients that send legacy OpenAI prompt/suffix requests. Example Continue config:
+
+```yaml
+models:
+ - name: FreeLLMAPI Autocomplete
+ provider: openai
+ model: auto
+ apiBase: http://localhost:3001/v1
+ apiKey: freellmapi-your-unified-key
+ useLegacyCompletionsEndpoint: true
+ roles:
+ - autocomplete
+```
+
**Tool calling**
Pass OpenAI-style `tools` and `tool_choice`; the assistant response round-trips back through the proxy exactly like the OpenAI API. Multi-step flows (assistant `tool_calls` → `tool` role follow-up → final answer) work across every provider the router can reach.
@@ -552,7 +568,7 @@ Stacking free tiers has real trade-offs. Be honest with yourself about them:
Contributors very welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for the dev loop, PR expectations, and the policy on AI/LLM-assisted contributions (short version: welcome, same quality bar as any other PR). Good first PRs:
- **Add a provider** — copy `server/src/providers/openai-compat.ts` as a template, wire it into `server/src/providers/index.ts`, seed its models in `server/src/db/index.ts`, add a test in `server/src/__tests__/providers/`.
-- **Add an endpoint** — moderations, legacy completions. The provider base class can grow new methods; adapters declare which they support.
+- **Add an endpoint** — moderations and other OpenAI-compatible surfaces. The provider base class can grow new methods; adapters declare which they support.
- **Improve the router** — cost-aware routing (cheapest-healthy-fastest tradeoffs), better latency-weighted priority, regional pinning.
- **Dashboard polish** — charts on the Analytics page, key rotation UX, batch import of keys from `.env`.
- **Docs** — more examples, client library snippets for Go/Rust/etc., a deployment recipe for Docker or Fly.
@@ -588,6 +604,7 @@ See [CONTRIBUTING.md](./CONTRIBUTING.md) for the full migration CLI and workflow
<a href="https://github.com/chongjiazhen"><img src="https://images.weserv.nl/?url=github.com/chongjiazhen.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@chongjiazhen" /></a>
<a href="https://github.com/vjsai"><img src="https://images.weserv.nl/?url=github.com/vjsai.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@vjsai" /></a>
<a href="https://github.com/long2ice"><img src="https://images.weserv.nl/?url=github.com/long2ice.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@long2ice" /></a>
+<a href="https://github.com/sadesguy"><img src="https://images.weserv.nl/?url=github.com/sadesguy.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@sadesguy" /></a>
<a href="https://github.com/hodlmybeer69-bit"><img src="https://images.weserv.nl/?url=github.com/hodlmybeer69-bit.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@hodlmybeer69-bit" /></a>
<a href="https://github.com/phoenixikkifullstack"><img src="https://images.weserv.nl/?url=github.com/phoenixikkifullstack.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@phoenixikkifullstack" /></a>
<a href="https://github.com/jtbrennan-git"><img src="https://images.weserv.nl/?url=github.com/jtbrennan-git.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@jtbrennan-git" /></a>
diff --git a/server/src/__tests__/routes/proxy-completions.test.ts b/server/src/__tests__/routes/proxy-completions.test.ts
new file mode 100644
index 00000000..b8824f76
--- /dev/null
+++ b/server/src/__tests__/routes/proxy-completions.test.ts
@@ -0,0 +1,235 @@
+import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vitest';
+import type { Express } from 'express';
+import { createApp } from '../../app.js';
+import { initDb, getDb, getUnifiedApiKey } from '../../db/index.js';
+import { encrypt } from '../../lib/crypto.js';
+import { setRoutingStrategy } from '../../services/router.js';
+
+async function request(app: Express, method: string, path: string, body?: any, headers: Record<string, string> = {}) {
+ const server = app.listen(0);
+ const addr = server.address() as any;
+ const url = `http://127.0.0.1:${addr.port}${path}`;
+
+ const res = await fetch(url, {
+ method,
+ headers: { ...(body ? { 'Content-Type': 'application/json' } : {}), ...headers },
+ body: body ? JSON.stringify(body) : undefined,
+ });
+
+ const data = await res.text();
+ server.close();
+
+ let json: any = null;
+ try { json = JSON.parse(data); } catch {}
+
+ return { status: res.status, body: json, headers: res.headers, raw: data };
+}
+
+function authHeaders() {
+ return { Authorization: `Bearer ${getUnifiedApiKey()}` };
+}
+
+function seedGroqKey() {
+ const db = getDb();
+ const key = encrypt('gsk_completion_test');
+ db.prepare(`
+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled)
+ VALUES ('groq', 'completion-test', ?, ?, ?, 'healthy', 1)
+ `).run(key.encrypted, key.iv, key.authTag);
+}
+
+describe('POST /v1/completions', () => {
+ let app: Express;
+
+ beforeAll(() => {
+ process.env.ENCRYPTION_KEY = '0'.repeat(64);
+ initDb(':memory:');
+ app = createApp();
+ });
+
+ beforeEach(() => {
+ const db = getDb();
+ setRoutingStrategy('priority');
+ db.prepare('DELETE FROM rate_limit_cooldowns').run();
+ db.prepare('DELETE FROM api_keys').run();
+ db.prepare('DELETE FROM requests').run();
+ seedGroqKey();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('adapts a legacy text completion request into a routed chat completion response', async () => {
+ let capturedBody: any = null;
+ const origFetch = global.fetch;
+
+ vi.spyOn(global, 'fetch').mockImplementation(async (url, init) => {
+ const urlStr = typeof url === 'string' ? url : url.toString();
+ if (urlStr.includes('api.groq.com/openai/v1/chat/completions')) {
+ capturedBody = JSON.parse(String(init?.body));
+ return {
+ ok: true,
+ headers: new Headers(),
+ json: () => Promise.resolve({
+ id: 'chatcmpl-completion',
+ object: 'chat.completion',
+ created: 123,
+ model: capturedBody.model,
+ choices: [{
+ index: 0,
+ message: { role: 'assistant', content: ' = 42;' },
+ finish_reason: 'stop',
+ }],
+ usage: { prompt_tokens: 10, completion_tokens: 4, total_tokens: 14 },
+ }),
+ } as any;
+ }
+ return origFetch(url, init);
+ });
+
+ const { status, body, headers } = await request(app, 'POST', '/v1/completions', {
+ model: 'auto',
+ prompt: 'const answer',
+ suffix: '\nconsole.log(answer);',
+ max_tokens: 12,
+ temperature: 0.2,
+ stop: ['\n\n'],
+ }, authHeaders());
+
+ expect(status).toBe(200);
+ expect(headers.get('x-routed-via')).toContain('groq/');
+ expect(body).toMatchObject({
+ id: 'cmpl-chatcmpl-completion',
+ object: 'text_completion',
+ choices: [{ index: 0, text: ' = 42;', finish_reason: 'stop' }],
+ usage: { prompt_tokens: 10, completion_tokens: 4, total_tokens: 14 },
+ });
+ expect(capturedBody.max_tokens).toBe(12);
+ expect(capturedBody.temperature).toBe(0.2);
+ expect(capturedBody.stop).toEqual(['\n\n']);
+ expect(capturedBody.messages[0].role).toBe('system');
+ expect(capturedBody.messages[1].content).toContain('const answer');
+ expect(capturedBody.messages[1].content).toContain('console.log(answer);');
+ });
+
+ it('accepts autocomplete clients that send many stop sequences and forwards a provider-safe subset', async () => {
+ let capturedBody: any = null;
+ const origFetch = global.fetch;
+
+ vi.spyOn(global, 'fetch').mockImplementation(async (url, init) => {
+ const urlStr = typeof url === 'string' ? url : url.toString();
+ if (urlStr.includes('api.groq.com/openai/v1/chat/completions')) {
+ capturedBody = JSON.parse(String(init?.body));
+ return {
+ ok: true,
+ headers: new Headers(),
+ json: () => Promise.resolve({
+ id: 'chatcmpl-stop',
+ object: 'chat.completion',
+ created: 123,
+ model: capturedBody.model,
+ choices: [{
+ index: 0,
+ message: { role: 'assistant', content: 'suggestion' },
+ finish_reason: 'stop',
+ }],
+ usage: { prompt_tokens: 5, completion_tokens: 2, total_tokens: 7 },
+ }),
+ } as any;
+ }
+ return origFetch(url, init);
+ });
+
+ const { status, body } = await request(app, 'POST', '/v1/completions', {
+ model: 'auto',
+ prompt: 'function demo() {',
+ max_tokens: 16,
+ stop: ['\n', '}', ';', '<|end|>', '<|fim_suffix|>', '<|fim_middle|>'],
+ }, authHeaders());
+
+ expect(status).toBe(200);
+ expect(body.choices[0].text).toBe('suggestion');
+ expect(capturedBody.stop).toEqual(['\n', '}', ';', '<|end|>']);
+ });
+
+ it('streams chat deltas as legacy text_completion SSE frames', async () => {
+ const origFetch = global.fetch;
+
+ vi.spyOn(global, 'fetch').mockImplementation(async (url, init) => {
+ const urlStr = typeof url === 'string' ? url : url.toString();
+ if (urlStr.includes('api.groq.com/openai/v1/chat/completions')) {
+ const body = JSON.parse(String(init?.body));
+ expect(body.stream).toBe(true);
+ const encoder = new TextEncoder();
+ const stream = new ReadableStream({
+ start(controller) {
+ controller.enqueue(encoder.encode('data: {"id":"chatcmpl-stream","object":"chat.completion.chunk","created":123,"model":"test","choices":[{"index":0,"delta":{"content":"foo"},"finish_reason":null}]}\n\n'));
+ controller.enqueue(encoder.encode('data: {"id":"chatcmpl-stream","object":"chat.completion.chunk","created":123,"model":"test","choices":[{"index":0,"delta":{"content":"bar"},"finish_reason":null}]}\n\n'));
+ controller.enqueue(encoder.encode('data: {"id":"chatcmpl-stream","object":"chat.completion.chunk","created":123,"model":"test","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}\n\n'));
+ controller.enqueue(encoder.encode('data: [DONE]\n\n'));
+ controller.close();
+ },
+ });
+ return {
+ ok: true,
+ headers: new Headers(),
+ body: stream,
+ } as any;
+ }
+ return origFetch(url, init);
+ });
+
+ const { status, raw, headers } = await request(app, 'POST', '/v1/completions', {
+ model: 'auto',
+ prompt: '',
+ stream: true,
+ }, authHeaders());
+
+ expect(status).toBe(200);
+ expect(headers.get('content-type')).toContain('text/event-stream');
+ expect(raw).toContain('"object":"text_completion"');
+ expect(raw).toContain('"text":"foo"');
+ expect(raw).toContain('"text":"bar"');
+ expect(raw).toContain('data: [DONE]');
+ });
+
+ it('passes stop through from chat completions after applying the same provider-safe cap', async () => {
+ let capturedBody: any = null;
+ const origFetch = global.fetch;
+
+ vi.spyOn(global, 'fetch').mockImplementation(async (url, init) => {
+ const urlStr = typeof url === 'string' ? url : url.toString();
+ if (urlStr.includes('api.groq.com/openai/v1/chat/completions')) {
+ capturedBody = JSON.parse(String(init?.body));
+ return {
+ ok: true,
+ headers: new Headers(),
+ json: () => Promise.resolve({
+ id: 'chatcmpl-chat-stop',
+ object: 'chat.completion',
+ created: 123,
+ model: capturedBody.model,
+ choices: [{
+ index: 0,
+ message: { role: 'assistant', content: 'done' },
+ finish_reason: 'stop',
+ }],
+ usage: { prompt_tokens: 3, completion_tokens: 1, total_tokens: 4 },
+ }),
+ } as any;
+ }
+ return origFetch(url, init);
+ });
+
+ const { status, body } = await request(app, 'POST', '/v1/chat/completions', {
+ model: 'auto',
+ messages: [{ role: 'user', content: 'hi' }],
+ stop: ['a', 'b', 'c', 'd', 'e'],
+ }, authHeaders());
+
+ expect(status).toBe(200);
+ expect(body.choices[0].message.content).toBe('done');
+ expect(capturedBody.stop).toEqual(['a', 'b', 'c', 'd']);
+ });
+});
diff --git a/server/src/providers/base.ts b/server/src/providers/base.ts
index 104ac13c..800d851c 100644
--- a/server/src/providers/base.ts
+++ b/server/src/providers/base.ts
@@ -44,6 +44,7 @@ export interface CompletionOptions {
temperature?: number;
max_tokens?: number;
top_p?: number;
+ stop?: string | string[];
tools?: ChatToolDefinition[];
tool_choice?: ChatToolChoice;
parallel_tool_calls?: boolean;
diff --git a/server/src/providers/cloudflare.ts b/server/src/providers/cloudflare.ts
index cf1eabdc..19d6cf43 100644
--- a/server/src/providers/cloudflare.ts
+++ b/server/src/providers/cloudflare.ts
@@ -52,6 +52,7 @@ export class CloudflareProvider extends BaseProvider {
temperature: options?.temperature,
max_tokens: options?.max_tokens,
top_p: options?.top_p,
+ stop: options?.stop,
tools: options?.tools,
tool_choice: options?.tool_choice,
parallel_tool_calls: options?.parallel_tool_calls,
@@ -98,6 +99,7 @@ export class CloudflareProvider extends BaseProvider {
temperature: options?.temperature,
max_tokens: options?.max_tokens,
top_p: options?.top_p,
+ stop: options?.stop,
tools: options?.tools,
tool_choice: options?.tool_choice,
parallel_tool_calls: options?.parallel_tool_calls,
diff --git a/server/src/providers/cohere.ts b/server/src/providers/cohere.ts
index ab1728e6..c2cc45fc 100644
--- a/server/src/providers/cohere.ts
+++ b/server/src/providers/cohere.ts
@@ -45,6 +45,7 @@ export class CohereProvider extends BaseProvider {
temperature: options?.temperature,
max_tokens: options?.max_tokens,
top_p: options?.top_p,
+ stop: options?.stop,
tools: sanitizeCohereTools(options?.tools),
tool_choice: options?.tool_choice,
};
@@ -89,6 +90,7 @@ export class CohereProvider extends BaseProvider {
temperature: options?.temperature,
max_tokens: options?.max_tokens,
top_p: options?.top_p,
+ stop: options?.stop,
tools: sanitizeCohereTools(options?.tools),
tool_choice: options?.tool_choice,
stream: true,
diff --git a/server/src/providers/google.ts b/server/src/providers/google.ts
index ec3004fd..aa0ea95c 100644
--- a/server/src/providers/google.ts
+++ b/server/src/providers/google.ts
@@ -383,6 +383,11 @@ function extractText(parts: GeminiPart[] | undefined): string | null {
return text.length > 0 ? text : null;
}
+function toGeminiStopSequences(stop: CompletionOptions['stop']): string[] | undefined {
+ if (!stop) return undefined;
+ return Array.isArray(stop) ? stop : [stop];
+}
+
export class GoogleProvider extends BaseProvider {
readonly platform = 'google' as const;
readonly name = 'Google AI Studio';
@@ -403,6 +408,7 @@ export class GoogleProvider extends BaseProvider {
temperature: options?.temperature,
maxOutputTokens: options?.max_tokens,
topP: options?.top_p,
+ stopSequences: toGeminiStopSequences(options?.stop),
},
tools,
// functionCallingConfig is only valid when real function tools are present;
@@ -479,6 +485,7 @@ export class GoogleProvider extends BaseProvider {
temperature: options?.temperature,
maxOutputTokens: options?.max_tokens,
topP: options?.top_p,
+ stopSequences: toGeminiStopSequences(options?.stop),
},
tools,
toolConfig: hasFunctionDeclarations(tools) ? toGeminiToolConfig(options?.tool_choice) : undefined,
diff --git a/server/src/providers/openai-compat.ts b/server/src/providers/openai-compat.ts
index 86caae9c..d6e7ade7 100644
--- a/server/src/providers/openai-compat.ts
+++ b/server/src/providers/openai-compat.ts
@@ -111,6 +111,7 @@ export class OpenAICompatProvider extends BaseProvider {
temperature: options?.temperature,
max_tokens: options?.max_tokens,
top_p: options?.top_p,
+ stop: options?.stop,
tools: options?.tools,
tool_choice: options?.tool_choice,
parallel_tool_calls: this.resolveParallelToolCalls(options),
@@ -183,6 +184,7 @@ export class OpenAICompatProvider extends BaseProvider {
temperature: options?.temperature,
max_tokens: options?.max_tokens,
top_p: options?.top_p,
+ stop: options?.stop,
tools: options?.tools,
tool_choice: options?.tool_choice,
parallel_tool_calls: this.resolveParallelToolCalls(options),
diff --git a/server/src/routes/proxy.ts b/server/src/routes/proxy.ts
index aed806e2..65aa964e 100644
--- a/server/src/routes/proxy.ts
+++ b/server/src/routes/proxy.ts
@@ -363,6 +363,13 @@ const toolChoiceSchema = z.union([
}),
]);
+const stopSchema = z.union([z.string(), z.array(z.string()).min(1).max(64)]);
+
+function providerSafeStop(stop: string | string[] | undefined): string | string[] | undefined {
+ if (!Array.isArray(stop)) return stop;
+ return stop.slice(0, 4);
+}
+
const chatCompletionSchema = z.object({
messages: z.array(z.union([
systemMessageSchema,
@@ -378,6 +385,7 @@ const chatCompletionSchema = z.object({
// treated as unset on forward. (#200)
max_tokens: z.number().int().optional(),
top_p: z.number().min(0).max(1).optional(),
+ stop: stopSchema.optional(),
stream: z.boolean().optional(),
// Top-level tool knobs may arrive as explicit nulls from clients that
// serialize every field of their request struct; all treated as absent
@@ -533,6 +541,380 @@ proxyRouter.post('/audio/speech', async (req: Request, res: Response) => {
}
});
+const CompletionBody = z.object({
+ model: z.string().optional(),
+ prompt: z.string(),
+ suffix: z.string().optional(),
+ temperature: z.number().min(0).max(2).optional(),
+ max_tokens: z.number().int().optional(),
+ top_p: z.number().min(0).max(1).optional(),
+ stop: stopSchema.optional(),
+ stream: z.boolean().optional(),
+});
+
+function completionPromptToMessages(prompt: string, suffix?: string): ChatMessage[] {
+ const hasSuffix = suffix !== undefined && suffix.length > 0;
+ return [
+ {
+ role: 'system',
+ content: [
+ 'You are a code autocomplete engine.',
+ 'Complete at the cursor and return only the text to insert.',
+ 'Do not include markdown fences, explanations, or repeat surrounding code.',
+ ].join(' '),
+ },
+ {
+ role: 'user',
+ content: hasSuffix
+ ? `Prefix before cursor:\n${prompt}\n\nSuffix after cursor:\n${suffix}\n\nCompletion to insert:`
+ : `Prefix before cursor:\n${prompt}\n\nCompletion to insert:`,
+ },
+ ];
+}
+
+function completionTextFromChat(result: any): string {
+ return contentToString(result?.choices?.[0]?.message?.content ?? '');
+}
+
+function completionIdFromChat(id: string | undefined): string {
+ if (!id) return `cmpl-${Date.now()}`;
+ return id.startsWith('cmpl-') ? id : `cmpl-${id}`;
+}
+
+function legacyCompletionChunk(route: RouteResult, chunk: any, text: string) {
+ return {
+ id: completionIdFromChat(chunk?.id),
+ object: 'text_completion',
+ created: chunk?.created ?? Math.floor(Date.now() / 1000),
+ model: route.modelId,
+ choices: [{
+ text,
+ index: chunk?.choices?.[0]?.index ?? 0,
+ logprobs: null,
+ finish_reason: chunk?.choices?.[0]?.finish_reason ?? null,
+ }],
+ };
+}
+
+// OpenAI-compatible legacy completions endpoint. Editor ghost-text clients
+// (notably Continue autocomplete) still send prompt/suffix requests here; route
+// those through chat models while preserving the legacy text_completion shape.
+proxyRouter.post('/completions', async (req: Request, res: Response) => {
+ const start = Date.now();
+ const requestGroupId = getRequestGroupId(req);
+ res.setHeader('X-Request-ID', requestGroupId);
+
+ const token = extractApiToken(req);
+ const unifiedKey = getUnifiedApiKey();
+ if (!token || !timingSafeStringEqual(token, unifiedKey)) {
+ res.status(401).json({
+ error: { message: 'Invalid API key', type: 'authentication_error' },
+ });
+ return;
+ }
+
+ const parsed = CompletionBody.safeParse(req.body);
+ if (!parsed.success) {
+ const detail = parsed.error.errors
+ .map(e => (e.path.length ? `${e.path.join('.')}: ${e.message}` : e.message))
+ .slice(0, 5)
+ .join(', ');
+ res.status(400).json({
+ error: { message: `Invalid request: ${detail}`, type: 'invalid_request_error' },
+ });
+ return;
+ }
+
+ const { model: requestedModel, prompt, suffix, temperature, top_p, stream } = parsed.data;
+ const requestedModelLabel = requestedModel ?? 'auto';
+ const max_tokens = parsed.data.max_tokens != null && parsed.data.max_tokens > 0
+ ? parsed.data.max_tokens : 128;
+ const stop = providerSafeStop(parsed.data.stop);
+ const messages = completionPromptToMessages(prompt, suffix);
+ const estimatedInputTokens = messages.reduce((sum, m) => sum + Math.ceil(contentToString(m.content).length / 4), 0);
+ const estimatedTotal = estimatedInputTokens + max_tokens;
+
+ let resolvedChain: ResolvedChain | undefined;
+ if (isAutoModel(requestedModel)) {
+ resolvedChain = resolveRoutingChain(requestedModel);
+ }
+
+ let preferredModel: number | undefined;
+ let groupChain: ChainRow[] | undefined;
+
+ if (!isAutoModel(requestedModel) && requestedModel) {
+ const db = getDb();
+ const members = isUnifyEnabled() ? resolveRequestedIdToMembers(requestedModel, getModelGroups()) : null;
+ if (members && members.length > 0) {
+ groupChain = resolveModelGroupCandidates(members);
+ if (groupChain.length === 0) {
+ const placeholders = members.map(() => '?').join(',');
+ const anyEnabled = db.prepare(`SELECT 1 FROM models WHERE id IN (${placeholders}) AND enabled = 1 LIMIT 1`).get(...members);
+ const reason = anyEnabled ? 'has no providers with an enabled key' : 'is disabled';
+ res.status(400).json({
+ error: {
+ message: `Model '${requestedModel}' ${reason}. Use 'auto' (or omit the 'model' field) to auto-route, or call /v1/models for the available list.`,
+ type: 'invalid_request_error',
+ code: 'model_not_found',
+ },
+ });
+ return;
+ }
+ } else {
+ const enabled = db.prepare('SELECT id FROM models WHERE model_id = ? AND enabled = 1').get(requestedModel) as { id: number } | undefined;
+ if (enabled) {
+ preferredModel = enabled.id;
+ } else {
+ const disabled = db.prepare('SELECT id FROM models WHERE model_id = ?').get(requestedModel) as { id: number } | undefined;
+ const reason = disabled ? 'is disabled' : 'is not in the catalog';
+ res.status(400).json({
+ error: {
+ message: `Model '${requestedModel}' ${reason}. Use 'auto' (or omit the 'model' field) to auto-route, or call /v1/models for the available list.`,
+ type: 'invalid_request_error',
+ code: 'model_not_found',
+ },
+ });
+ return;
+ }
+ }
+ }
+
+ const pinnedModelId = requestedModel && !isAutoModel(requestedModel) ? requestedModel : null;
+ const skipKeys = new Set<string>();
+ const skipModels = new Set<number>();
+ let lastError: any = null;
+
+ for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
+ let route: RouteResult;
+ try {
+ route = routeRequest(
+ estimatedTotal,
+ skipKeys.size > 0 ? skipKeys : undefined,
+ preferredModel,
+ false,
+ false,
+ skipModels.size > 0 ? skipModels : undefined,
+ groupChain ?? resolvedChain?.chain,
+ );
+ } catch (err: any) {
+ if (lastError) {
+ res.status(429).json({
+ error: {
+ message: `All models rate-limited. Last error: ${sanitizeProviderErrorMessage(lastError.message)}`,
+ type: 'rate_limit_error',
+ },
+ });
+ } else {
+ const disposition: string[] = Array.isArray(err.diagnostics) ? err.diagnostics : [];
+ console.warn(
+ `[Proxy] legacy completions routing exhausted (no upstream tried) req=${shortRequestId(requestGroupId)} ` +
+ `requested=${requestedModelLabel} candidates=${disposition.length}` +
+ (disposition.length ? `:\n ${disposition.join('\n ')}` : ''),
+ );
+ res.status(err.status ?? 503).json({
+ error: { message: err.message, type: 'routing_error' },
+ });
+ }
+ return;
+ }
+
+ traceRouteEvent('Proxy', {
+ event: attempt === 0 ? 'start' : 'next',
+ requestId: requestGroupId,
+ attempt,
+ platform: route.platform,
+ model: route.modelId,
+ requestedModel: attempt === 0 ? requestedModelLabel : undefined,
+ });
+
+ try {
+ if (stream) {
+ let totalOutputTokens = 0;
+ let headerSent = false;
+ let ttfbMs: number | null = null;
+ let sawText = false;
+ const buffered: unknown[] = [];
+
+ const flushHeaders = () => {
+ if (headerSent) return;
+ ttfbMs = Date.now() - start;
+ res.setHeader('Content-Type', 'text/event-stream');
+ res.setHeader('Cache-Control', 'no-cache');
+ res.setHeader('Connection', 'keep-alive');
+ res.setHeader('X-Routed-Via', `${route.platform}/${route.modelId}`);
+ if (attempt > 0) res.setHeader('X-Fallback-Attempts', String(attempt));
+ headerSent = true;
+ for (const frame of buffered) res.write(`data: ${JSON.stringify(frame)}\n\n`);
+ buffered.length = 0;
+ };
+
+ try {
+ const gen = route.provider.streamChatCompletion(
+ route.apiKey,
+ messages,
+ route.modelId,
+ { temperature, max_tokens, top_p, stop },
+ quotaContextForRoute(route, 'chat/completions'),
+ );
+
+ for await (const chunk of gen) {
+ const text = streamChunkText(chunk);
+ if (text.length > 0) sawText = true;
+ totalOutputTokens += Math.ceil(text.length / 4);
+ const frame = legacyCompletionChunk(route, chunk, text);
+ if (!headerSent && !sawText) {
+ buffered.push(frame);
+ continue;
+ }
+ flushHeaders();
+ res.write(`data: ${JSON.stringify(frame)}\n\n`);
+ }
+
+ if (!sawText) {
+ throw new Error(`empty completion from ${route.displayName} (legacy stream produced no text)`);
+ }
+
+ flushHeaders();
+ res.write('data: [DONE]\n\n');
+ res.end();
+
+ recordRequest(route.platform, route.modelId, route.keyId);
+ recordTokens(route.platform, route.modelId, route.keyId, estimatedInputTokens + totalOutputTokens);
+ recordSuccess(route.modelDbId);
+ traceRouteEvent('Proxy', {
+ event: 'ok',
+ requestId: requestGroupId,
+ attempt,
+ platform: route.platform,
+ model: route.modelId,
+ latencyMs: Date.now() - start,
+ inputTokens: estimatedInputTokens,
+ outputTokens: totalOutputTokens,
+ });
+ logRequest(route.platform, route.modelId, route.keyId, 'success', estimatedInputTokens, totalOutputTokens, Date.now() - start, null, ttfbMs, pinnedModelId);
+ return;
+ } catch (streamErr: any) {
+ if (headerSent) {
+ console.error(`[Proxy] Mid-stream legacy completion error from ${route.displayName}:`, streamErr.message);
+ const payload = { error: { message: `Provider error (${route.displayName}): stream interrupted`, type: 'stream_error' } };
+ try { res.write(`data: ${JSON.stringify(payload)}\n\n`); } catch { /* socket gone */ }
+ try { res.write('data: [DONE]\n\n'); res.end(); } catch { /* socket gone */ }
+ traceRouteEvent('Proxy', {
+ event: 'fail',
+ requestId: requestGroupId,
+ attempt,
+ platform: route.platform,
+ model: route.modelId,
+ latencyMs: Date.now() - start,
+ error: sanitizeProviderErrorMessage(streamErr.message),
+ });
+ logRequest(route.platform, route.modelId, route.keyId, 'error', estimatedInputTokens, totalOutputTokens, Date.now() - start, sanitizeProviderErrorMessage(streamErr.message), ttfbMs, pinnedModelId);
+ return;
+ }
+ throw streamErr;
+ }
+ } else {
+ const result = await route.provider.chatCompletion(
+ route.apiKey,
+ messages,
+ route.modelId,
+ { temperature, max_tokens, top_p, stop },
+ quotaContextForRoute(route, 'chat/completions'),
+ );
+
+ const text = completionTextFromChat(result);
+ if (!text) {
+ throw new Error(`empty completion from ${route.displayName}`);
+ }
+
+ const totalTokens = result.usage?.total_tokens ?? 0;
+ recordRequest(route.platform, route.modelId, route.keyId);
+ recordTokens(route.platform, route.modelId, route.keyId, totalTokens);
+ recordSuccess(route.modelDbId);
+
+ res.setHeader('X-Routed-Via', `${route.platform}/${route.modelId}`);
+ if (attempt > 0) res.setHeader('X-Fallback-Attempts', String(attempt));
+ res.json({
+ id: completionIdFromChat(result.id),
+ object: 'text_completion',
+ created: result.created ?? Math.floor(Date.now() / 1000),
+ model: route.modelId,
+ choices: [{
+ text,
+ index: result.choices?.[0]?.index ?? 0,
+ logprobs: null,
+ finish_reason: result.choices?.[0]?.finish_reason ?? 'stop',
+ }],
+ usage: result.usage,
+ });
+
+ traceRouteEvent('Proxy', {
+ event: 'ok',
+ requestId: requestGroupId,
+ attempt,
+ platform: route.platform,
+ model: route.modelId,
+ latencyMs: Date.now() - start,
+ inputTokens: result.usage?.prompt_tokens ?? 0,
+ outputTokens: result.usage?.completion_tokens ?? 0,
+ });
+ logRequest(route.platform, route.modelId, route.keyId, 'success', result.usage?.prompt_tokens ?? 0, result.usage?.completion_tokens ?? 0, Date.now() - start, null, null, pinnedModelId);
+ return;
+ }
+ } catch (err: any) {
+ const latency = Date.now() - start;
+ const safeError = sanitizeProviderErrorMessage(err.message);
+ traceRouteEvent('Proxy', {
+ event: 'fail',
+ requestId: requestGroupId,
+ attempt,
+ platform: route.platform,
+ model: route.modelId,
+ latencyMs: latency,
+ error: safeError,
+ });
+ logRequest(route.platform, route.modelId, route.keyId, 'error', estimatedInputTokens, 0, latency, safeError, null, pinnedModelId);
+
+ if (isRetryableError(err)) {
+ if (isModelNotFoundError(err) || isModelAccessForbiddenError(err)) skipModels.add(route.modelDbId);
+ skipKeys.add(`${route.platform}:${route.modelId}:${route.keyId}`);
+ setCooldown(
+ route.platform,
+ route.modelId,
+ route.keyId,
+ isPaymentRequiredError(err)
+ ? PAYMENT_REQUIRED_COOLDOWN_MS
+ : isModelAccessForbiddenError(err)
+ ? MODEL_FORBIDDEN_COOLDOWN_MS
+ : getCooldownDurationForLimit(route.platform, route.modelId, route.keyId, {
+ rpd: route.rpdLimit,
+ tpd: route.tpdLimit,
+ }, err.retryAfterMs),
+ );
+ recordRateLimitHit(route.modelDbId);
+ learnLimitFromError(route.modelDbId, err);
+ lastError = err;
+ continue;
+ }
+
+ res.status(502).json({
+ error: {
+ message: `Provider error (${route.displayName}): ${safeError}`,
+ type: 'provider_error',
+ },
+ });
+ return;
+ }
+ }
+
+ res.status(429).json({
+ error: {
+ message: `All models rate-limited after ${MAX_RETRIES} attempts. Last: ${sanitizeProviderErrorMessage(lastError?.message)}`,
+ type: 'rate_limit_error',
+ },
+ });
+});
+
proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
const start = Date.now();
const requestGroupId = getRequestGroupId(req);
@@ -577,6 +959,7 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
// 'required'; tool definitions get their 'function' type re-defaulted.
const max_tokens = parsed.data.max_tokens != null && parsed.data.max_tokens > 0
? parsed.data.max_tokens : undefined;
+ const stop = providerSafeStop(parsed.data.stop);
const tool_choice = parsed.data.tool_choice === 'any' ? 'required' as const : parsed.data.tool_choice ?? undefined;
const tools = parsed.data.tools?.map(t => ({ ...t, type: 'function' as const }));
const parallel_tool_calls = parsed.data.parallel_tool_calls ?? undefined;
@@ -733,7 +1116,7 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
res.status(422).json({ error: { message: 'Fusion does not support tool calling yet. Use a tool-capable model directly.', type: 'invalid_request_error', code: 'fusion_no_tools' } });
return;
}
- const fusionOptions = { temperature, max_tokens, top_p };
+ const fusionOptions = { temperature, max_tokens, top_p, stop };
const fusionConfig = parsed.data.fusion ?? {};
if (stream) {
@@ -1030,7 +1413,7 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
try {
const gen = route.provider.streamChatCompletion(
route.apiKey, outboundMessages, route.modelId,
- { temperature, max_tokens, top_p, tools, tool_choice, parallel_tool_calls },
+ { temperature, max_tokens, top_p, stop, tools, tool_choice, parallel_tool_calls },
quotaContextForRoute(route, 'chat/completions'),
);
@@ -1228,7 +1611,7 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
} else {
const result = await route.provider.chatCompletion(
route.apiKey, outboundMessages, route.modelId,
- { temperature, max_tokens, top_p, tools, tool_choice, parallel_tool_calls },
+ { temperature, max_tokens, top_p, stop, tools, tool_choice, parallel_tool_calls },
quotaContextForRoute(route, 'chat/completions'),
);
diff --git a/shared/types.ts b/shared/types.ts
index 49dee0d6..35ff3ffe 100644
--- a/shared/types.ts
+++ b/shared/types.ts
@@ -229,6 +229,7 @@ export interface ChatCompletionRequest {
max_tokens?: number;
stream?: boolean;
top_p?: number;
+ stop?: string | string[];
tools?: ChatToolDefinition[];
tool_choice?: ChatToolChoice;
parallel_tool_calls?: boolean;