🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
feat(router-runtime): add fallback options (#11531)
YuTengjing2c1af8a7283f
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.mdindex 4410c6f918d..f72df2c6dbf 100644--- a/.github/PULL_REQUEST_TEMPLATE.md+++ b/.github/PULL_REQUEST_TEMPLATE.md@@ -16,7 +16,7 @@<!-- Link to the issue that is fixed by this PR -->-<!-- Example: Fixes #123, Closes #456, Related to #789 -->+<!-- Example: Fixes #xxx, Closes #xxx, Related to #xxx -->#### 🔀 Description of Changediff --git a/docs/development/basic/chat-api.mdx b/docs/development/basic/chat-api.mdxindex 262b592c783..1f079fa5174 100644--- a/docs/development/basic/chat-api.mdx+++ b/docs/development/basic/chat-api.mdx@@ -223,7 +223,6 @@ AgentRuntime is a core abstraction layer in Lobe Chat that encapsulates a unifiechat(payload: ChatStreamPayload, options?: ChatCompetitionOptions): Promise<Response>;embeddings?(payload: EmbeddingsPayload, options?: EmbeddingsOptions): Promise<Embeddings[]>;models?(): Promise<any>;- textToImage?: (payload: TextToImagePayload) => Promise<string[]>;textToSpeech?: (payload: TextToSpeechPayload,options?: TextToSpeechOptions,diff --git a/docs/development/basic/chat-api.zh-CN.mdx b/docs/development/basic/chat-api.zh-CN.mdxindex 783a63c288f..b8332d5f541 100644--- a/docs/development/basic/chat-api.zh-CN.mdx+++ b/docs/development/basic/chat-api.zh-CN.mdx@@ -223,7 +223,6 @@ AgentRuntime 是 Lobe Chat 中的一个核心抽象层,它封装了与不同 Achat(payload: ChatStreamPayload, options?: ChatCompetitionOptions): Promise<Response>;embeddings?(payload: EmbeddingsPayload, options?: EmbeddingsOptions): Promise<Embeddings[]>;models?(): Promise<any>;- textToImage?: (payload: TextToImagePayload) => Promise<string[]>;textToSpeech?: (payload: TextToSpeechPayload,options?: TextToSpeechOptions,diff --git a/packages/model-runtime/src/core/BaseAI.ts b/packages/model-runtime/src/core/BaseAI.tsindex fc0a0cf318f..bb8cc3aa37a 100644--- a/packages/model-runtime/src/core/BaseAI.ts+++ b/packages/model-runtime/src/core/BaseAI.ts@@ -13,7 +13,6 @@ import {GenerateObjectPayload,ModelRequestOptions,PullModelParams,- TextToImagePayload,TextToSpeechOptions,TextToSpeechPayload,} from '../types';@@ -28,7 +27,6 @@ export interface LobeRuntimeAI {models?(): Promise<any>;- textToImage?: (payload: TextToImagePayload) => Promise<string[]>;createImage?: (payload: CreateImagePayload) => Promise<CreateImageResponse>;textToSpeech?: (diff --git a/packages/model-runtime/src/core/ModelRuntime.test.ts b/packages/model-runtime/src/core/ModelRuntime.test.tsindex fa7321c9811..cccb7f695f5 100644--- a/packages/model-runtime/src/core/ModelRuntime.test.ts+++ b/packages/model-runtime/src/core/ModelRuntime.test.ts@@ -226,43 +226,6 @@ describe('ModelRuntime', () => {});});- describe('ModelRuntime textToImage method', () => {- it('should run correctly', async () => {- const payload = {- model: 'stable-diffusion',- prompt: 'A beautiful landscape',- };-- const mockResponse = ['https://example.com/image1.jpg', 'https://example.com/image2.jpg'];-- vi.spyOn(LobeOpenAI.prototype, 'textToImage').mockResolvedValue(mockResponse);-- const result = await mockModelRuntime.textToImage(payload);-- expect(LobeOpenAI.prototype.textToImage).toHaveBeenCalledWith(payload);- expect(result).toBe(mockResponse);- });-- it('should handle undefined textToImage method gracefully', async () => {- const payload = {- model: 'stable-diffusion',- prompt: 'A beautiful landscape',- };-- // Mock runtime without textToImage method- const runtimeWithoutTextToImage = {- textToImage: undefined,- };-- // @ts-ignore - testing edge case- mockModelRuntime['_runtime'] = runtimeWithoutTextToImage;-- const result = await mockModelRuntime.textToImage(payload);-- expect(result).toBeUndefined();- });- });-describe('ModelRuntime createImage method', () => {it('should run correctly', async () => {const payload: CreateImagePayload = {diff --git a/packages/model-runtime/src/core/ModelRuntime.ts b/packages/model-runtime/src/core/ModelRuntime.tsindex 41e8bc4fee7..a1280d2e1f3 100644--- a/packages/model-runtime/src/core/ModelRuntime.ts+++ b/packages/model-runtime/src/core/ModelRuntime.ts@@ -13,7 +13,6 @@ import {GenerateObjectPayload,ModelRequestOptions,PullModelParams,- TextToImagePayload,TextToSpeechPayload,} from '../types';import { AgentRuntimeErrorType } from '../types/error';@@ -79,10 +78,6 @@ export class ModelRuntime {return this._runtime.generateObject!(payload);}- async textToImage(payload: TextToImagePayload) {- return this._runtime.textToImage?.(payload);- }-async createImage(payload: CreateImagePayload) {return this._runtime.createImage?.(payload);}diff --git a/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.ts b/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.tsindex 1f01ffff322..7138f7eb293 100644--- a/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.ts+++ b/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.ts@@ -6,8 +6,10 @@ import { LobeDeepSeekAI } from '../../providers/deepseek';import { LobeFalAI } from '../../providers/fal';import { LobeGoogleAI } from '../../providers/google';import { LobeMinimaxAI } from '../../providers/minimax';+import { LobeMoonshotAI } from '../../providers/moonshot';import { LobeOpenAI } from '../../providers/openai';import { LobeQwenAI } from '../../providers/qwen';+import { LobeVertexAI } from '../../providers/vertexai';import { LobeXAI } from '../../providers/xai';export const baseRuntimeMap = {@@ -19,7 +21,9 @@ export const baseRuntimeMap = {fal: LobeFalAI,google: LobeGoogleAI,minimax: LobeMinimaxAI,+ moonshot: LobeMoonshotAI,openai: LobeOpenAI,qwen: LobeQwenAI,+ vertexai: LobeVertexAI,xai: LobeXAI,};diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.tsindex 9a4f80e80b7..0170e2ce7c4 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts@@ -17,13 +17,14 @@ describe('createRouterRuntime', () => {const runtime = new Runtime();// 现在错误在使用时才抛出,因为是延迟创建- await expect(runtime.getRuntimeByModel('test-model')).rejects.toThrow('empty providers');+ await expect(+ runtime.chat({ model: 'test-model', messages: [], temperature: 0.7 }),+ ).rejects.toThrow('empty providers');});it('should create UniformRuntime class with valid routers', () => {class MockRuntime implements LobeRuntimeAI {chat = vi.fn();- textToImage = vi.fn();models = vi.fn();embeddings = vi.fn();textToSpeech = vi.fn();@@ -53,7 +54,6 @@ describe('createRouterRuntime', () => {mockConstructor(options);}chat = vi.fn();- textToImage = vi.fn();models = vi.fn();embeddings = vi.fn();textToSpeech = vi.fn();@@ -74,7 +74,7 @@ describe('createRouterRuntime', () => {const runtime = new Runtime({ apiKey: 'constructor-key' });// 触发 runtime 创建- await runtime.getRuntimeByModel('test-model');+ await runtime.chat({ model: 'test-model', messages: [], temperature: 0.7 });expect(mockConstructor).toHaveBeenCalledWith(expect.objectContaining({@@ -86,169 +86,6 @@ describe('createRouterRuntime', () => {});});- describe('model matching', () => {- it('should return correct runtime for matching model', async () => {- const mockRuntime = {- chat: vi.fn(),- textToImage: vi.fn(),- models: vi.fn(),- embeddings: vi.fn(),- textToSpeech: vi.fn(),- } as unknown as LobeRuntimeAI;-- const Runtime = createRouterRuntime({- id: 'test-runtime',- routers: [- {- apiType: 'openai',- options: {},- runtime: mockRuntime.constructor as any,- models: ['model-1', 'model-2'],- },- ],- });-- const runtime = new Runtime();- const selectedRuntime = await runtime.getRuntimeByModel('model-1');-- expect(selectedRuntime).toBeDefined();- });-- it('should support dynamic routers with asynchronous model fetching', async () => {- const mockRuntime = {- chat: vi.fn(),- textToImage: vi.fn(),- models: vi.fn(),- embeddings: vi.fn(),- textToSpeech: vi.fn(),- } as unknown as LobeRuntimeAI;-- const mockModelsFunction = vi.fn().mockResolvedValue(['async-model-1', 'async-model-2']);-- const Runtime = createRouterRuntime({- id: 'test-runtime',- routers: async () => {- // 异步获取模型列表- const models = await mockModelsFunction();- return [- {- apiType: 'openai',- options: {},- runtime: mockRuntime.constructor as any,- models, // 静态数组- },- ];- },- });-- const runtime = new Runtime();-- // 触发 routers 函数调用- const selectedRuntime = await runtime.getRuntimeByModel('async-model-1');-- expect(selectedRuntime).toBeDefined();- expect(mockModelsFunction).toHaveBeenCalled();- });-- it('should return fallback runtime when model not found', async () => {- const mockRuntime = {- chat: vi.fn(),- textToImage: vi.fn(),- models: vi.fn(),- embeddings: vi.fn(),- textToSpeech: vi.fn(),- } as unknown as LobeRuntimeAI;-- const Runtime = createRouterRuntime({- id: 'test-runtime',- routers: [- {- apiType: 'openai',- options: {},- runtime: mockRuntime.constructor as any,- models: ['known-model'],- },- ],- });-- const runtime = new Runtime();- const selectedRuntime = await runtime.getRuntimeByModel('unknown-model');-- expect(selectedRuntime).toBeDefined();- });- });-- describe('getRuntimeByModel', () => {- it('should return runtime that supports the model', async () => {- class MockRuntime1 implements LobeRuntimeAI {- chat = vi.fn();- }-- class MockRuntime2 implements LobeRuntimeAI {- chat = vi.fn();- }-- const Runtime = createRouterRuntime({- id: 'test-runtime',- routers: [- {- apiType: 'openai',- options: {},- runtime: MockRuntime1 as any,- models: ['gpt-4'],- },- {- apiType: 'anthropic',- options: {},- runtime: MockRuntime2 as any,- models: ['claude-3'],- },- ],- });-- const runtime = new Runtime();-- const result1 = await runtime.getRuntimeByModel('gpt-4');- expect(result1).toBeInstanceOf(MockRuntime1);-- const result2 = await runtime.getRuntimeByModel('claude-3');- expect(result2).toBeInstanceOf(MockRuntime2);- });-- it('should return last runtime when no model matches', async () => {- class MockRuntime1 implements LobeRuntimeAI {- chat = vi.fn();- }-- class MockRuntime2 implements LobeRuntimeAI {- chat = vi.fn();- }-- const Runtime = createRouterRuntime({- id: 'test-runtime',- routers: [- {- apiType: 'openai',- options: {},- runtime: MockRuntime1 as any,- models: ['gpt-4'],- },- {- apiType: 'anthropic',- options: {},- runtime: MockRuntime2 as any,- models: ['claude-3'],- },- ],- });-- const runtime = new Runtime();- const result = await runtime.getRuntimeByModel('unknown-model');-- expect(result).toBeInstanceOf(MockRuntime2);- });- });-describe('chat method', () => {it('should call chat on the correct runtime based on model', async () => {const mockChat = vi.fn().mockResolvedValue('chat-response');@@ -349,35 +186,6 @@ describe('createRouterRuntime', () => {});});- describe('textToImage method', () => {- it('should call textToImage on the correct runtime based on model', async () => {- const mockTextToImage = vi.fn().mockResolvedValue('image-response');-- class MockRuntime implements LobeRuntimeAI {- textToImage = mockTextToImage;- }-- const Runtime = createRouterRuntime({- id: 'test-runtime',- routers: [- {- apiType: 'openai',- options: {},- runtime: MockRuntime as any,- models: ['dall-e-3'],- },- ],- });-- const runtime = new Runtime();- const payload = { model: 'dall-e-3', prompt: 'test prompt' };-- const result = await runtime.textToImage(payload);- expect(result).toBe('image-response');- expect(mockTextToImage).toHaveBeenCalledWith(payload);- });- });-describe('models method', () => {it('should call models method on first runtime', async () => {const mockModels = vi.fn().mockResolvedValue(['model-1', 'model-2']);@@ -468,8 +276,7 @@ describe('createRouterRuntime', () => {describe('dynamic routers configuration', () => {it('should support function-based routers configuration', async () => {class MockRuntime implements LobeRuntimeAI {- chat = vi.fn();- textToImage = vi.fn();+ chat = vi.fn().mockResolvedValue('chat-response');models = vi.fn();embeddings = vi.fn();textToSpeech = vi.fn();@@ -509,7 +316,7 @@ describe('createRouterRuntime', () => {expect(runtime).toBeDefined();// 测试动态 routers 是否能正确工作- const result = await runtime.getRuntimeByModel('gpt-4');+ const result = await runtime.chat({ model: 'gpt-4', messages: [], temperature: 0.7 });expect(result).toBeDefined();// 验证动态函数被调用时传入了正确的参数@@ -532,7 +339,325 @@ describe('createRouterRuntime', () => {const runtime = new Runtime();// 现在错误在使用时才抛出,因为是延迟创建- await expect(runtime.getRuntimeByModel('test-model')).rejects.toThrow('empty providers');+ await expect(+ runtime.chat({ model: 'test-model', messages: [], temperature: 0.7 }),+ ).rejects.toThrow('empty providers');+ });++ it('should support async function-based routers configuration', async () => {+ const mockChat = vi.fn().mockResolvedValue('async-chat-response');++ class MockRuntime implements LobeRuntimeAI {+ chat = mockChat;+ }++ const asyncRoutersFunction = vi.fn(async () => [+ {+ apiType: 'openai' as const,+ options: { apiKey: 'async-key' },+ runtime: MockRuntime as any,+ models: ['gpt-4'],+ },+ ]);++ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ routers: asyncRoutersFunction,+ });++ const runtime = new Runtime();+ const result = await runtime.chat({ model: 'gpt-4', messages: [], temperature: 0.7 });++ expect(result).toBe('async-chat-response');+ expect(asyncRoutersFunction).toHaveBeenCalled();+ });+ });++ describe('fallback mechanism', () => {+ it('should fallback to next option when first option fails', async () => {+ // Test that errors are caught and re-thrown when all options fail+ const mockChatAlwaysFail = vi.fn().mockRejectedValue(new Error('All failed'));++ class AlwaysFailRuntime implements LobeRuntimeAI {+ chat = mockChatAlwaysFail;+ }++ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ routers: [+ {+ apiType: 'openai',+ options: [{ apiKey: 'key-1' }, { apiKey: 'key-2' }],+ runtime: AlwaysFailRuntime as any,+ models: ['gpt-4'],+ },+ ],+ });++ const runtime = new Runtime();+ await expect(+ runtime.chat({ model: 'gpt-4', messages: [], temperature: 0.7 }),+ ).rejects.toThrow('All failed');++ // Verify chat was called twice (once per option)+ expect(mockChatAlwaysFail).toHaveBeenCalledTimes(2);+ });++ it('should throw error when options array is empty', async () => {+ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ routers: [+ {+ apiType: 'openai',+ options: [] as any,+ models: ['gpt-4'],+ },+ ],+ });++ const runtime = new Runtime();+ await expect(+ runtime.chat({ model: 'gpt-4', messages: [], temperature: 0.7 }),+ ).rejects.toThrow('empty provider options');+ });++ it('should use apiType from option item when specified for fallback', async () => {+ const constructorCalls: any[] = [];++ class MockRuntime implements LobeRuntimeAI {+ constructor(options: any) {+ constructorCalls.push(options);+ }+ chat = vi.fn().mockResolvedValue('response');+ }++ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ routers: [+ {+ apiType: 'openai',+ options: [{ apiKey: 'openai-key' }, { apiKey: 'anthropic-key', apiType: 'anthropic' }],+ runtime: MockRuntime as any,+ models: ['gpt-4'],+ },+ ],+ });++ const runtime = new Runtime();+ await runtime.chat({ model: 'gpt-4', messages: [], temperature: 0.7 });++ // First option should be tried+ expect(constructorCalls.length).toBeGreaterThanOrEqual(1);+ });+ });++ describe('router matching', () => {+ it('should fallback to last router when model does not match any', async () => {+ const mockChatFirst = vi.fn().mockResolvedValue('first-response');+ const mockChatLast = vi.fn().mockResolvedValue('last-response');++ class FirstRuntime implements LobeRuntimeAI {+ chat = mockChatFirst;+ }++ class LastRuntime implements LobeRuntimeAI {+ chat = mockChatLast;+ }++ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ routers: [+ {+ apiType: 'openai',+ options: { apiKey: 'first-key' },+ runtime: FirstRuntime as any,+ models: ['gpt-4'],+ },+ {+ apiType: 'anthropic',+ options: { apiKey: 'last-key' },+ runtime: LastRuntime as any,+ models: ['claude-3'],+ },+ ],+ });++ const runtime = new Runtime();+ // Use a model that doesn't match any router+ const result = await runtime.chat({+ model: 'unknown-model',+ messages: [],+ temperature: 0.7,+ });++ expect(result).toBe('last-response');+ expect(mockChatLast).toHaveBeenCalled();+ expect(mockChatFirst).not.toHaveBeenCalled();+ });++ it('should match router with empty models array as fallback', async () => {+ const mockChatSpecific = vi.fn().mockResolvedValue('specific-response');+ const mockChatFallback = vi.fn().mockResolvedValue('fallback-response');++ class SpecificRuntime implements LobeRuntimeAI {+ chat = mockChatSpecific;+ }++ class FallbackRuntime implements LobeRuntimeAI {+ chat = mockChatFallback;+ }++ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ routers: [+ {+ apiType: 'openai',+ options: { apiKey: 'specific-key' },+ runtime: SpecificRuntime as any,+ models: ['gpt-4'],+ },+ {+ apiType: 'openai',+ options: { apiKey: 'fallback-key' },+ runtime: FallbackRuntime as any,+ models: [], // Empty models array acts as catch-all+ },+ ],+ });++ const runtime = new Runtime();+ const result = await runtime.chat({+ model: 'any-model',+ messages: [],+ temperature: 0.7,+ });++ expect(result).toBe('fallback-response');+ });+ });++ describe('createImage method', () => {+ it('should call createImage on the correct runtime', async () => {+ const mockCreateImage = vi+ .fn()+ .mockResolvedValue({ imageUrl: 'https://example.com/image.png' });++ class MockRuntime implements LobeRuntimeAI {+ createImage = mockCreateImage;+ }++ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ routers: [+ {+ apiType: 'openai',+ options: {},+ runtime: MockRuntime as any,+ models: ['gpt-image-1'],+ },+ ],+ });++ const runtime = new Runtime();+ const payload = { model: 'gpt-image-1', params: { prompt: 'a cat' } };++ const result = await runtime.createImage(payload);+ expect(result).toEqual({ imageUrl: 'https://example.com/image.png' });+ expect(mockCreateImage).toHaveBeenCalledWith(payload);+ });+ });++ describe('generateObject method', () => {+ it('should call generateObject on the correct runtime', async () => {+ const mockGenerateObject = vi.fn().mockResolvedValue({ name: 'test' });++ class MockRuntime implements LobeRuntimeAI {+ generateObject = mockGenerateObject;+ }++ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ routers: [+ {+ apiType: 'openai',+ options: {},+ runtime: MockRuntime as any,+ models: ['gpt-4'],+ },+ ],+ });++ const runtime = new Runtime();+ const payload = { model: 'gpt-4', messages: [{ role: 'user' as const, content: 'test' }] };+ const options = { user: 'test-user' };++ const result = await runtime.generateObject(payload, options);+ expect(result).toEqual({ name: 'test' });+ expect(mockGenerateObject).toHaveBeenCalledWith(payload, options);+ });+ });++ describe('constructor options handling', () => {+ it('should trim apiKey and baseURL', async () => {+ const constructorOptions: any[] = [];++ class MockRuntime implements LobeRuntimeAI {+ constructor(options: any) {+ constructorOptions.push(options);+ }+ chat = vi.fn().mockResolvedValue('response');+ }++ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ routers: [+ {+ apiType: 'openai',+ options: {},+ runtime: MockRuntime as any,+ models: ['gpt-4'],+ },+ ],+ });++ const runtime = new Runtime({+ apiKey: ' trimmed-key ',+ baseURL: ' https://api.example.com ',+ });++ await runtime.chat({ model: 'gpt-4', messages: [], temperature: 0.7 });++ expect(constructorOptions[0].apiKey).toBe('trimmed-key');+ expect(constructorOptions[0].baseURL).toBe('https://api.example.com');+ });++ it('should use default apiKey when not provided', async () => {+ const constructorOptions: any[] = [];++ class MockRuntime implements LobeRuntimeAI {+ constructor(options: any) {+ constructorOptions.push(options);+ }+ chat = vi.fn().mockResolvedValue('response');+ }++ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ apiKey: 'default-api-key',+ routers: [+ {+ apiType: 'openai',+ options: {},+ runtime: MockRuntime as any,+ models: ['gpt-4'],+ },+ ],+ });++ const runtime = new Runtime();+ await runtime.chat({ model: 'gpt-4', messages: [], temperature: 0.7 });++ expect(constructorOptions[0].apiKey).toBe('default-api-key');});});});diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.tsindex d9b65d318ce..520a75f26a3 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts@@ -1,11 +1,14 @@/*** @see https://github.com/lobehub/lobe-chat/discussions/6563*/+import type { GoogleGenAIOptions } from '@google/genai';import type { ChatModelCard } from '@lobechat/types';+import debug from 'debug';import OpenAI, { ClientOptions } from 'openai';import { Stream } from 'openai/streaming';import { LobeOpenAI } from '../../providers/openai';+import { LobeVertexAI } from '../../providers/vertexai';import {CreateImagePayload,CreateImageResponse,@@ -20,19 +23,15 @@ import {ChatStreamPayload,EmbeddingsOptions,EmbeddingsPayload,- TextToImagePayload,TextToSpeechPayload,} from '../../types';import { postProcessModelList } from '../../utils/postProcessModelList';+import { safeParseJSON } from '../../utils/safeParseJSON';import { LobeRuntimeAI } from '../BaseAI';import { CreateImageOptions, CustomClientOptions } from '../openaiCompatibleFactory';import { baseRuntimeMap } from './baseRuntimeMap';-export interface RuntimeItem {- id: string;- models?: string[];- runtime: LobeRuntimeAI;-}+const log = debug('lobe-model-runtime:router-runtime');interface ProviderIniOptions extends Record<string, any> {accessKeyId?: string;@@ -46,12 +45,25 @@ interface ProviderIniOptions extends Record<string, any> {sessionToken?: string;}+/**+ * Router option item used for inference.+ * When `options` is an array, items are tried in order for chat fallback.+ * `apiType` allows switching provider when falling back.+ */+interface RouterOptionItem extends ProviderIniOptions {+ apiType?: keyof typeof baseRuntimeMap;+ id?: string;+ remark?: string;+}++type RouterOptions = RouterOptionItem | RouterOptionItem[];+export type RuntimeClass = typeof LobeOpenAI;interface RouterInstance {apiType: keyof typeof baseRuntimeMap;models?: string[];- options: ProviderIniOptions;+ options: RouterOptions;runtime?: RuntimeClass;}@@ -121,6 +133,14 @@ export interface CreateRouterRuntimeOptions<T extends Record<string, any> = any>routers: Routers;}+const formatErrorMessage = (error: unknown): string => {+ if (error instanceof Error) {+ return error.name ? `${error.name}: ${error.message}` : error.message;+ }++ return String(error);+};+export const createRouterRuntime = ({id,routers,@@ -163,61 +183,200 @@ export const createRouterRuntime = ({return resolvedRouters;}- /**- * Create runtime for inference requests (chat, generateObject, etc.)- * Finds the router that matches the model, or uses the last router as fallback- */- private async createRuntimeForInference(model: string): Promise<RuntimeItem> {+ private async resolveMatchedRouter(model: string): Promise<RouterInstance> {const resolvedRouters = await this.resolveRouters(model);-- const matchedRouter =+ return (resolvedRouters.find((router) => {if (router.models && router.models.length > 0) {return router.models.includes(model);}return false;- }) ?? resolvedRouters.at(-1)!;+ }) ?? resolvedRouters.at(-1)!+ );+ }++ private normalizeRouterOptions(router: RouterInstance): RouterOptionItem[] {+ const routerOptions = Array.isArray(router.options) ? router.options : [router.options];++ if (routerOptions.length === 0 || routerOptions.some((optionItem) => !optionItem)) {+ throw new Error('empty provider options');+ }++ return routerOptions;+ }++ /**+ * Build a runtime instance for a specific option item.+ * Option items can override apiType to switch providers for fallback.+ */+ private createRuntimeFromOption(+ router: RouterInstance,+ optionItem: RouterOptionItem,+ ): {+ channelId?: string;+ id: keyof typeof baseRuntimeMap;+ remark?: string;+ runtime: LobeRuntimeAI;+ } {+ const { apiType: optionApiType, id: channelId, remark, ...optionOverrides } = optionItem;+ const resolvedApiType = optionApiType ?? router.apiType;+ const finalOptions = { ...this._params, ...this._options, ...optionOverrides };++ /**+ * Vertex AI uses GoogleGenAI credentials flow rather than API keys.+ * Accept JSON credentials in apiKey for compatibility with server config.+ */+ if (resolvedApiType === 'vertexai') {+ const { apiKey, googleAuthOptions, project, location, ...restOptions } = finalOptions;+ const credentials = safeParseJSON<Record<string, any>>(apiKey);+ const vertexOptions: GoogleGenAIOptions = {+ ...(restOptions as GoogleGenAIOptions),+ vertexai: true,+ };++ if (googleAuthOptions) {+ vertexOptions.googleAuthOptions = googleAuthOptions;+ } else if (credentials) {+ vertexOptions.googleAuthOptions = { credentials };+ }++ if (project) vertexOptions.project = project;+ if (location) vertexOptions.location = location as GoogleGenAIOptions['location'];++ return {+ channelId,+ id: resolvedApiType,+ remark,+ runtime: LobeVertexAI.initFromVertexAI(vertexOptions),+ };+ }const providerAI =- matchedRouter.runtime ?? baseRuntimeMap[matchedRouter.apiType] ?? LobeOpenAI;- const finalOptions = { ...this._params, ...this._options, ...matchedRouter.options };+ resolvedApiType === router.apiType+ ? (router.runtime ?? baseRuntimeMap[resolvedApiType] ?? LobeOpenAI)+ : (baseRuntimeMap[resolvedApiType] ?? LobeOpenAI);const runtime: LobeRuntimeAI = new providerAI({ ...finalOptions, id: this._id });return {- id: matchedRouter.apiType,- models: matchedRouter.models,+ channelId,+ id: resolvedApiType,+ remark,runtime,};}- /**- * Create all runtimes for listing models- */- private async createRuntimes(): Promise<RuntimeItem[]> {+ private async runWithFallback<T>(+ model: string,+ requestHandler: (runtime: LobeRuntimeAI) => Promise<T>,+ ): Promise<T> {+ const matchedRouter = await this.resolveMatchedRouter(model);+ const routerOptions = this.normalizeRouterOptions(matchedRouter);+ const totalOptions = routerOptions.length;++ log(+ 'resolve router for model=%s apiType=%s options=%d',+ model,+ matchedRouter.apiType,+ totalOptions,+ );++ let lastError: unknown;++ for (const [index, optionItem] of routerOptions.entries()) {+ const attempt = index + 1;+ const {+ channelId,+ id: resolvedApiType,+ remark,+ runtime,+ } = this.createRuntimeFromOption(matchedRouter, optionItem);++ try {+ const result = await requestHandler(runtime);++ if (totalOptions > 1 && attempt > 1) {+ log(+ 'fallback success for model=%s attempt=%d/%d apiType=%s channelId=%s remark=%s',+ model,+ attempt,+ totalOptions,+ resolvedApiType,+ channelId ?? '',+ remark ?? '',+ );+ }++ return result;+ } catch (error) {+ lastError = error;++ const message = formatErrorMessage(error);+ if (attempt < totalOptions) {+ log(+ 'attempt failed, fallback to next: model=%s attempt=%d/%d apiType=%s channelId=%s remark=%s error=%s',+ model,+ attempt,+ totalOptions,+ resolvedApiType,+ channelId ?? '',+ remark ?? '',+ message,+ );+ } else {+ log(+ 'attempt failed, no more fallbacks: model=%s attempt=%d/%d apiType=%s channelId=%s remark=%s error=%s',+ model,+ attempt,+ totalOptions,+ resolvedApiType,+ channelId ?? '',+ remark ?? '',+ message,+ );+ }+ }+ }++ throw lastError ?? new Error('empty provider options');+ }++ async models() {const resolvedRouters = await this.resolveRouters();- return resolvedRouters.map((router) => {- const providerAI = router.runtime ?? baseRuntimeMap[router.apiType] ?? LobeOpenAI;- const finalOptions = { ...this._params, ...this._options, ...router.options };- const runtime: LobeRuntimeAI = new providerAI({ ...finalOptions, id: this._id });+ const runtimes = resolvedRouters.map((router) => {+ const routerOptions = this.normalizeRouterOptions(router);+ const { id: resolvedApiType, runtime } = this.createRuntimeFromOption(+ router,+ routerOptions[0],+ );return {- id: router.apiType,+ id: resolvedApiType,models: router.models,runtime,};});- }- // Check if it can match a specific model, otherwise default to using the last runtime- async getRuntimeByModel(model: string) {- const runtimeItem = await this.createRuntimeForInference(model);- return runtimeItem.runtime;+ if (modelsOption && typeof modelsOption === 'function') {+ // If it's a functional configuration, use the last runtime's client to call the function+ const lastRuntime = runtimes.at(-1)?.runtime;+ if (lastRuntime && 'client' in lastRuntime) {+ const modelList = await modelsOption({ client: (lastRuntime as any).client });+ return await postProcessModelList(modelList);+ }+ }++ return runtimes.at(-1)?.runtime.models?.();}+ /**+ * Try router options in order for chat requests.+ * When options is an array, fall back to the next item on failure.+ */async chat(payload: ChatStreamPayload, options?: ChatMethodOptions) {try {- const runtime = await this.getRuntimeByModel(payload.model);- return await runtime.chat!(payload, options);+ return await this.runWithFallback(payload.model, (runtime) =>+ runtime.chat!(payload, options),+ );} catch (e) {if (params.chatCompletion?.handleError) {const error = params.chatCompletion.handleError(e, this._options);@@ -231,44 +390,26 @@ export const createRouterRuntime = ({}}- async generateObject(payload: GenerateObjectPayload, options?: GenerateObjectOptions) {- const runtime = await this.getRuntimeByModel(payload.model);- return runtime.generateObject!(payload, options);- }-async createImage(payload: CreateImagePayload) {- const runtime = await this.getRuntimeByModel(payload.model);- return runtime.createImage!(payload);+ return this.runWithFallback(payload.model, (runtime) => runtime.createImage!(payload));}- async textToImage(payload: TextToImagePayload) {- const runtime = await this.getRuntimeByModel(payload.model);- return runtime.textToImage!(payload);- }-- async models() {- if (modelsOption && typeof modelsOption === 'function') {- const runtimes = await this.createRuntimes();- // If it's a functional configuration, use the last runtime's client to call the function- const lastRuntime = runtimes.at(-1)?.runtime;- if (lastRuntime && 'client' in lastRuntime) {- const modelList = await modelsOption({ client: (lastRuntime as any).client });- return await postProcessModelList(modelList);- }- }-- const runtimes = await this.createRuntimes();- return runtimes.at(-1)?.runtime.models?.();+ async generateObject(payload: GenerateObjectPayload, options?: GenerateObjectOptions) {+ return this.runWithFallback(payload.model, (runtime) =>+ runtime.generateObject!(payload, options),+ );}async embeddings(payload: EmbeddingsPayload, options?: EmbeddingsOptions) {- const runtime = await this.getRuntimeByModel(payload.model);- return runtime.embeddings!(payload, options);+ return this.runWithFallback(payload.model, (runtime) =>+ runtime.embeddings!(payload, options),+ );}async textToSpeech(payload: TextToSpeechPayload, options?: EmbeddingsOptions) {- const runtime = await this.getRuntimeByModel(payload.model);- return runtime.textToSpeech!(payload, options);+ return this.runWithFallback(payload.model, (runtime) =>+ runtime.textToSpeech!(payload, options),+ );}};};diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.tsindex c66fcaca3b3..0c5c5547df8 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts@@ -19,7 +19,6 @@ import {EmbeddingsPayload,GenerateObjectOptions,GenerateObjectPayload,- TextToImagePayload,TextToSpeechOptions,TextToSpeechPayload,} from '../../types';@@ -736,19 +735,6 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an}}- async textToImage(payload: TextToImagePayload) {- const log = debug(`${this.logPrefix}:textToImage`);- log('textToImage called with prompt length: %d', payload.prompt?.length || 0);-- try {- const res = await this.client.images.generate(payload);- log('generated %d images', res.data?.length || 0);- return (res.data || []).map((o) => o.url) as string[];- } catch (error) {- throw this.handleError(error);- }- }-async textToSpeech(payload: TextToSpeechPayload, options?: TextToSpeechOptions) {const log = debug(`${this.logPrefix}:textToSpeech`);log(diff --git a/packages/model-runtime/src/providers/aihubmix/index.test.ts b/packages/model-runtime/src/providers/aihubmix/index.test.tsindex 29323f0cbc1..5d8991b2cad 100644--- a/packages/model-runtime/src/providers/aihubmix/index.test.ts+++ b/packages/model-runtime/src/providers/aihubmix/index.test.ts@@ -1,5 +1,4 @@// @vitest-environment node-import { ModelProvider } from 'model-bank';import { beforeEach, describe, expect, it, vi } from 'vitest';import { LobeAiHubMixAI } from './index';@@ -25,9 +24,7 @@ describe('LobeAiHubMixAI', () => {describe('chat', () => {it('should support chat method', async () => {- vi.spyOn(instance as any, 'getRuntimeByModel').mockResolvedValue({- chat: vi.fn().mockResolvedValue(new Response()),- });+ vi.spyOn(instance as any, 'runWithFallback').mockResolvedValue(new Response());const payload = {messages: [{ content: 'Hello', role: 'user' as const }],@@ -49,24 +46,21 @@ describe('LobeAiHubMixAI', () => {},};- vi.spyOn(instance as any, 'getRuntimeByModel').mockResolvedValue({- models: async () => {- try {- await mockClient.models.list();- } catch (error) {- console.warn(- 'Failed to fetch AiHubMix models. Please ensure your AiHubMix API key is valid:',- error,- );- return [];- }- },- });+ class MockRuntime {+ client = mockClient;+ }// The models method should return empty array on error- const models = await (instance as any)- .getRuntimeByModel('test-model')- .then((r: any) => r.models());+ vi.spyOn(instance as any, 'resolveRouters').mockResolvedValue([+ {+ apiType: 'openai',+ models: [],+ options: {},+ runtime: MockRuntime,+ },+ ]);++ const models = await instance.models();expect(models).toEqual([]);});});diff --git a/packages/model-runtime/src/types/index.ts b/packages/model-runtime/src/types/index.tsindex d1d433956b1..896093e60af 100644--- a/packages/model-runtime/src/types/index.ts+++ b/packages/model-runtime/src/types/index.ts@@ -4,7 +4,6 @@ export * from './error';export * from './image';export * from './model';export * from './structureOutput';-export * from './textToImage';export * from './toolsCalling';export * from './tts';export * from './type';diff --git a/packages/model-runtime/src/types/textToImage.ts b/packages/model-runtime/src/types/textToImage.tsdeleted file mode 100644index 35a2d5cb79a..00000000000--- a/packages/model-runtime/src/types/textToImage.ts+++ /dev/null@@ -1,36 +0,0 @@-export type DallEImageQuality = 'standard' | 'hd';-export type DallEImageStyle = 'vivid' | 'natural';-export type DallEImageSize = '1792x1024' | '1024x1024' | '1024x1792';--export interface TextToImagePayload {- model: string;- /**- * The number of images to generate. Must be between 1 and 10.- */- n?: number;- /**- * A text description of the desired image(s).- * The maximum length is 1000 characters.- */- prompt: string;- /**- * The quality of the image that will be generated.- * hd creates images with finer details and greater consistency across the image.- * This param is only supported for dall-e-3.- */- quality?: DallEImageQuality;- /**- * The size of the generated images.- * Must be one of '1792x1024' , '1024x1024' , '1024x1792'- */- size?: DallEImageSize;-- /**- * The style of the generated images. Must be one of vivid or natural.- * Vivid causes the model to lean towards generating hyper-real and dramatic images.- * Natural causes the model to produce more natural, less hyper-real looking images.- * This param is only supported for dall-e-3.- * @default vivid- */- style?: DallEImageStyle;-}diff --git a/packages/model-runtime/src/utils/createError.test.ts b/packages/model-runtime/src/utils/createError.test.tsindex 9cf967f2dda..384121fbcdf 100644--- a/packages/model-runtime/src/utils/createError.test.ts+++ b/packages/model-runtime/src/utils/createError.test.ts@@ -72,24 +72,4 @@ describe('AgentRuntimeError', () => {expect(result).toEqual(errorPayload);});});-- describe('textToImage', () => {- it('should return the same error object', () => {- const error = { message: 'Text to image failed', code: 'GENERATION_ERROR' };- const result = AgentRuntimeError.textToImage(error);-- expect(result).toBe(error);- expect(result).toEqual(error);- });-- it('should handle any type of error', () => {- const stringError = 'String error';- const numberError = 404;- const arrayError = ['error1', 'error2'];-- expect(AgentRuntimeError.textToImage(stringError)).toBe(stringError);- expect(AgentRuntimeError.textToImage(numberError)).toBe(numberError);- expect(AgentRuntimeError.textToImage(arrayError)).toBe(arrayError);- });- });});diff --git a/packages/model-runtime/src/utils/createError.ts b/packages/model-runtime/src/utils/createError.tsindex a95b3bb7849..78754fe6d11 100644--- a/packages/model-runtime/src/utils/createError.ts+++ b/packages/model-runtime/src/utils/createError.ts@@ -12,5 +12,4 @@ export const AgentRuntimeError = {error?: any,): AgentInitErrorPayload => ({ error, errorType }),createImage: (error: CreateImageErrorPayload): CreateImageErrorPayload => error,- textToImage: (error: any): any => error,};