SPB Git

Repository Public MIT

providers.test.ts 16.9 KB 288 lines typescript

1// @vitest-environment node2/**3 * =============================================================================4 *                  SP BOUCHER | SOFTWARE & RESEARCH5 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING6 * =============================================================================7 *8 * Project          : VQuant9 * File             : server/next/providers.test.ts10 * Module           : server11 * Repository       : https://git.spboucher.ai/vquant12 * Project Website  : https://vquant.spboucher.ai13 * Created          : 2026-11-2014 * Last Modified    : 2026-11-2015 *16 * Author           : Simon-Pierre Boucher17 * Position         : Professor of Finance18 * Institution      : Université du Québec en Outaouais (UQO)19 * Organization     : SP Boucher20 * Website          : https://spboucher.ai21 * Git              : https://git.spboucher.ai22 *23 * Preferred Contact: contact@spboucher.ai24 * Development      : dev@spboucher.ai25 * Support          : support@spboucher.ai26 * Security/Admin   : admin@spboucher.ai27 *28 * Copyright (c) 202629 * Simon-Pierre Boucher30 * All rights reserved where applicable. This file is governed by the31 * applicable project license, copyright notices and relevant law.32 * Existing third-party rights and notices remain unaffected.33 *34 * SPDX Identifier  : MIT35 * License          : MIT License36 * License File     : LICENSE37 *38 * Do not embed credentials, private keys, access tokens,39 * certificates or confidential personal information.40 *41 * =============================================================================42 * END OF SP BOUCHER SOURCE HEADER43 * =============================================================================44 */4546/**47 * Provider registry (contract §2.1): the curated table, discovery with a mocked fetch, the merge and its48 * availability rules, stale-while-error. No network.49 */50import { beforeEach, describe, expect, it } from "vitest";51import { ALLOWED_MODELS, DEFAULT_MODEL } from "../routes/validation";52import { OPENAI_COMPAT_SPECS, knownClaudeSpecs } from "../services/claude/tokenManagement";53import {54  CURATED_MODEL_IDS, DEFAULT_MODEL_ID, __resetRegistry, __setProviderState, curatedModels, fetchProviderModels, isSelectableModel, localBaseUrl, mergeProvider,55  openRouterPricing, pricingFor, providerConfigured, providerOf, refreshRegistry, registrySnapshot, upstreamModelId, type ProviderState,56} from "./providers";5758const ENV = { ANTHROPIC_API_KEY: "a", OPENAI_API_KEY: "o", GEMINI_API_KEY: "g", OPENROUTER_API_KEY: "r", LOCAL_LLM_BASE_URL: "http://10.0.0.5:8000", LOCAL_LLM_NAME: "MacLustr AI" };59const state = (models: ProviderState["models"], over: Partial<ProviderState> = {}): ProviderState => ({ checkedAt: 1, fetchedAt: 1, ok: true, error: null, models, ...over });60const json = (body: unknown, status = 200) => ({ ok: status >= 200 && status < 300, status, json: async () => body });6162/** A fetch that answers each listing endpoint from a table and records what was asked. */63function fakeFetch(routes: Record<string, unknown | (() => unknown)>) {64  const calls: Array<{ url: string; headers: Record<string, string> }> = [];65  const impl = async (url: string, init?: { headers?: Record<string, string> }) => {66    calls.push({ url, headers: init?.headers ?? {} });67    const key = Object.keys(routes).find((k) => url.startsWith(k));68    if (!key) return json({}, 404);69    const v = routes[key];70    const body = typeof v === "function" ? (v as () => unknown)() : v;71    return json(body);72  };73  return { impl, calls };74}7576beforeEach(() => __resetRegistry());7778describe("curated table", () => {79  it("is exactly the model list of the chat, with the default first", () => {80    expect([...CURATED_MODEL_IDS].sort()).toEqual([...ALLOWED_MODELS].sort());81    expect(DEFAULT_MODEL_ID).toBe(DEFAULT_MODEL);82  });8384  it("takes prices and output limits from the tables the model services use, and invents none", () => {85    const claude = knownClaudeSpecs();86    for (const m of curatedModels()) {87      const c = claude[m.id];88      const o = OPENAI_COMPAT_SPECS[m.id];89      expect(c || o, m.id).toBeTruthy();90      expect(m.pricing).toEqual(c ? { inputPerMTok: c.input, outputPerMTok: c.output } : { inputPerMTok: o.input, outputPerMTok: o.output });91      expect(m.maxOutput).toBe(c ? c.maxOutput : o.maxOut);92      expect(m.source).toBe("curated");93    }94    // Context is only stated where the app's own model list states it ("1M").95    expect(curatedModels().find((m) => m.id === "claude-sonnet-5-5")!.contextWindow).toBe(1_000_000);96    expect(curatedModels().find((m) => m.id === "gpt-5.5")!.contextWindow).toBeNull();97  });98});99100describe("providers", () => {101  it("is configured by its key or base URL only", () => {102    expect(providerConfigured("anthropic", {})).toBe(false);103    expect(providerConfigured("anthropic", { ANTHROPIC_API_KEY: " " })).toBe(false);104    expect(providerConfigured("openrouter", ENV)).toBe(true);105    expect(providerConfigured("local", { LOCAL_LLM_API_KEY: "k" })).toBe(false);106    expect(providerConfigured("local", ENV)).toBe(true);107  });108109  it("normalises the local base URL and maps ids to providers", () => {110    expect(localBaseUrl({ LOCAL_LLM_BASE_URL: "http://h:1/" })).toBe("http://h:1/v1");111    expect(localBaseUrl({ LOCAL_LLM_BASE_URL: "https://llm.example/v1" })).toBe("https://llm.example/v1");112    expect(localBaseUrl({})).toBeNull();113    expect(providerOf("openrouter:meta/llama")).toBe("openrouter");114    expect(providerOf("local:qwen")).toBe("local");115    expect(providerOf("gemini-3.5-flash")).toBe("google");116    expect(providerOf("gpt-5.5")).toBe("openai");117    expect(providerOf("claude-opus-5-5")).toBe("anthropic");118    expect(upstreamModelId("openrouter:meta/llama:free")).toBe("meta/llama:free");119    expect(upstreamModelId("gpt-5.5")).toBe("gpt-5.5");120  });121});122123describe("discovery", () => {124  it("reads each provider's listing and sends each key only to its own provider", async () => {125    const f = fakeFetch({126      "https://api.anthropic.com/v1/models": { data: [{ id: "claude-sonnet-5-5", display_name: "Claude Sonnet 5.5", max_input_tokens: 1_000_000, max_tokens: 128_000 }], has_more: false },127      "https://api.openai.com/v1/models": { data: [{ id: "gpt-5.5" }, { id: "text-embedding-3-large" }] },128      "https://generativelanguage.googleapis.com/v1beta/models": { models: [{ name: "models/gemini-3.5-flash", displayName: "Gemini 3.5 Flash", inputTokenLimit: 1048576, outputTokenLimit: 65536, supportedGenerationMethods: ["generateContent"] }, { name: "models/embed-1", supportedGenerationMethods: ["embedContent"] }] },129      "https://openrouter.ai/api/v1/models": { data: [{ id: "acme/tooler", name: "Acme Tooler", context_length: 200000, pricing: { prompt: "0.000003", completion: "0.000015" }, top_provider: { max_completion_tokens: 8192 }, architecture: { input_modalities: ["text", "image"] }, supported_parameters: ["tools", "reasoning"] }] },130      "http://10.0.0.5:8000/v1/models": { data: [{ id: "qwen3-30b" }] },131    });132    const a = await fetchProviderModels("anthropic", { fetchImpl: f.impl, env: ENV });133    expect(a).toEqual([{ id: "claude-sonnet-5-5", label: "Claude Sonnet 5.5", contextWindow: 1_000_000, maxOutput: 128_000 }]);134    expect((await fetchProviderModels("openai", { fetchImpl: f.impl, env: ENV })).map((m) => m.id)).toEqual(["gpt-5.5", "text-embedding-3-large"]);135    expect(await fetchProviderModels("google", { fetchImpl: f.impl, env: ENV })).toEqual([{ id: "gemini-3.5-flash", label: "Gemini 3.5 Flash", contextWindow: 1048576, maxOutput: 65536 }]);136    expect(await fetchProviderModels("openrouter", { fetchImpl: f.impl, env: ENV })).toEqual([{ id: "acme/tooler", label: "Acme Tooler", contextWindow: 200000, maxOutput: 8192, pricing: { inputPerMTok: 3, outputPerMTok: 15 }, tools: true, vision: true, reasoning: true }]);137    expect(await fetchProviderModels("local", { fetchImpl: f.impl, env: ENV })).toEqual([{ id: "qwen3-30b" }]);138139    const sent = (host: string) => JSON.stringify(f.calls.filter((c) => c.url.includes(host)).map((c) => c.headers));140    expect(sent("anthropic.com")).toContain('"x-api-key":"a"');141    expect(sent("openai.com")).toBe('[{"Authorization":"Bearer o"}]');142    expect(sent("googleapis.com")).toBe('[{"x-goog-api-key":"g"}]');143    expect(sent("openrouter.ai")).toBe('[{"Authorization":"Bearer r"}]');144    expect(sent("10.0.0.5")).toBe("[{}]"); // no local key configured: no header145  });146147  it("follows Anthropic pagination", async () => {148    let page = 0;149    const f = fakeFetch({ "https://api.anthropic.com/v1/models": () => (page++ === 0 ? { data: [{ id: "m1" }], has_more: true, last_id: "m1" } : { data: [{ id: "m2" }], has_more: false }) });150    expect((await fetchProviderModels("anthropic", { fetchImpl: f.impl, env: ENV })).map((m) => m.id)).toEqual(["m1", "m2"]);151    expect(f.calls[1].url).toContain("after_id=m1");152  });153154  it("parses OpenRouter prices per token and refuses what is not a price", () => {155    expect(openRouterPricing({ prompt: "0.00000025", completion: "0.000002" })).toEqual({ inputPerMTok: 0.25, outputPerMTok: 2 });156    expect(openRouterPricing({ prompt: "0", completion: "0" })).toEqual({ inputPerMTok: 0, outputPerMTok: 0 });157    expect(openRouterPricing({ prompt: "-1", completion: "-1" })).toBeNull(); // priced at request time158    expect(openRouterPricing({ prompt: "abc" })).toBeNull();159    expect(openRouterPricing(undefined)).toBeNull();160  });161162  it("never throws, reports the failure, and keeps the last good listing (stale-while-error)", async () => {163    let clock = 1_000_000;164    const now = () => clock;165    const ok = fakeFetch({ "https://openrouter.ai/api/v1/models": { data: [{ id: "acme/tooler", supported_parameters: ["tools"] }] } });166    await refreshRegistry({ fetchImpl: ok.impl, env: { OPENROUTER_API_KEY: "r" }, now });167    expect(registrySnapshot({ OPENROUTER_API_KEY: "r" }).find((p) => p.id === "openrouter")).toMatchObject({ ok: true, error: null, checkedAt: 1_000_000 });168169    // Within 6 h nothing is asked again.170    clock += 3_600_000;171    await refreshRegistry({ fetchImpl: ok.impl, env: { OPENROUTER_API_KEY: "r" }, now });172    expect(ok.calls).toHaveLength(1);173174    // After 6 h the listing is refreshed; this time the provider is down.175    clock += 6 * 3_600_000;176    const down = async () => {177      throw new Error("connect ECONNREFUSED sk-secretsecretsecret");178    };179    await expect(refreshRegistry({ fetchImpl: down as any, env: { OPENROUTER_API_KEY: "r" }, now })).resolves.toBeUndefined();180    const p = registrySnapshot({ OPENROUTER_API_KEY: "r" }).find((x) => x.id === "openrouter")!;181    expect(p.ok).toBe(false);182    expect(p.error).toContain("ECONNREFUSED");183    expect(p.error).not.toContain("secretsecret");184    expect(p.models.map((m) => m.id)).toEqual(["openrouter:acme/tooler"]);185    expect(p.models[0].selectable).toBe(true);186  });187188  it("reports an HTTP error of a listing endpoint without failing the others", async () => {189    const f = fakeFetch({ "https://api.openai.com/v1/models": { data: [{ id: "gpt-5.5" }] } }); // anthropic → 404190    await refreshRegistry({ fetchImpl: f.impl, env: { ANTHROPIC_API_KEY: "a", OPENAI_API_KEY: "o" } });191    const snap = registrySnapshot({ ANTHROPIC_API_KEY: "a", OPENAI_API_KEY: "o" });192    expect(snap.find((p) => p.id === "anthropic")).toMatchObject({ ok: false, error: "HTTP 404" });193    expect(snap.find((p) => p.id === "openai")).toMatchObject({ ok: true, error: null });194    expect(snap.find((p) => p.id === "google")).toMatchObject({ configured: false, ok: false, checkedAt: 0 });195  });196});197198describe("merge", () => {199  it("marks a curated id the listing does not return as unavailable, and keeps its curated facts", () => {200    const p = mergeProvider("anthropic", state([{ id: "claude-sonnet-5-5" }, { id: "claude-fable-5-2" }]), ENV);201    const by = Object.fromEntries(p.models.map((m) => [m.id, m]));202    expect(by["claude-sonnet-5-5"]).toMatchObject({ available: true, selectable: true, source: "curated", label: "Sonnet 5.5", tier: "balanced" });203    expect(by["claude-opus-4-8"]).toMatchObject({ available: false, selectable: false, source: "curated" });204    expect(by["claude-opus-4-8"].pricing).toEqual({ inputPerMTok: knownClaudeSpecs()["claude-opus-4-8"].input, outputPerMTok: knownClaudeSpecs()["claude-opus-4-8"].output });205    expect(p.logo).toBe("/brand/providers/anthropic.svg");206  });207208  it("keeps curated models usable while no listing has ever succeeded, and nothing when the provider has no key", () => {209    const pending = mergeProvider("openai", state(null, { ok: false, checkedAt: 0, fetchedAt: 0 }), ENV);210    expect(pending.models.every((m) => m.available && m.selectable)).toBe(true);211    const failed = mergeProvider("openai", state(null, { ok: false, error: "timed out" }), ENV);212    expect(failed).toMatchObject({ ok: false, error: "timed out" });213    expect(failed.models.every((m) => m.selectable)).toBe(true);214    const noKey = mergeProvider("openai", state(null, { ok: false }), {});215    expect(noKey).toMatchObject({ configured: false, ok: false, error: null });216    expect(noKey.models.length).toBeGreaterThan(0);217    expect(noKey.models.some((m) => m.available || m.selectable)).toBe(false);218  });219220  it("fills a context size the repository does not state from the provider's listing, never the reverse", () => {221    const p = mergeProvider("google", state([{ id: "gemini-3.5-flash", contextWindow: 1048576, maxOutput: 65536 }]), ENV);222    const m = p.models.find((x) => x.id === "gemini-3.5-flash")!;223    expect(m.contextWindow).toBe(1048576);224    expect(m.maxOutput).toBe(OPENAI_COMPAT_SPECS["gemini-3.5-flash"].maxOut);225  });226227  it("lists other native models without making them selectable, and hides non-chat ids", () => {228    const p = mergeProvider("openai", state([{ id: "gpt-5.5" }, { id: "gpt-9-experimental" }, { id: "text-embedding-3-large" }, { id: "whisper-1" }]), ENV);229    const extra = p.models.filter((m) => m.source === "api");230    expect(extra.map((m) => m.id)).toEqual(["gpt-9-experimental"]);231    expect(extra[0]).toMatchObject({ available: true, selectable: false, pricing: null, contextWindow: null });232  });233234  it("offers OpenRouter models with their listed price and context, selectable only when they take tools", () => {235    const p = mergeProvider("openrouter", state([236      { id: "acme/tooler", label: "Acme Tooler", contextWindow: 200000, maxOutput: 8192, pricing: { inputPerMTok: 3, outputPerMTok: 15 }, tools: true, vision: true, reasoning: false },237      { id: "acme/chat-only", pricing: null, tools: false },238    ]), ENV);239    expect(p.models[0]).toEqual({240      id: "openrouter:acme/tooler", label: "Acme Tooler", provider: "openrouter", tier: "frontier", contextWindow: 200000, maxOutput: 8192, pricing: { inputPerMTok: 3, outputPerMTok: 15 },241      capabilities: { tools: true, vision: true, reasoning: false, streaming: true }, available: true, source: "api", selectable: true,242    });243    expect(p.models[1]).toMatchObject({ id: "openrouter:acme/chat-only", label: "acme/chat-only", selectable: false, pricing: null });244  });245246  it("names the local provider from LOCAL_LLM_NAME and prices nothing there", () => {247    const p = mergeProvider("local", state([{ id: "qwen3-30b" }]), ENV);248    expect(p.name).toBe("MacLustr AI");249    expect(p.models).toHaveLength(1);250    expect(p.models[0]).toMatchObject({ id: "local:qwen3-30b", selectable: true, pricing: null, contextWindow: null });251    expect(mergeProvider("local", state(null), { LOCAL_LLM_BASE_URL: "http://h" }).name).toBe("Local");252  });253});254255describe("isSelectableModel / pricingFor", () => {256  const env = process.env;257  it("accepts curated ids before any discovery, auto, and nothing unknown", () => {258    process.env = { ...env, ANTHROPIC_API_KEY: "a", OPENAI_API_KEY: "o", GEMINI_API_KEY: "g" };259    try {260      expect(isSelectableModel("claude-opus-5-5")).toBe(true);261      expect(isSelectableModel("auto")).toBe(true);262      expect(isSelectableModel("claude-fable-5")).toBe(false);263      expect(isSelectableModel("openrouter:acme/tooler")).toBe(false);264      expect(isSelectableModel("")).toBe(false);265      expect(isSelectableModel(undefined)).toBe(false);266    } finally {267      process.env = env;268    }269  });270271  it("follows the listings once they exist", () => {272    process.env = { ...env, ANTHROPIC_API_KEY: "a", OPENROUTER_API_KEY: "r" };273    try {274      __setProviderState("anthropic", state([{ id: "claude-fable-5-2" }]));275      __setProviderState("openrouter", state([{ id: "acme/tooler", tools: true, pricing: { inputPerMTok: 3, outputPerMTok: 15 } }, { id: "acme/no-tools", tools: false }, { id: "acme/unpriced", tools: true }]));276      expect(isSelectableModel("claude-fable-5-2")).toBe(true);277      expect(isSelectableModel("claude-opus-4-8")).toBe(false); // no longer listed by the provider278      expect(isSelectableModel("openrouter:acme/tooler")).toBe(true);279      expect(isSelectableModel("openrouter:acme/no-tools")).toBe(false);280      expect(pricingFor("openrouter:acme/tooler")).toEqual({ inputPerMTok: 3, outputPerMTok: 15 });281      expect(pricingFor("openrouter:acme/unpriced")).toBeNull();282      expect(pricingFor("local:anything")).toBeNull();283    } finally {284      process.env = env;285    }286  });287});288
Files main
Menu

Theme