Spaces:
Running
Running
Sync from felladrin/MiniSearch@038cc22 (part 2)
Browse filesFiles changed (11)
- package-lock.json+3-3
- server/configEndpointServerHook.ts+5-22
- server/internalApiConfig.test.tsAdded+105
- server/internalApiConfig.tsAdded+85
- server/internalApiEndpointServerHook.test.ts+148-92
- server/internalApiEndpointServerHook.ts+47-185
- server/internalApiModelPicker.test.tsAdded+101
- server/internalApiModelPicker.tsAdded+72
- server/statusEndpointServerHook.ts+4-8
- server/utils/chatCompletionSse.tsAdded+68
- server/utils/readJsonBody.tsAdded+49
4506 unmodified lines4507450845094510451145124510451145124513451445154506 unmodified lines } }, "node_modules/knip": { "version": "6.47.0", "resolved": "https://registry.npmjs.org/knip/-/knip-6.47.0.tgz", "integrity": "sha512-nYmQnk0YqDXIJrYViJz88c8xw3tBDkpuAmofo58EkVPnKr6DnRKYtf6oIqcGVHZvXDE+gtmFuYx277/QsWng+A==", "version": "6.48.0", "resolved": "https://registry.npmjs.org/knip/-/knip-6.48.0.tgz", "integrity": "sha512-v+Gfp6uiOeXaaj+Khk2Z7/fTTZYWLnDwxZapQUyy8WoQFLYXiUHXqRdFJTwRnrKNA1gPXTPi5NGTKKLXyImVrg==", "dev": true, "funding": [ {12345456789101112141516171819202122232425261314156 unmodified lines222324252627284 unmodified lines33343549505152535455363738394041import type { PreviewServer, ViteDevServer } from "vite";import { DEFAULT_INFERENCE_TYPE, DEFAULT_INTERNAL_API_CONTEXT_LENGTH, DEFAULT_INTERNAL_API_NAME, DEFAULT_PARENT_WINDOW_ORIGINS, DEFAULT_WLLAMA_GPU_MODEL_ID, DEFAULT_WLLAMA_MODEL_ID, type ServerConfig,} from "../shared/serverConfig.ts";import { getInternalApiConfig } from "./internalApiConfig.ts";import { parseCommaSeparatedList } from "./parseCommaSeparatedList.ts";import { getSearchToken } from "./searchToken.ts";
function getInternalApiContextLength(): number { const value = process.env.INTERNAL_OPENAI_COMPATIBLE_API_CONTEXT_LENGTH; if (!value) return DEFAULT_INTERNAL_API_CONTEXT_LENGTH; const contextLength = Number(value); if (Number.isInteger(contextLength) && contextLength > 0) { return contextLength; } console.error( `INTERNAL_OPENAI_COMPATIBLE_API_CONTEXT_LENGTH is not a positive integer ("${value}"); using ${DEFAULT_INTERNAL_API_CONTEXT_LENGTH}.`, ); return DEFAULT_INTERNAL_API_CONTEXT_LENGTH;}
/** * Serves the server config at /api/config at runtime rather than compiling it * in, so the published Docker image is configurable via environment variables.6 unmodified lines return next(); }
const internalApi = getInternalApiConfig(); const config: ServerConfig = { accessKeysEnabled: parseCommaSeparatedList(process.env.ACCESS_KEYS).length > 0,4 unmodified lines // one, so most deployments would hand GPUs the CPU default. wllamaDefaultGpuModelId: process.env.WLLAMA_DEFAULT_GPU_MODEL_ID || DEFAULT_WLLAMA_GPU_MODEL_ID, internalApiEnabled: Boolean( process.env.INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL, ), internalApiName: process.env.INTERNAL_OPENAI_COMPATIBLE_API_NAME || DEFAULT_INTERNAL_API_NAME, internalApiContextLength: getInternalApiContextLength(), internalApiEnabled: Boolean(internalApi.baseUrl), internalApiName: internalApi.name, internalApiContextLength: internalApi.contextLength, defaultInferenceType: process.env.DEFAULT_INFERENCE_TYPE || DEFAULT_INFERENCE_TYPE, // Served here rather than compiled into the bundle so a client always123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105import { afterEach, describe, expect, it, vi } from "vitest";import { getInternalApiConfig } from "./internalApiConfig.ts";
afterEach(() => { vi.unstubAllEnvs(); vi.restoreAllMocks();});
function stubEnvironment(values: Record<string, string | undefined>) { for (const variable of [ "INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL", "INTERNAL_OPENAI_COMPATIBLE_API_KEY", "INTERNAL_OPENAI_COMPATIBLE_API_MODEL", "INTERNAL_OPENAI_COMPATIBLE_API_NAME", "INTERNAL_OPENAI_COMPATIBLE_API_CONTEXT_LENGTH", "INTERNAL_OPENAI_COMPATIBLE_API_REASONING_EFFORT", "MODEL_DEFAULT_MAX_TOKENS", "MODEL_REQUEST_TIMEOUT_MS", ]) { vi.stubEnv(variable, values[variable]); }}
describe("getInternalApiConfig", () => { it("returns the defaults when nothing is set", () => { stubEnvironment({});
expect(getInternalApiConfig()).toEqual({ baseUrl: undefined, apiKey: undefined, models: [], name: "Internal API", contextLength: 131072, reasoningEffort: undefined, maxOutputTokens: 8192, requestTimeoutMs: 30000, }); });
it("reads every variable that is set", () => { stubEnvironment({ INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL: "https://llm.example/v1", INTERNAL_OPENAI_COMPATIBLE_API_KEY: "test-key", INTERNAL_OPENAI_COMPATIBLE_API_MODEL: " model-a , model-b ,", INTERNAL_OPENAI_COMPATIBLE_API_NAME: "Company LLM", INTERNAL_OPENAI_COMPATIBLE_API_CONTEXT_LENGTH: "32768", INTERNAL_OPENAI_COMPATIBLE_API_REASONING_EFFORT: " low ", MODEL_DEFAULT_MAX_TOKENS: "4096", MODEL_REQUEST_TIMEOUT_MS: "60000", });
expect(getInternalApiConfig()).toEqual({ baseUrl: "https://llm.example/v1", apiKey: "test-key", models: ["model-a", "model-b"], name: "Company LLM", contextLength: 32768, reasoningEffort: "low", maxOutputTokens: 4096, requestTimeoutMs: 60000, }); });
// `parseInt` read "8k" as 8, so a typo cut every answer to 8 tokens. it.each(["8k", "abc", "0", "-1", "1.5", "0x2000", "1e4"])( "replaces %j with the default and logs it", (value) => { stubEnvironment({ MODEL_DEFAULT_MAX_TOKENS: value }); const consoleError = vi .spyOn(console, "error") .mockImplementation(() => {});
expect(getInternalApiConfig().maxOutputTokens).toBe(8192); expect(consoleError).toHaveBeenCalledWith( `MODEL_DEFAULT_MAX_TOKENS must be a whole number from 1 to ${Number.MAX_SAFE_INTEGER} ("${value}"); using 8192.`, ); }, );
// Node fires a longer timer after 1 ms, which would abort every attempt. it("rejects a timeout longer than a timer can wait", () => { stubEnvironment({ MODEL_REQUEST_TIMEOUT_MS: "2147483648" }); vi.spyOn(console, "error").mockImplementation(() => {});
expect(getInternalApiConfig().requestTimeoutMs).toBe(30000); });
it("accepts the longest timeout a timer can wait", () => { stubEnvironment({ MODEL_REQUEST_TIMEOUT_MS: "2147483647" });
expect(getInternalApiConfig().requestTimeoutMs).toBe(2147483647); });
it("logs a bad value once, not on every read", () => { stubEnvironment({ MODEL_REQUEST_TIMEOUT_MS: "30s" }); const consoleError = vi .spyOn(console, "error") .mockImplementation(() => {});
getInternalApiConfig(); getInternalApiConfig();
expect(consoleError).toHaveBeenCalledTimes(1); });});12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485import { DEFAULT_INTERNAL_API_CONTEXT_LENGTH, DEFAULT_INTERNAL_API_NAME,} from "../shared/serverConfig.ts";import { parseCommaSeparatedList } from "./parseCommaSeparatedList.ts";
/** The internal OpenAI-compatible API, as the environment configures it. */export interface InternalApiConfig { /** Unset when the internal API is disabled. */ baseUrl: string | undefined; apiKey: string | undefined; /** In order of preference. Empty means a random model from the API's `/models`. */ models: string[]; /** Shown in the UI as the name of the inference type. */ name: string; /** Context window of the models, in tokens; the browser sizes its prompt budgets from it. */ contextLength: number; /** Sent as `reasoning_effort`. Unset leaves the API's own default. */ reasoningEffort: string | undefined; /** Upper bound on the `max_tokens` a client may ask for. */ maxOutputTokens: number; /** How long the upstream may stay silent before an attempt is abandoned. */ requestTimeoutMs: number;}
const DEFAULT_MAX_OUTPUT_TOKENS = 8192;const DEFAULT_REQUEST_TIMEOUT_MS = 30000;/** Node runs a `setTimeout` with a longer delay after 1 ms instead. */const MAX_TIMER_DELAY_MS = 2_147_483_647;
// The config is read on every request, and `/status` is polled by the// container's health check, so a bad value would otherwise flood the log.// It lives as long as the module: a test that reuses a bad value from an// earlier test in the same file sees no second log.const reportedInvalidValues = new Set<string>();
function readPositiveInteger( variable: string, fallback: number, max = Number.MAX_SAFE_INTEGER,): number { const value = process.env[variable]?.trim(); if (!value) return fallback; // Digits only: `Number` alone also accepts `0x2000` and `1e4`. const parsed = /^\d+$/.test(value) ? Number(value) : Number.NaN; if (parsed > 0 && parsed <= max) return parsed; const report = `${variable}=${value}`; if (!reportedInvalidValues.has(report)) { reportedInvalidValues.add(report); console.error( `${variable} must be a whole number from 1 to ${max} ("${value}"); using ${fallback}.`, ); } return fallback;}
/** * Read on every call rather than cached at startup. In production the * environment never changes, but the tests stub it per case with * `vi.stubEnv`, and a cache would hand them the first test's values. */export function getInternalApiConfig(): InternalApiConfig { const env = process.env; return { baseUrl: env.INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL || undefined, apiKey: env.INTERNAL_OPENAI_COMPATIBLE_API_KEY || undefined, models: parseCommaSeparatedList(env.INTERNAL_OPENAI_COMPATIBLE_API_MODEL), name: env.INTERNAL_OPENAI_COMPATIBLE_API_NAME || DEFAULT_INTERNAL_API_NAME, contextLength: readPositiveInteger( "INTERNAL_OPENAI_COMPATIBLE_API_CONTEXT_LENGTH", DEFAULT_INTERNAL_API_CONTEXT_LENGTH, ), reasoningEffort: env.INTERNAL_OPENAI_COMPATIBLE_API_REASONING_EFFORT?.trim() || undefined, maxOutputTokens: readPositiveInteger( "MODEL_DEFAULT_MAX_TOKENS", DEFAULT_MAX_OUTPUT_TOKENS, ), requestTimeoutMs: readPositiveInteger( "MODEL_REQUEST_TIMEOUT_MS", DEFAULT_REQUEST_TIMEOUT_MS, MAX_TIMER_DELAY_MS, ), };}23 unmodified lines242526272829302728296 unmodified lines3637384339404162 unmodified lines1041051061121071081091101111121131141151161161171181191201211221234 unmodified lines128129130131132133134135136137138139140141142143144145146147183 unmodified lines33133233331631731831932032132232332432533433533670 unmodified lines40740840941041141240341341441541664 unmodified lines481482483474484485486487478479488489490491482492484485486487488493494495496497498492493499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557125 unmodified lines683684685627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716662663664665666667668669717718719720721722723724725726727728729730731732733734735671672673674675676677678679680681736737738739740741742743744745746747748749750617 unmodified lines136813691370130513061307130813091310131113121313131413711372137323 unmodified lines createOpenAICompatible: vi.fn(),}));
vi.mock("./config/modelConfig", () => ({ getModelConfig: vi.fn(),}));
vi.mock("../shared/openaiModels", async (importOriginal) => ({ ...(await importOriginal<typeof import("../shared/openaiModels")>()), listOpenAiCompatibleModels: vi.fn(),6 unmodified lines listOpenAiCompatibleModels, selectRandomModel,} from "../shared/openaiModels";import { getModelConfig } from "./config/modelConfig";import { handleTokenVerification } from "./handleTokenVerification";import { getInferenceStats } from "./inferencesSinceLastRestart";import { internalApiEndpointServerHook } from "./internalApiEndpointServerHook";62 unmodified lines}
function streamOf( pieces: Array<{ type: string; text?: string; error?: unknown }>, pieces: Array<{ type: string; text?: string; error?: unknown; finishReason?: string; }>,) { return { stream: (async function* () { // The SDK always gives a finish part its reason. for (const piece of pieces) yield piece as never; for (const piece of pieces) yield ( piece.type === "finish" ? { finishReason: "stop", ...piece } : piece ) as never; })(), };}4 unmodified lines vi.mocked(handleTokenVerification).mockResolvedValue({ shouldContinue: true, }); // The hook reads the real config, so a value exported in the shell that // runs the tests would otherwise leak into them. for (const variable of [ "INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL", "INTERNAL_OPENAI_COMPATIBLE_API_KEY", "INTERNAL_OPENAI_COMPATIBLE_API_MODEL", "INTERNAL_OPENAI_COMPATIBLE_API_NAME", "INTERNAL_OPENAI_COMPATIBLE_API_CONTEXT_LENGTH", "INTERNAL_OPENAI_COMPATIBLE_API_REASONING_EFFORT", "MODEL_DEFAULT_MAX_TOKENS", "MODEL_REQUEST_TIMEOUT_MS", ]) { vi.stubEnv(variable, undefined); } });
afterEach(() => {183 unmodified lines vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL", "http://test-api"); vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_KEY", "test-key"); vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", "test-model"); vi.mocked(getModelConfig).mockReturnValue({ maxRetries: 5, baseBackoffMs: 100, maxBackoffMs: 5000, requestTimeoutMs: 30000, maxConcurrentRequests: 10, defaultMaxTokens: 2048, temperature: 0.7, topP: 0.9, }); vi.mocked(createOpenAICompatible).mockReturnValue({ chatModel: vi.fn().mockReturnValue("mock-chat-model"), } as never);70 unmodified lines expect(writes).toContain("Recovered"); });
// The trailing comma must not add an empty model to the ladder, which // would end the request after two attempts instead of four. it("walks the configured list a second time before giving up", async () => { vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", "model-a,model-b"); vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", "model-a,model-b,"); vi.mocked(streamText).mockImplementation(() => streamOf([]) as never);
const response = await callWithFakeTimers();64 unmodified lines expect(writeCalls.some((s: string) => s.includes("[DONE]"))).toBe(true); });
it("clamps max_tokens to defaultMaxTokens", async () => { it("passes on why the upstream stopped, so a cut answer is not reported as complete", async () => { vi.mocked(streamText).mockImplementation( () => streamOf([ { type: "text-delta", text: "Ok" }, { type: "finish" }, { type: "text-delta", text: "Cut" }, { type: "finish", finishReason: "length" }, ]) as never, ); const handler = getRegisteredHandler(); const response = createResponse(); await handler( createRequest({ messages: [{ role: "user", content: "hi" }], max_tokens: 9999, }),
await getRegisteredHandler()( createRequest({ messages: [{ role: "user", content: "hi" }] }), response, vi.fn(), ); const callArgs = vi.mocked(streamText).mock.calls[0][0]; expect(callArgs.maxOutputTokens).toBe(2048);
const writes = response.write.mock.calls.map((c) => c[0]).join(""); expect(writes).toContain('"finish_reason":"length"'); expect(writes).not.toContain('"finish_reason":"stop"'); });
it("spells the finish reason the way OpenAI does", async () => { vi.mocked(streamText).mockImplementation( () => streamOf([ { type: "finish", finishReason: "content-filter" }, ]) as never, ); const response = createResponse();
await getRegisteredHandler()( createRequest({ messages: [{ role: "user", content: "hi" }] }), response, vi.fn(), );
const writes = response.write.mock.calls.map((c) => c[0]).join(""); expect(writes).toContain('"finish_reason":"content_filter"'); });
it.each([ [undefined, 8192], ["100", 100], ["8k", 8192], ])( "clamps max_tokens to MODEL_DEFAULT_MAX_TOKENS=%s, which gives %i", async (maxTokens, expected) => { vi.stubEnv("MODEL_DEFAULT_MAX_TOKENS", maxTokens); vi.spyOn(console, "error").mockImplementation(() => {}); vi.mocked(streamText).mockImplementation( () => streamOf([ { type: "text-delta", text: "Ok" }, { type: "finish" }, ]) as never, ); const handler = getRegisteredHandler(); const response = createResponse(); await handler( createRequest({ messages: [{ role: "user", content: "hi" }], max_tokens: 9999, }), response, vi.fn(), ); const callArgs = vi.mocked(streamText).mock.calls[0][0]; expect(callArgs.maxOutputTokens).toBe(expected); }, );
it("passes max_tokens unchanged when under cap", async () => { vi.mocked(streamText).mockImplementation( () =>125 unmodified lines ).toBe(true); });
it("aborts the upstream stream when no part arrives within the idle timeout", async () => { vi.mocked(streamText).mockImplementation( ({ abortSignal }: { abortSignal?: AbortSignal } = {}) => { // Yields one part, then yields an abort part when the signal fires โ // mirrors the AI SDK v7 pull handler behavior. return { stream: (async function* () { yield { type: "text-delta", text: "Half" } as never; await new Promise<void>((resolve) => { const check = () => { if (abortSignal?.aborted) { resolve(); } else { abortSignal?.addEventListener("abort", () => resolve(), { once: true, }); } }; check(); }); yield { type: "abort" } as never; })(), } as never; }, );
const handler = getRegisteredHandler(); const response = createResponse(); vi.useFakeTimers(); try { const pending = handler( createRequest({ messages: [{ role: "user", content: "hi" }] }), response, vi.fn(), it.each([ [undefined, 30_000], ["5000", 5000], ])( "aborts the upstream stream when no part arrives within MODEL_REQUEST_TIMEOUT_MS=%s (%i ms)", async (timeout, timeoutMs) => { vi.stubEnv("MODEL_REQUEST_TIMEOUT_MS", timeout); vi.mocked(streamText).mockImplementation( ({ abortSignal }: { abortSignal?: AbortSignal } = {}) => { // Yields one part, then yields an abort part when the signal fires โ // mirrors the AI SDK v7 pull handler behavior. return { stream: (async function* () { yield { type: "text-delta", text: "Half" } as never; await new Promise<void>((resolve) => { const check = () => { if (abortSignal?.aborted) { resolve(); } else { abortSignal?.addEventListener("abort", () => resolve(), { once: true, }); } }; check(); }); yield { type: "abort" } as never; })(), } as never; }, ); // Not yet past the timeout โ signal should be clear. await vi.advanceTimersByTimeAsync(29_999); expect( vi.mocked(streamText).mock.calls[0][0].abortSignal?.aborted, ).toBe(false); // Past the timeout โ signal should be set and the abort part emitted. await vi.advanceTimersByTimeAsync(2); await pending;
const handler = getRegisteredHandler(); const response = createResponse(); vi.useFakeTimers(); try { const pending = handler( createRequest({ messages: [{ role: "user", content: "hi" }] }), response, vi.fn(), ); // Not yet past the timeout โ signal should be clear. await vi.advanceTimersByTimeAsync(timeoutMs - 1); expect( vi.mocked(streamText).mock.calls[0][0].abortSignal?.aborted, ).toBe(false); // Past the timeout โ signal should be set and the abort part emitted. await vi.advanceTimersByTimeAsync(2); await pending;
// The abort is treated as an attempt failure: the stalled stream is // cut and the SSE error frame carries the message. const writes = response.write.mock.calls.map((c) => c[0] as string); expect( writes.some((s: string) => s.includes("Service unavailable")), ).toBe(true); expect(writes.some((s: string) => s.includes("stalled"))).toBe(true); } finally { vi.useRealTimers(); } }); // The abort is treated as an attempt failure: the stalled stream is // cut and the SSE error frame carries the message. const writes = response.write.mock.calls.map((c) => c[0] as string); expect( writes.some((s: string) => s.includes("Service unavailable")), ).toBe(true); expect(writes.some((s: string) => s.includes("stalled"))).toBe(true); } finally { vi.useRealTimers(); } }, );
it("retries the next model when the first model stalls before any content", async () => { vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);617 unmodified lines vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL", "http://test-api"); vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_KEY", "test-key"); vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", "test-model"); vi.mocked(getModelConfig).mockReturnValue({ maxRetries: 5, baseBackoffMs: 100, maxBackoffMs: 5000, requestTimeoutMs: 30000, maxConcurrentRequests: 10, defaultMaxTokens: 2048, temperature: 0.7, topP: 0.9, }); vi.mocked(createOpenAICompatible).mockReturnValue({ chatModel: vi.fn().mockReturnValue("mock-chat-model"), } as never);2 unmodified lines3456789106785 unmodified lines1415162217181920212223242526272829303132303133343510 unmodified lines4647484849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810949505112 unmodified lines646566676869707148 unmodified lines12012112218218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721812312412512633 unmodified lines1601611622582592602611631641651661671682 unmodified lines1711721732702711741751761771782752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073081791801811821831841851861871881891901911921931941951963091971981995 unmodified lines2052062073213222082092102112123272132142152162173332182192202217 unmodified lines22923023134723223323412 unmodified lines24724824936625025125225338 unmodified lines29229329441129529629729829930030130241730330430530630730830931020 unmodified lines3313323334444454464474484494504514524534544554564574584594604614624634644654664674684694704714723343353363372 unmodified linesimport { APICallError, streamText } from "ai";import type { PreviewServer, ViteDevServer } from "vite";import { z } from "zod";import { listOpenAiCompatibleModels, selectRandomModel,} from "../shared/openaiModels.ts";import { getModelConfig } from "./config/modelConfig.ts";import { handleTokenVerification } from "./handleTokenVerification.ts";import { type AttemptFailureReason,5 unmodified lines recordModelFailure, recordModelFallback, recordModelStreamed, recordModelsRefetched, recordStreamEndedWithoutFinish,} from "./inferencesSinceLastRestart.ts";import { getInternalApiConfig } from "./internalApiConfig.ts";import { createModelPicker } from "./internalApiModelPicker.ts";import { createChunkPayload, sendSseData, sendSseDone, sendSseError,} from "./utils/chatCompletionSse.ts";import { sendJsonError } from "./utils/httpResponse.ts";import { readJsonBody } from "./utils/readJsonBody.ts";import { parseRequestUrl } from "./utils/requestUrl.ts";import { calculateBackoffTime, isResponseWritable, safeEndResponse, safeWriteResponse,} from "./utils/streamUtils.ts";
const chatCompletionRequestSchema = z.object({10 unmodified lines max_tokens: z.number().optional(),});
interface ChatCompletionChunk { id: string; object: string; created: number; model?: string; choices: Array<{ index: number; delta: { content?: string }; finish_reason: string | null; }>;}
function createChunkPayload( model: string, content?: string, finish_reason: string | null = null,): ChatCompletionChunk { return { id: `chatcmpl-${Date.now()}`, object: "chat.completion.chunk", created: Math.floor(Date.now() / 1000), model, choices: [ { index: 0, delta: content ? { content } : {}, finish_reason, }, ], };}
function ensureSseHeaders(response: ServerResponse): void { if (response.headersSent) return;
response.setHeader("Content-Type", "text/event-stream"); response.setHeader("Cache-Control", "no-store"); response.setHeader("Connection", "keep-alive");}
function sendSseData(response: ServerResponse, data: unknown): void { ensureSseHeaders(response); safeWriteResponse(response, `data: ${JSON.stringify(data)}\n\n`);}
function sendSseDone(response: ServerResponse): void { safeWriteResponse(response, "data: [DONE]\n\n"); safeEndResponse(response);}
function sendSseError( response: ServerResponse, message: string, model?: string,): void { sendSseData(response, { error: message, ...(model ? { model } : {}), }); sendSseDone(response);}
function hasJsonContentType(request: IncomingMessage): boolean { const contentType = request.headers["content-type"]; if (typeof contentType !== "string") return false;12 unmodified lines return error.statusCode >= 500 ? "serverError" : "otherHttpError";}
const maxBodyBytes = 1024 * 1024;
/** Self-hosted `/inference` endpoint: streams an OpenAI-compatible chat completion from the internal API, retrying across models. */export function internalApiEndpointServerHook< T extends ViteDevServer | PreviewServer,48 unmodified lines let outcome: InferenceOutcome = "unclassified";
try { const maxBodyBytes = 1024 * 1024; const body = await new Promise< | { status: "ok"; value: unknown } | { status: "tooLarge" } | { status: "invalid" } >((resolve) => { const chunks: Buffer[] = []; let totalBytes = 0; let settled = false; request.on("data", (chunk: Buffer | string) => { if (settled) return; totalBytes += Buffer.byteLength(chunk); if (totalBytes > maxBodyBytes) { settled = true; resolve({ status: "tooLarge" }); return; } chunks.push(Buffer.from(chunk)); }); request.on("end", () => { if (settled) return; settled = true; try { resolve({ status: "ok", value: JSON.parse(Buffer.concat(chunks).toString()), }); } catch { resolve({ status: "invalid" }); } }); request.on("error", () => { if (settled) return; settled = true; resolve({ status: "invalid" }); }); }); const body = await readJsonBody(request, maxBodyBytes);
if (body.status === "tooLarge") { outcome = "badRequest";33 unmodified lines } const requestBody = parsedRequestBody.data;
if ( !process.env.INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL || !process.env.INTERNAL_OPENAI_COMPATIBLE_API_KEY ) { const internalApi = getInternalApiConfig(); const { baseUrl, apiKey } = internalApi; if (!baseUrl || !apiKey) { outcome = "notConfigured"; sendJsonError(response, 500, { error: "OpenAI API configuration is missing",2 unmodified lines }
const openaiProvider = createOpenAICompatible({ baseURL: process.env.INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL, apiKey: process.env.INTERNAL_OPENAI_COMPATIBLE_API_KEY, baseURL: baseUrl, apiKey, name: "openai", });
const configuredModels = ( process.env.INTERNAL_OPENAI_COMPATIBLE_API_MODEL ?? "" ) .split(",") .map((id) => id.trim()) .filter(Boolean); // Each configured model, in order of preference, then the same list // once more, so a single configured model also gets one retry. const configuredLadder = [...configuredModels, ...configuredModels]; let model: string | undefined = configuredModels[0]; let availableModels: { id: string }[] = []; const attemptedModels = new Set<string>(); // Set before the try so a failing `/models` endpoint does not trigger // another refetch on the next failed attempt. let hasRefetched = false;
if (!model) { try { availableModels = await listOpenAiCompatibleModels( process.env.INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL, process.env.INTERNAL_OPENAI_COMPATIBLE_API_KEY, ); const selectedModel = selectRandomModel(availableModels); model = selectedModel || undefined; } catch (error) { console.error( "Error fetching models:", error instanceof Error ? error.message : error, ); outcome = "modelListUnavailable"; sendJsonError(response, 500, { error: "Failed to fetch available models", }); return; const modelPicker = createModelPicker({ models: internalApi.models, baseUrl, apiKey, }); let model: string | undefined; try { model = await modelPicker.first(); } catch (error) { console.error( "Error fetching models:", error instanceof Error ? error.message : error, ); outcome = "modelListUnavailable"; sendJsonError(response, 500, { error: "Failed to fetch available models", }); return; } }
if (!model) {5 unmodified lines // Passed through unchecked: providers disagree on the accepted values // (`none`, `minimal`, `xhigh`...), and an unknown one comes back from // the upstream as an HTTP error in the log. const reasoningEffort = process.env.INTERNAL_OPENAI_COMPATIBLE_API_REASONING_EFFORT?.trim(); const { reasoningEffort } = internalApi; const providerOptions = reasoningEffort ? { openai: { reasoningEffort } } : undefined;
const config = getModelConfig(); const maxAttempts = 5; let lastError: unknown = null;
const clampedMaxTokens = requestBody.max_tokens !== undefined ? Math.min(requestBody.max_tokens, config.defaultMaxTokens) ? Math.min(requestBody.max_tokens, internalApi.maxOutputTokens) : undefined; const clampedTemperature = requestBody.temperature !== undefined7 unmodified lines let hasEmittedContent = false; for (let attempt = 1; attempt <= maxAttempts; attempt++) { if (!model) break; attemptedModels.add(model);
if (!isResponseWritable(response)) { outcome = "abandoned";12 unmodified lines if (idleTimeoutId !== undefined) clearTimeout(idleTimeoutId); idleTimeoutId = setTimeout( () => abortController.abort(), config.requestTimeoutMs, internalApi.requestTimeoutMs, ); }
38 unmodified lines // records the failure and walks the retry ladder. clearTimeout(idleTimeoutId); throw new Error( `Upstream stalled for ${config.requestTimeoutMs}ms`, `Upstream stalled for ${internalApi.requestTimeoutMs}ms`, ); } else if (part.type === "finish") { clearTimeout(idleTimeoutId); // The SDK spells its reasons with a hyphen where OpenAI uses an // underscore (`content-filter`, `tool-calls`). sendSseData( response, createChunkPayload(model, undefined, "stop"), createChunkPayload( model, undefined, part.finishReason.replace("-", "_"), ), ); sendSseDone(response); outcome = "streamed";20 unmodified lines if (hasEmittedContent) break; if (attempt >= maxAttempts) break;
// A provider whose pool changes mid-flight needs a fresh listing to // recover; without the `!hasRefetched` guard we would loop on a // stale list. if ( configuredModels.length === 0 && availableModels.every((m) => attemptedModels.has(m.id)) && !hasRefetched ) { hasRefetched = true; try { availableModels = await listOpenAiCompatibleModels( process.env.INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL, process.env.INTERNAL_OPENAI_COMPATIBLE_API_KEY, ); recordModelsRefetched(); } catch (refetchError) { console.warn( "Failed to refetch models:", refetchError instanceof Error ? refetchError.message : refetchError, ); } }
const nextModel = configuredModels.length > 0 ? configuredLadder[attempt] : selectRandomModel(availableModels, attemptedModels); const nextModel = await modelPicker.next(); if (!nextModel) break; if (nextModel !== model) recordModelFallback(); model = nextModel;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101import { afterEach, describe, expect, it, vi } from "vitest";
vi.mock("../shared/openaiModels.ts", async (importOriginal) => ({ ...(await importOriginal<typeof import("../shared/openaiModels.ts")>()), listOpenAiCompatibleModels: vi.fn(),}));
import { listOpenAiCompatibleModels } from "../shared/openaiModels.ts";import { getInferenceStats } from "./inferencesSinceLastRestart.ts";import { createModelPicker } from "./internalApiModelPicker.ts";
const connection = { baseUrl: "http://test-api", apiKey: "test-key" };
afterEach(() => { vi.resetAllMocks(); vi.restoreAllMocks();});
describe("createModelPicker", () => { it("walks the configured models in order, then once more", async () => { const picker = createModelPicker({ ...connection, models: ["model-a", "model-b"], });
const picked = [await picker.first()]; for (let i = 0; i < 4; i++) picked.push(await picker.next());
expect(picked).toEqual([ "model-a", "model-b", "model-a", "model-b", undefined, ]); expect(listOpenAiCompatibleModels).not.toHaveBeenCalled(); });
it("never hands out the same random model twice", async () => { // Always the first model left, so a missing exclusion repeats it every // time instead of only by chance. vi.spyOn(Math, "random").mockReturnValue(0); vi.mocked(listOpenAiCompatibleModels).mockResolvedValue([ { id: "model-a" }, { id: "model-b" }, { id: "model-c" }, ]); const picker = createModelPicker({ ...connection, models: [] });
const picked = [await picker.first(), await picker.next()]; picked.push(await picker.next());
expect(picked).toEqual(["model-a", "model-b", "model-c"]); });
it("lists the pool again once every model was tried, and picks from the new list", async () => { vi.mocked(listOpenAiCompatibleModels) .mockResolvedValueOnce([{ id: "model-a" }]) .mockResolvedValueOnce([{ id: "model-a" }, { id: "model-b" }]); const picker = createModelPicker({ ...connection, models: [] }); const refetchesBefore = getInferenceStats().modelsRefetched;
expect(await picker.first()).toBe("model-a"); expect(await picker.next()).toBe("model-b"); expect(getInferenceStats().modelsRefetched).toBe(refetchesBefore + 1); });
// Without the try/catch, a failed refetch would escape `next()` and the // client would get a 500 instead of the 503 that says every model failed. it("returns no model instead of throwing when listing the pool again fails", async () => { vi.mocked(listOpenAiCompatibleModels) .mockResolvedValueOnce([{ id: "model-a" }]) .mockRejectedValueOnce(new Error("models endpoint down")); const consoleWarn = vi.spyOn(console, "warn").mockImplementation(() => {}); const picker = createModelPicker({ ...connection, models: [] }); const refetchesBefore = getInferenceStats().modelsRefetched;
await picker.first();
await expect(picker.next()).resolves.toBeUndefined(); expect(consoleWarn).toHaveBeenCalledWith( "Failed to refetch models:", "models endpoint down", ); expect(getInferenceStats().modelsRefetched).toBe(refetchesBefore); });
it("lists the pool again at most once per request", async () => { vi.mocked(listOpenAiCompatibleModels) .mockResolvedValueOnce([{ id: "model-a" }]) .mockResolvedValueOnce([{ id: "model-b" }]) .mockResolvedValueOnce([{ id: "model-c" }]); const picker = createModelPicker({ ...connection, models: [] });
await picker.first(); await picker.next();
expect(await picker.next()).toBeUndefined(); expect(listOpenAiCompatibleModels).toHaveBeenCalledTimes(2); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172import { listOpenAiCompatibleModels, selectRandomModel,} from "../shared/openaiModels.ts";import { recordModelsRefetched } from "./inferencesSinceLastRestart.ts";
/** * Chooses the model for each attempt of one `/inference` request. With * configured models, it walks them in order of preference and then once * more, so a single configured model also gets one retry. Without them, it * picks at random from the API's `/models`, never the same model twice. */export function createModelPicker({ models, baseUrl, apiKey,}: { models: string[]; baseUrl: string; apiKey: string;}) { const ladder = [...models, ...models]; let position = 0; let availableModels: { id: string }[] = []; // Every model handed out counts as attempted: the hook runs each one it // gets, so marking here keeps the exclusion from depending on the caller. const attemptedModels = new Set<string>(); let hasRefetched = false;
function handOut(model: string | null | undefined): string | undefined { if (!model) return undefined; attemptedModels.add(model); return model; }
return { /** The model for the first attempt. Throws when the API's model list cannot be fetched. */ async first(): Promise<string | undefined> { if (models.length > 0) return handOut(ladder[position]); availableModels = await listOpenAiCompatibleModels(baseUrl, apiKey); return handOut(selectRandomModel(availableModels)); },
/** The model for the next attempt, or undefined when none is left. */ async next(): Promise<string | undefined> { if (models.length > 0) { position++; return handOut(ladder[position]); }
// A provider whose pool changes mid-flight needs a fresh listing to // recover. Once per request at most. if ( availableModels.every((m) => attemptedModels.has(m.id)) && !hasRefetched ) { hasRefetched = true; try { availableModels = await listOpenAiCompatibleModels(baseUrl, apiKey); recordModelsRefetched(); } catch (refetchError) { console.warn( "Failed to refetch models:", refetchError instanceof Error ? refetchError.message : refetchError, ); } }
return handOut(selectRandomModel(availableModels, attemptedModels)); }, };}3 unmodified lines456789910111297 unmodified lines1101111121131141151161171181191131141151161171183 unmodified linesimport { getBiEncoderStatus } from "./biEncoderService.ts";import { getFallbackProviderStats } from "./fallbackSearchService.ts";import { getInferenceStats } from "./inferencesSinceLastRestart.ts";import { getInternalApiConfig } from "./internalApiConfig.ts";import { getPageReadCircuitStats } from "./pageReadHostBreaker.ts";import { getPageReadStats } from "./pageReadsSinceLastRestart.ts";import { parseCommaSeparatedList } from "./parseCommaSeparatedList.ts";import { getRerankerStatus } from "./rerankerService.ts";import { getRerankingStats } from "./rerankingSinceLastRestart.ts";import {97 unmodified lines }, authorization: getAuthorizationStats(), // The per-model counters go out as an array in the configured order, // never keyed by model name: `/status` needs no token. Same parse the // inference hook uses for its ladder. inference: getInferenceStats( parseCommaSeparatedList( process.env.INTERNAL_OPENAI_COMPATIBLE_API_MODEL, ), ), // never keyed by model name: `/status` needs no token. The same list the // inference hook walks for its ladder. inference: getInferenceStats(getInternalApiConfig().models), activeSessions: getActiveSessionsAmount(), searches: { ...getSearchStats(),1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768import type { ServerResponse } from "node:http";import { safeEndResponse, safeWriteResponse } from "./streamUtils.ts";
interface ChatCompletionChunk { id: string; object: string; created: number; model?: string; choices: Array<{ index: number; delta: { content?: string }; finish_reason: string | null; }>;}
/** One OpenAI `chat.completion.chunk`; the last one of an answer carries the `finish_reason`. */export function createChunkPayload( model: string, content?: string, finish_reason: string | null = null,): ChatCompletionChunk { return { id: `chatcmpl-${Date.now()}`, object: "chat.completion.chunk", created: Math.floor(Date.now() / 1000), model, choices: [ { index: 0, delta: content ? { content } : {}, finish_reason, }, ], };}
function ensureSseHeaders(response: ServerResponse): void { if (response.headersSent) return;
response.setHeader("Content-Type", "text/event-stream"); response.setHeader("Cache-Control", "no-store"); response.setHeader("Connection", "keep-alive");}
/** Writes one `data:` event, sending the stream headers first if nothing went out yet. */export function sendSseData(response: ServerResponse, data: unknown): void { ensureSseHeaders(response); safeWriteResponse(response, `data: ${JSON.stringify(data)}\n\n`);}
/** Ends the stream the way OpenAI does, with `data: [DONE]`. */export function sendSseDone(response: ServerResponse): void { safeWriteResponse(response, "data: [DONE]\n\n"); safeEndResponse(response);}
/** Reports a failure inside an open stream, where an HTTP status can no longer change. */export function sendSseError( response: ServerResponse, message: string, model?: string,): void { sendSseData(response, { error: message, ...(model ? { model } : {}), }); sendSseDone(response);}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849import type { IncomingMessage } from "node:http";
export type JsonBody = | { status: "ok"; value: unknown } | { status: "tooLarge" } | { status: "invalid" };
/** * Reads and parses a JSON request body, stopping as soon as it passes * `maxBytes`. It never rejects: a body that is too large, is not JSON, or * whose stream errors comes back as a status for the caller to answer. */export function readJsonBody( request: IncomingMessage, maxBytes: number,): Promise<JsonBody> { return new Promise((resolve) => { const chunks: Buffer[] = []; let totalBytes = 0; let settled = false; request.on("data", (chunk: Buffer | string) => { if (settled) return; totalBytes += Buffer.byteLength(chunk); if (totalBytes > maxBytes) { settled = true; resolve({ status: "tooLarge" }); return; } chunks.push(Buffer.from(chunk)); }); request.on("end", () => { if (settled) return; settled = true; try { resolve({ status: "ok", value: JSON.parse(Buffer.concat(chunks).toString()), }); } catch { resolve({ status: "invalid" }); } }); request.on("error", () => { if (settled) return; settled = true; resolve({ status: "invalid" }); }); });}package-lock.json+3-3
server/configEndpointServerHook.ts+5-22
server/internalApiConfig.test.tsAdded+105
server/internalApiConfig.tsAdded+85
server/internalApiEndpointServerHook.test.ts+148-92
server/internalApiEndpointServerHook.ts+47-185
server/internalApiModelPicker.test.tsAdded+101
server/internalApiModelPicker.tsAdded+72
server/statusEndpointServerHook.ts+4-8
server/utils/chatCompletionSse.tsAdded+68
server/utils/readJsonBody.tsAdded+49