diff --git a/docs/openapi.yaml b/docs/openapi.yaml index 8e16c6a587..46dca73813 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -432,6 +432,38 @@ paths: items: $ref: "#/components/schemas/Model" + /api/v1/providers/{provider}/models: + get: + tags: [Models] + summary: List models for a specific provider + description: Returns only models for the selected provider with provider prefix removed from each model id. + security: + - BearerAuth: [] + parameters: + - in: path + name: provider + required: true + schema: + type: string + description: Provider id or alias (for example `openai`, `claude`, `cc`). + responses: + "200": + description: Provider-scoped model list + content: + application/json: + schema: + type: object + properties: + object: + type: string + example: list + data: + type: array + items: + $ref: "#/components/schemas/Model" + "400": + description: Unknown provider + /api/models: get: tags: [Models] diff --git a/src/app/api/v1/providers/[provider]/models/route.ts b/src/app/api/v1/providers/[provider]/models/route.ts new file mode 100644 index 0000000000..525660e4a4 --- /dev/null +++ b/src/app/api/v1/providers/[provider]/models/route.ts @@ -0,0 +1,85 @@ +import { getUnifiedModelsResponse } from "@/app/api/v1/models/catalog"; +import { getRegistryEntry } from "@omniroute/open-sse/config/providerRegistry.ts"; + +/** + * Handle CORS preflight + */ +export async function OPTIONS() { + return new Response(null, { + headers: { + "Access-Control-Allow-Methods": "GET, OPTIONS", + "Access-Control-Allow-Headers": "*", + }, + }); +} + +/** + * GET /v1/providers/{provider}/models + * Returns models for one provider with unprefixed ids. + */ +export async function GET(request: Request, { params }: { params: Promise<{ provider: string }> }) { + const { provider: rawProvider } = await params; + const providerEntry = getRegistryEntry(rawProvider); + + if (!providerEntry) { + return Response.json( + { + error: { + message: `Unknown provider: ${rawProvider}`, + type: "invalid_request_error", + code: "invalid_provider", + }, + }, + { status: 400 } + ); + } + + const response = await getUnifiedModelsResponse(request); + const payload = (await response + .clone() + .json() + .catch(() => null)) as { object?: string; data?: Array> } | null; + + if (!response.ok || !payload || !Array.isArray(payload.data)) { + return response; + } + + const providerId = providerEntry.id; + const providerAlias = providerEntry.alias || providerId; + + const toUnprefixedModelId = (model: Record) => { + const root = typeof model.root === "string" && model.root.trim().length > 0 ? model.root : null; + if (root) return root; + + const id = typeof model.id === "string" ? model.id : ""; + if (!id) return id; + if (id.startsWith(`${providerAlias}/`)) return id.slice(providerAlias.length + 1); + if (id.startsWith(`${providerId}/`)) return id.slice(providerId.length + 1); + return id; + }; + + const filtered = payload.data.filter((model) => model?.owned_by === providerId); + const deduped = new Map>(); + + for (const model of filtered) { + const unprefixedId = toUnprefixedModelId(model); + if (!unprefixedId) continue; + if (deduped.has(unprefixedId)) continue; + deduped.set(unprefixedId, { + ...model, + id: unprefixedId, + parent: null, + }); + } + + return Response.json( + { + object: payload.object || "list", + data: [...deduped.values()], + }, + { + status: response.status, + headers: response.headers, + } + ); +} diff --git a/src/app/docs/components/ApiExplorerClient.tsx b/src/app/docs/components/ApiExplorerClient.tsx index 20f5a189a9..bf04eb1aac 100644 --- a/src/app/docs/components/ApiExplorerClient.tsx +++ b/src/app/docs/components/ApiExplorerClient.tsx @@ -28,6 +28,12 @@ const API_ENDPOINTS: ApiEndpoint[] = [ description: "List available models across all providers", tag: "Models", }, + { + method: "GET", + path: "/v1/providers/openai/models", + description: "List models for a specific provider (ids without provider prefix)", + tag: "Models", + }, { method: "POST", path: "/v1/embeddings", @@ -99,6 +105,7 @@ const EXAMPLE_BODIES: Record = { 2 ), "/v1/models": "", + "/v1/providers/openai/models": "", "/v1/embeddings": JSON.stringify( { model: "openai/text-embedding-3-small", input: "Hello world" }, null, diff --git a/tests/unit/provider-scoped-models-route.test.ts b/tests/unit/provider-scoped-models-route.test.ts new file mode 100644 index 0000000000..55b40205cb --- /dev/null +++ b/tests/unit/provider-scoped-models-route.test.ts @@ -0,0 +1,119 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-provider-models-")); +process.env.DATA_DIR = TEST_DATA_DIR; + +const core = await import("../../src/lib/db/core.ts"); +const providersDb = await import("../../src/lib/db/providers.ts"); +const combosDb = await import("../../src/lib/db/combos.ts"); +const providerModelsRoute = + await import("../../src/app/api/v1/providers/[provider]/models/route.ts"); + +async function resetStorage() { + core.resetDbInstance(); + fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true }); + fs.mkdirSync(TEST_DATA_DIR, { recursive: true }); +} + +async function seedConnection(provider: string, overrides: Record = {}) { + return providersDb.createProviderConnection({ + provider, + authType: overrides.authType || "apikey", + name: overrides.name || `${provider}-${Math.random().toString(16).slice(2, 8)}`, + apiKey: overrides.apiKey || "sk-test", + accessToken: overrides.accessToken, + isActive: overrides.isActive ?? true, + testStatus: overrides.testStatus || "active", + providerSpecificData: overrides.providerSpecificData || {}, + }); +} + +test.beforeEach(async () => { + await resetStorage(); +}); + +test.after(async () => { + core.resetDbInstance(); + fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true }); +}); + +test("provider models route returns only selected provider models with unprefixed ids", async () => { + await seedConnection("openai", { name: "openai-main" }); + await seedConnection("claude", { + authType: "oauth", + name: "claude-main", + apiKey: null, + accessToken: "claude-access", + }); + await combosDb.createCombo({ + name: "team-router", + strategy: "priority", + models: ["openai/gpt-4o"], + }); + + const response = await providerModelsRoute.GET( + new Request("http://localhost/api/v1/providers/openai/models"), + { + params: Promise.resolve({ provider: "openai" }), + } + ); + + const body = (await response.json()) as any; + const ids = body.data.map((model: any) => model.id); + + assert.equal(response.status, 200); + assert.ok(ids.length > 0); + assert.equal( + ids.some((id: string) => id.includes("/")), + false + ); + assert.equal( + body.data.some((model: any) => model.owned_by !== "openai"), + false + ); + assert.equal(ids.includes("team-router"), false); +}); + +test("provider models route accepts provider alias in path", async () => { + await seedConnection("claude", { + authType: "oauth", + name: "claude-main", + apiKey: null, + accessToken: "claude-access", + }); + + const response = await providerModelsRoute.GET( + new Request("http://localhost/api/v1/providers/cc/models"), + { + params: Promise.resolve({ provider: "cc" }), + } + ); + + const body = (await response.json()) as any; + const ids = body.data.map((model: any) => model.id); + + assert.equal(response.status, 200); + assert.ok(ids.includes("claude-sonnet-4-6")); + assert.equal( + ids.some((id: string) => id.startsWith("cc/") || id.startsWith("claude/")), + false + ); +}); + +test("provider models route returns 400 for unknown provider", async () => { + const response = await providerModelsRoute.GET( + new Request("http://localhost/api/v1/providers/nope/models"), + { + params: Promise.resolve({ provider: "nope" }), + } + ); + + const body = (await response.json()) as any; + + assert.equal(response.status, 400); + assert.equal(body.error.code, "invalid_provider"); +});