Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

fix(aihubmix): use full models endpoint to return complete model list (#14511)

Bianzinanf4de472e8250
diff --git a/packages/model-runtime/src/providers/aihubmix/index.test.ts b/packages/model-runtime/src/providers/aihubmix/index.test.ts
index 5d8991b2cad..c470506afa4 100644
--- a/packages/model-runtime/src/providers/aihubmix/index.test.ts
+++ b/packages/model-runtime/src/providers/aihubmix/index.test.ts
@@ -1,8 +1,12 @@
// @vitest-environment node
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import * as modelParse from '../../utils/modelParse';
import { LobeAiHubMixAI } from './index';
+const mockFetch = vi.fn();
+global.fetch = mockFetch;
+
describe('LobeAiHubMixAI', () => {
let instance: InstanceType<typeof LobeAiHubMixAI>;
@@ -10,6 +14,12 @@ describe('LobeAiHubMixAI', () => {
instance = new LobeAiHubMixAI({ apiKey: 'test_api_key' });
});
+ afterEach(() => {
+ vi.clearAllMocks();
+ vi.restoreAllMocks();
+ mockFetch.mockReset();
+ });
+
describe('constructor', () => {
it('should initialize with correct provider', () => {
expect(instance).toBeDefined();
@@ -38,30 +48,140 @@ describe('LobeAiHubMixAI', () => {
});
describe('models', () => {
- it('should return empty array on error', async () => {
- // Mock the client to throw an error
- const mockClient = {
- models: {
- list: vi.fn().mockRejectedValue(new Error('API Error')),
- },
- };
+ const mockModels = [
+ { id: 'gpt-4o', object: 'model', created: 1, owned_by: 'openai' },
+ { model_id: 'claude-3-5-sonnet', object: 'model', created: 1, owned_by: 'anthropic' },
+ ];
+
+ it('should fetch from full endpoint with correct headers', async () => {
+ mockFetch.mockResolvedValueOnce(
+ new Response(JSON.stringify({ data: mockModels }), { status: 200 }),
+ );
+
+ await instance.models();
+
+ expect(mockFetch).toHaveBeenCalledWith(
+ 'https://aihubmix.com/api/v1/models',
+ expect.objectContaining({
+ headers: expect.objectContaining({
+ 'Authorization': 'Bearer test_api_key',
+ 'APP-Code': 'LobeHub',
+ }),
+ }),
+ );
+ });
+
+ it('should normalize model_id field to id', async () => {
+ mockFetch.mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ data: [{ model_id: 'some-model', object: 'model', created: 1, owned_by: 'test' }],
+ }),
+ { status: 200 },
+ ),
+ );
+
+ // Normalization must set id so processMultiProviderModelList receives a valid model
+ const list = await instance.models();
+ expect(list.some((m) => m.id === 'some-model')).toBe(true);
+ });
+
+ it('should map AiHubMix API fields to LobeHub model card fields', async () => {
+ const spy = vi.spyOn(modelParse, 'processMultiProviderModelList').mockResolvedValueOnce([]);
+
+ mockFetch.mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ data: [
+ {
+ model_id: 'test-llm',
+ desc: 'A test LLM',
+ types: 'llm',
+ features: 'tools,function_calling,thinking,web',
+ input_modalities: 'text,image',
+ context_length: 128_000,
+ max_output: 8192,
+ pricing: { input: 1, output: 3, cache_read: 0.25, cache_write: 0.5 },
+ },
+ ],
+ }),
+ { status: 200 },
+ ),
+ );
+
+ await instance.models();
+
+ expect(spy).toHaveBeenCalledWith(
+ expect.arrayContaining([
+ expect.objectContaining({
+ contextWindowTokens: 128_000,
+ description: 'A test LLM',
+ functionCall: true,
+ id: 'test-llm',
+ maxOutput: 8192,
+ pricing: { cachedInput: 0.25, input: 1, output: 3, writeCacheInput: 0.5 },
+ reasoning: true,
+ search: true,
+ type: 'chat',
+ vision: true,
+ }),
+ ]),
+ 'aihubmix',
+ );
+ });
+
+ it('should filter out rerank models so they do not appear as chat models', async () => {
+ const spy = vi.spyOn(modelParse, 'processMultiProviderModelList').mockResolvedValueOnce([]);
+
+ mockFetch.mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ data: [
+ { model_id: 'cohere-rerank-v4.0', types: 'rerank' },
+ { model_id: 'qwen3-reranker-8b', types: 'reranking' },
+ { model_id: 'gpt-4o', types: 'llm' },
+ ],
+ }),
+ { status: 200 },
+ ),
+ );
+
+ await instance.models();
+
+ const passedModels = spy.mock.calls.at(-1)![0] as { id: string }[];
+ expect(passedModels.find((m) => m.id === 'cohere-rerank-v4.0')).toBeUndefined();
+ expect(passedModels.find((m) => m.id === 'qwen3-reranker-8b')).toBeUndefined();
+ expect(passedModels.find((m) => m.id === 'gpt-4o')).toBeDefined();
+ });
+
+ it('should return empty array when API key is missing', async () => {
+ const instanceNoKey = new LobeAiHubMixAI({ apiKey: '' });
+ const list = await instanceNoKey.models();
+ expect(list).toEqual([]);
+ expect(mockFetch).not.toHaveBeenCalled();
+ });
+
+ it('should return empty array on non-ok HTTP response', async () => {
+ mockFetch.mockResolvedValueOnce(new Response('Unauthorized', { status: 401 }));
+
+ const list = await instance.models();
+ expect(list).toEqual([]);
+ });
+
+ it('should return empty array on network error', async () => {
+ mockFetch.mockRejectedValueOnce(new Error('Network Error'));
+
+ const list = await instance.models();
+ expect(list).toEqual([]);
+ });
+
+ it('should return empty array on timeout (AbortError)', async () => {
+ mockFetch.mockRejectedValueOnce(
+ Object.assign(new Error('The operation was aborted'), { name: 'AbortError' }),
+ );
- class MockRuntime {
- client = mockClient;
- }
-
- // The models method should return empty array on error
- vi.spyOn(instance as any, 'resolveRouters').mockResolvedValue([
- {
- apiType: 'openai',
- models: [],
- options: {},
- runtime: MockRuntime,
- },
- ]);
-
- const models = await instance.models();
- expect(models).toEqual([]);
+ const list = await instance.models();
+ expect(list).toEqual([]);
});
});
});
diff --git a/packages/model-runtime/src/providers/aihubmix/index.ts b/packages/model-runtime/src/providers/aihubmix/index.ts
index 6e13a825891..5c9a50fe6bc 100644
--- a/packages/model-runtime/src/providers/aihubmix/index.ts
+++ b/packages/model-runtime/src/providers/aihubmix/index.ts
@@ -6,14 +6,141 @@ import { createRouterRuntime } from '../../core/RouterRuntime';
import type { CreateRouterRuntimeOptions } from '../../core/RouterRuntime/createRuntime';
import { detectModelProvider, processMultiProviderModelList } from '../../utils/modelParse';
+/**
+ * Response schema for GET https://aihubmix.com/api/v1/models
+ * See https://docs.aihubmix.com/cn/api/Models-API
+ */
export interface AiHubMixModelCard {
- created: number;
- id: string;
- object: string;
- owned_by: string;
+ /** Context window size in tokens. */
+ context_length?: number;
+ /** Model description (English). */
+ desc?: string;
+ /**
+ * Comma-separated capability flags.
+ * Known values: thinking | tools | function_calling | web | structured_outputs
+ */
+ features?: string;
+ /**
+ * Comma-separated input modalities.
+ * Known values: text | image | audio | video | pdf
+ */
+ input_modalities?: string;
+ /** Maximum output length in tokens. */
+ max_output?: number;
+ /** Unique model identifier (new endpoint uses model_id; legacy endpoint uses id). */
+ model_id?: string;
+ /**
+ * Display name of the model.
+ * Note: not present in official API response examples; kept for forward compatibility.
+ */
+ model_name?: string;
+ /**
+ * Pricing in USD per million tokens.
+ * cache_write is the cache-write price (present in field docs but absent from response examples).
+ */
+ pricing?: {
+ cache_read?: number;
+ cache_write?: number;
+ input?: number;
+ output?: number;
+ };
+ /**
+ * Model type.
+ * Current values: llm | image_generation | video | tts | stt | embedding | rerank
+ * Legacy aliases (auto-mapped by the platform): t2t→llm | t2i→image_generation | t2v→video | reranking→rerank
+ */
+ types?: string;
}
-const baseURL = 'https://api.aihubmix.com';
+/**
+ * Maps AiHubMix `types` field values to LobeHub AiModelType.
+ * Both current identifiers and legacy aliases are included; the platform
+ * auto-maps them server-side, but we handle both defensively on the client.
+ * See https://docs.aihubmix.com/cn/api/Models-API
+ *
+ * Note: `rerank` / `reranking` are intentionally omitted — they are not part of
+ * LobeHub's AiModelType and are filtered out before model list processing to
+ * prevent rerank models from silently falling back to `chat` and failing at
+ * inference time.
+ */
+const TYPE_MAP: Record<string, string> = {
+ // Current type identifiers
+ embedding: 'embedding',
+ image_generation: 'image',
+ llm: 'chat',
+ stt: 'stt',
+ tts: 'tts',
+ video: 'video',
+ // Legacy aliases (platform docs note automatic bidirectional mapping)
+ t2i: 'image', // t2i ↔ image_generation
+ t2t: 'chat', // t2t ↔ llm
+ t2v: 'video', // t2v ↔ video
+};
+
+/**
+ * AiHubMix `types` values that have no corresponding LobeHub AiModelType.
+ * Models with these types are filtered out before processing to prevent them
+ * from incorrectly appearing as chat models in the UI.
+ */
+const UNSUPPORTED_AIHUBMIX_TYPES = new Set(['rerank', 'reranking']);
+
+/**
+ * Map AiHubMix full-catalog API response fields to LobeHub model card fields.
+ * The new endpoint returns its own schema (model_id, desc, types, features, etc.)
+ * which must be normalized before being passed to processMultiProviderModelList.
+ */
+const mapAiHubMixModel = (m: any): { [key: string]: any; id: string } => {
+ const id: string = m.id ?? m.model_id;
+
+ // Parse features into a Set only when the field is present and non-empty
+ const featureList =
+ typeof m.features === 'string' && m.features.trim()
+ ? m.features.split(',').map((s: string) => s.trim())
+ : null;
+ const featureSet = featureList ? new Set(featureList) : null;
+
+ // Parse input_modalities into an array when present
+ const inputModalities =
+ typeof m.input_modalities === 'string'
+ ? m.input_modalities.split(',').map((s: string) => s.trim())
+ : null;
+
+ // Remap pricing field names: cache_read → cachedInput, cache_write → writeCacheInput
+ const rawPricing = m.pricing && typeof m.pricing === 'object' ? m.pricing : null;
+ const pricing = rawPricing
+ ? {
+ ...(typeof rawPricing.input === 'number' && { input: rawPricing.input }),
+ ...(typeof rawPricing.output === 'number' && { output: rawPricing.output }),
+ ...(typeof rawPricing.cache_read === 'number' && { cachedInput: rawPricing.cache_read }),
+ ...(typeof rawPricing.cache_write === 'number' && {
+ writeCacheInput: rawPricing.cache_write,
+ }),
+ }
+ : null;
+
+ return {
+ ...m,
+ id,
+ ...(m.desc !== undefined && { description: m.desc }),
+ ...(m.model_name !== undefined && { displayName: m.model_name }),
+ ...(m.context_length !== undefined && { contextWindowTokens: m.context_length }),
+ ...(m.max_output !== undefined && { maxOutput: m.max_output }),
+ ...(m.types !== undefined && { type: TYPE_MAP[m.types] }),
+ ...(pricing !== null && { pricing }),
+ // Map `features` capabilities only when the field is present; when absent,
+ // processMultiProviderModelList falls back to keyword-based detection.
+ // Known features values: thinking | tools | function_calling | web | structured_outputs
+ // `structured_outputs` has no corresponding LobeHub model card field and is intentionally omitted.
+ ...(featureSet && {
+ functionCall: featureSet.has('tools') || featureSet.has('function_calling'),
+ reasoning: featureSet.has('thinking'),
+ search: featureSet.has('web'),
+ }),
+ ...(inputModalities && { vision: inputModalities.includes('image') }),
+ };
+};
+
+const baseURL = 'https://aihubmix.com';
export const params: CreateRouterRuntimeOptions = {
debug: {
@@ -24,10 +151,35 @@ export const params: CreateRouterRuntimeOptions = {
},
id: ModelProvider.AiHubMix,
models: async ({ client }) => {
+ const apiKey = (client as any).apiKey as string | undefined;
+ if (!apiKey) return [];
+
+ // AiHubMix exposes two model list endpoints:
+ // - https://aihubmix.com/v1/models — returns per-user-group list only (~256 models)
+ // - https://aihubmix.com/api/v1/models — returns the complete model catalog (800+)
+ // Use the full endpoint so users can access all available models.
+ // See https://docs.aihubmix.com/cn/api/Models-API
+ // 'APP-Code' is an AiHubMix-required client identifier.
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 10_000);
try {
- const modelsPage = (await client.models.list()) as any;
- const modelList: AiHubMixModelCard[] = modelsPage.data || [];
+ const response = await fetch('https://aihubmix.com/api/v1/models', {
+ headers: {
+ 'Authorization': `Bearer ${apiKey}`,
+ 'APP-Code': 'LobeHub',
+ },
+ signal: controller.signal,
+ });
+
+ if (!response.ok) {
+ const text = await response.text().catch(() => '');
+ throw new Error(`HTTP ${response.status}: ${text}`);
+ }
+ const json = (await response.json()) as { data?: any[] };
+ const modelList = (json.data || [])
+ .filter((m: any) => !UNSUPPORTED_AIHUBMIX_TYPES.has(m.types ?? ''))
+ .map((m: any) => mapAiHubMixModel(m));
return await processMultiProviderModelList(modelList, 'aihubmix');
} catch (error) {
console.warn(
@@ -35,6 +187,8 @@ export const params: CreateRouterRuntimeOptions = {
error,
);
return [];
+ } finally {
+ clearTimeout(timeoutId);
}
},
routers: [