🤯 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: support sortRouterOptions hook in RouterRuntime (#17064)
YuTengjingef27177a847d
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.tsindex 23c1055212a..cd4162f7b31 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts@@ -1480,4 +1480,206 @@ describe('createRouterRuntime', () => {expect(constructorOptions[0]).toEqual(expect.objectContaining({ id: 'lobehub' }));});});++ describe('sortRouterOptions hook', () => {+ const createRecordingRuntime = (attemptedKeys: string[], failKeys: Set<string> = new Set()) =>+ class RecordingRuntime implements LobeRuntimeAI {+ private apiKey: string;++ constructor(options: any) {+ this.apiKey = options.apiKey;+ }++ chat = vi.fn().mockImplementation(async () => {+ attemptedKeys.push(this.apiKey);+ if (failKeys.has(this.apiKey)) throw new Error(`${this.apiKey} failed`);+ return 'ok';+ });+ };++ it('should try options in the order returned by the hook', async () => {+ const attemptedKeys: string[] = [];+ const sortRouterOptions = vi.fn().mockImplementation(({ options }) => [...options].reverse());++ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ routers: [+ {+ apiType: 'openai',+ id: 'router-a',+ models: ['gpt-4'],+ options: [+ { apiKey: 'key-1', id: 'channel-a' },+ { apiKey: 'key-2', id: 'channel-b' },+ ],+ runtime: createRecordingRuntime(attemptedKeys) as any,+ },+ ],+ sortRouterOptions,+ });++ const runtime = new Runtime();+ await runtime.chat({ messages: [], model: 'gpt-4', temperature: 0.7 });++ expect(sortRouterOptions).toHaveBeenCalledWith({+ model: 'gpt-4',+ options: [+ expect.objectContaining({ id: 'channel-a' }),+ expect.objectContaining({ id: 'channel-b' }),+ ],+ routerId: 'router-a',+ });+ // Reversed order: channel-b is tried first and succeeds+ expect(attemptedKeys).toEqual(['key-2']);+ });++ it('should still fall back through all options after reordering', async () => {+ const attemptedKeys: string[] = [];++ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ routers: [+ {+ apiType: 'openai',+ models: ['gpt-4'],+ options: [{ apiKey: 'key-1' }, { apiKey: 'key-2' }],+ runtime: createRecordingRuntime(attemptedKeys, new Set(['key-2'])) as any,+ },+ ],+ sortRouterOptions: ({ options }) => [...options].reverse(),+ });++ const runtime = new Runtime();+ await runtime.chat({ messages: [], model: 'gpt-4', temperature: 0.7 });++ expect(attemptedKeys).toEqual(['key-2', 'key-1']);+ });++ it('should keep original order when the hook throws', async () => {+ const attemptedKeys: string[] = [];++ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ routers: [+ {+ apiType: 'openai',+ models: ['gpt-4'],+ options: [{ apiKey: 'key-1' }, { apiKey: 'key-2' }],+ runtime: createRecordingRuntime(attemptedKeys) as any,+ },+ ],+ sortRouterOptions: () => {+ throw new Error('hook failed');+ },+ });++ const runtime = new Runtime();+ await runtime.chat({ messages: [], model: 'gpt-4', temperature: 0.7 });++ expect(attemptedKeys).toEqual(['key-1']);+ });++ it('should ignore results that are not a permutation of the input', async () => {+ const attemptedKeys: string[] = [];++ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ routers: [+ {+ apiType: 'openai',+ models: ['gpt-4'],+ options: [{ apiKey: 'key-1' }, { apiKey: 'key-2' }],+ runtime: createRecordingRuntime(attemptedKeys) as any,+ },+ ],+ // Dropping options and returning copies must both be rejected+ sortRouterOptions: ({ options }) => [{ ...options[1] }],+ });++ const runtime = new Runtime();+ await runtime.chat({ messages: [], model: 'gpt-4', temperature: 0.7 });++ expect(attemptedKeys).toEqual(['key-1']);+ });++ it('should not let an in-place sorting hook mutate the shared options array', async () => {+ const attemptedKeys: string[] = [];+ const sharedOptions = [+ { apiKey: 'key-1', id: 'channel-a' },+ { apiKey: 'key-2', id: 'channel-b' },+ ];++ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ routers: [+ {+ apiType: 'openai',+ models: ['gpt-4'],+ options: sharedOptions,+ runtime: createRecordingRuntime(attemptedKeys) as any,+ },+ ],+ // Natural in-place usage: sort the received array and return it+ sortRouterOptions: ({ options }) => options.reverse(),+ });++ const runtime = new Runtime();+ await runtime.chat({ messages: [], model: 'gpt-4', temperature: 0.7 });++ // Reorder applies to this request...+ expect(attemptedKeys).toEqual(['key-2']);+ // ...but the shared config array stays untouched for concurrent requests+ expect(sharedOptions.map((o) => o.id)).toEqual(['channel-a', 'channel-b']);+ });++ it('should reject a hook that shrinks and returns the received array', async () => {+ const attemptedKeys: string[] = [];++ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ routers: [+ {+ apiType: 'openai',+ models: ['gpt-4'],+ options: [{ apiKey: 'key-1' }, { apiKey: 'key-2' }],+ runtime: createRecordingRuntime(attemptedKeys) as any,+ },+ ],+ // Mutating the received array must not fool the permutation check+ sortRouterOptions: ({ options }) => {+ options.pop();+ return options;+ },+ });++ const runtime = new Runtime();+ await runtime.chat({ messages: [], model: 'gpt-4', temperature: 0.7 });++ expect(attemptedKeys).toEqual(['key-1']);+ });++ it('should not invoke the hook for a single option', async () => {+ const attemptedKeys: string[] = [];+ const sortRouterOptions = vi.fn();++ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ routers: [+ {+ apiType: 'openai',+ models: ['gpt-4'],+ options: { apiKey: 'key-1' },+ runtime: createRecordingRuntime(attemptedKeys) as any,+ },+ ],+ sortRouterOptions,+ });++ const runtime = new Runtime();+ await runtime.chat({ messages: [], model: 'gpt-4', temperature: 0.7 });++ expect(sortRouterOptions).not.toHaveBeenCalled();+ expect(attemptedKeys).toEqual(['key-1']);+ });+ });});diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.tsindex cfcee752532..458cd7af722 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts@@ -139,6 +139,12 @@ interface RouteAttemptContextValidationParams extends RouteAttemptContext {routerId?: string;}+export interface SortRouterOptionsParams {+ model: string;+ options: RouterOptionItem[];+ routerId?: string;+}+export interface CreateRouterRuntimeOptions<T extends Record<string, any> = any> {apiKey?: string;chatCompletion?: {@@ -207,6 +213,15 @@ export interface CreateRouterRuntimeOptions<T extends Record<string, any> = any>model: string;optionIndex: number;}) => boolean | Promise<boolean>;+ /**+ * Reorder fallback options before each request (e.g. demote temporarily+ * unhealthy channels). Must return a permutation of the input options;+ * any other result (wrong length, foreign items, thrown error) is ignored+ * so a misbehaving hook can never reduce availability.+ */+ sortRouterOptions?: (+ params: SortRouterOptionsParams,+ ) => RouterOptionItem[] | Promise<RouterOptionItem[]>;}export const createRouterRuntime = ({@@ -408,6 +423,60 @@ export const createRouterRuntime = ({return routerOptions;}+ private async applySortRouterOptions(+ router: RouterInstance,+ model: string,+ routerOptions: RouterOptionItem[],+ ): Promise<RouterOptionItem[]> {+ if (!params.sortRouterOptions || routerOptions.length <= 1) return routerOptions;++ const startedAt = Date.now();+ try {+ // Hand the hook a copy: hooks may sort in place (`options.sort(...)`), and the+ // input can be the shared `router.options` array reused across concurrent+ // requests. Keeping the original untouched also keeps it a trustworthy+ // baseline — validating a same-reference return would always pass, even+ // after mutations like `options.pop()`.+ const sorted = await params.sortRouterOptions({+ model,+ options: [...routerOptions],+ routerId: router.id,+ });+ const isPermutation =+ Array.isArray(sorted) &&+ sorted.length === routerOptions.length &&+ routerOptions.every((optionItem) => sorted.includes(optionItem));++ if (this._id === 'lobehub') {+ timing(+ 'sortRouterOptions done model=%s routerId=%s durationMs=%d applied=%s',+ model,+ router.id,+ getDurationMs(startedAt),+ isPermutation,+ );+ }++ // Copy again so a hook retaining its returned array cannot mutate the+ // list while runWithFallback awaits provider calls between attempts.+ if (isPermutation) return [...sorted];++ log('sortRouterOptions returned a non-permutation result, ignoring');+ return routerOptions;+ } catch (error) {+ if (this._id === 'lobehub') {+ timing(+ 'sortRouterOptions error model=%s routerId=%s durationMs=%d',+ model,+ router.id,+ getDurationMs(startedAt),+ );+ }+ log('sortRouterOptions callback error: %O', error);+ return routerOptions;+ }+ }+/*** Build a runtime instance for a specific option item.* Option items can override apiType to switch providers for fallback.@@ -502,7 +571,11 @@ export const createRouterRuntime = ({const totalStartedAt = Date.now();const { metadata, toolsCount, user } = routeContext;const matchedRouter = await this.resolveMatchedRouter(model);- const routerOptions = this.normalizeRouterOptions(matchedRouter);+ const routerOptions = await this.applySortRouterOptions(+ matchedRouter,+ model,+ this.normalizeRouterOptions(matchedRouter),+ );const totalOptions = routerOptions.length;if (this._id === 'lobehub') {