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.

✨ feat(model-runtime): improve routing context and fallback (#18596)

YuTengjing3ba63cd0331b
diff --git a/apps/server/src/modules/ModelRuntime/index.test.ts b/apps/server/src/modules/ModelRuntime/index.test.ts
index 7885135cb66..59ef0f88423 100644
--- a/apps/server/src/modules/ModelRuntime/index.test.ts
+++ b/apps/server/src/modules/ModelRuntime/index.test.ts
@@ -412,7 +412,7 @@ describe('initModelRuntimeFromServerConfig', () => {
expect(initialize).toHaveBeenCalledWith(
ModelProvider.LobeHub,
- { userId: 'user-1' },
+ { userId: 'user-1', workspaceId: 'workspace-1' },
expect.anything(),
);
initialize.mockRestore();
diff --git a/apps/server/src/modules/ModelRuntime/index.ts b/apps/server/src/modules/ModelRuntime/index.ts
index 245b88f51b4..1a8f3312bc0 100644
--- a/apps/server/src/modules/ModelRuntime/index.ts
+++ b/apps/server/src/modules/ModelRuntime/index.ts
@@ -519,7 +519,7 @@ export const initModelRuntimeFromDB = async (
const hooks = mergeModelRuntimeHooks(businessHooks, tracingHooks);
// 6. Initialize ModelRuntime with the payload and hooks
- return initModelRuntimeWithUserPayload(provider, payload, { userId }, hooks);
+ return initModelRuntimeWithUserPayload(provider, payload, { userId, workspaceId }, hooks);
};
export const SERVER_DEFAULT_HETEROGENEOUS_AGENT_TYPES = ['claude-code', 'codex'] as const;
@@ -656,7 +656,7 @@ export const initModelRuntimeFromServerConfig = async (params: {
);
return ModelRuntime.initializeWithProvider(
ModelProvider.LobeHub,
- { userId: params.actorUserId },
+ { userId: params.actorUserId, workspaceId: params.workspaceId },
mergeModelRuntimeHooks(businessHooks, tracingHooks),
);
};
diff --git a/packages/business/model-runtime/package.json b/packages/business/model-runtime/package.json
index 39c6ed809d0..6a727609842 100644
--- a/packages/business/model-runtime/package.json
+++ b/packages/business/model-runtime/package.json
@@ -5,5 +5,8 @@
"exports": {
".": "./src/index.ts"
},
- "main": "./src/index.ts"
+ "main": "./src/index.ts",
+ "devDependencies": {
+ "@lobechat/types": "workspace:*"
+ }
}
diff --git a/packages/business/model-runtime/src/router-runtime-options.ts b/packages/business/model-runtime/src/router-runtime-options.ts
index f51b8b6479d..2f4b4fd33fd 100644
--- a/packages/business/model-runtime/src/router-runtime-options.ts
+++ b/packages/business/model-runtime/src/router-runtime-options.ts
@@ -1,3 +1,5 @@
+import type { RouterRuntimeRequestContext } from '@lobechat/types';
+
interface RouterInstance {
apiType: string;
models?: string[];
@@ -16,7 +18,7 @@ interface RouterInstance {
interface LobehubRouterRuntimeOptions {
id: string;
- routers: (options: any, runtimeContext: { model?: string }) => Promise<RouterInstance[]>;
+ routers: (options: any, runtimeContext: RouterRuntimeRequestContext) => Promise<RouterInstance[]>;
}
export const lobehubRouterRuntimeOptions: LobehubRouterRuntimeOptions = {
diff --git a/packages/model-bank/src/aiModels/openai.ts b/packages/model-bank/src/aiModels/openai.ts
index 081653d1900..e728bd80431 100644
--- a/packages/model-bank/src/aiModels/openai.ts
+++ b/packages/model-bank/src/aiModels/openai.ts
@@ -60,8 +60,8 @@ export const openaiChatModels: AIChatModelCard[] = [
name: 'textInput',
strategy: 'tiered',
tiers: [
- { rate: 5, upTo: 272_000 },
- { rate: 10, upTo: 'infinity' },
+ { rate: 4, upTo: 272_000 },
+ { rate: 8, upTo: 'infinity' },
],
unit: 'millionTokens',
},
@@ -69,8 +69,8 @@ export const openaiChatModels: AIChatModelCard[] = [
name: 'textInput_cacheRead',
strategy: 'tiered',
tiers: [
- { rate: 0.5, upTo: 272_000 },
- { rate: 1, upTo: 'infinity' },
+ { rate: 0.4, upTo: 272_000 },
+ { rate: 0.8, upTo: 'infinity' },
],
unit: 'millionTokens',
},
@@ -78,8 +78,8 @@ export const openaiChatModels: AIChatModelCard[] = [
name: 'textInput_cacheWrite',
strategy: 'tiered',
tiers: [
- { rate: 6.25, upTo: 272_000 },
- { rate: 12.5, upTo: 'infinity' },
+ { rate: 5, upTo: 272_000 },
+ { rate: 10, upTo: 'infinity' },
],
unit: 'millionTokens',
},
@@ -87,8 +87,8 @@ export const openaiChatModels: AIChatModelCard[] = [
name: 'textOutput',
strategy: 'tiered',
tiers: [
- { rate: 30, upTo: 272_000 },
- { rate: 45, upTo: 'infinity' },
+ { rate: 20, upTo: 272_000 },
+ { rate: 30, upTo: 'infinity' },
],
unit: 'millionTokens',
},
diff --git a/packages/model-runtime/src/core/ModelRuntime.ts b/packages/model-runtime/src/core/ModelRuntime.ts
index 4f64a2e90b0..d72d4efa0e5 100644
--- a/packages/model-runtime/src/core/ModelRuntime.ts
+++ b/packages/model-runtime/src/core/ModelRuntime.ts
@@ -509,6 +509,7 @@ export class ModelRuntime {
apiKey?: string;
baseURL?: string;
userId?: string;
+ workspaceId?: string;
}
>,
hooks?: ModelRuntimeHooks,
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
index b4f6efcaed8..c59d5474d08 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
@@ -584,6 +584,93 @@ describe('createRouterRuntime', () => {
);
});
+ it.each<
+ [
+ string,
+ (
+ runtime: InstanceType<ReturnType<typeof createRouterRuntime>>,
+ options: any,
+ ) => Promise<unknown>,
+ ]
+ >([
+ [
+ 'chat',
+ (runtime, options) =>
+ runtime.chat({ messages: [], model: 'request-model', temperature: 0.7 }, options),
+ ],
+ [
+ 'createImage',
+ (runtime, options) =>
+ runtime.createImage(
+ { model: 'request-model', params: { prompt: 'a cat' } } as any,
+ options,
+ ),
+ ],
+ [
+ 'createVideo',
+ (runtime, options) =>
+ runtime.createVideo(
+ { model: 'request-model', params: { prompt: 'a cat' } } as any,
+ options,
+ ),
+ ],
+ [
+ 'generateObject',
+ (runtime, options) =>
+ runtime.generateObject(
+ {
+ messages: [],
+ model: 'request-model',
+ schema: { name: 'result', schema: { properties: {}, type: 'object' } },
+ },
+ options,
+ ),
+ ],
+ [
+ 'embeddings',
+ (runtime, options) =>
+ runtime.embeddings({ input: 'hello', model: 'request-model' }, options),
+ ],
+ [
+ 'textToSpeech',
+ (runtime, options) =>
+ runtime.textToSpeech({ input: 'hello', model: 'request-model', voice: 'alloy' }, options),
+ ],
+ ])(
+ 'should forward request pricing context to dynamic routers for %s',
+ async (_method, call) => {
+ class MockRuntime implements LobeRuntimeAI {
+ chat = vi.fn().mockResolvedValue('chat-response');
+ createImage = vi.fn().mockResolvedValue({ imageUrl: 'image-url' });
+ createVideo = vi.fn().mockResolvedValue({ inferenceId: 'video-id' });
+ embeddings = vi.fn().mockResolvedValue([]);
+ generateObject = vi.fn().mockResolvedValue({});
+ textToSpeech = vi.fn().mockResolvedValue('speech-response');
+ }
+
+ const dynamicRoutersFunction = vi.fn(() => [
+ {
+ apiType: 'openai' as const,
+ models: ['request-model'],
+ options: {},
+ runtime: MockRuntime as any,
+ },
+ ]);
+ const Runtime = createRouterRuntime({
+ id: 'test-runtime',
+ routers: dynamicRoutersFunction,
+ });
+ const pricingContext = { plan: 'premium', scope: 'personal' } as const;
+
+ await call(new Runtime(), { pricingContext });
+
+ expect(dynamicRoutersFunction).toHaveBeenCalledWith(expect.any(Object), {
+ model: 'request-model',
+ pricingContext,
+ });
+ },
+ );
+
it('should throw NoAvailableProvider error when dynamic routers function returns empty array', async () => {
const emptyRoutersFunction = () => [];
@@ -819,6 +906,54 @@ describe('createRouterRuntime', () => {
expect(mockChatAlwaysFail).toHaveBeenCalledTimes(2);
});
+ it('should fallback when a provider reports insufficient account quota', async () => {
+ const attemptedKeys: string[] = [];
+
+ class AccountBalanceRuntime implements LobeRuntimeAI {
+ private readonly apiKey: string;
+
+ constructor(options: { apiKey: string }) {
+ this.apiKey = options.apiKey;
+ }
+
+ chat = vi.fn().mockImplementation(async () => {
+ attemptedKeys.push(this.apiKey);
+
+ if (this.apiKey === 'key-1') {
+ throw {
+ error: {
+ code: 'invalid_request_error',
+ message: 'Insufficient Balance',
+ type: 'unknown_error',
+ },
+ errorType: AgentRuntimeErrorType.InsufficientQuota,
+ status: 402,
+ };
+ }
+
+ return 'success';
+ });
+ }
+
+ const Runtime = createRouterRuntime({
+ id: 'test-runtime',
+ routers: [
+ {
+ apiType: 'openai',
+ models: ['gpt-4'],
+ options: [{ apiKey: 'key-1' }, { apiKey: 'key-2' }],
+ runtime: AccountBalanceRuntime as any,
+ },
+ ],
+ });
+
+ const runtime = new Runtime();
+ await expect(runtime.chat({ model: 'gpt-4', messages: [], temperature: 0.7 })).resolves.toBe(
+ 'success',
+ );
+ expect(attemptedKeys).toEqual(['key-1', 'key-2']);
+ });
+
it('should throw error when options array is empty', async () => {
const Runtime = createRouterRuntime({
id: 'test-runtime',
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
index 9fe5aa4d343..a155530bae7 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
@@ -2,7 +2,11 @@
* @see https://github.com/lobehub/lobe-chat/discussions/6563
*/
import type { GoogleGenAIOptions } from '@google/genai';
-import type { ChatModelCard } from '@lobechat/types';
+import type {
+ ChatModelCard,
+ ModelPricingContext,
+ RouterRuntimeRequestContext,
+} from '@lobechat/types';
import { AgentRuntimeErrorType } from '@lobechat/types';
import { createTimingHelpers, getDurationMs } from '@lobechat/utils';
import debug from 'debug';
@@ -96,9 +100,7 @@ type Routers =
| RouterInstance[]
| ((
options: LobeClientOptions & Record<string, any>,
- runtimeContext: {
- model?: string;
- },
+ runtimeContext: RouterRuntimeRequestContext,
) => RouterInstance[] | Promise<RouterInstance[]>);
export interface RouteAttemptResult {
@@ -130,6 +132,7 @@ interface RouteAttemptMetadata {
interface RouteAttemptContext {
allowedApiTypes?: ReadonlySet<ApiType>;
metadata?: Record<string, unknown>;
+ pricingContext?: ModelPricingContext;
toolsCount?: number;
user?: string;
}
@@ -322,12 +325,15 @@ export const createRouterRuntime = ({
/**
* Resolve routers configuration and validate
*/
- private async resolveRouters(model?: string): Promise<RouterInstance[]> {
+ 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, { model })
+ ? await this._routers(this._options, runtimeContext)
: this._routers;
if (this._id === 'lobehub') {
@@ -357,9 +363,15 @@ export const createRouterRuntime = ({
}
}
- private async resolveMatchedRouter(model: string): Promise<RouterInstance> {
+ private async resolveMatchedRouter(
+ model: string,
+ pricingContext?: ModelPricingContext,
+ ): Promise<RouterInstance> {
const startedAt = Date.now();
- const resolvedRouters = await this.resolveRouters(model);
+ const resolvedRouters = await this.resolveRouters({
+ model,
+ ...(pricingContext ? { pricingContext } : {}),
+ });
const baseURL = this._options.baseURL;
// Priority 1: Match by baseURLPattern (RegExp only)
@@ -589,8 +601,8 @@ export const createRouterRuntime = ({
routeContext: RouteAttemptContext = {},
): Promise<T> {
const totalStartedAt = Date.now();
- const { allowedApiTypes, metadata, toolsCount, user } = routeContext;
- const matchedRouter = await this.resolveMatchedRouter(model);
+ const { allowedApiTypes, metadata, pricingContext, toolsCount, user } = routeContext;
+ const matchedRouter = await this.resolveMatchedRouter(model, pricingContext);
const sortedRouterOptions = await this.applySortRouterOptions(
matchedRouter,
model,
@@ -874,6 +886,7 @@ export const createRouterRuntime = ({
{
allowedApiTypes: containsRawAudio ? RAW_AUDIO_API_TYPES : undefined,
metadata: options?.metadata,
+ pricingContext: options?.pricingContext,
toolsCount: payload.tools?.length ?? 0,
user: options?.user,
},
@@ -895,7 +908,7 @@ export const createRouterRuntime = ({
return this.runWithFallback(
payload.model,
(runtime) => runtime.createImage!(payload, options),
- { metadata: options?.metadata },
+ { metadata: options?.metadata, pricingContext: options?.pricingContext },
);
}
@@ -903,7 +916,7 @@ export const createRouterRuntime = ({
return this.runWithFallback(
payload.model,
(runtime) => runtime.createVideo!(payload, options),
- { metadata: options?.metadata },
+ { metadata: options?.metadata, pricingContext: options?.pricingContext },
);
}
@@ -925,7 +938,7 @@ export const createRouterRuntime = ({
async handleCreateVideoWebhook(payload: HandleCreateVideoWebhookPayload) {
const model = (payload.body as any)?.model;
- const resolvedRouters = await this.resolveRouters(model);
+ const resolvedRouters = await this.resolveRouters({ model });
const routerOptions = this.normalizeRouterOptions(resolvedRouters[0]);
const { runtime } = await this.createRuntimeFromOption(resolvedRouters[0], routerOptions[0]);
return runtime.handleCreateVideoWebhook!(payload);
@@ -937,6 +950,7 @@ export const createRouterRuntime = ({
(runtime) => runtime.generateObject!(payload, options),
{
metadata: options?.metadata,
+ pricingContext: options?.pricingContext,
toolsCount: payload.tools?.length ?? 0,
user: options?.user,
},
@@ -947,7 +961,11 @@ export const createRouterRuntime = ({
return this.runWithFallback(
payload.model,
(runtime) => runtime.embeddings!(payload, options),
- { metadata: options?.metadata, user: options?.user },
+ {
+ metadata: options?.metadata,
+ pricingContext: options?.pricingContext,
+ user: options?.user,
+ },
);
}
@@ -957,6 +975,7 @@ export const createRouterRuntime = ({
(runtime) => runtime.textToSpeech!(payload, options),
{
metadata: options?.metadata,
+ pricingContext: options?.pricingContext,
user: options?.user,
},
);
diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts
index 86e1c1e0df7..0a19b89c094 100644
--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts
+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts
@@ -1,5 +1,6 @@
// @vitest-environment node
import Anthropic from '@anthropic-ai/sdk';
+import { AgentRuntimeErrorType } from '@lobechat/types';
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { ModelRuntimeDiagnostics } from '../../types/providerDiagnostics';
@@ -7,6 +8,7 @@ import {
createAnthropicCompatibleRuntime,
createDefaultAnthropicClient,
DEFAULT_ANTHROPIC_TIMEOUT,
+ handleDefaultAnthropicError,
} from './index';
vi.mock('@anthropic-ai/sdk', () => {
@@ -143,6 +145,33 @@ describe('createDefaultAnthropicClient', () => {
});
});
+describe('handleDefaultAnthropicError', () => {
+ it('should classify provider balance errors as insufficient quota', () => {
+ expect(
+ handleDefaultAnthropicError(
+ {
+ error: {
+ error: {
+ code: 'invalid_request_error',
+ message: 'Insufficient Balance',
+ type: 'unknown_error',
+ },
+ },
+ status: 402,
+ },
+ { apiKey: 'test-key', baseURL: 'https://api.example.com/anthropic' },
+ ),
+ ).toMatchObject({
+ error: {
+ code: 'invalid_request_error',
+ message: 'Insufficient Balance',
+ type: 'unknown_error',
+ },
+ errorType: AgentRuntimeErrorType.InsufficientQuota,
+ });
+ });
+});
+
describe('createAnthropicCompatibleRuntime', () => {
it('should normalize default baseURL before creating a custom client', () => {
const createClient = vi.fn((options) => ({ baseURL: options.baseURL }) as unknown as Anthropic);
@@ -214,6 +243,48 @@ describe('createAnthropicCompatibleRuntime', () => {
expect(createClient.mock.calls[0][0]).not.toHaveProperty('modelIdMapping');
});
+ it('should classify provider balance errors without a custom error handler', async () => {
+ const messagesCreate = vi.fn().mockRejectedValue({
+ error: {
+ error: {
+ code: 'invalid_request_error',
+ message: 'Insufficient Balance',
+ type: 'unknown_error',
+ },
+ },
+ status: 402,
+ });
+ const Runtime = createAnthropicCompatibleRuntime({
+ chatCompletion: {
+ handlePayload: (payload) => ({
+ max_tokens: 1024,
+ messages: [],
+ model: payload.model,
+ }),
+ },
+ customClient: {
+ createClient: () =>
+ ({
+ baseURL: 'https://api.example.com/anthropic',
+ messages: { create: messagesCreate },
+ }) as unknown as Anthropic,
+ },
+ provider: 'test-provider',
+ });
+ const runtime = new Runtime({ apiKey: 'test-key' });
+
+ await expect(
+ runtime.chat({
+ messages: [{ content: 'hi', role: 'user' }],
+ model: 'test-model',
+ responseMode: 'json',
+ stream: false,
+ } as any),
+ ).rejects.toMatchObject({
+ errorType: AgentRuntimeErrorType.InsufficientQuota,
+ });
+ });
+
it('should retain the exact provider request and raw streaming response diagnostics', async () => {
const rawEvents = [
{
diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts
index 57a0fa55103..1f6379a475b 100644
--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts
+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts
@@ -349,6 +349,15 @@ export const handleDefaultAnthropicError = <T extends Record<string, any> = any>
};
}
+ if (ErrorClassifier.isInsufficientQuota(errorMsg)) {
+ return {
+ endpoint: desensitizedEndpoint,
+ error: errorResult,
+ errorType: AgentRuntimeErrorType.InsufficientQuota,
+ message,
+ };
+ }
+
if (ErrorClassifier.isExceededContextWindow(errorMsg)) {
return {
endpoint: desensitizedEndpoint,
@@ -833,6 +842,16 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =
});
}
+ if (ErrorClassifier.isInsufficientQuota(errorMsg)) {
+ return AgentRuntimeError.chat({
+ endpoint: desensitizedEndpoint,
+ error: errorResult,
+ errorType: AgentRuntimeErrorType.InsufficientQuota,
+ message,
+ provider: this.id,
+ });
+ }
+
if (ErrorClassifier.isExceededContextWindow(errorMsg)) {
return AgentRuntimeError.chat({
endpoint: desensitizedEndpoint,
diff --git a/packages/model-runtime/src/types/pricing.ts b/packages/model-runtime/src/types/pricing.ts
index 2be5e936f43..21cd417bedd 100644
--- a/packages/model-runtime/src/types/pricing.ts
+++ b/packages/model-runtime/src/types/pricing.ts
@@ -1,4 +1 @@
-export interface ModelPricingContext {
- plan: string;
- scope: 'personal';
-}
+export type { ModelPricingContext } from '@lobechat/types';
diff --git a/packages/model-runtime/src/utils/isNonRetryableRequestError.test.ts b/packages/model-runtime/src/utils/isNonRetryableRequestError.test.ts
index 8b994220896..3442985b93a 100644
--- a/packages/model-runtime/src/utils/isNonRetryableRequestError.test.ts
+++ b/packages/model-runtime/src/utils/isNonRetryableRequestError.test.ts
@@ -160,6 +160,20 @@ describe('isNonRetryableRequestError', () => {
).toBe(false);
});
+ it('returns false for standardized provider account balance errors', () => {
+ expect(
+ isNonRetryableRequestError({
+ error: {
+ code: 'invalid_request_error',
+ message: 'Insufficient Balance',
+ type: 'unknown_error',
+ },
+ errorType: AgentRuntimeErrorType.InsufficientQuota,
+ status: 402,
+ }),
+ ).toBe(false);
+ });
+
it('returns false for channel-specific auth and model errors', () => {
expect(
isNonRetryableRequestError({
diff --git a/packages/model-runtime/src/utils/isNonRetryableRequestError.ts b/packages/model-runtime/src/utils/isNonRetryableRequestError.ts
index bc24e067ec0..5453a82de45 100644
--- a/packages/model-runtime/src/utils/isNonRetryableRequestError.ts
+++ b/packages/model-runtime/src/utils/isNonRetryableRequestError.ts
@@ -17,6 +17,7 @@ const RETRYABLE_ERROR_CODES = new Set([
'invalidapikey',
'invalidproviderapikey',
'insufficient_quota',
+ AgentRuntimeErrorType.InsufficientQuota.toLowerCase(),
'model_not_found',
'quota_exceeded',
'rate_limit_exceeded',
diff --git a/packages/openapi/src/services/chat.service.test.ts b/packages/openapi/src/services/chat.service.test.ts
index fc15ecea72b..bd52c3e2dae 100644
--- a/packages/openapi/src/services/chat.service.test.ts
+++ b/packages/openapi/src/services/chat.service.test.ts
@@ -69,8 +69,8 @@ vi.mock('@/server/modules/ModelRuntime', () => ({
}));
describe('ChatService payload construction', () => {
- const buildService = () => {
- const service = new ChatService({} as LobeChatDatabase, 'user-1');
+ const buildService = (workspaceId?: string) => {
+ const service = new ChatService({} as LobeChatDatabase, 'user-1', workspaceId);
// Bypass permission + credential resolution; only the payload is under test.
(service as any).resolveOperationPermission = vi.fn().mockResolvedValue({ isPermitted: true });
(service as any).getApiKey = vi.fn().mockResolvedValue(JSON.stringify({ apiKey: 'k' }));
@@ -112,6 +112,17 @@ describe('ChatService payload construction', () => {
expect(chatMock.mock.calls[0][0]).toMatchObject({ temperature: 0.7 });
});
+
+ it('passes workspace context to the runtime constructor', async () => {
+ await buildService('workspace-1').chat({ messages } as any);
+
+ expect(initModelRuntimeWithUserPayloadMock).toHaveBeenCalledWith(
+ 'p',
+ { apiKey: 'k', userId: 'user-1' },
+ { workspaceId: 'workspace-1' },
+ undefined,
+ );
+ });
});
/**
diff --git a/packages/openapi/src/services/chat.service.ts b/packages/openapi/src/services/chat.service.ts
index 75a068f11ff..003f120f857 100644
--- a/packages/openapi/src/services/chat.service.ts
+++ b/packages/openapi/src/services/chat.service.ts
@@ -373,7 +373,7 @@ export class ChatService extends BaseService {
const modelRuntime = await initModelRuntimeWithUserPayload(
provider,
{ apiKey, userId: this.userId! },
- {},
+ this.workspaceId ? { workspaceId: this.workspaceId } : {},
hooks,
);
diff --git a/packages/types/src/agentRuntime.ts b/packages/types/src/agentRuntime.ts
index f936767ebbd..73c6335b5db 100644
--- a/packages/types/src/agentRuntime.ts
+++ b/packages/types/src/agentRuntime.ts
@@ -1,3 +1,15 @@
+/** Request-scoped pricing inputs resolved before model execution. */
+export interface ModelPricingContext {
+ plan: string;
+ scope: 'personal';
+}
+
+/** Request-scoped data available to dynamic model router resolution. */
+export interface RouterRuntimeRequestContext {
+ model?: string;
+ pricingContext?: ModelPricingContext;
+}
+
export enum RequestTrigger {
AgentSignal = 'agent_signal',
Api = 'api',