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

fix(model-discovery): route custom-endpoint models with modality metadata to their native table (#1506) (#1556)

Alan Voe5df303b4b0a
diff --git a/client/src/components/keys/discover-models-dialog.tsx b/client/src/components/keys/discover-models-dialog.tsx
index b26b7f5a..b8c17af2 100644
--- a/client/src/components/keys/discover-models-dialog.tsx
+++ b/client/src/components/keys/discover-models-dialog.tsx
@@ -101,7 +101,13 @@ export function DiscoverModelsDialog({
...(endpoint.keyId === undefined ? { baseUrl: endpoint.baseUrl } : { keyId: endpoint.keyId }),
...(endpoint.apiKey ? { apiKey: endpoint.apiKey } : {}),
...(endpoint.groupLabel?.trim() ? { groupLabel: endpoint.groupLabel.trim() } : {}),
- models: [...selected],
+ // #1506: forward each picked model's discovered kind so the server
+ // registers generic-id media/embedding models in the right table
+ // instead of re-classifying by id and dropping them to chat.
+ models: [...selected].map(id => {
+ const discovered = models.find(m => m.id === id)
+ return discovered?.kind ? { model: id, kind: discovered.kind } : id
+ }),
}),
}),
onSuccess: (data) => {
diff --git a/server/src/__tests__/routes/custom-model-kind-forwarding.test.ts b/server/src/__tests__/routes/custom-model-kind-forwarding.test.ts
new file mode 100644
index 00000000..c15f947e
--- /dev/null
+++ b/server/src/__tests__/routes/custom-model-kind-forwarding.test.ts
@@ -0,0 +1,145 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { Express, AddressInfo } from 'express';
+import { createApp } from '../../app.js';
+import { initDb, getDb } from '../../db/index.js';
+import { mintDashboardToken, isGatedApiPath } from '../helpers/auth.js';
+
+const realFetch = globalThis.fetch;
+let dashToken = '';
+
+async function post(app: Express, path: string, body: unknown) {
+ const server = app.listen(0, '127.0.0.1');
+ if (!server.listening) await new Promise<void>(resolve => server.once('listening', () => resolve()));
+ const { port } = server.address() as AddressInfo;
+ const res = await realFetch(`http://127.0.0.1:${port}${path}`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ ...(isGatedApiPath(path) ? { Authorization: `Bearer ${dashToken}` } : {}),
+ },
+ body: JSON.stringify(body),
+ });
+ const data = await res.json().catch(() => null);
+ server.close();
+ return { status: res.status, body: data };
+}
+
+// #1506: a custom endpoint model whose id carries no media keyword but whose
+// metadata (`type`/`model_type`/`object`) declares a modality. Discovery
+// classifies it by that metadata, and the dashboard forwards the verdict so
+// registration lands in the matching table instead of silently 404ing as chat.
+describe('custom model modality forwarded from discovery (#1506)', () => {
+ let app: Express;
+
+ beforeEach(() => {
+ process.env.ENCRYPTION_KEY = '0'.repeat(64);
+ process.env.CATALOG_SYNC_DISABLED = '1';
+ initDb(':memory:');
+ app = createApp();
+ dashToken = mintDashboardToken();
+ });
+
+ afterEach(() => {
+ globalThis.fetch = realFetch;
+ vi.restoreAllMocks();
+ });
+
+ it('registers a forwarded "audio" kind into media_models, not chat', async () => {
+ const res = await post(app, '/api/keys/custom', {
+ baseUrl: 'http://127.0.0.1:9090/v1',
+ apiKey: 'kind-secret',
+ models: [{ model: 'generic-audio-7b', kind: 'audio' }],
+ });
+ expect(res.status).toBe(201);
+ expect(res.body.videoSkipped).toEqual([]);
+ const inMedia = getDb().prepare(
+ "SELECT modality FROM media_models WHERE platform = 'custom' AND model_id = 'generic-audio-7b'",
+ ).get() as { modality: string } | undefined;
+ expect(inMedia?.modality).toBe('audio');
+ // Must NOT have landed in the chat models table.
+ expect(getDb().prepare(
+ "SELECT 1 FROM models WHERE platform = 'custom' AND model_id = 'generic-audio-7b' AND endpoint_scope = 'http://127.0.0.1:9090/v1'",
+ ).get()).toBeUndefined();
+ });
+
+ it('registers a forwarded "image" kind into media_models, not chat', async () => {
+ const res = await post(app, '/api/keys/custom', {
+ baseUrl: 'http://127.0.0.1:9091/v1',
+ apiKey: 'kind-secret',
+ models: [{ model: 'generic-image-3b', kind: 'image' }],
+ });
+ expect(res.status).toBe(201);
+ const inMedia = getDb().prepare(
+ "SELECT modality FROM media_models WHERE platform = 'custom' AND model_id = 'generic-image-3b'",
+ ).get() as { modality: string } | undefined;
+ expect(inMedia?.modality).toBe('image');
+ expect(getDb().prepare(
+ "SELECT 1 FROM models WHERE platform = 'custom' AND model_id = 'generic-image-3b' AND endpoint_scope = 'http://127.0.0.1:9091/v1'",
+ ).get()).toBeUndefined();
+ });
+
+ it('routes a forwarded "video" kind to the skip list, not a chat row', async () => {
+ const res = await post(app, '/api/keys/custom', {
+ baseUrl: 'http://127.0.0.1:9092/v1',
+ apiKey: 'kind-secret',
+ models: [{ model: 'generic-vgen-7b', kind: 'video' }],
+ });
+ expect(res.status).toBe(201);
+ expect(res.body.videoSkipped).toEqual(['generic-vgen-7b']);
+ expect(getDb().prepare(
+ "SELECT 1 FROM models WHERE platform = 'custom' AND model_id = 'generic-vgen-7b' AND endpoint_scope = 'http://127.0.0.1:9092/v1'",
+ ).get()).toBeUndefined();
+ });
+
+ it('still classifies by id when no kind is forwarded (unchanged #1051 behavior)', async () => {
+ const res = await post(app, '/api/keys/custom', {
+ baseUrl: 'http://127.0.0.1:9093/v1',
+ apiKey: 'kind-secret',
+ models: ['flute-tts-1'],
+ });
+ expect(res.status).toBe(201);
+ const inMedia = getDb().prepare(
+ "SELECT modality FROM media_models WHERE platform = 'custom' AND model_id = 'flute-tts-1'",
+ ).get() as { modality: string } | undefined;
+ expect(inMedia?.modality).toBe('audio');
+ });
+
+ // End-to-end: the dashboard discovers a metadata-only audio model, forwards
+ // its kind, and the server registers it in the right table — reproducing the
+ // full round trip the previous (discovery-only) change was missing.
+ it('discovery -> forwarded-kind registration round-trip (#1506)', async () => {
+ const fetchMock = vi.fn(async (input: RequestInfo) => {
+ const url = String(input);
+ if (url.endsWith('/models')) {
+ return new Response(JSON.stringify({
+ data: [{ id: 'generic-audio-7b', type: 'audio' }],
+ }), { status: 200, headers: { 'content-type': 'application/json' } });
+ }
+ return new Response(JSON.stringify({ data: [] }), { status: 200, headers: { 'content-type': 'application/json' } });
+ });
+ globalThis.fetch = fetchMock as unknown as typeof globalThis.fetch;
+
+ const dis = await post(app, '/api/keys/custom/discover-models', {
+ baseUrl: 'http://127.0.0.1:9094/v1',
+ apiKey: 'discover-secret',
+ });
+ expect(dis.status).toBe(200);
+ const discovered = dis.body.models[0];
+ expect(discovered?.id).toBe('generic-audio-7b');
+ expect(discovered?.kind).toBe('audio');
+
+ const reg = await post(app, '/api/keys/custom', {
+ baseUrl: 'http://127.0.0.1:9094/v1',
+ apiKey: 'discover-secret',
+ models: [{ model: discovered.id, kind: discovered.kind }],
+ });
+ expect(reg.status).toBe(201);
+ const inMedia = getDb().prepare(
+ "SELECT modality FROM media_models WHERE platform = 'custom' AND model_id = 'generic-audio-7b'",
+ ).get() as { modality: string } | undefined;
+ expect(inMedia?.modality).toBe('audio');
+ expect(getDb().prepare(
+ "SELECT 1 FROM models WHERE platform = 'custom' AND model_id = 'generic-audio-7b' AND endpoint_scope = 'http://127.0.0.1:9094/v1'",
+ ).get()).toBeUndefined();
+ });
+});
diff --git a/server/src/__tests__/services/model-discovery.test.ts b/server/src/__tests__/services/model-discovery.test.ts
index cfdffe02..f655fb3f 100644
--- a/server/src/__tests__/services/model-discovery.test.ts
+++ b/server/src/__tests__/services/model-discovery.test.ts
@@ -388,6 +388,30 @@ describe('non-chat kind inferred from the model id (#1051)', () => {
expect(n.kind).toBe('embedding');
});
+ it('classifies bare "audio" and "image" type metadata (#1506)', () => {
+ // OpenRouter and similar OpenAI-compatible relays use bare `type` values.
+ // A model whose id carries no keyword at all must still be classified by
+ // its metadata, not silently fall through to chat and 404 every chain.
+ const [a] = parseModelCatalog({ data: [{ id: 'generic-model-7b', type: 'audio' }] });
+ expect(a.kind).toBe('audio');
+ const [i] = parseModelCatalog({ data: [{ id: 'generic-model-3b', type: 'image' }] });
+ expect(i.kind).toBe('image');
+ // The same bare value on a different metadata key classifies the same way.
+ const [m] = parseModelCatalog({ data: [{ id: 'm1', model_type: 'audio' }] });
+ expect(m.kind).toBe('audio');
+ const [n] = parseModelCatalog({ data: [{ id: 'm2', object: 'image' }] });
+ expect(n.kind).toBe('image');
+ });
+
+ it('keeps vision-chat task metadata as chat, not image or audio generation (#1506)', () => {
+ // Hugging Face style tasks name an input modality; only the bare values
+ // above mean a generation model.
+ for (const type of ['image-text-to-text', 'image-to-text', 'audio-text-to-text', 'any-to-any']) {
+ const [m] = parseModelCatalog({ data: [{ id: 'generic-model-9b', type }] });
+ expect(m.kind, type).toBeUndefined();
+ }
+ });
+
it("ignores OpenAI's uninformative object:'model'", () => {
const [m] = parseModelCatalog({ data: [{ id: 'gpt-x', object: 'model' }] });
expect(m.kind).toBeUndefined();
diff --git a/server/src/routes/keys.ts b/server/src/routes/keys.ts
index 8be3f10a..a6a4a270 100644
--- a/server/src/routes/keys.ts
+++ b/server/src/routes/keys.ts
@@ -17,7 +17,7 @@ import { resolveCustomEndpointKey, customEndpointKeyIds, siblingEndpointKeyId, e
import { registerCustomModels, registerCustomChatModels } from '../services/custom-model-register.js';
import { registerCustomMediaModel } from '../services/custom-media-register.js';
import { isSearchPlatform } from '../lib/search-platforms.js';
-import { discoverEndpointModels, probeEndpointModel, classifyModelId, ModelDiscoveryError } from '../services/model-discovery.js';
+import { discoverEndpointModels, probeEndpointModel, classifyModelId, ModelDiscoveryError, type DiscoveredModelKind } from '../services/model-discovery.js';
import { probeEmbeddingDimensions, registerCustomEmbeddingModel } from '../services/embeddings.js';
import { endpointScopeForBaseUrl, normalizeBaseUrl } from '../lib/endpoint-scope.js';
import { recordCustomModelTombstone } from '../services/custom-model-tombstone.js';
@@ -825,6 +825,11 @@ const modelEntrySchema = z.union([
displayName: z.string().optional(),
supportsTools: z.boolean().optional(),
supportsVision: z.boolean().optional(),
+ // #1506: a kind forwarded from discovery metadata (the endpoint's own
+ // `type`/metadata) so an id with no media keyword still routes to the
+ // table that can serve it. Absent, the handler falls back to the
+ // id-based classifier (#1051).
+ kind: z.enum(['embedding', 'image', 'audio', 'transcription', 'video']).optional(),
}),
]);
// `baseUrl` and `keyId` are both optional but at least one is required: the
@@ -1309,9 +1314,9 @@ keysRouter.post('/custom', async (req: Request, res: Response) => {
// whatever name it already has on re-registration (see the upsert below).
const topTools = parsed.data.supportsTools;
const topVision = parsed.data.supportsVision;
- const entries: { modelId: string; displayName: string | null; supportsTools?: boolean; supportsVision?: boolean }[] = [];
+ const entries: { modelId: string; displayName: string | null; supportsTools?: boolean; supportsVision?: boolean; kind?: DiscoveredModelKind }[] = [];
const seen = new Set<string>();
- const addEntry = (rawId: string, rawDisplay?: string, tools?: boolean, vision?: boolean) => {
+ const addEntry = (rawId: string, rawDisplay?: string, tools?: boolean, vision?: boolean, kind?: DiscoveredModelKind) => {
const modelId = rawId.trim();
if (!modelId || seen.has(modelId)) return;
seen.add(modelId);
@@ -1320,12 +1325,13 @@ keysRouter.post('/custom', async (req: Request, res: Response) => {
displayName: rawDisplay?.trim() || null,
supportsTools: tools ?? topTools,
supportsVision: vision ?? topVision,
+ kind,
});
};
if (parsed.data.model?.trim()) addEntry(parsed.data.model, parsed.data.displayName);
for (const m of parsed.data.models ?? []) {
if (typeof m === 'string') addEntry(m);
- else addEntry(m.model, m.displayName, m.supportsTools, m.supportsVision);
+ else addEntry(m.model, m.displayName, m.supportsTools, m.supportsVision, m.kind);
}
// A lone model submitted through the plural `models` also carries its name in
// the top-level `displayName` — that is exactly what the dashboard's custom
@@ -1380,7 +1386,14 @@ keysRouter.post('/custom', async (req: Request, res: Response) => {
// on the entry is an operator override: someone who says "this is a chat
// model with vision/tools" wins over the keyword guess.
const overridden = (e: typeof entries[number]) => e.supportsTools !== undefined || e.supportsVision !== undefined;
- const kindOf = (e: typeof entries[number]) => overridden(e) ? undefined : classifyModelId(e.modelId);
+ const kindOf = (e: typeof entries[number]) => {
+ // #1506: a forwarded discovery kind is authoritative for a generic-id
+ // model; an explicit capability flag forces chat over both the kind and
+ // the id guess (#1051).
+ if (overridden(e)) return undefined;
+ if (e.kind !== undefined) return e.kind;
+ return classifyModelId(e.modelId);
+ };
const chatEntries = entries.filter(e => kindOf(e) === undefined || kindOf(e) === 'embedding');
const embedEntries = chatEntries.filter(e => kindOf(e) === 'embedding');
const pureChatEntries = chatEntries.filter(e => kindOf(e) !== 'embedding');
diff --git a/server/src/services/model-discovery.ts b/server/src/services/model-discovery.ts
index 3dcd3b09..64d4b898 100644
--- a/server/src/services/model-discovery.ts
+++ b/server/src/services/model-discovery.ts
@@ -306,9 +306,9 @@ const KIND_METADATA_KEYS = ['type', 'task', 'object', 'model_type', 'modelType']
const KIND_METADATA_VALUES: ReadonlyArray<readonly [DiscoveredModelKind, RegExp]> = [
['embedding', /embedding/],
['transcription', /(speech-?to-?text|transcri|asr\b|\bstt\b)/],
- ['audio', /(text-?to-?speech|\btts\b|speech-?synthesis)/],
+ ['audio', /(text-?to-?speech|\btts\b|speech-?synthesis|^audio$)/],
['video', /video/],
- ['image', /(text-?to-?image|image-?generation|diffusion)/],
+ ['image', /(text-?to-?image|image-?generation|diffusion|^images?$)/],
];
/** The model's kind read off its id, for upstreams that advertise no usable