🤯 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
♻️ refactor(model-runtime): extract shared Router routing helpers (#22818)
Arvin Xu25e3c3152d04
diff --git a/packages/model-runtime/src/core/RouterRuntime/attemptContext.ts b/packages/model-runtime/src/core/RouterRuntime/attemptContext.tsnew file mode 100644index 00000000000..eb447f5f2ec--- /dev/null+++ b/packages/model-runtime/src/core/RouterRuntime/attemptContext.ts@@ -0,0 +1,63 @@+import { type RouteAttemptMetadata } from './attemptIdentity';+import type { RouteAttemptContext, RouterRuntimeDeps } from './routeSelection';++interface RouteAttemptContextValidationParams extends RouteAttemptContext {+ apiType: string;+ channelId?: string;+ model: string;+ routerId?: string;+}++export const attachRouteAttemptMetadata = (+ deps: RouterRuntimeDeps,+ metadata: Record<string, unknown> | undefined,+ routeAttempt: RouteAttemptMetadata,+) => {+ if (!metadata || deps.id !== 'lobehub') return;++ metadata.routeAttempt = routeAttempt;+};++export const validateRouteAttemptContext = (+ deps: RouterRuntimeDeps,+ {+ apiType,+ channelId,+ metadata,+ model,+ routerId,+ toolsCount,+ user,+ }: RouteAttemptContextValidationParams,+) => {+ const runtimeUserId = typeof deps.options.userId === 'string' ? deps.options.userId : undefined;+ const effectiveUserId = runtimeUserId || user;+ const trigger = metadata?.trigger;+ const traceId = typeof metadata?.traceId === 'string' ? metadata.traceId : undefined;++ /** Pre-auth flows have no user id yet, so their stable trace id identifies the request. */+ if (deps.id !== 'lobehub' || ((effectiveUserId || traceId) && trigger)) {+ return effectiveUserId;+ }+ if (process.env.NODE_ENV !== 'development') return effectiveUserId;++ const diagnostic = {+ apiType,+ channelId,+ metadataKeys: Object.keys(metadata ?? {}),+ missingTrigger: !trigger,+ missingUser: !effectiveUserId,+ model,+ optionUserPresent: Boolean(user),+ providerId: deps.id,+ routerId,+ runtimeUserIdPresent: Boolean(runtimeUserId),+ stack: new Error('RouteAttemptMissingContext').stack?.split('\n').slice(0, 20),+ toolsCount: toolsCount ?? 0,+ traceId,+ trigger,+ };++ // Example bug: modelRuntime.chat(payload) without metadata would record trigger=null.+ throw new Error(`[RouteAttemptMissingContext] ${JSON.stringify(diagnostic)}`);+};diff --git a/packages/model-runtime/src/core/RouterRuntime/attemptErrors.ts b/packages/model-runtime/src/core/RouterRuntime/attemptErrors.tsnew file mode 100644index 00000000000..f0acf5f0197--- /dev/null+++ b/packages/model-runtime/src/core/RouterRuntime/attemptErrors.ts@@ -0,0 +1,10 @@+import { isImageDecodingRequestError, shouldStopFallbackForError } from '../../utils/routeFallback';++/** Whether a failed attempt may fall back to the next channel, and why not when it may not. */+export const classifyAttemptError = (error: unknown) => {+ const nonRetryable = shouldStopFallbackForError(error);+ const nonRetryableReason =+ nonRetryable && isImageDecodingRequestError(error) ? ('imageDecode' as const) : undefined;++ return { nonRetryable, nonRetryableReason };+};diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.tsindex aadf4ca8e93..7409edc045c 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts@@ -1,12 +1,8 @@/** @see https://github.com/lobehub/lobe-chat/discussions/6563 */-import type { GoogleGenAIOptions } from '@google/genai';-import type { ModelPricingContext, RouterRuntimeRequestContext } from '@lobechat/types';-import { AgentRuntimeErrorType } from '@lobechat/types';+import type { ModelPricingContext } from '@lobechat/types';import debug from 'debug';import { nanoid } from 'nanoid';-import { LobeOpenAI } from '../../providers/openai';-import { LobeVertexAI } from '../../providers/vertexai';import type {ASROptions,ASRPayload,@@ -28,32 +24,39 @@ import type {TextToSpeechPayload,VideoPollingRoute,} from '../../types';-import { AgentRuntimeError } from '../../utils/createError';-import type { ModelIdMappingOptions } from '../../utils/modelIdMapping';import { postProcessModelList } from '../../utils/postProcessModelList';-import { isImageDecodingRequestError, shouldStopFallbackForError } from '../../utils/routeFallback';-import { safeParseJSON } from '../../utils/safeParseJSON';-import { setRuntimeSignatureScopeSource } from '../../utils/signatureScope';-import { createTimingHelpers, getDurationMs } from '../../utils/timing';+import { shouldStopFallbackForError } from '../../utils/routeFallback';+import { getDurationMs } from '../../utils/timing';import { createVideoWithCompletionMode } from '../../utils/videoCompletionMode';import type { LobeRuntimeAI } from '../BaseAI';import type { ApiType } from './apiTypes';-import { type RouteAttemptMetadata, withAttemptUsage } from './attemptIdentity';+import { attachRouteAttemptMetadata, validateRouteAttemptContext } from './attemptContext';+import { classifyAttemptError } from './attemptErrors';+import { withAttemptUsage } from './attemptIdentity';import { getChatAttemptObservation, observeChatAttempt } from './chatAttempt';import { createChatAttemptFallbackCheck, resolveHoldReasoning } from './chatFallbackHooks';import type { ChatStreamFallbackAttempt } from './chatStreamFallback';import { createChatStreamFallbackResponse } from './chatStreamFallback';import { runDecision } from './decisionRuntime';+import { createRuntimeFromOption } from './optionRuntime';import type { RouteAttemptResult, RouteAttemptStart } from './routeAttempt';import { createRouteRequestTasks } from './routeRequestTasks';import type {CreateRouterRuntimeOptions,LobeClientOptions,RouterInstance,- RouterOptionItem,- RouterRuntimeMethod,Routers,} from './routerOptions';+import {+ normalizeRouterOptions,+ resolveMatchedRouter,+ resolvePinnedRoute,+ resolveRouters,+ type RouteAttemptContext,+ type RouterRuntimeDeps,+ selectRouteOptions,+} from './routeSelection';+import { createRouterTracer, type RouterTracer } from './tracer';export type { RouteAttemptResult } from './routeAttempt';export type {@@ -64,18 +67,6 @@ export type {} from './routerOptions';const log = debug('lobe-model-runtime:router-runtime');-const { logger: timing } = createTimingHelpers('lobe-server:chat:lobehub:timing');--interface RouteAttemptContext {- allowedApiTypes?: ReadonlySet<ApiType>;- metadata?: Record<string, unknown>;- method: RouterRuntimeMethod;- /** Skip routing and fallback: only the route's router/channel may serve the request. */- pinnedRoute?: VideoPollingRoute;- pricingContext?: ModelPricingContext;- toolsCount?: number;- user?: string;-}const RAW_AUDIO_API_TYPES = new Set<ApiType>(['google', 'openai', 'vertexai', 'xiaomimimo']);@@ -85,13 +76,6 @@ const hasRawAudioInput = (payload: ChatStreamPayload) =>Array.isArray(message.content) && message.content.some((part) => part.type === 'audio_url'),);-interface RouteAttemptContextValidationParams extends RouteAttemptContext {- apiType: string;- channelId?: string;- model: string;- routerId?: string;-}-export const createRouterRuntime = ({id,routers,@@ -105,56 +89,25 @@ export const createRouterRuntime = ({private _routers: Routers;private _params: any;private _id: string;+ private trace: RouterTracer;- private attachRouteAttemptMetadata(- metadata: Record<string, unknown> | undefined,- routeAttempt: RouteAttemptMetadata,- ) {- if (!metadata || this._id !== 'lobehub') return;-- metadata.routeAttempt = routeAttempt;+ /** What the routing helpers read; built per call so it always reflects current state. */+ private get deps(): RouterRuntimeDeps {+ return {+ id: this._id,+ options: this._options,+ params: this._params,+ routers: this._routers,+ trace: this.trace,+ };}- private validateRouteAttemptContext({- apiType,- channelId,- metadata,- model,- routerId,- toolsCount,- user,- }: RouteAttemptContextValidationParams) {- const runtimeUserId =- typeof this._options.userId === 'string' ? this._options.userId : undefined;- const effectiveUserId = runtimeUserId || user;- const trigger = metadata?.trigger;- const traceId = typeof metadata?.traceId === 'string' ? metadata.traceId : undefined;-- /** Pre-auth flows have no user id yet, so their stable trace id identifies the request. */- if (this._id !== 'lobehub' || ((effectiveUserId || traceId) && trigger)) {- return effectiveUserId;- }- if (process.env.NODE_ENV !== 'development') return effectiveUserId;-- const diagnostic = {- apiType,- channelId,- metadataKeys: Object.keys(metadata ?? {}),- missingTrigger: !trigger,- missingUser: !effectiveUserId,- model,- optionUserPresent: Boolean(user),- providerId: this._id,- routerId,- runtimeUserIdPresent: Boolean(runtimeUserId),- stack: new Error('RouteAttemptMissingContext').stack?.split('\n').slice(0, 20),- toolsCount: toolsCount ?? 0,- traceId,- trigger,- };+ private resolveMatchedRouter(model: string, pricingContext?: ModelPricingContext) {+ return resolveMatchedRouter(this.deps, model, pricingContext);+ }- // Example bug: modelRuntime.chat(payload) without metadata would record trigger=null.- throw new Error(`[RouteAttemptMissingContext] ${JSON.stringify(diagnostic)}`);+ private normalizeRouterOptions(router: RouterInstance) {+ return normalizeRouterOptions(this.deps, router);}constructor(options: LobeClientOptions & Record<string, any> = {}) {@@ -169,296 +122,15 @@ export const createRouterRuntime = ({this._routers = routers;this._params = params;this._id = options.id ?? id;-- if (this._id === 'lobehub') {- timing(- 'constructor done providerId=%s durationMs=%d hasApiKey=%s hasBaseURL=%s',- this._id,- getDurationMs(startedAt),- !!this._options.apiKey,- !!this._options.baseURL,- );- }- }-- /**- * Resolve routers configuration and validate- */- private async resolveRouters(- runtimeContext: RouterRuntimeRequestContext = {},- ): Promise<RouterInstance[]> {- const startedAt = Date.now();- const { model } = runtimeContext;- try {- const resolvedRouters =- typeof this._routers === 'function'- ? await this._routers(this._options, runtimeContext)- : this._routers;-- if (this._id === 'lobehub') {- timing(- 'resolveRouters done model=%s durationMs=%d routerCount=%d dynamic=%s',- model,- getDurationMs(startedAt),- resolvedRouters.length,- typeof this._routers === 'function',- );- }-- if (resolvedRouters.length === 0) {- throw AgentRuntimeError.chat({- error: { message: 'empty providers' },- errorType: AgentRuntimeErrorType.NoAvailableProvider,- provider: this._id,- });- }-- return resolvedRouters;- } catch (error) {- if (this._id === 'lobehub') {- timing('resolveRouters error model=%s durationMs=%d', model, getDurationMs(startedAt));- }- throw error;- }- }-- private async resolveMatchedRouter(- model: string,- pricingContext?: ModelPricingContext,- ): Promise<RouterInstance> {- const startedAt = Date.now();- const resolvedRouters = await this.resolveRouters({- model,- ...(pricingContext ? { pricingContext } : {}),- });- const baseURL = this._options.baseURL;-- // Priority 1: Match by baseURLPattern (RegExp only)- if (baseURL) {- const baseURLMatch = resolvedRouters.find((router) => router.baseURLPattern?.test(baseURL));- if (baseURLMatch) {- if (this._id === 'lobehub') {- timing(- 'resolveMatchedRouter done model=%s match=baseURL routerId=%s apiType=%s durationMs=%d',- model,- baseURLMatch.id,- baseURLMatch.apiType,- getDurationMs(startedAt),- );- }- return baseURLMatch;- }- }-- // Priority 2: Match by models- const modelMatch = resolvedRouters.find((router) => {- if (router.models && router.models.length > 0) {- return router.models.includes(model);- }- return false;- });- if (modelMatch) {- if (this._id === 'lobehub') {- timing(- 'resolveMatchedRouter done model=%s match=models routerId=%s apiType=%s durationMs=%d',- model,- modelMatch.id,- modelMatch.apiType,- getDurationMs(startedAt),- );- }- return modelMatch;- }-- // Fallback: Use the last router- const fallbackRouter = resolvedRouters.at(-1)!;- if (this._id === 'lobehub') {- timing(- 'resolveMatchedRouter done model=%s match=fallback routerId=%s apiType=%s durationMs=%d',- model,- fallbackRouter.id,- fallbackRouter.apiType,- getDurationMs(startedAt),- );- }- return fallbackRouter;- }-- private normalizeRouterOptions(router: RouterInstance): RouterOptionItem[] {- const startedAt = Date.now();- const routerOptions = Array.isArray(router.options) ? router.options : [router.options];-- if (routerOptions.length === 0 || routerOptions.some((optionItem) => !optionItem)) {- throw new Error('empty provider options');- }-- if (this._id === 'lobehub') {- timing(- 'normalizeRouterOptions done routerId=%s options=%d durationMs=%d',- router.id,- routerOptions.length,- getDurationMs(startedAt),- );- }-- return routerOptions;- }-- private async applySortRouterOptions(- router: RouterInstance,- model: string,- routerOptions: RouterOptionItem[],- routeContext: RouteAttemptContext,- ): 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({- metadata: routeContext.metadata,- method: routeContext.method,- model,- options: [...routerOptions],- routerId: router.id,- userId:- (typeof this._options.userId === 'string' ? this._options.userId : undefined) ||- routeContext.user,- });- 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.- */- private async createRuntimeFromOption(- router: RouterInstance,- optionItem: RouterOptionItem,- ): Promise<{- channelId?: string;- id: ApiType;- remark?: string;- runtime: LobeRuntimeAI;- }> {- const startedAt = Date.now();- const { apiType: optionApiType, id: channelId, remark, ...optionOverrides } = optionItem;- delete optionOverrides.weight;- const resolvedApiType = optionApiType ?? router.apiType;- const finalOptions = {- ...this._params,- ...this._options,- ...optionOverrides,- };- const signatureScopeSource = {- apiType: resolvedApiType,- channelId,- provider: this._id,- routerId: router.id ?? this._id,- };-- /**- * 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 & ModelIdMappingOptions = {- ...(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'];-- if (this._id === 'lobehub') {- timing(- 'createRuntimeFromOption done routerId=%s channelId=%s apiType=%s durationMs=%d vertex=true',- router.id,- channelId,- resolvedApiType,- getDurationMs(startedAt),- );- }-- const runtime = LobeVertexAI.initFromVertexAI(vertexOptions);- setRuntimeSignatureScopeSource(runtime, signatureScopeSource);-- return {- channelId,- id: resolvedApiType,- remark,- runtime,- };- }-- const { baseRuntimeMap } = await import('./baseRuntimeMap');- const providerAI =- resolvedApiType === router.apiType- ? (router.runtime ?? baseRuntimeMap[resolvedApiType] ?? LobeOpenAI)- : (baseRuntimeMap[resolvedApiType] ?? LobeOpenAI);- const runtime: LobeRuntimeAI = new providerAI({ ...finalOptions, id: this._id });- setRuntimeSignatureScopeSource(runtime, signatureScopeSource);-- if (this._id === 'lobehub') {- timing(- 'createRuntimeFromOption done routerId=%s channelId=%s apiType=%s durationMs=%d',- router.id,- channelId,- resolvedApiType,- getDurationMs(startedAt),- );- }-- return {- channelId,- id: resolvedApiType,- remark,- runtime,- };+ this.trace = createRouterTracer(this._id);++ this.trace(+ 'constructor done providerId=%s durationMs=%d hasApiKey=%s hasBaseURL=%s',+ this._id,+ getDurationMs(startedAt),+ !!this._options.apiKey,+ !!this._options.baseURL,+ );}/**@@ -472,21 +144,10 @@ export const createRouterRuntime = ({routeContext: RouteAttemptContext,): Promise<Response> {const requestId = nanoid();- const { allowedApiTypes, metadata, pricingContext, toolsCount, user } = routeContext;- const matchedRouter = await this.resolveMatchedRouter(payload.model, pricingContext);- const eligibleRouterOptions = this.normalizeRouterOptions(matchedRouter).filter(- (option) =>- !allowedApiTypes || allowedApiTypes.has(option.apiType ?? matchedRouter.apiType),- );- if (eligibleRouterOptions.length === 0) {- throw new TypeError(- `No provider route supports raw audio input for model ${payload.model}`,- );- }- const routerOptions = await this.applySortRouterOptions(- matchedRouter,+ const { metadata, toolsCount, user } = routeContext;+ const { matchedRouter, routerOptions } = await selectRouteOptions(+ this.deps,payload.model,- eligibleRouterOptions,routeContext,);const firstChannelId = routerOptions[0]?.id;@@ -535,8 +196,8 @@ export const createRouterRuntime = ({id: resolvedApiType,remark,runtime,- } = await this.createRuntimeFromOption(matchedRouter, optionItem);- const routeAttemptUserId = this.validateRouteAttemptContext({+ } = await createRuntimeFromOption(this.deps, matchedRouter, optionItem);+ const routeAttemptUserId = validateRouteAttemptContext(this.deps, {apiType: resolvedApiType,channelId,metadata,@@ -581,7 +242,7 @@ export const createRouterRuntime = ({durationMs,success: true,});- this.attachRouteAttemptMetadata(metadata, {+ attachRouteAttemptMetadata(this.deps, metadata, {apiType: resolvedApiType,attemptId: attempt.attemptId,channelId,@@ -633,11 +294,7 @@ export const createRouterRuntime = ({response,};} catch (error) {- const nonRetryable = shouldStopFallbackForError(error);- const nonRetryableReason =- nonRetryable && isImageDecodingRequestError(error)- ? ('imageDecode' as const)- : undefined;+ const { nonRetryable, nonRetryableReason } = classifyAttemptError(error);reportReturnedAttempt(attempt, {// Defer cancellation health handling to the terminal outcome, which intentionally ignores it.completionPending: options?.signal?.aborted ?? false,@@ -678,40 +335,24 @@ export const createRouterRuntime = ({): Promise<T> {const totalStartedAt = Date.now();const requestId = nanoid();- const { allowedApiTypes, metadata, pinnedRoute, pricingContext, toolsCount, user } =- routeContext;- const pinned = await this.resolvePinnedRoute(model, pinnedRoute);- const matchedRouter =- pinned?.router ?? (await this.resolveMatchedRouter(model, pricingContext));- const eligibleRouterOptions = this.normalizeRouterOptions(matchedRouter).filter(- (option) =>- !allowedApiTypes || allowedApiTypes.has(option.apiType ?? matchedRouter.apiType),+ const { metadata, toolsCount, user } = routeContext;+ const { matchedRouter, routerOptions } = await selectRouteOptions(+ this.deps,+ model,+ routeContext,);- if (eligibleRouterOptions.length === 0) {- throw new TypeError(`No provider route supports raw audio input for model ${model}`);- }- const routerOptions = pinned- ? [pinned.option]- : await this.applySortRouterOptions(- matchedRouter,- model,- eligibleRouterOptions,- routeContext,- );const totalOptions = routerOptions.length;const firstChannelId = routerOptions[0]?.id;const weighted = routerOptions.some((option) => option.weight !== undefined);- if (this._id === 'lobehub') {- timing(- 'runWithFallback start model=%s routerId=%s apiType=%s options=%d traceId=%s',- model,- matchedRouter.id,- matchedRouter.apiType,- totalOptions,- metadata?.traceId,- );- }+ this.trace(+ 'runWithFallback start model=%s routerId=%s apiType=%s options=%d traceId=%s',+ model,+ matchedRouter.id,+ matchedRouter.apiType,+ totalOptions,+ metadata?.traceId,+ );log('resolve router for model=%s apiType=%s options=%d',@@ -730,8 +371,8 @@ export const createRouterRuntime = ({id: resolvedApiType,remark,runtime,- } = await this.createRuntimeFromOption(matchedRouter, optionItem);- const routeAttemptUserId = this.validateRouteAttemptContext({+ } = await createRuntimeFromOption(this.deps, matchedRouter, optionItem);+ const routeAttemptUserId = validateRouteAttemptContext(this.deps, {apiType: resolvedApiType,channelId,metadata,@@ -759,33 +400,29 @@ export const createRouterRuntime = ({};try {- if (this._id === 'lobehub') {- timing(- 'attempt request start model=%s attempt=%d/%d routerId=%s channelId=%s apiType=%s traceId=%s',- model,- attempt,- totalOptions,- matchedRouter.id,- channelId,- resolvedApiType,- metadata?.traceId,- );- }+ this.trace(+ 'attempt request start model=%s attempt=%d/%d routerId=%s channelId=%s apiType=%s traceId=%s',+ model,+ attempt,+ totalOptions,+ matchedRouter.id,+ channelId,+ resolvedApiType,+ metadata?.traceId,+ );const result = await requestHandler(runtime, attemptContext);- if (this._id === 'lobehub') {- timing(- 'attempt request success model=%s attempt=%d/%d routerId=%s channelId=%s apiType=%s durationMs=%d totalMs=%d traceId=%s',- model,- attempt,- totalOptions,- matchedRouter.id,- channelId,- resolvedApiType,- getDurationMs(startTime),- getDurationMs(totalStartedAt),- metadata?.traceId,- );- }+ this.trace(+ 'attempt request success model=%s attempt=%d/%d routerId=%s channelId=%s apiType=%s durationMs=%d totalMs=%d traceId=%s',+ model,+ attempt,+ totalOptions,+ matchedRouter.id,+ channelId,+ resolvedApiType,+ getDurationMs(startTime),+ getDurationMs(totalStartedAt),+ metadata?.traceId,+ );if (totalOptions > 1 && attempt > 1) {log(@@ -844,7 +481,7 @@ export const createRouterRuntime = ({log('onRouteAttempt callback error: %O', e);});- this.attachRouteAttemptMetadata(metadata, {+ attachRouteAttemptMetadata(this.deps, metadata, {apiType: resolvedApiType,attemptId: attemptContext.attemptId,channelId,@@ -860,26 +497,21 @@ export const createRouterRuntime = ({return result;} catch (error) {lastError = error;- if (this._id === 'lobehub') {- timing(- 'attempt request error model=%s attempt=%d/%d routerId=%s channelId=%s apiType=%s durationMs=%d totalMs=%d traceId=%s',- model,- attempt,- totalOptions,- matchedRouter.id,- channelId,- resolvedApiType,- getDurationMs(startTime),- getDurationMs(totalStartedAt),- metadata?.traceId,- );- }+ this.trace(+ 'attempt request error model=%s attempt=%d/%d routerId=%s channelId=%s apiType=%s durationMs=%d totalMs=%d traceId=%s',+ model,+ attempt,+ totalOptions,+ matchedRouter.id,+ channelId,+ resolvedApiType,+ getDurationMs(startTime),+ getDurationMs(totalStartedAt),+ metadata?.traceId,+ );- const shouldStopFallback = shouldStopFallbackForError(error);- const nonRetryableReason =- shouldStopFallback && isImageDecodingRequestError(error)- ? ('imageDecode' as const)- : undefined;+ const { nonRetryable: shouldStopFallback, nonRetryableReason } =+ classifyAttemptError(error);params.onRouteAttempt?.({@@ -916,17 +548,15 @@ export const createRouterRuntime = ({optionIndex: index,});- if (this._id === 'lobehub') {- timing(- 'shouldStopFallback done model=%s attempt=%d/%d durationMs=%d shouldStop=%s traceId=%s',- model,- attempt,- totalOptions,- getDurationMs(shouldStopStartedAt),- shouldStopFallback,- metadata?.traceId,- );- }+ this.trace(+ 'shouldStopFallback done model=%s attempt=%d/%d durationMs=%d shouldStop=%s traceId=%s',+ model,+ attempt,+ totalOptions,+ getDurationMs(shouldStopStartedAt),+ shouldStopFallback,+ metadata?.traceId,+ );if (shouldStopFallback) {throw error;@@ -964,28 +594,26 @@ export const createRouterRuntime = ({}}- if (this._id === 'lobehub') {- timing(- 'runWithFallback failed model=%s routerId=%s options=%d totalMs=%d traceId=%s',- model,- matchedRouter.id,- totalOptions,- getDurationMs(totalStartedAt),- metadata?.traceId,- );- }+ this.trace(+ 'runWithFallback failed model=%s routerId=%s options=%d totalMs=%d traceId=%s',+ model,+ matchedRouter.id,+ totalOptions,+ getDurationMs(totalStartedAt),+ metadata?.traceId,+ );throw lastError ?? new Error('empty provider options');}async models() {- const resolvedRouters = await this.resolveRouters();+ const resolvedRouters = await resolveRouters(this.deps);const matchedRouter = this._options.baseURL? (resolvedRouters.find((router) => router.baseURLPattern?.test(this._options.baseURL!)) ??resolvedRouters.at(-1)!): resolvedRouters.at(-1)!;- const routerOptions = this.normalizeRouterOptions(matchedRouter);- const { runtime } = await this.createRuntimeFromOption(matchedRouter, routerOptions[0]);+ const routerOptions = normalizeRouterOptions(this.deps, matchedRouter);+ const { runtime } = await createRuntimeFromOption(this.deps, matchedRouter, routerOptions[0]);if (modelsOption &&@@ -1080,48 +708,16 @@ export const createRouterRuntime = ({);}- /**- * Resolve the exact router/channel that created a video instead of re-running normal- * routing: stateful providers such as Gemini Omni scope the interaction to the creating- * API key, so another channel's key can neither read nor continue it. Fail loudly when- * that route disappears rather than silently switching keys.- */- private async resolvePinnedRoute(model: string | undefined, route?: VideoPollingRoute) {- if (!route?.routerId && !route?.channelId) return;-- const resolvedRouters = await this.resolveRouters({ model });- const router = route.routerId- ? resolvedRouters.find((item) => item.id === route.routerId)- : resolvedRouters.find((item) =>- this.normalizeRouterOptions(item).some((option) => option.id === route.channelId),- );-- if (!router) {- throw new Error('The video generation route is no longer available');- }-- const routerOptions = this.normalizeRouterOptions(router);- const option = route.channelId- ? routerOptions.find((item) => item.id === route.channelId)- : routerOptions[0];-- if (!option) {- throw new Error('The video generation channel is no longer available');- }-- return { option, router };- }-async handlePollVideoStatus(inferenceId: string, model?: string, route?: VideoPollingRoute) {- const pinned = await this.resolvePinnedRoute(model, route);+ const pinned = await resolvePinnedRoute(this.deps, model, route);let matchedRouter = pinned?.router;if (!matchedRouter && model) {- matchedRouter = await this.resolveMatchedRouter(model);+ matchedRouter = await resolveMatchedRouter(this.deps, model);}if (!matchedRouter) {- const resolvedRouters = await this.resolveRouters({ model });+ const resolvedRouters = await resolveRouters(this.deps, { model });const { baseURL } = this._options;matchedRouter =(baseURL@@ -1129,12 +725,13 @@ export const createRouterRuntime = ({: undefined) ?? resolvedRouters.at(-1)!;}- const selectedOption = pinned?.option ?? this.normalizeRouterOptions(matchedRouter)[0];+ const selectedOption = pinned?.option ?? normalizeRouterOptions(this.deps, matchedRouter)[0];if (!selectedOption) {throw new Error('The video generation channel is no longer available');}- const { id: apiType, runtime } = await this.createRuntimeFromOption(+ const { id: apiType, runtime } = await createRuntimeFromOption(+ this.deps,matchedRouter,selectedOption,);@@ -1152,9 +749,13 @@ export const createRouterRuntime = ({async handleCreateVideoWebhook(payload: HandleCreateVideoWebhookPayload) {const model = payload.model ?? (payload.body as { model?: string } | undefined)?.model;- const resolvedRouters = await this.resolveRouters({ model });- const routerOptions = this.normalizeRouterOptions(resolvedRouters[0]);- const { runtime } = await this.createRuntimeFromOption(resolvedRouters[0], routerOptions[0]);+ const resolvedRouters = await resolveRouters(this.deps, { model });+ const routerOptions = normalizeRouterOptions(this.deps, resolvedRouters[0]);+ const { runtime } = await createRuntimeFromOption(+ this.deps,+ resolvedRouters[0],+ routerOptions[0],+ );return runtime.handleCreateVideoWebhook!(payload);}diff --git a/packages/model-runtime/src/core/RouterRuntime/optionRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/optionRuntime.tsnew file mode 100644index 00000000000..49981aeb82f--- /dev/null+++ b/packages/model-runtime/src/core/RouterRuntime/optionRuntime.ts@@ -0,0 +1,100 @@+import type { GoogleGenAIOptions } from '@google/genai';++import { LobeOpenAI } from '../../providers/openai';+import { LobeVertexAI } from '../../providers/vertexai';+import type { ModelIdMappingOptions } from '../../utils/modelIdMapping';+import { safeParseJSON } from '../../utils/safeParseJSON';+import { setRuntimeSignatureScopeSource } from '../../utils/signatureScope';+import { getDurationMs } from '../../utils/timing';+import type { LobeRuntimeAI } from '../BaseAI';+import type { RouterInstance, RouterOptionItem } from './routerOptions';+import type { RouterRuntimeDeps } from './routeSelection';++/**+ * Build a runtime instance for a specific option item.+ * Option items can override apiType to switch providers for fallback.+ */+export const createRuntimeFromOption = async (+ deps: RouterRuntimeDeps,+ router: RouterInstance,+ optionItem: RouterOptionItem,+) => {+ const startedAt = Date.now();+ const { apiType: optionApiType, id: channelId, remark, ...optionOverrides } = optionItem;+ delete optionOverrides.weight;+ const resolvedApiType = optionApiType ?? router.apiType;+ const finalOptions = {+ ...deps.params,+ ...deps.options,+ ...optionOverrides,+ };+ const signatureScopeSource = {+ apiType: resolvedApiType,+ channelId,+ provider: deps.id,+ routerId: router.id ?? deps.id,+ };++ /**+ * 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 & ModelIdMappingOptions = {+ ...(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'];++ deps.trace(+ 'createRuntimeFromOption done routerId=%s channelId=%s apiType=%s durationMs=%d vertex=true',+ router.id,+ channelId,+ resolvedApiType,+ getDurationMs(startedAt),+ );++ const runtime = LobeVertexAI.initFromVertexAI(vertexOptions);+ setRuntimeSignatureScopeSource(runtime, signatureScopeSource);++ return {+ channelId,+ id: resolvedApiType,+ remark,+ runtime,+ };+ }++ const { baseRuntimeMap } = await import('./baseRuntimeMap');+ const providerAI =+ resolvedApiType === router.apiType+ ? (router.runtime ?? baseRuntimeMap[resolvedApiType] ?? LobeOpenAI)+ : (baseRuntimeMap[resolvedApiType] ?? LobeOpenAI);+ const runtime: LobeRuntimeAI = new providerAI({ ...finalOptions, id: deps.id });+ setRuntimeSignatureScopeSource(runtime, signatureScopeSource);++ deps.trace(+ 'createRuntimeFromOption done routerId=%s channelId=%s apiType=%s durationMs=%d',+ router.id,+ channelId,+ resolvedApiType,+ getDurationMs(startedAt),+ );++ return {+ channelId,+ id: resolvedApiType,+ remark,+ runtime,+ };+};diff --git a/packages/model-runtime/src/core/RouterRuntime/routeSelection.ts b/packages/model-runtime/src/core/RouterRuntime/routeSelection.tsnew file mode 100644index 00000000000..264f038cdb8--- /dev/null+++ b/packages/model-runtime/src/core/RouterRuntime/routeSelection.ts@@ -0,0 +1,275 @@+import type { ModelPricingContext, RouterRuntimeRequestContext } from '@lobechat/types';+import { AgentRuntimeErrorType } from '@lobechat/types';+import debug from 'debug';++import type { VideoPollingRoute } from '../../types';+import { AgentRuntimeError } from '../../utils/createError';+import { getDurationMs } from '../../utils/timing';+import type { ApiType } from './apiTypes';+import type {+ CreateRouterRuntimeOptions,+ LobeClientOptions,+ RouterInstance,+ RouterOptionItem,+ RouterRuntimeMethod,+ Routers,+} from './routerOptions';+import type { RouterTracer } from './tracer';++const log = debug('lobe-model-runtime:router-runtime');++/** What the routing helpers read from a router runtime; rebuilt per call from its current state. */+export interface RouterRuntimeDeps {+ id: string;+ options: LobeClientOptions & Record<string, any>;+ params: Omit<CreateRouterRuntimeOptions, 'apiKey' | 'id' | 'models' | 'routers'> &+ Record<string, any>;+ routers: Routers;+ trace: RouterTracer;+}++export interface RouteAttemptContext {+ allowedApiTypes?: ReadonlySet<ApiType>;+ metadata?: Record<string, unknown>;+ method: RouterRuntimeMethod;+ /** Skip routing and fallback: only the route's router/channel may serve the request. */+ pinnedRoute?: VideoPollingRoute;+ pricingContext?: ModelPricingContext;+ toolsCount?: number;+ user?: string;+}++/**+ * Resolve routers configuration and validate+ */+export const resolveRouters = async (+ deps: RouterRuntimeDeps,+ runtimeContext: RouterRuntimeRequestContext = {},+): Promise<RouterInstance[]> => {+ const startedAt = Date.now();+ const { model } = runtimeContext;+ try {+ const resolvedRouters =+ typeof deps.routers === 'function'+ ? await deps.routers(deps.options, runtimeContext)+ : deps.routers;++ deps.trace(+ 'resolveRouters done model=%s durationMs=%d routerCount=%d dynamic=%s',+ model,+ getDurationMs(startedAt),+ resolvedRouters.length,+ typeof deps.routers === 'function',+ );++ if (resolvedRouters.length === 0) {+ throw AgentRuntimeError.chat({+ error: { message: 'empty providers' },+ errorType: AgentRuntimeErrorType.NoAvailableProvider,+ provider: deps.id,+ });+ }++ return resolvedRouters;+ } catch (error) {+ deps.trace('resolveRouters error model=%s durationMs=%d', model, getDurationMs(startedAt));+ throw error;+ }+};++export const resolveMatchedRouter = async (+ deps: RouterRuntimeDeps,+ model: string,+ pricingContext?: ModelPricingContext,+): Promise<RouterInstance> => {+ const startedAt = Date.now();+ const resolvedRouters = await resolveRouters(deps, {+ model,+ ...(pricingContext ? { pricingContext } : {}),+ });+ const baseURL = deps.options.baseURL;++ // Priority 1: Match by baseURLPattern (RegExp only)+ if (baseURL) {+ const baseURLMatch = resolvedRouters.find((router) => router.baseURLPattern?.test(baseURL));+ if (baseURLMatch) {+ deps.trace(+ 'resolveMatchedRouter done model=%s match=baseURL routerId=%s apiType=%s durationMs=%d',+ model,+ baseURLMatch.id,+ baseURLMatch.apiType,+ getDurationMs(startedAt),+ );+ return baseURLMatch;+ }+ }++ // Priority 2: Match by models+ const modelMatch = resolvedRouters.find((router) => {+ if (router.models && router.models.length > 0) {+ return router.models.includes(model);+ }+ return false;+ });+ if (modelMatch) {+ deps.trace(+ 'resolveMatchedRouter done model=%s match=models routerId=%s apiType=%s durationMs=%d',+ model,+ modelMatch.id,+ modelMatch.apiType,+ getDurationMs(startedAt),+ );+ return modelMatch;+ }++ // Fallback: Use the last router+ const fallbackRouter = resolvedRouters.at(-1)!;+ deps.trace(+ 'resolveMatchedRouter done model=%s match=fallback routerId=%s apiType=%s durationMs=%d',+ model,+ fallbackRouter.id,+ fallbackRouter.apiType,+ getDurationMs(startedAt),+ );+ return fallbackRouter;+};++export const normalizeRouterOptions = (+ deps: RouterRuntimeDeps,+ router: RouterInstance,+): RouterOptionItem[] => {+ const startedAt = Date.now();+ const routerOptions = Array.isArray(router.options) ? router.options : [router.options];++ if (routerOptions.length === 0 || routerOptions.some((optionItem) => !optionItem)) {+ throw new Error('empty provider options');+ }++ deps.trace(+ 'normalizeRouterOptions done routerId=%s options=%d durationMs=%d',+ router.id,+ routerOptions.length,+ getDurationMs(startedAt),+ );++ return routerOptions;+};++export const applySortRouterOptions = async (+ deps: RouterRuntimeDeps,+ router: RouterInstance,+ model: string,+ routerOptions: RouterOptionItem[],+ routeContext: RouteAttemptContext,+): Promise<RouterOptionItem[]> => {+ if (!deps.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 deps.params.sortRouterOptions({+ metadata: routeContext.metadata,+ method: routeContext.method,+ model,+ options: [...routerOptions],+ routerId: router.id,+ userId:+ (typeof deps.options.userId === 'string' ? deps.options.userId : undefined) ||+ routeContext.user,+ });+ const isPermutation =+ Array.isArray(sorted) &&+ sorted.length === routerOptions.length &&+ routerOptions.every((optionItem) => sorted.includes(optionItem));++ deps.trace(+ '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) {+ deps.trace(+ 'sortRouterOptions error model=%s routerId=%s durationMs=%d',+ model,+ router.id,+ getDurationMs(startedAt),+ );+ log('sortRouterOptions callback error: %O', error);+ return routerOptions;+ }+};++/**+ * Resolve the exact router/channel that created a video instead of re-running normal+ * routing: stateful providers such as Gemini Omni scope the interaction to the creating+ * API key, so another channel's key can neither read nor continue it. Fail loudly when+ * that route disappears rather than silently switching keys.+ */+export const resolvePinnedRoute = async (+ deps: RouterRuntimeDeps,+ model: string | undefined,+ route?: VideoPollingRoute,+) => {+ if (!route?.routerId && !route?.channelId) return;++ const resolvedRouters = await resolveRouters(deps, { model });+ const router = route.routerId+ ? resolvedRouters.find((item) => item.id === route.routerId)+ : resolvedRouters.find((item) =>+ normalizeRouterOptions(deps, item).some((option) => option.id === route.channelId),+ );++ if (!router) {+ throw new Error('The video generation route is no longer available');+ }++ const routerOptions = normalizeRouterOptions(deps, router);+ const option = route.channelId+ ? routerOptions.find((item) => item.id === route.channelId)+ : routerOptions[0];++ if (!option) {+ throw new Error('The video generation channel is no longer available');+ }++ return { option, router };+};++/**+ * Pick the router and the ordered channels that may serve a request: the pinned+ * route when one is given, otherwise the matched router's eligible channels in+ * the order `sortRouterOptions` chose.+ */+export const selectRouteOptions = async (+ deps: RouterRuntimeDeps,+ model: string,+ routeContext: RouteAttemptContext,+) => {+ const { allowedApiTypes, pinnedRoute, pricingContext } = routeContext;+ const pinned = await resolvePinnedRoute(deps, model, pinnedRoute);+ const matchedRouter = pinned?.router ?? (await resolveMatchedRouter(deps, model, pricingContext));+ const eligibleRouterOptions = normalizeRouterOptions(deps, matchedRouter).filter(+ (option) => !allowedApiTypes || allowedApiTypes.has(option.apiType ?? matchedRouter.apiType),+ );+ if (eligibleRouterOptions.length === 0) {+ throw new TypeError(`No provider route supports raw audio input for model ${model}`);+ }+ const routerOptions = pinned+ ? [pinned.option]+ : await applySortRouterOptions(deps, matchedRouter, model, eligibleRouterOptions, routeContext);++ return { matchedRouter, routerOptions };+};diff --git a/packages/model-runtime/src/core/RouterRuntime/tracer.ts b/packages/model-runtime/src/core/RouterRuntime/tracer.tsnew file mode 100644index 00000000000..750ae113907--- /dev/null+++ b/packages/model-runtime/src/core/RouterRuntime/tracer.ts@@ -0,0 +1,9 @@+import { createTimingHelpers } from '../../utils/timing';++const { logger: timing } = createTimingHelpers('lobe-server:chat:lobehub:timing');++export type RouterTracer = (formatter: string, ...args: unknown[]) => void;++/** Only the hosted `lobehub` router emits request timing; other routers stay silent. */+export const createRouterTracer = (providerId: string): RouterTracer =>+ providerId === 'lobehub' ? (formatter, ...args) => timing(formatter, ...args) : () => {};