SPB Git

Repository Public

fake-llm.ts 8.5 KB 117 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Note SPBoucher AI8 * File             : tests/helpers/fake-llm.ts9 * Module           : tests10 * Repository       : https://git.spboucher.ai/note-spboucher-ai11 * Project Website  : https://note.spboucher.ai12 * Created          : 2026-11-1913 * Last Modified    : 2026-11-1914 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243/**44 * Local fake of an OpenAI-compatible endpoint (Chat Completions + SSE, GET /models) for the adapter tests. No network, no key, no cost.45 * Behaviour is chosen by the requested model id:46 *   echo            streams `reply(body)` in small text deltas, then a usage frame, then [DONE]47 *   tools           streams one tool call whose arguments arrive split over several deltas48 *   err-401 / err-429 / err-500   always answer that HTTP status with an OpenAI-style error body49 *   flaky-503       answers 503 `flakyFailures` times, then behaves like echo50 *   midstream       starts streaming, then sends an `{"error":…}` frame51 *   stall           sends one delta, then nothing (idle timeout)52 *   hang            never answers (total timeout / abort)53 *   close-empty     200 with an empty stream54 * Every request body is recorded in `requests` so tests can assert the exact wire contract.55 */56import http from "node:http";57import type { AddressInfo } from "node:net";58import { eq } from "drizzle-orm";59import { db, schema } from "../../src/db/index";60import { invalidateCatalog } from "../../src/lib/ai/catalog";6162export interface FakeLLM { url: string; key: string; requests: { path: string; auth: string | null; body: any }[]; reply: (body: any) => string; models: unknown[]; modelsPublic: boolean; flakyFailures: number; close: () => Promise<void> }63const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));6465export async function startFakeLLM(): Promise<FakeLLM> {66  const state: FakeLLM = { url: "", key: "sk-fake-" + Math.random().toString(36).slice(2), requests: [], reply: () => "Bonjour du faux modèle.", models: [], modelsPublic: false, flakyFailures: 1, close: async () => {} };67  let flaky = 0; const open = new Set<http.ServerResponse>();68  const server = http.createServer(async (req, res) => {69    const chunks: Buffer[] = []; for await (const c of req) chunks.push(c as Buffer);70    const raw = Buffer.concat(chunks).toString("utf8"); let body: any = null; try { body = raw ? JSON.parse(raw) : null; } catch { /* keep null */ }71    const auth = req.headers.authorization ?? null; const path = (req.url ?? "").split("?")[0];72    state.requests.push({ path, auth, body });73    const json = (status: number, obj: unknown) => { res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(obj)); };74    const authed = auth === `Bearer ${state.key}`;75    if (req.method === "GET" && path === "/v1/models") { if (!authed && !state.modelsPublic) return json(401, { error: { message: "Missing or invalid API key", type: "invalid_request_error" } }); return json(200, { object: "list", data: state.models }); }76    if (req.method !== "POST" || path !== "/v1/chat/completions") return json(404, { error: { message: "not found" } });77    if (!authed) return json(401, { error: { message: "Incorrect API key provided", type: "invalid_request_error" } });78    const model: string = body?.model ?? "";79    if (model === "err-401") return json(401, { error: { message: "Incorrect API key provided", type: "invalid_request_error" } });80    if (model === "err-429") return json(429, { error: { message: "Rate limit reached for requests", type: "rate_limit_error" } });81    if (model === "err-500") return json(500, { error: { message: "The server had an error while processing your request" } });82    if (model === "flaky-503" && flaky < state.flakyFailures) { flaky++; return json(503, { error: { message: "Service temporarily overloaded" } }); }83    if (model === "hang") { open.add(res); return; }84    res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" }); open.add(res);85    const send = (obj: unknown) => res.write(`data: ${JSON.stringify(obj)}\n\n`);86    const frame = (delta: unknown, finish: string | null = null) => ({ id: "chatcmpl-fake", object: "chat.completion.chunk", model, choices: [{ index: 0, delta, finish_reason: finish }] });87    if (model === "close-empty") { res.end(); return; }88    res.write(": keep-alive comment\n\n");89    if (model === "tools") {90      send(frame({ role: "assistant", tool_calls: [{ index: 0, id: "call_abc", type: "function", function: { name: body.tools?.[0]?.function?.name ?? "tool", arguments: "" } }] }));91      for (const part of ['{"pa', 'geId":"p-1",', '"tags":["a","b"]}']) send(frame({ tool_calls: [{ index: 0, function: { arguments: part } }] }));92      send(frame({}, "tool_calls")); send({ id: "chatcmpl-fake", choices: [], usage: { prompt_tokens: 40, completion_tokens: 12 } }); res.write("data: [DONE]\n\n"); res.end(); return;93    }94    const text = state.reply(body); const parts = text.match(/[\s\S]{1,7}/g) ?? [];95    if (model === "midstream") { send(frame({ role: "assistant", content: parts[0] ?? "x" })); send({ error: { message: "Upstream provider disconnected", code: 502 } }); res.end(); return; }96    if (model === "stall") { send(frame({ role: "assistant", content: parts[0] ?? "x" })); return; }97    send(frame({ role: "assistant", content: "" }));98    for (const p of parts) { send(frame({ content: p })); await sleep(1); }99    send(frame({}, "stop"));100    send({ id: "chatcmpl-fake", choices: [], usage: { prompt_tokens: 120, completion_tokens: parts.length, prompt_tokens_details: { cached_tokens: 20 }, completion_tokens_details: { reasoning_tokens: 3 } } });101    res.write("data: [DONE]\n\n"); res.end();102  });103  await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));104  state.url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/v1`;105  state.close = async () => { for (const r of open) r.destroy(); await new Promise<void>((r) => server.close(() => r())); };106  return state;107}108109/** Register the fake as an `openai_compatible` provider row + models, with its key in a private env variable. Returns a cleanup. */110export async function registerFakeProvider(fake: FakeLLM, id: string, models: { id: string; capabilities?: Record<string, unknown>; inputPrice?: number; outputPrice?: number; contextWindow?: number; enabled?: boolean }[] = []) {111  const keyEnv = `FAKE_LLM_KEY_${id.toUpperCase().replace(/[^A-Z0-9]/g, "_")}`; process.env[keyEnv] = fake.key;112  await db.insert(schema.aiProviders).values({ id, name: `Fake ${id}`, kind: "openai_compatible", baseUrl: fake.url, keyEnv, label: `Fake ${id}` }).onConflictDoUpdate({ target: schema.aiProviders.id, set: { baseUrl: fake.url, keyEnv, kind: "openai_compatible", enabled: true } });113  for (const m of models) await db.insert(schema.aiModels).values({ id: `${id}:${m.id}`, provider: id, displayName: m.id, category: "text", available: true, enabled: m.enabled ?? true, capabilities: m.capabilities ?? {}, inputPrice: m.inputPrice ?? null, outputPrice: m.outputPrice ?? null, contextWindow: m.contextWindow ?? null, creator: "unknown", route: id }).onConflictDoNothing();114  invalidateCatalog();115  return { keyEnv, cleanup: async () => { await db.delete(schema.aiModels).where(eq(schema.aiModels.provider, id)); await db.delete(schema.aiProviders).where(eq(schema.aiProviders.id, id)); delete process.env[keyEnv]; invalidateCatalog(); } };116}117
Files main
Menu

Theme