🤯 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(model-runtime): support decision models via OpenRouter (#20836)
YuTengjinge92c83578779
diff --git a/apps/cli/src/commands/model.ts b/apps/cli/src/commands/model.tsindex 267a1e6a646..44d243d544a 100644--- a/apps/cli/src/commands/model.ts+++ b/apps/cli/src/commands/model.ts@@ -50,7 +50,7 @@ export function registerModelCommand(program: Command) {.option('--enabled', 'Only show enabled models').option('--type <type>',- 'Filter by model type (chat|embedding|tts|asr|image|video|text2music|realtime)',+ 'Filter by model type (chat|embedding|tts|asr|image|video|text2music|realtime|decision)',).option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)').action(@@ -148,7 +148,7 @@ export function registerModelCommand(program: Command) {.option('--display-name <name>', 'Display name').option('--type <type>',- 'Model type (chat|embedding|tts|asr|image|video|text2music|realtime)',+ 'Model type (chat|embedding|tts|asr|image|video|text2music|realtime|decision)','chat',).action(@@ -174,7 +174,10 @@ export function registerModelCommand(program: Command) {.description('Update model info').requiredOption('--provider <providerId>', 'Provider ID').option('--display-name <name>', 'Display name')- .option('--type <type>', 'Model type (chat|embedding|tts|asr|image|video|text2music|realtime)')+ .option(+ '--type <type>',+ 'Model type (chat|embedding|tts|asr|image|video|text2music|realtime|decision)',+ ).action(async (id: string, options: { displayName?: string; provider: string; type?: string }) => {if (!options.displayName && !options.type) {diff --git a/locales/en-US/modelProvider.json b/locales/en-US/modelProvider.jsonindex 94df9f8a0c6..10c3f8243fd 100644--- a/locales/en-US/modelProvider.json+++ b/locales/en-US/modelProvider.json@@ -289,6 +289,7 @@"providerModels.item.modelConfig.type.extra": "Different model types have distinct use cases and capabilities","providerModels.item.modelConfig.type.options.asr": "Speech-to-Text","providerModels.item.modelConfig.type.options.chat": "Chat",+ "providerModels.item.modelConfig.type.options.decision": "Decision","providerModels.item.modelConfig.type.options.embedding": "Embedding","providerModels.item.modelConfig.type.options.image": "Image Generation","providerModels.item.modelConfig.type.options.realtime": "Real-time Chat",@@ -343,6 +344,7 @@"providerModels.tabs.all": "All","providerModels.tabs.asr": "ASR","providerModels.tabs.chat": "Chat",+ "providerModels.tabs.decision": "Decision","providerModels.tabs.embedding": "Embedding","providerModels.tabs.image": "Image","providerModels.tabs.tts": "TTS",diff --git a/locales/zh-CN/modelProvider.json b/locales/zh-CN/modelProvider.jsonindex 229349e4f9d..08196c5292f 100644--- a/locales/zh-CN/modelProvider.json+++ b/locales/zh-CN/modelProvider.json@@ -289,6 +289,7 @@"providerModels.item.modelConfig.type.extra": "不同模型类型拥有差异化的使用场景与能力","providerModels.item.modelConfig.type.options.asr": "语音转文本","providerModels.item.modelConfig.type.options.chat": "对话",+ "providerModels.item.modelConfig.type.options.decision": "决策","providerModels.item.modelConfig.type.options.embedding": "向量化","providerModels.item.modelConfig.type.options.image": "图片生成","providerModels.item.modelConfig.type.options.realtime": "实时对话",@@ -343,6 +344,7 @@"providerModels.tabs.all": "全部","providerModels.tabs.asr": "ASR","providerModels.tabs.chat": "对话",+ "providerModels.tabs.decision": "决策","providerModels.tabs.embedding": "向量化","providerModels.tabs.image": "图片","providerModels.tabs.tts": "TTS",diff --git a/packages/builtin-skills/src/lobehub/references/model.ts b/packages/builtin-skills/src/lobehub/references/model.tsindex e174580681a..fef88a3b287 100644--- a/packages/builtin-skills/src/lobehub/references/model.ts+++ b/packages/builtin-skills/src/lobehub/references/model.ts@@ -27,6 +27,7 @@ The \`--type\` filter accepts the following values:| \`video\` | Video generation models || \`text2music\` | Music generation models || \`realtime\` | Realtime audio/video models |+| \`decision\` | Decision models that answer typed questions with probabilities |## Tipsdiff --git a/packages/locales/src/default/modelProvider.ts b/packages/locales/src/default/modelProvider.tsindex bfe0866ca2e..18ecc4c776b 100644--- a/packages/locales/src/default/modelProvider.ts+++ b/packages/locales/src/default/modelProvider.ts@@ -377,6 +377,7 @@ export default {'Different model types have distinct use cases and capabilities','providerModels.item.modelConfig.type.options.asr': 'Speech-to-Text','providerModels.item.modelConfig.type.options.chat': 'Chat',+ 'providerModels.item.modelConfig.type.options.decision': 'Decision','providerModels.item.modelConfig.type.options.embedding': 'Embedding','providerModels.item.modelConfig.type.options.image': 'Image Generation','providerModels.item.modelConfig.type.options.realtime': 'Real-time Chat',@@ -436,6 +437,7 @@ export default {'providerModels.tabs.all': 'All','providerModels.tabs.asr': 'ASR','providerModels.tabs.chat': 'Chat',+ 'providerModels.tabs.decision': 'Decision','providerModels.tabs.embedding': 'Embedding','providerModels.tabs.image': 'Image','providerModels.tabs.tts': 'TTS',diff --git a/packages/model-bank/package.json b/packages/model-bank/package.jsonindex 77990467a2e..12e59ce550f 100644--- a/packages/model-bank/package.json+++ b/packages/model-bank/package.json@@ -65,7 +65,7 @@"./imageParameters": "./src/const/imageParameters.ts","./opencodeCodingPlan": "./src/aiModels/opencodeCodingPlan.ts","./opencodeZen": "./src/aiModels/opencodeZen.ts",- "./openrouter": "./src/aiModels/openrouter.ts",+ "./openrouter": "./src/aiModels/openrouter/index.ts","./perplexity": "./src/aiModels/perplexity.ts","./ppio": "./src/aiModels/ppio.ts","./qiniu": "./src/aiModels/qiniu.ts",diff --git a/packages/model-bank/src/aiModels/openrouter/decision.ts b/packages/model-bank/src/aiModels/openrouter/decision.tsnew file mode 100644index 00000000000..534b9732eb7--- /dev/null+++ b/packages/model-bank/src/aiModels/openrouter/decision.ts@@ -0,0 +1,31 @@+import type { AIDecisionModelCard } from '../../types/aiModel';++// https://openrouter.ai/models?output_modalities=decisions+export const openrouterDecisionModels: AIDecisionModelCard[] = [+ {+ contextWindowTokens: 64_000,+ description:+ 'TypeSafe Jev is a System One decision model: it answers yes/no, choice, and score questions with calibrated probabilities instead of generating text.',+ displayName: 'Jev 1.13',+ id: 'typesafe/jev-1.13',+ pricing: {+ currency: 'USD',+ units: [{ name: 'textInput', rate: 0.042, strategy: 'fixed', unit: 'millionTokens' }],+ },+ releasedAt: '2026-09-17',+ type: 'decision',+ },+ {+ contextWindowTokens: 1_050_000,+ description:+ 'GPT-6 Luna served through the Decisions API: returns typed answers with probabilities for caller-defined questions, billed on input tokens only.',+ displayName: 'GPT-6 Luna Decisions',+ id: 'openai/gpt-6-luna-decisions',+ pricing: {+ currency: 'USD',+ units: [{ name: 'textInput', rate: 0.1, strategy: 'fixed', unit: 'millionTokens' }],+ },+ releasedAt: '2026-10-06',+ type: 'decision',+ },+];diff --git a/packages/model-bank/src/aiModels/openrouter.ts b/packages/model-bank/src/aiModels/openrouter/index.tssimilarity index 99%rename from packages/model-bank/src/aiModels/openrouter.tsrename to packages/model-bank/src/aiModels/openrouter/index.tsindex cfc15c4ecd9..e46abda0d5c 100644--- a/packages/model-bank/src/aiModels/openrouter.ts+++ b/packages/model-bank/src/aiModels/openrouter/index.ts@@ -1,4 +1,5 @@-import type { AIChatModelCard } from '../types/aiModel';+import type { AIChatModelCard } from '../../types/aiModel';+import { openrouterDecisionModels } from './decision';// https://openrouter.ai/docs/api-reference/list-available-modelsconst openrouterChatModels: AIChatModelCard[] = [@@ -1203,6 +1204,5 @@ const openrouterChatModels: AIChatModelCard[] = [},];-export const allModels = [...openrouterChatModels];-+export const allModels = [...openrouterChatModels, ...openrouterDecisionModels];export default allModels;diff --git a/packages/model-bank/src/types/aiModel.ts b/packages/model-bank/src/types/aiModel.tsindex 70a93e347c2..af36f2a112a 100644--- a/packages/model-bank/src/types/aiModel.ts+++ b/packages/model-bank/src/types/aiModel.ts@@ -21,6 +21,7 @@ export const AiModelTypeSchema = z.enum(['video','text2music','realtime',+ 'decision',] as const);export type AiModelType = z.infer<typeof AiModelTypeSchema>;@@ -676,6 +677,16 @@ export interface AIASRModelCard extends AIBaseModelCard {type: 'asr';}+/**+ * Decision models answer caller-defined typed questions with calibrated probabilities+ * instead of generating text, and are called through `decide` rather than `chat`.+ * @see https://openrouter.ai/docs/guides/community/jev+ */+export interface AIDecisionModelCard extends AIBaseModelCard {+ pricing?: Pricing;+ type: 'decision';+}+export interface AIRealtimeModelCard extends AIBaseModelCard {abilities?: {/**diff --git a/packages/model-runtime/src/core/BaseAI.ts b/packages/model-runtime/src/core/BaseAI.tsindex 204a46dfe86..de622750d83 100644--- a/packages/model-runtime/src/core/BaseAI.ts+++ b/packages/model-runtime/src/core/BaseAI.ts@@ -13,6 +13,9 @@ import type {CreateVideoMethodOptions,CreateVideoPayload,CreateVideoResult,+ DecisionOptions,+ DecisionPayload,+ DecisionResponse,Embeddings,EmbeddingsOptions,EmbeddingsPayload,@@ -42,6 +45,12 @@ export interface LobeRuntimeAI {options?: CreateVideoMethodOptions,) => Promise<CreateVideoResult>;+ /**+ * Answer typed questions with probabilities through a decision model.+ * Only implemented by providers that serve decision models.+ */+ decide?: (payload: DecisionPayload, options?: DecisionOptions) => Promise<DecisionResponse>;+embeddings?: (payload: EmbeddingsPayload, options?: EmbeddingsOptions) => Promise<Embeddings[]>;generateObject?: (diff --git a/packages/model-runtime/src/core/ModelRuntime.decide.test.ts b/packages/model-runtime/src/core/ModelRuntime.decide.test.tsnew file mode 100644index 00000000000..6e737dcacce--- /dev/null+++ b/packages/model-runtime/src/core/ModelRuntime.decide.test.ts@@ -0,0 +1,98 @@+// @vitest-environment node+import { describe, expect, it, vi } from 'vitest';++import { AgentRuntimeErrorType } from '../types/error';+import { ModelRuntime, type ModelRuntimeHooks } from './ModelRuntime';++vi.mock('../providers/lobehub', () => ({+ LobeHubAI: class LobeHubAI {},+}));++const createMockRuntime = (hooks?: ModelRuntimeHooks) => {+ const mockRuntimeAI = { chat: vi.fn() } as any;+ return { runtime: new ModelRuntime(mockRuntimeAI, hooks), mockRuntimeAI };+};++const decidePayload = {+ model: 'typesafe/jev-1.13',+ questions: {+ refund: {+ criteria: { false: 'No refund requested.', true: 'Asks for money back.' },+ instructions: 'Is the customer asking for a refund?',+ type: 'boolean' as const,+ },+ },+ state: 'I was charged twice and want my money back.',+};++const decision = {+ answers: { refund: { probability: 0.99, type: 'boolean' } },+ model: 'typesafe/jev-1.13-20260917',+};++describe('ModelRuntime decide hooks', () => {+ it('passes the response and provider usage to onDecideFinal after beforeDecide', async () => {+ const usage = { cost: 0.000_018, inputTextTokens: 436, totalInputTokens: 436 };+ const beforeDecide = vi.fn();+ const onDecideFinal = vi.fn();+ const { runtime, mockRuntimeAI } = createMockRuntime({ beforeDecide, onDecideFinal });+ mockRuntimeAI.decide = vi.fn(async (_payload: any, options: any) => {+ await options.onUsage(usage);+ return decision;+ });++ const options = { user: 'u1' };+ const result = await runtime.decide(decidePayload, options);++ expect(result).toEqual(decision);+ expect(beforeDecide).toHaveBeenCalledWith(decidePayload, options);+ expect(onDecideFinal).toHaveBeenCalledWith(+ { latencyMs: expect.any(Number), response: decision, usage },+ { options, payload: decidePayload },+ );+ });++ it('passes the provider-reported charge to onDecideFinal and the caller callback', async () => {+ const onDecideFinal = vi.fn();+ const onProviderReportedCost = vi.fn();+ const { runtime, mockRuntimeAI } = createMockRuntime({ onDecideFinal });+ mockRuntimeAI.decide = vi.fn(async (_payload: any, options: any) => {+ await options.onProviderReportedCost(0.000_018);+ return decision;+ });++ const result = await runtime.decide(decidePayload, { onProviderReportedCost });++ expect(result).toEqual(decision);+ expect(onProviderReportedCost).toHaveBeenCalledWith(0.000_018);+ expect(onDecideFinal).toHaveBeenCalledWith(+ expect.objectContaining({ providerReportedCost: 0.000_018, response: decision }),+ expect.anything(),+ );+ });++ it('calls onDecideError and re-throws when the provider fails', async () => {+ const providerError = { errorType: 'ProviderBizError', error: { message: 'boom' } };+ const onDecideError = vi.fn();+ const onDecideFinal = vi.fn();+ const { runtime, mockRuntimeAI } = createMockRuntime({ onDecideError, onDecideFinal });+ mockRuntimeAI.decide = vi.fn().mockRejectedValue(providerError);++ await expect(runtime.decide(decidePayload)).rejects.toBe(providerError);+ expect(onDecideFinal).not.toHaveBeenCalled();+ expect(onDecideError).toHaveBeenCalledWith(providerError, {+ options: undefined,+ payload: decidePayload,+ });+ });++ it('rejects instead of resolving undefined when the provider cannot decide', async () => {+ const beforeDecide = vi.fn();+ const { runtime } = createMockRuntime({ beforeDecide });++ await expect(runtime.decide(decidePayload)).rejects.toMatchObject({+ errorType: AgentRuntimeErrorType.CapabilityNotSupported,+ });+ expect(beforeDecide).not.toHaveBeenCalled();+ });+});diff --git a/packages/model-runtime/src/core/ModelRuntime.ts b/packages/model-runtime/src/core/ModelRuntime.tsindex a6f82b897ac..e9f987bf7b2 100644--- a/packages/model-runtime/src/core/ModelRuntime.ts+++ b/packages/model-runtime/src/core/ModelRuntime.ts@@ -12,6 +12,10 @@ import type {ChatCompletionErrorPayload,ChatMethodOptions,ChatStreamPayload,+ DecisionOptions,+ DecisionPayload,+ DecisionQuestions,+ DecisionResponse,EmbeddingsOptions,EmbeddingsPayload,GenerateObjectOptions,@@ -74,6 +78,9 @@ const getLobeHubTimingMetadata = (options?: {}): Record<string, unknown> | undefined =>options?.metadata?.provider === 'lobehub' ? options.metadata : undefined;+const getRuntimeProviderId = (runtime: LobeRuntimeAI) =>+ 'id' in runtime && typeof runtime.id === 'string' ? runtime.id : 'unknown';+const buildGenerateObjectSpeed = (startedAt: number, usage: ModelUsage): ModelPerformance => {const latency = Math.max(Date.now() - startedAt, 0);const totalOutputTokens = usage.totalOutputTokens ?? usage.outputTextTokens ?? 0;@@ -107,6 +114,7 @@ export interface ModelRuntimeHooks {payload: CreateVideoPayload,options?: CreateVideoMethodOptions,) => Promise<void>;+ beforeDecide?: (payload: DecisionPayload, options?: DecisionOptions) => Promise<void>;beforeEmbeddings?: (payload: EmbeddingsPayload, options?: EmbeddingsOptions) => Promise<void>;beforeGenerateObject?: (payload: GenerateObjectPayload,@@ -147,6 +155,27 @@ export interface ModelRuntimeHooks {context: { options?: ChatMethodOptions; payload: ChatStreamPayload },) => void | Promise<void>;+ onDecideError?: (+ error: ChatCompletionErrorPayload,+ context: { options?: DecisionOptions; payload: DecisionPayload },+ ) => void | Promise<void>;++ /**+ * Fires once after a successful decision, including when some answers are refusals.+ * `usage` is undefined when the provider reports none, so consumers can still settle or+ * release anything taken in `beforeDecide`.+ */+ onDecideFinal?: (+ data: {+ latencyMs: number;+ /** USD charge reported by the upstream provider. Server-side only, like chat's. */+ providerReportedCost?: number;+ response: DecisionResponse;+ usage?: ModelUsage;+ },+ context: { options?: DecisionOptions; payload: DecisionPayload },+ ) => void | Promise<void>;+onEmbeddingsError?: (error: ChatCompletionErrorPayload,context: { options?: EmbeddingsOptions; payload: EmbeddingsPayload },@@ -595,6 +624,68 @@ export class ModelRuntime {}}+ async decide<Q extends DecisionQuestions>(+ payload: DecisionPayload<Q>,+ options?: DecisionOptions,+ ): Promise<DecisionResponse<Q>> {+ // Unlike the optional-chained passthroughs above, an unsupported provider must not+ // resolve to `undefined`: callers branch on the answers and would read it as a result.+ // Thrown before the hooks run, so there is nothing for `onDecideError` to release.+ const decide = this._runtime.decide?.bind(this._runtime);+ if (!decide) {+ throw AgentRuntimeError.chat({+ error: new Error('Decision models are not supported by this provider'),+ errorType: AgentRuntimeErrorType.CapabilityNotSupported,+ provider: getRuntimeProviderId(this._runtime),+ });+ }++ try {+ const hookOptions = this._hooks?.beforeDecide && !options ? {} : options;+ await this._hooks?.beforeDecide?.(payload, hookOptions);++ const startTime = Date.now();+ let usage: ModelUsage | undefined;+ let providerReportedCost: number | undefined;+ const finalOptions = this._hooks?.onDecideFinal+ ? {+ ...hookOptions,+ onProviderReportedCost: async (cost: number) => {+ providerReportedCost = cost;+ await hookOptions?.onProviderReportedCost?.(cost);+ },+ onUsage: async (reported: ModelUsage) => {+ usage = reported;+ await hookOptions?.onUsage?.(reported);+ },+ }+ : hookOptions;++ const response = await decide(payload, finalOptions);++ if (this._hooks?.onDecideFinal) {+ try {+ await this._hooks.onDecideFinal(+ { latencyMs: Date.now() - startTime, providerReportedCost, response, usage },+ { options, payload },+ );+ } catch (e) {+ console.error('[ModelRuntime] onDecideFinal hook error:', e);+ }+ }++ return response as DecisionResponse<Q>;+ } catch (error) {+ if (this._hooks?.onDecideError) {+ await this._hooks.onDecideError(error as ChatCompletionErrorPayload, {+ options,+ payload,+ });+ }+ throw error;+ }+ }+async pullModel(params: PullModelParams, options?: ModelRequestOptions) {return this._runtime.pullModel?.(params, options);}diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.decide.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.decide.test.tsnew file mode 100644index 00000000000..9c384c97984--- /dev/null+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.decide.test.ts@@ -0,0 +1,78 @@+import { AgentRuntimeErrorType, RequestTrigger } from '@lobechat/types';+import { afterEach, describe, expect, it, vi } from 'vitest';++import type { LobeRuntimeAI } from '../BaseAI';+import { createRouterRuntime } from './createRuntime';++describe('createRouterRuntime decide', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllEnvs();+ });++ it('should route decide calls and record the lobehub route attempt', async () => {+ vi.stubEnv('NODE_ENV', 'development');+ const decision = {+ answers: { refund: { probability: 0.9, type: 'boolean' } },+ model: 'jev',+ };+ const mockDecide = vi.fn().mockResolvedValue(decision);++ class MockRuntime implements LobeRuntimeAI {+ decide = mockDecide;+ }++ const Runtime = createRouterRuntime({+ id: 'lobehub',+ routers: [+ {+ apiType: 'openai',+ models: ['typesafe/jev-1.13'],+ options: { id: 'channel-1' },+ runtime: MockRuntime as any,+ },+ ],+ });++ const runtime = new Runtime({ userId: 'user-1' });+ const metadata: Record<string, unknown> = { trigger: RequestTrigger.Api };++ await expect(+ runtime.decide(+ {+ model: 'typesafe/jev-1.13',+ questions: {+ refund: {+ criteria: { false: 'no', true: 'yes' },+ instructions: 'Refund request?',+ type: 'boolean',+ },+ },+ state: 'Give me my money back',+ },+ { metadata, user: 'user-1' },+ ),+ ).resolves.toEqual(decision);+ expect(metadata.routeAttempt).toEqual(expect.objectContaining({ success: true }));+ });++ it('should reject decide when the matched runtime cannot decide', async () => {+ class MockRuntime implements LobeRuntimeAI {}++ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ routers: [+ {+ apiType: 'openai',+ models: ['typesafe/jev-1.13'],+ options: {},+ runtime: MockRuntime as any,+ },+ ],+ });++ await expect(+ new Runtime().decide({ model: 'typesafe/jev-1.13', questions: {}, state: 'x' }),+ ).rejects.toMatchObject({ errorType: AgentRuntimeErrorType.CapabilityNotSupported });+ });+});diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.tsindex edd4ef3a0bc..1fc145273b5 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts@@ -2,41 +2,30 @@* @see https://github.com/lobehub/lobe-chat/discussions/6563*/import type { GoogleGenAIOptions } from '@google/genai';-import type {- ChatModelCard,- ModelPricingContext,- RouterRuntimeRequestContext,-} from '@lobechat/types';+import type { ModelPricingContext, RouterRuntimeRequestContext } from '@lobechat/types';import { AgentRuntimeErrorType } from '@lobechat/types';import { createTimingHelpers, getDurationMs } from '@lobechat/utils';import debug from 'debug';import { nanoid } from 'nanoid';-import type { ClientOptions } from 'openai';-import type OpenAI from 'openai';-import type { Stream } from 'openai/streaming';import { LobeOpenAI } from '../../providers/openai';import { LobeVertexAI } from '../../providers/vertexai';import type {ASROptions,ASRPayload,- ChatCompletionErrorPayload,ChatMethodOptions,- ChatStreamCallbacks,ChatStreamPayload,CreateImageMethodOptions,CreateImagePayload,- CreateImageResponse,CreateVideoMethodOptions,CreateVideoPayload,- CreateVideoResult,+ DecisionOptions,+ DecisionPayload,EmbeddingsOptions,EmbeddingsPayload,GenerateObjectOptions,GenerateObjectPayload,HandleCreateVideoWebhookPayload,- HandleCreateVideoWebhookResult,- ILobeAgentRuntimeErrorType,TextToSpeechPayload,VideoPollingRoute,} from '../../types';@@ -48,73 +37,32 @@ import { safeParseJSON } from '../../utils/safeParseJSON';import { setRuntimeSignatureScopeSource } from '../../utils/signatureScope';import { createVideoWithCompletionMode } from '../../utils/videoCompletionMode';import type { LobeRuntimeAI } from '../BaseAI';-import type {- CreateImageOptions,- CreateVideoOptions,- CustomClientOptions,-} from '../openaiCompatibleFactory';-import type { ApiType, RuntimeClass } from './apiTypes';+import type { ApiType } from './apiTypes';import { getChatAttemptObservation, observeChatAttempt } from './chatAttempt';import type { ChatStreamFallbackAttempt } from './chatStreamFallback';import { createChatStreamFallbackResponse } from './chatStreamFallback';-import type { RouteAttemptFinished, RouteAttemptResult, RouteAttemptStart } from './routeAttempt';+import type { RouteAttemptResult, RouteAttemptStart } from './routeAttempt';import { createRouteRequestTasks } from './routeRequestTasks';+import type {+ CreateRouterRuntimeOptions,+ LobeClientOptions,+ RouterInstance,+ RouterOptionItem,+ RouterRuntimeMethod,+ Routers,+} from './routerOptions';export type { RouteAttemptResult } from './routeAttempt';+export type {+ CreateRouterRuntimeOptions,+ RouterRuntimeMethod,+ RouteSuccessParams,+ SortRouterOptionsParams,+} from './routerOptions';const log = debug('lobe-model-runtime:router-runtime');const { logger: timing } = createTimingHelpers('lobe-server:chat:lobehub:timing');-interface ProviderIniOptions extends Record<string, any> {- accessKeyId?: string;- accessKeySecret?: string;- apiKey?: string;- apiVersion?: string;- baseURL?: string;- baseURLOrAccountID?: string;- dangerouslyAllowBrowser?: boolean;- modelIdMapping?: Record<string, string>;- region?: string;- sdkType?: string;- 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?: ApiType;- id?: string;- remark?: string;- /** Relative share of new user bindings; zero keeps the channel as fallback only. */- weight?: number;-}--type RouterOptions = RouterOptionItem | RouterOptionItem[];--interface RouterInstance {- apiType: ApiType;- baseURLPattern?: RegExp;- id?: string;- models?: string[];- options: RouterOptions;- runtime?: RuntimeClass;-}--// OpenAI SDK v6 widened `apiKey` to `string | ApiKeySetter`; lobehub only ever-// passes a plain string, so narrow it back to keep `.trim()` / string assignments valid.-type LobeClientOptions = Omit<ClientOptions, 'apiKey'> & { apiKey?: string };-type ConstructorOptions<T extends Record<string, any> = any> = LobeClientOptions & T;--type Routers =- | RouterInstance[]- | ((- options: LobeClientOptions & Record<string, any>,- runtimeContext: RouterRuntimeRequestContext,- ) => RouterInstance[] | Promise<RouterInstance[]>);-interface RouteAttemptMetadata {apiType: string;channelId?: string;@@ -153,122 +101,6 @@ interface RouteAttemptContextValidationParams extends RouteAttemptContext {routerId?: string;}-export interface SortRouterOptionsParams {- metadata?: Record<string, unknown>;- method: RouterRuntimeMethod;- model: string;- options: RouterOptionItem[];- routerId?: string;- userId?: string;-}--export interface RouteSuccessParams {- channelId?: string;- channelWeight?: number;- firstChannelId?: string;- method: RouterRuntimeMethod;- model: string;- routeRequestManaged?: boolean;- routerId?: string;- trackDeferredWork?: (task: Promise<void>) => void;- userId?: string;- weighted: boolean;-}--export type RouterRuntimeMethod =- | 'chat'- | 'createImage'- | 'createVideo'- | 'embeddings'- | 'generateObject'- | 'textToSpeech'- | 'transcribe';--export interface CreateRouterRuntimeOptions<T extends Record<string, any> = any> {- apiKey?: string;- chatCompletion?: {- excludeUsage?: boolean;- handleError?: (- error: any,- options: ConstructorOptions<T>,- ) => Omit<ChatCompletionErrorPayload, 'provider'> | undefined;- handlePayload?: (- payload: ChatStreamPayload,- options: ConstructorOptions<T>,- ) => OpenAI.ChatCompletionCreateParamsStreaming;- handleStream?: (- stream: Stream<OpenAI.ChatCompletionChunk> | ReadableStream,- { callbacks, inputStartAt }: { callbacks?: ChatStreamCallbacks; inputStartAt?: number },- ) => ReadableStream;- handleStreamBizErrorType?: (error: {- message: string;- name: string;- }) => ILobeAgentRuntimeErrorType | undefined;- handleTransformResponseToStream?: (- data: OpenAI.ChatCompletion,- ) => ReadableStream<OpenAI.ChatCompletionChunk>;- noUserId?: boolean;- };- constructorOptions?: ConstructorOptions<T>;- createImage?: (- payload: CreateImagePayload,- options: CreateImageOptions,- ) => Promise<CreateImageResponse>;- createVideo?: (- payload: CreateVideoPayload,- options: CreateVideoOptions,- ) => Promise<CreateVideoResult>;- customClient?: CustomClientOptions<T>;- debug?: {- chatCompletion: () => boolean;- responses?: () => boolean;- };- defaultHeaders?: Record<string, any>;- errorType?: {- bizError: ILobeAgentRuntimeErrorType;- invalidAPIKey: ILobeAgentRuntimeErrorType;- };- handleCreateVideoWebhook?: (- payload: HandleCreateVideoWebhookPayload,- options: CreateVideoOptions,- ) => Promise<HandleCreateVideoWebhookResult>;- id: string;- models?:- | ((params: { client: OpenAI; options?: ConstructorOptions<T> }) => Promise<ChatModelCard[]>)- | {- transformModel?: (model: OpenAI.Model) => ChatModelCard;- };- onRouteAttempt?: (result: RouteAttemptResult) => Promise<void>;- onRouteAttemptFinished?: (result: RouteAttemptFinished) => Promise<void>;- /** Awaited before returning so a successful fallback can update routing affinity. */- onRouteSuccess?: (result: RouteSuccessParams) => void | Promise<void>;- responses?: {- handlePayload?: (- payload: ChatStreamPayload,- options: ConstructorOptions<T>,- ) => ChatStreamPayload;- };- routers: Routers;- /** Register once while the request context is available. */- scheduleRouteRequestSettled?: (settled: Promise<void>) => void | Promise<void>;- shouldFallbackChatAttempt?: (result: RouteAttemptFinished) => boolean | Promise<boolean>;- shouldStopFallback?: (params: {- error: unknown;- metadata?: Record<string, unknown>;- 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 = ({id,routers,@@ -1382,6 +1214,30 @@ export const createRouterRuntime = ({{ metadata: options?.metadata, method: 'transcribe', user: options?.user },);}++ async decide(payload: DecisionPayload, options?: DecisionOptions) {+ return this.runWithFallback(+ payload.model,+ (runtime) => {+ // Route options pick runtimes by apiType, and most of those classes cannot serve+ // decision models; fail this attempt explicitly so fallback can move on.+ if (!runtime.decide) {+ throw AgentRuntimeError.chat({+ error: new Error('Decision models are not supported by the matched runtime'),+ errorType: AgentRuntimeErrorType.CapabilityNotSupported,+ provider: this._id,+ });+ }+ return runtime.decide(payload, options);+ },+ {+ metadata: options?.metadata,+ method: 'decide',+ pricingContext: options?.pricingContext,+ user: options?.user,+ },+ );+ }};};diff --git a/packages/model-runtime/src/core/RouterRuntime/routerOptions.ts b/packages/model-runtime/src/core/RouterRuntime/routerOptions.tsnew file mode 100644index 00000000000..b8926fc8d0f--- /dev/null+++ b/packages/model-runtime/src/core/RouterRuntime/routerOptions.ts@@ -0,0 +1,191 @@+import type { ChatModelCard, RouterRuntimeRequestContext } from '@lobechat/types';+import type { ClientOptions } from 'openai';+import type OpenAI from 'openai';+import type { Stream } from 'openai/streaming';++import type {+ ChatCompletionErrorPayload,+ ChatStreamCallbacks,+ ChatStreamPayload,+ CreateImagePayload,+ CreateImageResponse,+ CreateVideoPayload,+ CreateVideoResult,+ HandleCreateVideoWebhookPayload,+ HandleCreateVideoWebhookResult,+ ILobeAgentRuntimeErrorType,+} from '../../types';+import type {+ CreateImageOptions,+ CreateVideoOptions,+ CustomClientOptions,+} from '../openaiCompatibleFactory';+import type { ApiType, RuntimeClass } from './apiTypes';+import type { RouteAttemptFinished, RouteAttemptResult } from './routeAttempt';++export interface ProviderIniOptions extends Record<string, any> {+ accessKeyId?: string;+ accessKeySecret?: string;+ apiKey?: string;+ apiVersion?: string;+ baseURL?: string;+ baseURLOrAccountID?: string;+ dangerouslyAllowBrowser?: boolean;+ modelIdMapping?: Record<string, string>;+ region?: string;+ sdkType?: string;+ 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.+ */+export interface RouterOptionItem extends ProviderIniOptions {+ apiType?: ApiType;+ id?: string;+ remark?: string;+ /** Relative share of new user bindings; zero keeps the channel as fallback only. */+ weight?: number;+}++export type RouterOptions = RouterOptionItem | RouterOptionItem[];++export interface RouterInstance {+ apiType: ApiType;+ baseURLPattern?: RegExp;+ id?: string;+ models?: string[];+ options: RouterOptions;+ runtime?: RuntimeClass;+}++// OpenAI SDK v6 widened `apiKey` to `string | ApiKeySetter`; lobehub only ever+// passes a plain string, so narrow it back to keep `.trim()` / string assignments valid.+export type LobeClientOptions = Omit<ClientOptions, 'apiKey'> & { apiKey?: string };+export type ConstructorOptions<T extends Record<string, any> = any> = LobeClientOptions & T;++export type Routers =+ | RouterInstance[]+ | ((+ options: LobeClientOptions & Record<string, any>,+ runtimeContext: RouterRuntimeRequestContext,+ ) => RouterInstance[] | Promise<RouterInstance[]>);++export interface SortRouterOptionsParams {+ metadata?: Record<string, unknown>;+ method: RouterRuntimeMethod;+ model: string;+ options: RouterOptionItem[];+ routerId?: string;+ userId?: string;+}++export interface RouteSuccessParams {+ channelId?: string;+ channelWeight?: number;+ firstChannelId?: string;+ method: RouterRuntimeMethod;+ model: string;+ routeRequestManaged?: boolean;+ routerId?: string;+ trackDeferredWork?: (task: Promise<void>) => void;+ userId?: string;+ weighted: boolean;+}++export type RouterRuntimeMethod =+ | 'chat'+ | 'createImage'+ | 'createVideo'+ | 'decide'+ | 'embeddings'+ | 'generateObject'+ | 'textToSpeech'+ | 'transcribe';++export interface CreateRouterRuntimeOptions<T extends Record<string, any> = any> {+ apiKey?: string;+ chatCompletion?: {+ excludeUsage?: boolean;+ handleError?: (+ error: any,+ options: ConstructorOptions<T>,+ ) => Omit<ChatCompletionErrorPayload, 'provider'> | undefined;+ handlePayload?: (+ payload: ChatStreamPayload,+ options: ConstructorOptions<T>,+ ) => OpenAI.ChatCompletionCreateParamsStreaming;+ handleStream?: (+ stream: Stream<OpenAI.ChatCompletionChunk> | ReadableStream,+ { callbacks, inputStartAt }: { callbacks?: ChatStreamCallbacks; inputStartAt?: number },+ ) => ReadableStream;+ handleStreamBizErrorType?: (error: {+ message: string;+ name: string;+ }) => ILobeAgentRuntimeErrorType | undefined;+ handleTransformResponseToStream?: (+ data: OpenAI.ChatCompletion,+ ) => ReadableStream<OpenAI.ChatCompletionChunk>;+ noUserId?: boolean;+ };+ constructorOptions?: ConstructorOptions<T>;+ createImage?: (+ payload: CreateImagePayload,+ options: CreateImageOptions,+ ) => Promise<CreateImageResponse>;+ createVideo?: (+ payload: CreateVideoPayload,+ options: CreateVideoOptions,+ ) => Promise<CreateVideoResult>;+ customClient?: CustomClientOptions<T>;+ debug?: {+ chatCompletion: () => boolean;+ responses?: () => boolean;+ };+ defaultHeaders?: Record<string, any>;+ errorType?: {+ bizError: ILobeAgentRuntimeErrorType;+ invalidAPIKey: ILobeAgentRuntimeErrorType;+ };+ handleCreateVideoWebhook?: (+ payload: HandleCreateVideoWebhookPayload,+ options: CreateVideoOptions,+ ) => Promise<HandleCreateVideoWebhookResult>;+ id: string;+ models?:+ | ((params: { client: OpenAI; options?: ConstructorOptions<T> }) => Promise<ChatModelCard[]>)+ | {+ transformModel?: (model: OpenAI.Model) => ChatModelCard;+ };+ onRouteAttempt?: (result: RouteAttemptResult) => Promise<void>;+ onRouteAttemptFinished?: (result: RouteAttemptFinished) => Promise<void>;+ /** Awaited before returning so a successful fallback can update routing affinity. */+ onRouteSuccess?: (result: RouteSuccessParams) => void | Promise<void>;+ responses?: {+ handlePayload?: (+ payload: ChatStreamPayload,+ options: ConstructorOptions<T>,+ ) => ChatStreamPayload;+ };+ routers: Routers;+ /** Register once while the request context is available. */+ scheduleRouteRequestSettled?: (settled: Promise<void>) => void | Promise<void>;+ shouldFallbackChatAttempt?: (result: RouteAttemptFinished) => boolean | Promise<boolean>;+ shouldStopFallback?: (params: {+ error: unknown;+ metadata?: Record<string, unknown>;+ 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[]>;+}diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/decide.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/decide.test.tsnew file mode 100644index 00000000000..73beac2632d--- /dev/null+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/decide.test.ts@@ -0,0 +1,310 @@+// @vitest-environment node+import { afterEach, describe, expect, it, vi } from 'vitest';++import type { DecisionPayload } from '../../types';+import { AgentRuntimeErrorType } from '../../types/error';+import { createOpenAICompatibleRuntime } from './index';++// Price from the real OpenRouter cards so the test also covers the decision card's pricing.+vi.mock('@lobechat/business-model-bank/model-config', async () => {+ const { default: openrouterModels } = await import('model-bank/openrouter');+ return {+ loadModels: async () =>+ openrouterModels.map((model) => ({ ...model, providerId: 'openrouter' })),+ };+});++const DecideRuntime = createOpenAICompatibleRuntime({+ baseURL: 'https://openrouter.ai/api/v1',+ decide: { path: '/systemone' },+ provider: 'openrouter',+});++const createInstance = () => new DecideRuntime({ apiKey: 'test-key' });++const payload = {+ model: 'typesafe/jev-1.13',+ questions: {+ intent: {+ criteria: { billing: 'Payment problems.', other: 'Anything else.' },+ instructions: 'What is the ticket about?',+ type: 'choice',+ },+ refund: {+ criteria: { false: 'No refund requested.', true: 'Asks for money back.' },+ instructions: 'Is the customer asking for a refund?',+ type: 'boolean',+ },+ urgency: {+ criteria: ['Low', 'Medium', 'High'],+ instructions: 'How urgent is the ticket?',+ type: 'score',+ },+ },+ state: 'I was charged twice and want my money back today.',+} satisfies DecisionPayload;++const systemOneResponse = {+ answers: {+ intent: {+ choice: 'billing',+ confidence: 0.93,+ probabilities: { billing: 0.97, other: 0.03 },+ type: 'choice',+ },+ refund: { noul: 0.99, type: 'noul' },+ urgency: {+ confidence: 0.5,+ legend: { '0': 'Low', '1': 'Medium', '2': 'High' },+ probabilities: { '0': 0.05, '1': 0.25, '2': 0.7 },+ score: 1.65,+ type: 'score',+ },+ },+ id: 'gen-1',+ model: 'typesafe/jev-1.13-20260917',+ provider: 'TypeSafe',+ usage: { cost: 0.000_018, input_tokens: 436, output_tokens: 71 },+};++describe('decide via System One', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('is only installed for providers that configure a decision endpoint', () => {+ const PlainRuntime = createOpenAICompatibleRuntime({+ baseURL: 'https://api.test.com/v1',+ provider: 'test-provider',+ });++ expect(new PlainRuntime({ apiKey: 'test-key' }).decide).toBeUndefined();+ expect(createInstance().decide).toBeTypeOf('function');+ });++ it('sends System One questions without SDK retries and maps answers back', async () => {+ const instance = createInstance();+ const post = vi.spyOn(instance['client'], 'post').mockResolvedValue(systemOneResponse as never);++ const result = await instance.decide!(payload, { user: 'user-1' });++ expect(post).toHaveBeenCalledWith(+ '/systemone',+ expect.objectContaining({+ body: {+ model: 'typesafe/jev-1.13',+ questions: {+ ...payload.questions,+ refund: { ...payload.questions.refund, type: 'noul' },+ },+ state: payload.state,+ user: 'user-1',+ },+ maxRetries: 0,+ }),+ );+ expect(result).toEqual({+ answers: {+ intent: {+ choice: 'billing',+ confidence: 0.93,+ probabilities: { billing: 0.97, other: 0.03 },+ type: 'choice',+ },+ refund: { probability: 0.99, type: 'boolean' },+ urgency: { confidence: 0.5, probabilities: [0.05, 0.25, 0.7], score: 1.65, type: 'score' },+ },+ id: 'gen-1',+ model: 'typesafe/jev-1.13-20260917',+ provider: 'TypeSafe',+ usage: expect.objectContaining({ totalTokens: 507 }),+ });+ });++ it('returns usage priced on input tokens only and passes the same usage to onUsage', async () => {+ const instance = createInstance();+ vi.spyOn(instance['client'], 'post').mockResolvedValue(systemOneResponse as never);+ const onUsage = vi.fn();++ const { usage } = await instance.decide!(payload, { onUsage });++ expect(onUsage).toHaveBeenCalledWith(usage);+ expect(usage).toMatchObject({+ inputTextTokens: 436,+ outputTextTokens: 71,+ totalInputTokens: 436,+ totalTokens: 507,+ });+ // 436 input tokens × $0.042/M = 18.3 credits, ceiled to whole credits; the 71 output tokens are free.+ expect(usage?.cost).toBe(0.000_019);+ });++ it('passes the provider-reported charge separately without touching usage or the response', async () => {+ const instance = createInstance();+ vi.spyOn(instance['client'], 'post').mockResolvedValue(systemOneResponse as never);+ const onProviderReportedCost = vi.fn();++ const result = await instance.decide!(payload, { onProviderReportedCost });++ expect(onProviderReportedCost).toHaveBeenCalledWith(0.000_018);+ // `usage.cost` stays the model-bank price (19 credits), not OpenRouter's 0.000018.+ expect(result.usage?.cost).toBe(0.000_019);+ expect(JSON.stringify(result)).not.toContain('0.000018');+ expect(Object.keys(result).sort()).toEqual(['answers', 'id', 'model', 'provider', 'usage']);+ });++ it.each([+ ['missing', undefined],+ ['negative', -1],+ ['non-numeric', 'free'],+ ])('ignores a %s provider-reported charge without failing the decision', async (_, cost) => {+ const instance = createInstance();+ vi.spyOn(instance['client'], 'post').mockResolvedValue({+ ...systemOneResponse,+ usage: { ...systemOneResponse.usage, cost },+ } as never);+ const onProviderReportedCost = vi.fn();++ const result = await instance.decide!(payload, { onProviderReportedCost });++ expect(onProviderReportedCost).not.toHaveBeenCalled();+ expect(result.usage?.cost).toBe(0.000_019);+ });++ it('returns usage without an onUsage callback', async () => {+ const instance = createInstance();+ vi.spyOn(instance['client'], 'post').mockResolvedValue(systemOneResponse as never);++ const result = await instance.decide!(payload);++ expect(result.usage).toMatchObject({ cost: 0.000_019, totalTokens: 507 });+ });++ it('omits probabilities when the provider does not report a distribution', async () => {+ const instance = createInstance();+ const { probabilities: _, ...intent } = systemOneResponse.answers.intent;+ const { probabilities: __, ...urgency } = systemOneResponse.answers.urgency;+ vi.spyOn(instance['client'], 'post').mockResolvedValue({+ ...systemOneResponse,+ answers: { ...systemOneResponse.answers, intent, urgency },+ } as never);++ const result = await instance.decide!(payload);++ expect(result.answers.intent).toEqual({ choice: 'billing', confidence: 0.93, type: 'choice' });+ expect(result.answers.urgency).toEqual({ confidence: 0.5, score: 1.65, type: 'score' });+ });++ it('forwards boolean questions without criteria and structured guidance as-is', async () => {+ const instance = createInstance();+ const post = vi.spyOn(instance['client'], 'post').mockResolvedValue({+ answers: {+ intent: { choice: 'billing', type: 'choice' },+ refund: { noul: 0.8, type: 'noul' },+ },+ model: 'typesafe/jev-1.13',+ } as never);+ const questions = {+ intent: {+ criteria: { billing: { examples: ['charged twice'] }, other: null },+ instructions: { task: 'Classify the ticket', tone: 'strict' },+ type: 'choice',+ },+ refund: { instructions: 'Is the customer asking for a refund?', type: 'boolean' },+ } satisfies DecisionPayload['questions'];++ const result = await instance.decide!({ model: 'typesafe/jev-1.13', questions, state: 'x' });++ expect(post.mock.calls[0][1]).toMatchObject({+ body: { questions: { ...questions, refund: { ...questions.refund, type: 'noul' } } },+ });+ expect(result.answers.refund).toEqual({ probability: 0.8, type: 'boolean' });+ });++ it('returns a refusal as an answer instead of failing the whole call', async () => {+ const instance = createInstance();+ vi.spyOn(instance['client'], 'post').mockResolvedValue({+ ...systemOneResponse,+ answers: { ...systemOneResponse.answers, intent: { reason: 'unsafe', type: 'refusal' } },+ } as never);++ const result = await instance.decide!(payload);++ expect(result.answers.intent).toEqual({ reason: 'unsafe', type: 'refusal' });+ expect(result.answers.refund).toEqual({ probability: 0.99, type: 'boolean' });+ });++ it.each([+ [+ 'a choice outside the requested options',+ { intent: { ...systemOneResponse.answers.intent, choice: 'shipping' } },+ ],+ [+ 'a choice without a probability for every option',+ { intent: { ...systemOneResponse.answers.intent, probabilities: { billing: 1 } } },+ ],+ [+ 'a score without a probability for every level',+ {+ urgency: {+ ...systemOneResponse.answers.urgency,+ probabilities: { '0': 0.3, '1': 0.7 },+ },+ },+ ],+ ['an answer of the wrong type', { refund: systemOneResponse.answers.intent }],+ ['a missing answer', { refund: undefined }],+ ])('rejects %s as a provider error', async (_, answers) => {+ const instance = createInstance();+ vi.spyOn(instance['client'], 'post').mockResolvedValue({+ ...systemOneResponse,+ // An `undefined` override drops that answer from the response entirely.+ answers: Object.fromEntries(+ Object.entries({ ...systemOneResponse.answers, ...answers }).filter(+ ([, answer]) => answer !== undefined,+ ),+ ),+ } as never);+ const onUsage = vi.fn();++ await expect(instance.decide!(payload, { onUsage })).rejects.toMatchObject({+ errorType: AgentRuntimeErrorType.ProviderBizError,+ provider: 'openrouter',+ });+ expect(onUsage).not.toHaveBeenCalled();+ });++ it('rejects a missing probability for an option named like an object method', async () => {+ const instance = createInstance();+ vi.spyOn(instance['client'], 'post').mockResolvedValue({+ answers: {+ pick: { choice: 'other', probabilities: { other: 1 }, type: 'choice' },+ },+ model: 'typesafe/jev-1.13',+ } as never);++ await expect(+ instance.decide!({+ model: 'typesafe/jev-1.13',+ questions: {+ pick: {+ criteria: { other: 'Anything else.', toString: 'A method-named option.' },+ instructions: 'Pick one.',+ type: 'choice',+ },+ },+ state: 'x',+ }),+ ).rejects.toMatchObject({ errorType: AgentRuntimeErrorType.ProviderBizError });+ });++ it('rejects a request without questions before calling the provider', async () => {+ const instance = createInstance();+ const post = vi.spyOn(instance['client'], 'post');++ await expect(+ instance.decide!({ model: 'typesafe/jev-1.13', questions: {}, state: 'x' }),+ ).rejects.toMatchObject({ errorType: AgentRuntimeErrorType.InvalidRequestFormat });+ expect(post).not.toHaveBeenCalled();+ });+});diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/decide.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/decide.tsnew file mode 100644index 00000000000..efe28796849--- /dev/null+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/decide.ts@@ -0,0 +1,253 @@+import type { ModelUsage } from '@lobechat/types';+import { AgentRuntimeErrorType } from '@lobechat/types';+import { isRecord } from '@lobechat/utils/object';+import createDebug from 'debug';+import type OpenAI from 'openai';+import { z } from 'zod';++import type {+ DecisionAnswer,+ DecisionOptions,+ DecisionPayload,+ DecisionQuestion,+ DecisionResponse,+} from '../../types';+import { AgentRuntimeError } from '../../utils/createError';+import { getModelPricing } from '../../utils/getModelPricing';+import type { ModelIdMappingOptions } from '../../utils/modelIdMapping';+import { resolveMappedModelId } from '../../utils/modelIdMapping';+import { withUsageCost } from '../usageConverters/utils/withUsageCost';++const log = createDebug('lobe-model-runtime:decide');++/**+ * System One wire format, shared by TypeSafe and OpenRouter.+ * @see https://openrouter.ai/docs/api/api-reference/systemone/submit-a-system-one-request+ */+const SystemOneAnswerSchema = z.discriminatedUnion('type', [+ z.object({ noul: z.number().min(0).max(1), type: z.literal('noul') }),+ z.object({+ choice: z.string(),+ confidence: z.number().optional(),+ probabilities: z.record(z.string(), z.number().min(0).max(1)).optional(),+ type: z.literal('choice'),+ }),+ z.object({+ confidence: z.number().optional(),+ /** Level index (as a string key) → probability. */+ probabilities: z.record(z.string(), z.number().min(0).max(1)).optional(),+ score: z.number(),+ type: z.literal('score'),+ }),+ // The refusal payload is undocumented; keep whatever text the provider sends.+ z.object({ reason: z.string().optional(), type: z.literal('refusal') }).passthrough(),+]);++const SystemOneResponseSchema = z.object({+ answers: z.record(z.string(), SystemOneAnswerSchema),+ id: z.string().optional(),+ model: z.string(),+ provider: z.string().optional(),+ usage: z+ .object({+ /**+ * USD charge OpenRouter reports for the call. Kept loose so an unusable value is dropped+ * like chat's provider-reported cost instead of failing an otherwise valid decision.+ */+ cost: z.unknown().optional(),+ input_tokens: z.number().int().nonnegative(),+ output_tokens: z.number().int().nonnegative().optional(),+ })+ .optional(),+});++type SystemOneAnswer = z.infer<typeof SystemOneAnswerSchema>;++const toProviderReportedCost = (value: unknown): number | undefined =>+ typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;++const toSystemOneQuestion = (question: DecisionQuestion) =>+ question.type === 'boolean' ? { ...question, type: 'noul' as const } : question;++class InvalidDecisionResponseError extends Error {}++const toDecisionAnswer = (+ name: string,+ question: DecisionQuestion,+ answer: SystemOneAnswer | undefined,+): DecisionAnswer => {+ if (!answer) throw new InvalidDecisionResponseError(`Missing answer for question "${name}"`);+ if (answer.type === 'refusal') return { reason: answer.reason, type: 'refusal' };++ if (question.type === 'boolean' && answer.type === 'noul') {+ return { probability: answer.noul, type: 'boolean' };+ }++ if (question.type === 'choice' && answer.type === 'choice') {+ if (!Object.hasOwn(question.criteria, answer.choice)) {+ throw new InvalidDecisionResponseError(+ `Question "${name}" chose "${answer.choice}", which is not a requested option`,+ );+ }+ const reported = answer.probabilities;+ // The distribution is optional upstream, but a partial one would read a gap as zero.+ const probabilities =+ reported &&+ Object.fromEntries(+ Object.keys(question.criteria).map((option) => {+ // Own keys only: option names such as `toString` would otherwise hit the prototype.+ if (!Object.hasOwn(reported, option)) {+ throw new InvalidDecisionResponseError(+ `Question "${name}" has no probability for option "${option}"`,+ );+ }+ return [option, reported[option]];+ }),+ );+ return { choice: answer.choice, confidence: answer.confidence, probabilities, type: 'choice' };+ }++ if (question.type === 'score' && answer.type === 'score') {+ const reported = answer.probabilities;+ // A missing level probability is not evidence of zero, so reject rather than fill it.+ const probabilities =+ reported &&+ question.criteria.map((_, level) => {+ const probability = reported[String(level)];+ if (probability === undefined) {+ throw new InvalidDecisionResponseError(+ `Question "${name}" has no probability for score level ${level}`,+ );+ }+ return probability;+ });+ return { confidence: answer.confidence, probabilities, score: answer.score, type: 'score' };+ }++ throw new InvalidDecisionResponseError(+ `Question "${name}" is a ${question.type} question but got a ${answer.type} answer`,+ );+};++/**+ * Serves decision models through a System One endpoint. Only providers that set this expose+ * `decide`, so callers can tell decision support apart from plain chat compatibility.+ */+export interface SystemOneDecideConfig {+ /** Endpoint path relative to the client base URL, e.g. `/systemone`. */+ path: string;+}++interface RequestSystemOneDecisionParams extends SystemOneDecideConfig {+ provider: string;+ /** Model id sent upstream; may differ from `payload.model` after id mapping. */+ requestModel: string;+}++const requestSystemOneDecision = async (+ client: OpenAI,+ payload: DecisionPayload,+ options: DecisionOptions | undefined,+ { path, provider, requestModel }: RequestSystemOneDecisionParams,+): Promise<DecisionResponse> => {+ const questionEntries = Object.entries(payload.questions);+ if (questionEntries.length === 0) {+ throw AgentRuntimeError.chat({+ error: { message: 'A decision request needs at least one question' },+ errorType: AgentRuntimeErrorType.InvalidRequestFormat,+ provider,+ });+ }++ log('decide model=%s questions=%d', requestModel, questionEntries.length);++ const raw = await client.post(path, {+ body: {+ model: requestModel,+ questions: Object.fromEntries(+ questionEntries.map(([name, question]) => [name, toSystemOneQuestion(question)]),+ ),+ state: payload.state,+ ...(options?.user && { user: options.user }),+ },+ headers: options?.headers,+ // Callers own retry policy: a decision is often one arm of a timed experiment, and hidden+ // SDK retries would multiply latency and spend without the caller seeing the attempts.+ maxRetries: 0,+ signal: options?.signal,+ });++ const parsed = SystemOneResponseSchema.safeParse(raw);+ let response: DecisionResponse;+ try {+ if (!parsed.success) throw new InvalidDecisionResponseError(parsed.error.message);++ response = {+ answers: Object.fromEntries(+ questionEntries.map(([name, question]) => [+ name,+ toDecisionAnswer(name, question, parsed.data.answers[name]),+ ]),+ ),+ id: parsed.data.id,+ model: parsed.data.model,+ provider: parsed.data.provider,+ };+ } catch (error) {+ if (!(error instanceof InvalidDecisionResponseError)) throw error;+ throw AgentRuntimeError.chat({+ error: { message: `Invalid decision response: ${error.message}` },+ errorType: AgentRuntimeErrorType.ProviderBizError,+ provider,+ });+ }++ const usage = parsed.data.usage;+ if (usage) {+ const outputTokens = usage.output_tokens ?? 0;+ const tokens = {+ inputTextTokens: usage.input_tokens,+ // Decision models bill input only, but report output tokens anyway (Jev returns non-zero+ // counts). Keep them for observability; cost comes from the model's pricing units.+ outputTextTokens: outputTokens,+ totalInputTokens: usage.input_tokens,+ totalOutputTokens: outputTokens,+ totalTokens: usage.input_tokens + outputTokens,+ } satisfies ModelUsage;+ const pricing = await getModelPricing(payload.model, provider, options?.pricingContext);+ response.usage = withUsageCost(tokens, pricing);+ await options?.onUsage?.(response.usage);++ const providerReportedCost = toProviderReportedCost(usage.cost);+ if (providerReportedCost !== undefined) {+ await options?.onProviderReportedCost?.(providerReportedCost);+ }+ }++ return response;+};++interface CreateSystemOneDecisionParams extends SystemOneDecideConfig {+ /** Maps transport failures (HTTP, network) to the provider's runtime error payload. */+ handleError: (error: unknown) => unknown;+ modelIdMappingOptions?: ModelIdMappingOptions;+ provider: string;+}++export const createSystemOneDecision = async (+ client: OpenAI,+ payload: DecisionPayload,+ options: DecisionOptions | undefined,+ { handleError, modelIdMappingOptions, ...params }: CreateSystemOneDecisionParams,+): Promise<DecisionResponse> => {+ try {+ return await requestSystemOneDecision(client, payload, options, {+ ...params,+ requestModel: resolveMappedModelId(payload.model, modelIdMappingOptions),+ });+ } catch (error) {+ // Validation failures are already runtime error payloads; only map transport errors.+ if (isRecord(error) && 'errorType' in error) throw error;+ throw handleError(error);+ }+};diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/factoryOptions.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/factoryOptions.tsnew file mode 100644index 00000000000..232314b14d7--- /dev/null+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/factoryOptions.ts@@ -0,0 +1,211 @@+import type { ChatModelCard } from '@lobechat/types';+import type { AiFullModelCard } from 'model-bank';+import type { ClientOptions } from 'openai';+import type OpenAI from 'openai';+import type { Stream } from 'openai/streaming';++import type {+ ChatCompletionErrorPayload,+ ChatStreamCallbacks,+ ChatStreamPayload,+ GenerateObjectPayload,+} from '../../types';+import type { ILobeAgentRuntimeErrorType } from '../../types/error';+import type { CreateImagePayload, CreateImageResponse } from '../../types/image';+import type {+ CreateVideoPayload,+ CreateVideoResult,+ HandleCreateVideoWebhookPayload,+ HandleCreateVideoWebhookResult,+ PollVideoStatusResult,+ VideoGenerationCapabilities,+} from '../../types/video';+import type { ModelIdMappingOptions } from '../../utils/modelIdMapping';+import type { AssertContextWithinWindowOptions } from '../../utils/resolveSafeMaxTokens';+import type { ChatPayloadForTransformStream } from '../streams/protocol';+import type { SystemOneDecideConfig } from './decide';++// OpenAI SDK v6 widened `apiKey` to `string | ApiKeySetter`; lobehub only ever+// passes a plain string, so narrow it back to keep `.trim()` / string assignments valid.+export type LobeClientOptions = Omit<ClientOptions, 'apiKey'> & { apiKey?: string };+export type ConstructorOptions<T extends Record<string, any> = any> = LobeClientOptions &+ ModelIdMappingOptions &+ T;+export type OpenAIExtraParams = { prompt_cache_key?: string; safety_identifier?: string };+export type ChatCompletionCreateParamsWithPromptCacheKey = Omit<+ OpenAI.ChatCompletionCreateParamsNonStreaming,+ 'reasoning_effort'+> &+ Pick<OpenAIExtraParams, 'prompt_cache_key'> &+ Pick<GenerateObjectPayload, 'reasoning_effort'>;+export type ResponseCreateParamsWithPromptCacheKey = (+ OpenAI.Responses.ResponseCreateParamsStreaming | OpenAI.Responses.ResponseCreateParams+) &+ OpenAIExtraParams;+// Exclude openai's own `provider` (added in openai SDK 6.45.0 as `provider?: Provider`+// for its third-party-provider feature) — otherwise intersecting it with our+// `provider: string` collapses to `Provider & string`, breaking every call site+// that passes a plain provider id string.+export type CreateImageOptions = Omit<ClientOptions, 'apiKey' | 'provider'> &+ ModelIdMappingOptions & {+ apiKey: string;+ provider: string;+ };++// See CreateImageOptions above: drop openai's `provider` so ours stays `string`.+export type CreateVideoOptions = Omit<ClientOptions, 'apiKey' | 'provider'> &+ ModelIdMappingOptions & {+ apiKey: string;+ provider: string;+ };++export interface CustomClientOptions<T extends Record<string, any> = any> {+ createChatCompletionStream?: (+ client: any,+ payload: ChatStreamPayload,+ instance: any,+ ) => ReadableStream<any>;+ createClient?: (options: ConstructorOptions<T>) => any;+}++export interface OpenAICompatibleFactoryOptions<T extends Record<string, any> = any> {+ apiKey?: string;+ baseURL?: string;+ chatCompletion?: {+ /**+ * When set, the factory runs a pre-flight token estimate against the+ * provided model list before dispatching to upstream. If the estimated+ * prompt tokens strictly exceed the model's context window, the+ * request is aborted with a structured `ExceededContextWindow` error+ * — see .+ *+ * This is for providers like NVIDIA / DeepSeek where the harness does+ * not cap `max_tokens` itself but we still want to fail fast on doomed+ * requests instead of round-tripping to the upstream just to get a+ * 400 back. Providers that manage `max_tokens` themselves (e.g.+ * MiniMax via `resolveSafeMaxTokens`) still benefit because the+ * factory's centralised error handler converts the same error class.+ */+ contextPreFlight?: AssertContextWithinWindowOptions & {+ models: AiFullModelCard[];+ };+ excludeUsage?: boolean;+ forceImageBase64?: boolean;+ forceVideoBase64?: boolean;+ handleError?: (+ error: any,+ options: ConstructorOptions<T>,+ ) => Omit<ChatCompletionErrorPayload, 'provider'> | undefined;+ handlePayload?: (+ payload: ChatStreamPayload,+ options: ConstructorOptions<T>,+ ) => OpenAI.ChatCompletionCreateParamsStreaming;+ handleStream?: (+ stream: Stream<OpenAI.ChatCompletionChunk> | ReadableStream,+ options: {+ callbacks?: ChatStreamCallbacks;+ inputStartAt?: number;+ payload?: ChatPayloadForTransformStream;+ },+ ) => ReadableStream;+ handleStreamBizErrorType?: (error: {+ message: string;+ name: string;+ }) => ILobeAgentRuntimeErrorType | undefined;+ handleTransformResponseToStream?: (+ data: OpenAI.ChatCompletion,+ ) => ReadableStream<OpenAI.ChatCompletionChunk>;+ noUserId?: boolean;+ /** Convert internal audio_url parts to OpenAI input_audio (WAV/MP3 only). */+ supportsAudioInput?: boolean;+ /**+ * If true, route chat requests to Responses API path directly+ */+ useResponse?: boolean;+ /**+ * Allow only some models to use Responses API by simple matching.+ * If any string appears in model id or RegExp matches, Responses API is used.+ */+ useResponseModels?: Array<string | RegExp>;+ };+ constructorOptions?: ConstructorOptions<T>;+ createImage?: (+ payload: CreateImagePayload,+ options: CreateImageOptions,+ ) => Promise<CreateImageResponse>;+ createVideo?: (+ payload: CreateVideoPayload,+ options: CreateVideoOptions,+ ) => Promise<CreateVideoResult>;+ customClient?: CustomClientOptions<T>;+ debug?: {+ chatCompletion: () => boolean;+ responses?: () => boolean;+ };+ decide?: SystemOneDecideConfig;+ errorType?: {+ bizError: ILobeAgentRuntimeErrorType;+ invalidAPIKey: ILobeAgentRuntimeErrorType;+ };+ generateObject?: {+ /**+ * Transform schema before sending to the provider (e.g., filter unsupported properties)+ */+ handleSchema?: (schema: any) => any;+ /**+ * Transform Chat Completions payload before sending generateObject requests to the provider.+ */+ handlePayload?: (+ payload: GenerateObjectPayload,+ requestPayload: ChatCompletionCreateParamsWithPromptCacheKey,+ options: ConstructorOptions<T>,+ ) => ChatCompletionCreateParamsWithPromptCacheKey;+ /**+ * If true, route generateObject requests to Responses API path directly+ */+ useResponse?: boolean;+ /**+ * Allow only some models to use Responses API by simple matching.+ * If any string appears in model id or RegExp matches, Responses API is used.+ */+ useResponseModels?: Array<string | RegExp>;+ /**+ * Use tool calling to simulate structured output for providers that don't support native structured output+ */+ useToolsCalling?: boolean;+ };+ handleCreateVideoWebhook?: (+ payload: HandleCreateVideoWebhookPayload,+ options: CreateVideoOptions,+ ) => Promise<HandleCreateVideoWebhookResult>;+ handlePollVideoStatus?: (+ inferenceId: string,+ options: CreateVideoOptions,+ ) => Promise<PollVideoStatusResult>;+ models?:+ | ((params: { client: OpenAI; options?: ConstructorOptions<T> }) => Promise<ChatModelCard[]>)+ | {+ transformModel?: (model: OpenAI.Model) => ChatModelCard;+ };+ /**+ * Additional provider-specific model patterns that support `prompt_cache_key`.+ * OpenAI models are handled by the factory default; other providers must opt in.+ */+ promptCacheKeyModels?: Array<string | RegExp>;+ provider: string;+ responses?: {+ handlePayload?: (+ payload: ChatStreamPayload,+ options: ConstructorOptions<T>,+ ) => ChatStreamPayload;+ prepareRequest?: (+ payload: ResponseCreateParamsWithPromptCacheKey,+ options: ConstructorOptions<T>,+ ) => {+ headers?: Record<string, string>;+ payload: ResponseCreateParamsWithPromptCacheKey;+ };+ };+ videoGenerationCapabilities?:+ VideoGenerationCapabilities | ((model: string) => VideoGenerationCapabilities);+}diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.tsindex 32851cf3531..6b1daf9ed33 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts@@ -2,9 +2,8 @@ import type { ChatModelCard } from '@lobechat/types';import dayjs from 'dayjs';import utc from 'dayjs/plugin/utc';import debug from 'debug';-import type { AiFullModelCard, AiModelType } from 'model-bank';+import type { AiModelType } from 'model-bank';import { LOBE_DEFAULT_MODEL_LIST } from 'model-bank';-import type { ClientOptions } from 'openai';import type OpenAI from 'openai';import type { Stream } from 'openai/streaming';@@ -21,7 +20,6 @@ import type {ChatCompletionErrorPayload,ChatCompletionTool,ChatMethodOptions,- ChatStreamCallbacks,ChatStreamPayload,Embeddings,EmbeddingsOptions,@@ -31,18 +29,12 @@ import type {TextToSpeechOptions,TextToSpeechPayload,} from '../../types';-import type { ILobeAgentRuntimeErrorType } from '../../types/error';import { AgentRuntimeErrorType } from '../../types/error';-import type {- CreateImageMethodOptions,- CreateImagePayload,- CreateImageResponse,-} from '../../types/image';+import type { CreateImageMethodOptions, CreateImagePayload } from '../../types/image';import type {CreateVideoPayload,CreateVideoResult,HandleCreateVideoWebhookPayload,- HandleCreateVideoWebhookResult,PollVideoStatusResult,VideoGenerationCapabilities,} from '../../types/video';@@ -58,7 +50,6 @@ import { detectModelProvider } from '../../utils/modelParse';import { postProcessModelList } from '../../utils/postProcessModelList';import {assertContextWithinWindow,- type AssertContextWithinWindowOptions,ContextExceededPreFlightError,} from '../../utils/resolveSafeMaxTokens';import { StreamingResponse } from '../../utils/response';@@ -83,6 +74,15 @@ import {import { OpenAICompatibleClient } from './client';import { createOpenAICompatibleImage } from './createImage';import { createOpenAICompatibleVideo, pollOpenAICompatibleVideoStatus } from './createVideo';+import { createSystemOneDecision } from './decide';+import type {+ ChatCompletionCreateParamsWithPromptCacheKey,+ ConstructorOptions,+ LobeClientOptions,+ OpenAICompatibleFactoryOptions,+ OpenAIExtraParams,+ ResponseCreateParamsWithPromptCacheKey,+} from './factoryOptions';import { transformResponseAPIToStream, transformResponseToStream } from './nonStreamToStream';import {initializeOpenAIDiagnostics,@@ -105,6 +105,12 @@ import {export type { PollVideoStatusResult };export * from './createVideo';+export type {+ CreateImageOptions,+ CreateVideoOptions,+ CustomClientOptions,+ OpenAICompatibleFactoryOptions,+} from './factoryOptions';export * from './nonStreamToStream';/**@@ -136,34 +142,7 @@ export const CHAT_MODELS_BLOCK_LIST = ['dall-e',];-// OpenAI SDK v6 widened `apiKey` to `string | ApiKeySetter`; lobehub only ever-// passes a plain string, so narrow it back to keep `.trim()` / string assignments valid.-type LobeClientOptions = Omit<ClientOptions, 'apiKey'> & { apiKey?: string };-type ConstructorOptions<T extends Record<string, any> = any> = LobeClientOptions &- ModelIdMappingOptions &- T;-type OpenAIExtraParams = { prompt_cache_key?: string; safety_identifier?: string };-type ChatCompletionCreateParamsWithPromptCacheKey = Omit<- OpenAI.ChatCompletionCreateParamsNonStreaming,- 'reasoning_effort'-> &- Pick<OpenAIExtraParams, 'prompt_cache_key'> &- Pick<GenerateObjectPayload, 'reasoning_effort'>;type GenerateObjectReasoningParams = Pick<GenerateObjectPayload, 'reasoning_effort' | 'thinking'>;-type ResponseCreateParamsWithPromptCacheKey = (- OpenAI.Responses.ResponseCreateParamsStreaming | OpenAI.Responses.ResponseCreateParams-) &- OpenAIExtraParams;-// Exclude openai's own `provider` (added in openai SDK 6.45.0 as `provider?: Provider`-// for its third-party-provider feature) — otherwise intersecting it with our-// `provider: string` collapses to `Provider & string`, breaking every call site-// that passes a plain provider id string.-export type CreateImageOptions = Omit<ClientOptions, 'apiKey' | 'provider'> &- ModelIdMappingOptions & {- apiKey: string;- provider: string;- };-const getGenerateObjectReasoningParams = ({reasoning_effort,thinking,@@ -192,163 +171,6 @@ const getGenerateObjectResponsesReasoningParams = ({: {};};-// See CreateImageOptions above: drop openai's `provider` so ours stays `string`.-export type CreateVideoOptions = Omit<ClientOptions, 'apiKey' | 'provider'> &- ModelIdMappingOptions & {- apiKey: string;- provider: string;- };--export interface CustomClientOptions<T extends Record<string, any> = any> {- createChatCompletionStream?: (- client: any,- payload: ChatStreamPayload,- instance: any,- ) => ReadableStream<any>;- createClient?: (options: ConstructorOptions<T>) => any;-}--export interface OpenAICompatibleFactoryOptions<T extends Record<string, any> = any> {- apiKey?: string;- baseURL?: string;- chatCompletion?: {- /**- * When set, the factory runs a pre-flight token estimate against the- * provided model list before dispatching to upstream. If the estimated- * prompt tokens strictly exceed the model's context window, the- * request is aborted with a structured `ExceededContextWindow` error- * — see .- *- * This is for providers like NVIDIA / DeepSeek where the harness does- * not cap `max_tokens` itself but we still want to fail fast on doomed- * requests instead of round-tripping to the upstream just to get a- * 400 back. Providers that manage `max_tokens` themselves (e.g.- * MiniMax via `resolveSafeMaxTokens`) still benefit because the- * factory's centralised error handler converts the same error class.- */- contextPreFlight?: AssertContextWithinWindowOptions & {- models: AiFullModelCard[];- };- excludeUsage?: boolean;- forceImageBase64?: boolean;- forceVideoBase64?: boolean;- handleError?: (- error: any,- options: ConstructorOptions<T>,- ) => Omit<ChatCompletionErrorPayload, 'provider'> | undefined;- handlePayload?: (- payload: ChatStreamPayload,- options: ConstructorOptions<T>,- ) => OpenAI.ChatCompletionCreateParamsStreaming;- handleStream?: (- stream: Stream<OpenAI.ChatCompletionChunk> | ReadableStream,- options: {- callbacks?: ChatStreamCallbacks;- inputStartAt?: number;- payload?: ChatPayloadForTransformStream;- },- ) => ReadableStream;- handleStreamBizErrorType?: (error: {- message: string;- name: string;- }) => ILobeAgentRuntimeErrorType | undefined;- handleTransformResponseToStream?: (- data: OpenAI.ChatCompletion,- ) => ReadableStream<OpenAI.ChatCompletionChunk>;- noUserId?: boolean;- /** Convert internal audio_url parts to OpenAI input_audio (WAV/MP3 only). */- supportsAudioInput?: boolean;- /**- * If true, route chat requests to Responses API path directly- */- useResponse?: boolean;- /**- * Allow only some models to use Responses API by simple matching.- * If any string appears in model id or RegExp matches, Responses API is used.- */- useResponseModels?: Array<string | RegExp>;- };- constructorOptions?: ConstructorOptions<T>;- createImage?: (- payload: CreateImagePayload,- options: CreateImageOptions,- ) => Promise<CreateImageResponse>;- createVideo?: (- payload: CreateVideoPayload,- options: CreateVideoOptions,- ) => Promise<CreateVideoResult>;- customClient?: CustomClientOptions<T>;- debug?: {- chatCompletion: () => boolean;- responses?: () => boolean;- };- errorType?: {- bizError: ILobeAgentRuntimeErrorType;- invalidAPIKey: ILobeAgentRuntimeErrorType;- };- generateObject?: {- /**- * Transform schema before sending to the provider (e.g., filter unsupported properties)- */- handleSchema?: (schema: any) => any;- /**- * Transform Chat Completions payload before sending generateObject requests to the provider.- */- handlePayload?: (- payload: GenerateObjectPayload,- requestPayload: ChatCompletionCreateParamsWithPromptCacheKey,- options: ConstructorOptions<T>,- ) => ChatCompletionCreateParamsWithPromptCacheKey;- /**- * If true, route generateObject requests to Responses API path directly- */- useResponse?: boolean;- /**- * Allow only some models to use Responses API by simple matching.- * If any string appears in model id or RegExp matches, Responses API is used.- */- useResponseModels?: Array<string | RegExp>;- /**- * Use tool calling to simulate structured output for providers that don't support native structured output- */- useToolsCalling?: boolean;- };- handleCreateVideoWebhook?: (- payload: HandleCreateVideoWebhookPayload,- options: CreateVideoOptions,- ) => Promise<HandleCreateVideoWebhookResult>;- handlePollVideoStatus?: (- inferenceId: string,- options: CreateVideoOptions,- ) => Promise<PollVideoStatusResult>;- models?:- | ((params: { client: OpenAI; options?: ConstructorOptions<T> }) => Promise<ChatModelCard[]>)- | {- transformModel?: (model: OpenAI.Model) => ChatModelCard;- };- /**- * Additional provider-specific model patterns that support `prompt_cache_key`.- * OpenAI models are handled by the factory default; other providers must opt in.- */- promptCacheKeyModels?: Array<string | RegExp>;- provider: string;- responses?: {- handlePayload?: (- payload: ChatStreamPayload,- options: ConstructorOptions<T>,- ) => ChatStreamPayload;- prepareRequest?: (- payload: ResponseCreateParamsWithPromptCacheKey,- options: ConstructorOptions<T>,- ) => {- headers?: Record<string, string>;- payload: ResponseCreateParamsWithPromptCacheKey;- };- };- videoGenerationCapabilities?:- VideoGenerationCapabilities | ((model: string) => VideoGenerationCapabilities);-}-export const createOpenAICompatibleRuntime = <T extends Record<string, any> = any>({provider,baseURL: DEFAULT_BASE_URL,@@ -363,6 +185,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anpromptCacheKeyModels,createImage: customCreateImage,createVideo: customCreateVideo,+ decide: decideConfig,videoGenerationCapabilities,handleCreateVideoWebhook: customHandleCreateVideoWebhook,handlePollVideoStatus: customHandlePollVideoStatus,@@ -382,6 +205,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anprivate subscriptionChannelId?: Promise<string>;baseURL!: string;+ decide?: LobeRuntimeAI['decide'];protected _options: ConstructorOptions<T>;getVideoGenerationCapabilities(model: string): VideoGenerationCapabilities {@@ -426,6 +250,16 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an);}this.logPrefix = `lobe-model-runtime:${this.id}`;++ if (decideConfig) {+ this.decide = (payload, decideOptions) =>+ createSystemOneDecision(this.client, payload, decideOptions, {+ ...decideConfig,+ handleError: (error) => this.handleError(error),+ modelIdMappingOptions: this.modelIdMappingOptions,+ provider: this.id,+ });+ }}/**diff --git a/packages/model-runtime/src/providers/openrouter/index.decision.test.ts b/packages/model-runtime/src/providers/openrouter/index.decision.test.tsnew file mode 100644index 00000000000..1ef01775179--- /dev/null+++ b/packages/model-runtime/src/providers/openrouter/index.decision.test.ts@@ -0,0 +1,75 @@+// @vitest-environment node+import { afterEach, describe, expect, it, vi } from 'vitest';++import { params } from './index';++const loadModelsMock = vi.hoisted(() => vi.fn().mockResolvedValue([]));++vi.mock('@lobechat/business-model-bank/model-config', () => ({+ loadModels: loadModelsMock,+}));++vi.spyOn(console, 'error').mockImplementation(() => {});++const chatModel = {+ architecture: { input_modalities: ['text'], output_modalities: ['text'] },+ context_length: 8192,+ created: 1679587200,+ id: 'openai/gpt-4',+ name: 'OpenAI: GPT-4',+ pricing: { completion: '0.00006', prompt: '0.00003' },+ supported_parameters: ['tools'],+ top_provider: { context_length: 8192, is_moderated: false, max_completion_tokens: 4096 },+};++const decisionModel = {+ architecture: { input_modalities: ['text'], output_modalities: ['decisions'] },+ context_length: 64000,+ created: 1789603200,+ description: 'Calibrated probabilities for typed questions.',+ id: 'typesafe/jev-1.13',+ name: 'TypeSafe: Jev 1.13',+ pricing: { completion: '0', prompt: '0.000000042' },+};++const stubModelsApi = (decisionResponse: () => Promise<unknown>) =>+ vi.stubGlobal(+ 'fetch',+ vi.fn((url: string) =>+ url.includes('output_modalities=decisions')+ ? decisionResponse()+ : Promise.resolve({ json: async () => ({ data: [chatModel] }), ok: true }),+ ),+ );++describe('LobeOpenRouterAI decision models', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ vi.clearAllMocks();+ });++ it('lists decision models as decision cards priced on input only', async () => {+ stubModelsApi(async () => ({ json: async () => ({ data: [decisionModel] }), ok: true }));++ const models = await params.models();++ expect(fetch).toHaveBeenCalledWith(+ 'https://openrouter.ai/api/v1/models?output_modalities=decisions',+ );+ expect(models.find((model) => model.id === 'openai/gpt-4')?.type).toBe('chat');+ expect(models.find((model) => model.id === 'typesafe/jev-1.13')).toMatchObject({+ contextWindowTokens: 64000,+ displayName: 'TypeSafe: Jev 1.13',+ pricing: { units: [expect.objectContaining({ name: 'textInput', rate: 0.042 })] },+ type: 'decision',+ });+ });++ it('keeps the chat model list when the decision list fails', async () => {+ stubModelsApi(async () => ({ ok: false, status: 500 }));++ const models = await params.models();++ expect(models.map((model) => model.id)).toEqual(['openai/gpt-4']);+ });+});diff --git a/packages/model-runtime/src/providers/openrouter/index.ts b/packages/model-runtime/src/providers/openrouter/index.tsindex 000ce6161dc..a3451c02bcb 100644--- a/packages/model-runtime/src/providers/openrouter/index.ts+++ b/packages/model-runtime/src/providers/openrouter/index.ts@@ -10,6 +10,19 @@ const formatPrice = (price?: string) => {return Number((Number(price) * 1e6).toPrecision(5));};+const fetchOpenRouterModels = async (outputModality?: string) => {+ const url = new URL('https://openrouter.ai/api/v1/models');+ if (outputModality) url.searchParams.set('output_modalities', outputModality);++ const response = await fetch(url.toString());+ if (!response.ok) {+ throw new Error(`OpenRouter models API request failed with status ${response.status}`);+ }++ const data = (await response.json()) as { data: OpenRouterModelCard[] };+ return data.data;+};+export const params = {baseURL: 'https://openrouter.ai/api/v1',chatCompletion: {@@ -92,14 +105,28 @@ export const params = {debug: {chatCompletion: () => process.env.DEBUG_OPENROUTER_CHAT_COMPLETION === '1',},+ decide: { path: '/systemone' },models: async () => {- const response = await fetch('https://openrouter.ai/api/v1/models');- if (!response.ok) {- throw new Error(`OpenRouter models API request failed with status ${response.status}`);- }-- const data = (await response.json()) as { data: OpenRouterModelCard[] };- const modelList = data.data;+ // The default listing omits decision models; they are only returned when filtering by+ // their output modality, so fetch both lists.+ const [modelList, decisionModelList] = await Promise.all([+ fetchOpenRouterModels(),+ fetchOpenRouterModels('decisions').catch((error) => {+ console.error('[OpenRouter] Failed to fetch decision models:', error);+ return [];+ }),+ ]);++ const decisionModels = decisionModelList.map((model) => ({+ contextWindowTokens: model.top_provider?.context_length || model.context_length,+ description: model.description,+ displayName: model.name,+ id: model.id,+ // Decision models bill input tokens only.+ pricing: { input: formatPrice(model.pricing.prompt) },+ releasedAt: new Date(model.created * 1000).toISOString().split('T')[0],+ type: 'decision' as const,+ }));// Process the model info fetched from the frontend and convert to standard formatconst formattedModels = modelList.map((model) => {@@ -197,7 +224,10 @@ export const params = {};});- return await processMultiProviderModelList(formattedModels, 'openrouter');+ return await processMultiProviderModelList(+ [...formattedModels, ...decisionModels],+ 'openrouter',+ );},provider: ModelProvider.OpenRouter,} satisfies OpenAICompatibleFactoryOptions;diff --git a/packages/model-runtime/src/types/decision.ts b/packages/model-runtime/src/types/decision.tsnew file mode 100644index 00000000000..66753bff73a--- /dev/null+++ b/packages/model-runtime/src/types/decision.ts@@ -0,0 +1,144 @@+import type { ModelUsage } from '@lobechat/types';++import type { ModelPricingContext } from './pricing';++export type DecisionJsonValue =+ string | number | boolean | null | DecisionJsonValue[] | { [key: string]: DecisionJsonValue };++/** Plain text or structured JSON, as accepted for `state`, `instructions`, and criteria. */+export type DecisionContent = string | DecisionJsonValue[] | { [key: string]: DecisionJsonValue };++/**+ * Asks how likely a yes/no proposition is to be true.+ * Sent as a System One `noul` question.+ */+export interface DecisionBooleanQuestion {+ /** Guidance for when the proposition is true and when it is false; `instructions` may suffice. */+ criteria?: { false: DecisionContent; true: DecisionContent };+ instructions: DecisionContent;+ type: 'boolean';+}++/**+ * Asks the model to pick exactly one option from a caller-defined set.+ */+export interface DecisionChoiceQuestion {+ /** Option key → guidance describing when to pick it, or `null` when the key is self-explanatory. */+ criteria: Record<string, DecisionContent | null>;+ instructions: DecisionContent;+ type: 'choice';+}++/**+ * Asks the model to place the state on an ordered rubric.+ */+export interface DecisionScoreQuestion {+ /** Rubric level descriptions ordered from lowest to highest; level indices start at 0. */+ criteria: DecisionContent[];+ instructions: DecisionContent;+ type: 'score';+}++export type DecisionQuestion =+ DecisionBooleanQuestion | DecisionChoiceQuestion | DecisionScoreQuestion;++export type DecisionQuestions = Record<string, DecisionQuestion>;++/**+ * Typed questions about one shared state, answered with probabilities instead of generated text.+ *+ * The shape follows the System One request (named questions + criteria) used by TypeSafe,+ * OpenRouter, and vLLM Semantic Router, with the vendor term `noul` renamed to `boolean`.+ * @see https://openrouter.ai/docs/api/api-reference/systemone/submit-a-system-one-request+ */+export interface DecisionPayload<Q extends DecisionQuestions = DecisionQuestions> {+ model: string;+ /** Question name → question. Names come back as the keys of `answers`. */+ questions: Q;+ /** The content every question is evaluated against. */+ state: DecisionContent;+}++export interface DecisionBooleanAnswer {+ /** Probability (0–1) that the proposition is true. */+ probability: number;+ type: 'boolean';+}++export interface DecisionChoiceAnswer<K extends string = string> {+ choice: K;+ /**+ * Provider-defined concentration of `probabilities`. It is not the probability of being+ * correct, so do not threshold it like a boolean probability.+ */+ confidence?: number;+ /**+ * Option key → probability, one entry per requested option. Omitted when the provider does+ * not report a distribution; when present it always covers every option.+ */+ probabilities?: Record<K, number>;+ type: 'choice';+}++export interface DecisionScoreAnswer {+ confidence?: number;+ /**+ * Probability per rubric level, in the same order as the requested `criteria`. Omitted when the+ * provider does not report a distribution; when present it always covers every level.+ */+ probabilities?: number[];+ /** Probability-weighted mean of the zero-based level index; it may fall between levels. */+ score: number;+ type: 'score';+}++/**+ * The model declined this question. Other questions in the same call may still be answered,+ * so this is an answer rather than an error and never triggers a route fallback.+ */+export interface DecisionRefusalAnswer {+ reason?: string;+ type: 'refusal';+}++export type DecisionAnswer<Q extends DecisionQuestion = DecisionQuestion> =+ | DecisionRefusalAnswer+ | (Q extends DecisionBooleanQuestion+ ? DecisionBooleanAnswer+ : Q extends DecisionChoiceQuestion+ ? DecisionChoiceAnswer<Extract<keyof Q['criteria'], string>>+ : DecisionScoreAnswer);++export interface DecisionResponse<Q extends DecisionQuestions = DecisionQuestions> {+ answers: { [K in keyof Q]: DecisionAnswer<Q[K]> };+ id?: string;+ /** Model that actually served the request, possibly a dated version of the requested id. */+ model: string;+ /** Upstream provider that served the request, when reported. */+ provider?: string;+ /** Provider-reported token usage, with `cost` when the model has pricing. */+ usage?: ModelUsage;+}++export interface DecisionOptions {+ headers?: Record<string, string>;+ /** Metadata passed to hooks (billing, tracing, route attempts), e.g. `trigger`. */+ metadata?: Record<string, unknown>;+ /**+ * Receives the USD charge the upstream provider reported for this call (OpenRouter+ * `usage.cost`). Server-side only: it is kept out of `DecisionResponse` and never replaces the+ * model-bank `usage.cost`, matching chat's `OnFinishData.providerReportedCost`.+ */+ onProviderReportedCost?: (cost: number) => void | Promise<void>;+ /**+ * Receives the provider-reported token usage (with `cost` when the model has pricing)+ * after a successful decision.+ */+ onUsage?: (usage: ModelUsage) => void | Promise<void>;+ pricingContext?: ModelPricingContext;+ signal?: AbortSignal;+ /**+ * userId for the request+ */+ user?: string;+}diff --git a/packages/model-runtime/src/types/index.ts b/packages/model-runtime/src/types/index.tsindex 71d70810063..3283ef4ab5f 100644--- a/packages/model-runtime/src/types/index.ts+++ b/packages/model-runtime/src/types/index.ts@@ -1,5 +1,6 @@export * from './asr';export * from './chat';+export * from './decision';export * from './embeddings';export * from './error';export * from './image';diff --git a/packages/openapi/openapi.yml b/packages/openapi/openapi.ymlindex e886cee7fe0..e522ca7610d 100644--- a/packages/openapi/openapi.yml+++ b/packages/openapi/openapi.yml@@ -17318,6 +17318,7 @@ paths:- text2video- text2music- realtime+ - decision- stt- type: "null"responses:@@ -17498,6 +17499,7 @@ paths:- text2video- text2music- realtime+ - decision- stt- type: "null"id:@@ -17792,6 +17794,7 @@ paths:- text2video- text2music- realtime+ - decision- stt- type: "null"responses:diff --git a/packages/openapi/src/types/model.type.ts b/packages/openapi/src/types/model.type.tsindex 9e730527620..4c3a8f59790 100644--- a/packages/openapi/src/types/model.type.ts+++ b/packages/openapi/src/types/model.type.ts@@ -15,6 +15,7 @@ const MODEL_TYPES = ['text2video','text2music','realtime',+ 'decision',] as const;// `stt` was renamed to the standard `asr`. It is still accepted on input as adiff --git a/src/features/Settings/provider/features/ModelList/CreateNewModelModal/utils.ts b/src/features/Settings/provider/features/ModelList/CreateNewModelModal/utils.tsindex d1dbb1012e5..e0870701945 100644--- a/src/features/Settings/provider/features/ModelList/CreateNewModelModal/utils.ts+++ b/src/features/Settings/provider/features/ModelList/CreateNewModelModal/utils.ts@@ -14,6 +14,7 @@ export const CUSTOM_MODEL_TYPES: AiModelType[] = ['asr','text2music','realtime',+ 'decision',];export const hasDuplicateModelId = (id: string | undefined, existingModelIds: string[]) => {diff --git a/src/features/Settings/provider/features/ModelList/ModelItem.tsx b/src/features/Settings/provider/features/ModelList/ModelItem.tsxindex c9527122f5a..218d6d9d78e 100644--- a/src/features/Settings/provider/features/ModelList/ModelItem.tsx+++ b/src/features/Settings/provider/features/ModelList/ModelItem.tsx@@ -121,6 +121,8 @@ const ModelItem = memo<ModelItemProps>(}),].filter(Boolean) as string[];}+ // Decision models bill input tokens only.+ case 'decision':case 'embedding': {const inputRate = getTextInputUnitRate(pricing);return [diff --git a/src/features/Settings/provider/features/ModelList/index.tsx b/src/features/Settings/provider/features/ModelList/index.tsxindex 83ae49827b2..7a16a53cf58 100644--- a/src/features/Settings/provider/features/ModelList/index.tsx+++ b/src/features/Settings/provider/features/ModelList/index.tsx@@ -9,6 +9,7 @@ import {ImageIcon,MessageSquareTextIcon,MicIcon,+ SplitIcon,VideoIcon,} from 'lucide-react';import { memo, Suspense, useMemo, useState } from 'react';@@ -52,6 +53,7 @@ const Content = memo<ContentProps>(({ id }) => {all: allModels.length,asr: 0,chat: 0,+ decision: 0,embedding: 0,image: 0,tts: 0,@@ -116,6 +118,12 @@ const Content = memo<ContentProps>(({ id }) => {key: 'tts',label: formatTabLabel(t('providerModels.tabs.tts'), modelCounts.tts),},+ {+ count: modelCounts.decision,+ icon: <Icon icon={SplitIcon} size={16} />,+ key: 'decision',+ label: formatTabLabel(t('providerModels.tabs.decision'), modelCounts.decision),+ },];// Only show tabs that have models (count > 0), but always show 'all' tabdiff --git a/src/routes/(main)/community/(list)/model/features/List/ModelTypeIcon.tsx b/src/routes/(main)/community/(list)/model/features/List/ModelTypeIcon.tsxindex 67514c2ba6b..59ee9c4658c 100644--- a/src/routes/(main)/community/(list)/model/features/List/ModelTypeIcon.tsx+++ b/src/routes/(main)/community/(list)/model/features/List/ModelTypeIcon.tsx@@ -9,6 +9,7 @@ import {MicIcon,MusicIcon,PhoneIcon,+ SplitIcon,VideoIcon,} from 'lucide-react';import { type AiModelType } from 'model-bank';@@ -17,6 +18,7 @@ import { memo } from 'react';const icons: Record<AiModelType, LucideIcon> = {asr: MicIcon,chat: MessageSquareTextIcon,+ decision: SplitIcon,embedding: BoltIcon,image: ImageIcon,realtime: PhoneIcon,