🤯 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): call OpenAI's native Decisions API from decide() (#21359)
YuTengjing9711bc232918
diff --git a/packages/database/src/models/__tests__/aiModel.generatedModels.test.ts b/packages/database/src/models/__tests__/aiModel.generatedModels.test.tsnew file mode 100644index 00000000000..c776acc1c6f--- /dev/null+++ b/packages/database/src/models/__tests__/aiModel.generatedModels.test.ts@@ -0,0 +1,77 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import type { AiProviderModelListItem } from 'model-bank';+import { CHAT_MODEL_IMAGE_GENERATION_PARAMS } from 'model-bank';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { aiModels, users } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { AiModelModel } from '../aiModel';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'ai-model-generated-models-test-user-id';+const aiProviderModel = new AiModelModel(serverDB, userId);++beforeEach(async () => {+ await serverDB.delete(users).where(eq(users.id, userId));+ await serverDB.insert(users).values({ id: userId });+});++afterEach(async () => {+ await serverDB.delete(aiModels).where(eq(aiModels.userId, userId));+ await serverDB.delete(users).where(eq(users.id, userId));+});++/**+ * Cards generated from a whitelisted chat model (`<id>:image`, `<id>:decision`) can collide+ * with a card the provider already lists under that id; the generated one wins.+ */+describe('AiModelModel.batchUpdateAiModels with generated models', () => {+ it('should keep a generated image model when it follows a provider duplicate', async () => {+ const baseModelId = 'gemini-3.1-flash-image-preview';+ const generatedImageModelId = `${baseModelId}:image`;+ const models = [+ {+ id: baseModelId,+ type: 'chat',+ },+ {+ displayName: 'Provider Image Model',+ id: generatedImageModelId,+ type: 'image',+ },+ {+ displayName: 'LobeHub Image Model',+ id: generatedImageModelId,+ parameters: CHAT_MODEL_IMAGE_GENERATION_PARAMS,+ type: 'image',+ },+ ] as AiProviderModelListItem[];++ const result = await aiProviderModel.batchUpdateAiModels('openai', models);++ expect(result).toHaveLength(2);+ expect(await aiProviderModel.findById(generatedImageModelId)).toMatchObject({+ displayName: 'LobeHub Image Model',+ parameters: CHAT_MODEL_IMAGE_GENERATION_PARAMS,+ });+ });++ it('should keep a generated decision model when it follows a provider duplicate', async () => {+ const models = [+ { id: 'gpt-6-luna', type: 'chat' },+ { displayName: 'Provider Decision Model', id: 'gpt-6-luna:decision', type: 'decision' },+ { displayName: 'GPT-6 Luna Decisions', id: 'gpt-6-luna:decision', type: 'decision' },+ ] as AiProviderModelListItem[];++ const result = await aiProviderModel.batchUpdateAiModels('openai', models);++ expect(result).toHaveLength(2);+ expect(await aiProviderModel.findById('gpt-6-luna:decision')).toMatchObject({+ displayName: 'GPT-6 Luna Decisions',+ type: 'decision',+ });+ });+});diff --git a/packages/database/src/models/__tests__/aiModel.test.ts b/packages/database/src/models/__tests__/aiModel.test.tsindex e51db8ceb1a..6db56438753 100644--- a/packages/database/src/models/__tests__/aiModel.test.ts+++ b/packages/database/src/models/__tests__/aiModel.test.ts@@ -1,7 +1,6 @@// @vitest-environment nodeimport { and, eq, isNull } from 'drizzle-orm';import type { AiProviderModelListItem } from 'model-bank';-import { CHAT_MODEL_IMAGE_GENERATION_PARAMS } from 'model-bank';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { getTestDB } from '../../core/getTestDB';@@ -754,36 +753,6 @@ describe('AiModelModel', () => {});});- it('should keep a generated image model when it follows a provider duplicate', async () => {- const baseModelId = 'gemini-3.1-flash-image-preview';- const generatedImageModelId = `${baseModelId}:image`;- const models = [- {- id: baseModelId,- type: 'chat',- },- {- displayName: 'Provider Image Model',- id: generatedImageModelId,- type: 'image',- },- {- displayName: 'LobeHub Image Model',- id: generatedImageModelId,- parameters: CHAT_MODEL_IMAGE_GENERATION_PARAMS,- type: 'image',- },- ] as AiProviderModelListItem[];-- const result = await aiProviderModel.batchUpdateAiModels('openai', models);-- expect(result).toHaveLength(2);- expect(await aiProviderModel.findById(generatedImageModelId)).toMatchObject({- displayName: 'LobeHub Image Model',- parameters: CHAT_MODEL_IMAGE_GENERATION_PARAMS,- });- });-it('should normalize ISO releasedAt values before inserting remote models', async () => {const models = [{diff --git a/packages/database/src/models/aiModel.ts b/packages/database/src/models/aiModel.tsindex 990ae3cdbc1..1a7988b8678 100644--- a/packages/database/src/models/aiModel.ts+++ b/packages/database/src/models/aiModel.ts@@ -7,15 +7,13 @@ import type {EnabledAiModel,ToggleAiModelEnableParams,} from 'model-bank';-import { AiModelSourceEnum, isAutoGeneratedImageModelId, normalizeAiModelType } from 'model-bank';+import { AiModelSourceEnum, getAutoGeneratedModelSourceId, normalizeAiModelType } from 'model-bank';import type { AiModelSelectItem, NewAiModelItem } from '../schemas';import { aiModels } from '../schemas';import type { LobeChatDatabase } from '../type';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';-const IMAGE_MODEL_SUFFIX = ':image';-export class AiModelModel {private userId: string;private workspaceId?: string;@@ -325,7 +323,8 @@ export class AiModelModel {// non-chat model (e.g. a speech-to-text card) into a `chat` row, which would leak it into// chat pickers. Only the inserted row takes the builtin type; an existing row keeps its own.const type =- value.type ?? (await this.#resolveDefaultModelTypes(value.providerId, [value.id])).get(value.id);+ value.type ??+ (await this.#resolveDefaultModelTypes(value.providerId, [value.id])).get(value.id);if (type) insertValues.type = normalizeAiModelType(type);const updateValues: Partial<typeof aiModels.$inferInsert> = {@@ -362,9 +361,8 @@ export class AiModelModel {continue;}- const shouldKeepLast =- isAutoGeneratedImageModelId(model.id) &&- sourceModelIds.has(model.id.slice(0, -IMAGE_MODEL_SUFFIX.length));+ const sourceModelId = getAutoGeneratedModelSourceId(model.id);+ const shouldKeepLast = !!sourceModelId && sourceModelIds.has(sourceModelId);if (shouldKeepLast) uniqueModelMap.set(model.id, model);}diff --git a/packages/model-bank/package.json b/packages/model-bank/package.jsonindex 12e59ce550f..cbc92e7a8d8 100644--- a/packages/model-bank/package.json+++ b/packages/model-bank/package.json@@ -61,7 +61,7 @@"./nvidia": "./src/aiModels/nvidia.ts","./ollama": "./src/aiModels/ollama.ts","./ollamacloud": "./src/aiModels/ollamacloud.ts",- "./openai": "./src/aiModels/openai.ts",+ "./openai": "./src/aiModels/openai/index.ts","./imageParameters": "./src/const/imageParameters.ts","./opencodeCodingPlan": "./src/aiModels/opencodeCodingPlan.ts","./opencodeZen": "./src/aiModels/opencodeZen.ts",diff --git a/packages/model-bank/src/aiModels/openai/decision.ts b/packages/model-bank/src/aiModels/openai/decision.tsnew file mode 100644index 00000000000..acf1b385c48--- /dev/null+++ b/packages/model-bank/src/aiModels/openai/decision.ts@@ -0,0 +1,33 @@+import type { AIDecisionModelCard } from '../../types/aiModel';++// https://developers.openai.com/api/docs/guides/decisions+export const openaiDecisionModels: AIDecisionModelCard[] = [+ {+ 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',+ /** Sent upstream as `gpt-6-luna`; the suffix only keeps the id apart from the chat card. */+ id: 'gpt-6-luna:decision',+ /**+ * Input only: no output, cache-read or cache-write charges. The long-context multiplier+ * still applies, so the tiers mirror the chat card's input tiers.+ * @see https://developers.openai.com/api/docs/guides/decisions#pricing-and-availability+ */+ pricing: {+ units: [+ {+ name: 'textInput',+ unit: 'millionTokens',+ strategy: 'tiered',+ tiers: [+ { rate: 0.1, upTo: 272_000 },+ { rate: 0.2, upTo: 'infinity' },+ ],+ },+ ],+ },+ releasedAt: '2026-10-06',+ type: 'decision',+ },+];diff --git a/packages/model-bank/src/aiModels/openai.ts b/packages/model-bank/src/aiModels/openai/index.tssimilarity index 76%rename from packages/model-bank/src/aiModels/openai.tsrename to packages/model-bank/src/aiModels/openai/index.tsindex 3fc70ace131..29490d1dd4b 100644--- a/packages/model-bank/src/aiModels/openai.ts+++ b/packages/model-bank/src/aiModels/openai/index.ts@@ -1,13 +1,17 @@-import { gptImage1Schema, gptImage2Schema } from '../const/imageParameters';-import type {- AIASRModelCard,- AIChatModelCard,- AIEmbeddingModelCard,- AIImageModelCard,- AIRealtimeModelCard,- AITTSModelCard,- AIVideoModelCard,-} from '../types/aiModel';+import type { AIChatModelCard } from '../../types/aiModel';+import { openaiDecisionModels } from './decision';+import {+ openaiASRModels,+ openaiEmbeddingModels,+ openaiImageModels,+ openaiRealtimeModels,+ openaiTTSModels,+ openaiVideoModels,+} from './nonChat';++// Keep every card array importable from `model-bank/openai` as before the split.+export * from './decision';+export * from './nonChat';export const openaiChatModels: AIChatModelCard[] = [{@@ -1587,365 +1591,6 @@ export const openaiChatModels: AIChatModelCard[] = [},];-export const openaiEmbeddingModels: AIEmbeddingModelCard[] = [- {- contextWindowTokens: 8192,- description: 'The most capable embedding model for English and non-English tasks.',- displayName: 'Text Embedding 3 Large',- id: 'text-embedding-3-large',- maxDimension: 3072,- pricing: {- currency: 'USD',- units: [{ name: 'textInput', rate: 0.13, strategy: 'fixed', unit: 'millionTokens' }],- },- releasedAt: '2024-01-25',- type: 'embedding',- },- {- contextWindowTokens: 8192,- description:- 'An efficient, cost-effective next-generation embedding model for retrieval and RAG scenarios.',- displayName: 'Text Embedding 3 Small',- id: 'text-embedding-3-small',- maxDimension: 1536,- pricing: {- currency: 'USD',- units: [{ name: 'textInput', rate: 0.02, strategy: 'fixed', unit: 'millionTokens' }],- },- releasedAt: '2024-01-25',- type: 'embedding',- },-];--// Text-to-speech models-export const openaiTTSModels: AITTSModelCard[] = [- {- description: 'The latest text-to-speech model optimized for real-time speed.',- displayName: 'TTS-1',- id: 'tts-1',- pricing: {- units: [{ name: 'textInput', rate: 15, strategy: 'fixed', unit: 'millionCharacters' }],- },- type: 'tts',- },- {- description: 'The latest text-to-speech model optimized for quality.',- displayName: 'TTS-1 HD',- id: 'tts-1-hd',- pricing: {- units: [{ name: 'textInput', rate: 30, strategy: 'fixed', unit: 'millionCharacters' }],- },- type: 'tts',- },- {- description:- 'GPT-4o mini TTS is a text-to-speech model built on GPT-4o mini, converting text into natural-sounding speech with a max input of 2000 tokens.',- displayName: 'GPT-4o Mini TTS',- id: 'gpt-4o-mini-tts',- pricing: {- units: [- { name: 'textInput', rate: 0.6, strategy: 'fixed', unit: 'millionTokens' },- { name: 'audioOutput', rate: 12, strategy: 'fixed', unit: 'millionTokens' },- ],- },- type: 'tts',- },-];--// Speech recognition models-export const openaiASRModels: AIASRModelCard[] = [- {- description:- 'A general speech recognition model supporting multilingual ASR, speech translation, and language identification.',- displayName: 'Whisper',- enabled: true,- id: 'whisper-1',- pricing: {- units: [- {- name: 'audioInput',- rate: 0.0001, // $0.006 per minute => $0.0001 per second- strategy: 'fixed',- unit: 'second',- },- ],- },- type: 'asr',- },- {- contextWindowTokens: 16_000,- description:- 'GPT-4o Transcribe is a speech-to-text model that transcribes audio with GPT-4o, improving word error rate, language ID, and accuracy over the original Whisper model.',- displayName: 'GPT-4o Transcribe',- id: 'gpt-4o-transcribe',- maxOutput: 2000,- pricing: {- units: [- { name: 'textInput', rate: 2.5, strategy: 'fixed', unit: 'millionTokens' },- { name: 'audioInput', rate: 6, strategy: 'fixed', unit: 'millionTokens' },- { name: 'textOutput', rate: 10, strategy: 'fixed', unit: 'millionTokens' },- ],- },- type: 'asr',- },- {- contextWindowTokens: 16_000,- description:- 'GPT-4o Mini Transcribe is a speech-to-text model that transcribes audio with GPT-4o, improving word error rate, language ID, and accuracy over the original Whisper model.',- displayName: 'GPT-4o Mini Transcribe',- enabled: true,- id: 'gpt-4o-mini-transcribe',- maxOutput: 2000,- pricing: {- units: [- { name: 'textInput', rate: 1.25, strategy: 'fixed', unit: 'millionTokens' },- { name: 'audioInput', rate: 3, strategy: 'fixed', unit: 'millionTokens' },- { name: 'textOutput', rate: 5, strategy: 'fixed', unit: 'millionTokens' },- ],- },- type: 'asr',- },-];--// Image generation models-export const openaiImageModels: AIImageModelCard[] = [- {- description:- "OpenAI's next-generation multimodal image model with native reasoning, up to 4K resolution, near-perfect text rendering, and high-fidelity multilingual support.",- displayName: 'GPT Image 2',- enabled: true,- id: 'gpt-image-2',- parameters: gptImage2Schema,- pricing: {- // Medium quality at 1024x1024: ~1767 output tokens * $30/M = $0.053 per image.- // Source: https://developers.openai.com/api/docs/guides/image-generation#calculating-costs- approximatePricePerImage: 0.053,- units: [- { name: 'textInput', rate: 5, strategy: 'fixed', unit: 'millionTokens' },- { name: 'textInput_cacheRead', rate: 1.25, strategy: 'fixed', unit: 'millionTokens' },- { name: 'imageInput', rate: 8, strategy: 'fixed', unit: 'millionTokens' },- { name: 'imageInput_cacheRead', rate: 2, strategy: 'fixed', unit: 'millionTokens' },- { name: 'imageOutput', rate: 30, strategy: 'fixed', unit: 'millionTokens' },- ],- },- releasedAt: '2026-04-21',- type: 'image',- },- {- description:- 'An enhanced GPT Image 1 model with 4× faster generation, more precise editing, and improved text rendering.',- displayName: 'GPT Image 1.5',- id: 'gpt-image-1.5',- parameters: gptImage1Schema,- pricing: {- approximatePricePerImage: 0.034,- units: [- { name: 'textInput', rate: 5, strategy: 'fixed', unit: 'millionTokens' },- { name: 'textInput_cacheRead', rate: 1.25, strategy: 'fixed', unit: 'millionTokens' },- { name: 'imageInput', rate: 8, strategy: 'fixed', unit: 'millionTokens' },- { name: 'imageInput_cacheRead', rate: 2, strategy: 'fixed', unit: 'millionTokens' },- { name: 'imageOutput', rate: 32, strategy: 'fixed', unit: 'millionTokens' },- ],- },- releasedAt: '2025-12-16',- type: 'image',- },- // https://platform.openai.com/docs/models/gpt-image-1- {- description: 'ChatGPT native multimodal image generation model.',- displayName: 'GPT Image 1',- id: 'gpt-image-1',- parameters: gptImage1Schema,- pricing: {- approximatePricePerImage: 0.042,- units: [- { name: 'textInput', rate: 5, strategy: 'fixed', unit: 'millionTokens' },- { name: 'textInput_cacheRead', rate: 1.25, strategy: 'fixed', unit: 'millionTokens' },- { name: 'imageInput', rate: 10, strategy: 'fixed', unit: 'millionTokens' },- { name: 'imageInput_cacheRead', rate: 2.5, strategy: 'fixed', unit: 'millionTokens' },- { name: 'imageOutput', rate: 40, strategy: 'fixed', unit: 'millionTokens' },- ],- },- type: 'image',- },- {- description:- 'A lower-cost GPT Image 1 variant with native text and image input and image output.',- displayName: 'GPT Image 1 Mini',- id: 'gpt-image-1-mini',- parameters: gptImage1Schema,- pricing: {- approximatePricePerImage: 0.011,- units: [- { name: 'textInput', rate: 2, strategy: 'fixed', unit: 'millionTokens' },- { name: 'textInput_cacheRead', rate: 0.2, strategy: 'fixed', unit: 'millionTokens' },- { name: 'imageInput', rate: 2.5, strategy: 'fixed', unit: 'millionTokens' },- { name: 'imageInput_cacheRead', rate: 0.25, strategy: 'fixed', unit: 'millionTokens' },- { name: 'imageOutput', rate: 8, strategy: 'fixed', unit: 'millionTokens' },- ],- },- releasedAt: '2025-10-06',- type: 'image',- },-];--// GPT-4o and GPT-4o-mini realtime models-export const openaiRealtimeModels: AIRealtimeModelCard[] = [- {- abilities: {- functionCall: true,- vision: true,- },- contextWindowTokens: 32_000,- description:- 'A general real-time model supporting real-time text and audio I/O, plus image input.',- displayName: 'GPT Realtime',- id: 'gpt-realtime',- maxOutput: 4096,- pricing: {- units: [- { name: 'audioInput', rate: 32, strategy: 'fixed', unit: 'millionTokens' },- { name: 'audioOutput', rate: 64, strategy: 'fixed', unit: 'millionTokens' },- { name: 'audioInput_cacheRead', rate: 0.4, strategy: 'fixed', unit: 'millionTokens' },-- { name: 'textInput', rate: 4, strategy: 'fixed', unit: 'millionTokens' },- { name: 'textOutput', rate: 16, strategy: 'fixed', unit: 'millionTokens' },- { name: 'textInput_cacheRead', rate: 0.4, strategy: 'fixed', unit: 'millionTokens' },-- { name: 'imageInput', rate: 5, strategy: 'fixed', unit: 'millionTokens' },- { name: 'imageInput_cacheRead', rate: 0.5, strategy: 'fixed', unit: 'millionTokens' },- ],- },- releasedAt: '2025-08-28',- type: 'realtime',- },- {- contextWindowTokens: 16_000,- description: 'GPT-4o realtime variant with audio and text real-time I/O.',- displayName: 'GPT-4o Realtime 241217',- id: 'gpt-4o-realtime-preview',- maxOutput: 4096,- pricing: {- units: [- { name: 'audioInput', rate: 40, strategy: 'fixed', unit: 'millionTokens' },- { name: 'audioOutput', rate: 80, strategy: 'fixed', unit: 'millionTokens' },- { name: 'audioInput_cacheRead', rate: 2.5, strategy: 'fixed', unit: 'millionTokens' },- { name: 'textInput_cacheRead', rate: 2.5, strategy: 'fixed', unit: 'millionTokens' },- { name: 'textInput', rate: 5, strategy: 'fixed', unit: 'millionTokens' },- { name: 'textOutput', rate: 20, strategy: 'fixed', unit: 'millionTokens' },- ],- },- releasedAt: '2024-12-17',- type: 'realtime',- },- {- contextWindowTokens: 32_000,- description: 'GPT-4o realtime variant with audio and text real-time I/O.',- displayName: 'GPT-4o Realtime 250603',- id: 'gpt-4o-realtime-preview-2025-06-03',- maxOutput: 4096,- pricing: {- units: [- { name: 'audioInput', rate: 40, strategy: 'fixed', unit: 'millionTokens' },- { name: 'audioOutput', rate: 80, strategy: 'fixed', unit: 'millionTokens' },- { name: 'audioInput_cacheRead', rate: 2.5, strategy: 'fixed', unit: 'millionTokens' },- { name: 'textInput_cacheRead', rate: 2.5, strategy: 'fixed', unit: 'millionTokens' },- { name: 'textInput', rate: 5, strategy: 'fixed', unit: 'millionTokens' },- { name: 'textOutput', rate: 20, strategy: 'fixed', unit: 'millionTokens' },- ],- },- releasedAt: '2025-06-03',- type: 'realtime',- },- {- contextWindowTokens: 16_000,- description: 'GPT-4o realtime variant with audio and text real-time I/O.',- displayName: 'GPT-4o Realtime 241001',- id: 'gpt-4o-realtime-preview-2024-10-01', // deprecated on 2025-10-10- maxOutput: 4096,- pricing: {- units: [- { name: 'audioInput', rate: 100, strategy: 'fixed', unit: 'millionTokens' },- { name: 'audioOutput', rate: 200, strategy: 'fixed', unit: 'millionTokens' },- { name: 'audioInput_cacheRead', rate: 20, strategy: 'fixed', unit: 'millionTokens' },- { name: 'textInput_cacheRead', rate: 2.5, strategy: 'fixed', unit: 'millionTokens' },- { name: 'textInput', rate: 5, strategy: 'fixed', unit: 'millionTokens' },- { name: 'textOutput', rate: 20, strategy: 'fixed', unit: 'millionTokens' },- ],- },- releasedAt: '2024-10-01',- type: 'realtime',- },- {- contextWindowTokens: 128_000,- description: 'GPT-4o-mini realtime variant with audio and text real-time I/O.',- displayName: 'GPT-4o Mini Realtime',- id: 'gpt-4o-mini-realtime-preview',- maxOutput: 4096,- pricing: {- units: [- { name: 'audioInput', rate: 10, strategy: 'fixed', unit: 'millionTokens' },- { name: 'audioOutput', rate: 20, strategy: 'fixed', unit: 'millionTokens' },- { name: 'audioInput_cacheRead', rate: 0.3, strategy: 'fixed', unit: 'millionTokens' },- { name: 'textInput_cacheRead', rate: 0.3, strategy: 'fixed', unit: 'millionTokens' },- { name: 'textInput', rate: 0.6, strategy: 'fixed', unit: 'millionTokens' },- { name: 'textOutput', rate: 2.4, strategy: 'fixed', unit: 'millionTokens' },- ],- },- releasedAt: '2024-12-17',- type: 'realtime',- },-];--export const openaiVideoModels: AIVideoModelCard[] = [- {- description:- 'Sora 2 is our new powerful media generation model, generating videos with synced audio. It can create richly detailed, dynamic clips from natural language or images.',- displayName: 'Sora 2',- enabled: true,- id: 'sora-2',- parameters: {- duration: { default: 4, enum: [4, 8, 12] },- imageUrl: {- default: null,- },- prompt: { default: '' },- size: {- default: '720x1280',- enum: ['720x1280', '1280x720', '1024x1792', '1792x1024'],- },- },- pricing: {- units: [{ name: 'videoGeneration', rate: 0.1, strategy: 'fixed', unit: 'second' }],- },- releasedAt: '2025-12-08',- type: 'video',- },- {- description:- 'Sora 2 Pro is our state-of-the-art, most advanced media generation model, generating videos with synced audio. It can create richly detailed, dynamic clips from natural language or images.',- displayName: 'Sora 2 Pro',- enabled: true,- id: 'sora-2-pro',- parameters: {- duration: { default: 4, enum: [4, 8, 12] },- imageUrl: {- default: null,- },- prompt: { default: '' },- size: {- default: '720x1280',- enum: ['720x1280', '1280x720', '1024x1792', '1792x1024'],- },- },- pricing: {- units: [{ name: 'videoGeneration', rate: 0.5, strategy: 'fixed', unit: 'second' }],- },- releasedAt: '2025-10-06',- type: 'video',- },-];-export const allModels = [...openaiChatModels,...openaiEmbeddingModels,@@ -1954,6 +1599,7 @@ export const allModels = [...openaiImageModels,...openaiRealtimeModels,...openaiVideoModels,+ ...openaiDecisionModels,];export default allModels;diff --git a/packages/model-bank/src/aiModels/openai/nonChat.ts b/packages/model-bank/src/aiModels/openai/nonChat.tsnew file mode 100644index 00000000000..f91eab1fbf3--- /dev/null+++ b/packages/model-bank/src/aiModels/openai/nonChat.ts@@ -0,0 +1,370 @@+import { gptImage1Schema, gptImage2Schema } from '../../const/imageParameters';+import type {+ AIASRModelCard,+ AIEmbeddingModelCard,+ AIImageModelCard,+ AIRealtimeModelCard,+ AITTSModelCard,+ AIVideoModelCard,+} from '../../types/aiModel';++/** OpenAI cards for endpoints other than chat and decisions; `allModels` lives in `./index`. */++export const openaiEmbeddingModels: AIEmbeddingModelCard[] = [+ {+ contextWindowTokens: 8192,+ description: 'The most capable embedding model for English and non-English tasks.',+ displayName: 'Text Embedding 3 Large',+ id: 'text-embedding-3-large',+ maxDimension: 3072,+ pricing: {+ currency: 'USD',+ units: [{ name: 'textInput', rate: 0.13, strategy: 'fixed', unit: 'millionTokens' }],+ },+ releasedAt: '2024-01-25',+ type: 'embedding',+ },+ {+ contextWindowTokens: 8192,+ description:+ 'An efficient, cost-effective next-generation embedding model for retrieval and RAG scenarios.',+ displayName: 'Text Embedding 3 Small',+ id: 'text-embedding-3-small',+ maxDimension: 1536,+ pricing: {+ currency: 'USD',+ units: [{ name: 'textInput', rate: 0.02, strategy: 'fixed', unit: 'millionTokens' }],+ },+ releasedAt: '2024-01-25',+ type: 'embedding',+ },+];++// Text-to-speech models+export const openaiTTSModels: AITTSModelCard[] = [+ {+ description: 'The latest text-to-speech model optimized for real-time speed.',+ displayName: 'TTS-1',+ id: 'tts-1',+ pricing: {+ units: [{ name: 'textInput', rate: 15, strategy: 'fixed', unit: 'millionCharacters' }],+ },+ type: 'tts',+ },+ {+ description: 'The latest text-to-speech model optimized for quality.',+ displayName: 'TTS-1 HD',+ id: 'tts-1-hd',+ pricing: {+ units: [{ name: 'textInput', rate: 30, strategy: 'fixed', unit: 'millionCharacters' }],+ },+ type: 'tts',+ },+ {+ description:+ 'GPT-4o mini TTS is a text-to-speech model built on GPT-4o mini, converting text into natural-sounding speech with a max input of 2000 tokens.',+ displayName: 'GPT-4o Mini TTS',+ id: 'gpt-4o-mini-tts',+ pricing: {+ units: [+ { name: 'textInput', rate: 0.6, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'audioOutput', rate: 12, strategy: 'fixed', unit: 'millionTokens' },+ ],+ },+ type: 'tts',+ },+];++// Speech recognition models+export const openaiASRModels: AIASRModelCard[] = [+ {+ description:+ 'A general speech recognition model supporting multilingual ASR, speech translation, and language identification.',+ displayName: 'Whisper',+ enabled: true,+ id: 'whisper-1',+ pricing: {+ units: [+ {+ name: 'audioInput',+ rate: 0.0001, // $0.006 per minute => $0.0001 per second+ strategy: 'fixed',+ unit: 'second',+ },+ ],+ },+ type: 'asr',+ },+ {+ contextWindowTokens: 16_000,+ description:+ 'GPT-4o Transcribe is a speech-to-text model that transcribes audio with GPT-4o, improving word error rate, language ID, and accuracy over the original Whisper model.',+ displayName: 'GPT-4o Transcribe',+ id: 'gpt-4o-transcribe',+ maxOutput: 2000,+ pricing: {+ units: [+ { name: 'textInput', rate: 2.5, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'audioInput', rate: 6, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textOutput', rate: 10, strategy: 'fixed', unit: 'millionTokens' },+ ],+ },+ type: 'asr',+ },+ {+ contextWindowTokens: 16_000,+ description:+ 'GPT-4o Mini Transcribe is a speech-to-text model that transcribes audio with GPT-4o, improving word error rate, language ID, and accuracy over the original Whisper model.',+ displayName: 'GPT-4o Mini Transcribe',+ enabled: true,+ id: 'gpt-4o-mini-transcribe',+ maxOutput: 2000,+ pricing: {+ units: [+ { name: 'textInput', rate: 1.25, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'audioInput', rate: 3, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textOutput', rate: 5, strategy: 'fixed', unit: 'millionTokens' },+ ],+ },+ type: 'asr',+ },+];++// Image generation models+export const openaiImageModels: AIImageModelCard[] = [+ {+ description:+ "OpenAI's next-generation multimodal image model with native reasoning, up to 4K resolution, near-perfect text rendering, and high-fidelity multilingual support.",+ displayName: 'GPT Image 2',+ enabled: true,+ id: 'gpt-image-2',+ parameters: gptImage2Schema,+ pricing: {+ // Medium quality at 1024x1024: ~1767 output tokens * $30/M = $0.053 per image.+ // Source: https://developers.openai.com/api/docs/guides/image-generation#calculating-costs+ approximatePricePerImage: 0.053,+ units: [+ { name: 'textInput', rate: 5, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textInput_cacheRead', rate: 1.25, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'imageInput', rate: 8, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'imageInput_cacheRead', rate: 2, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'imageOutput', rate: 30, strategy: 'fixed', unit: 'millionTokens' },+ ],+ },+ releasedAt: '2026-04-21',+ type: 'image',+ },+ {+ description:+ 'An enhanced GPT Image 1 model with 4× faster generation, more precise editing, and improved text rendering.',+ displayName: 'GPT Image 1.5',+ id: 'gpt-image-1.5',+ parameters: gptImage1Schema,+ pricing: {+ approximatePricePerImage: 0.034,+ units: [+ { name: 'textInput', rate: 5, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textInput_cacheRead', rate: 1.25, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'imageInput', rate: 8, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'imageInput_cacheRead', rate: 2, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'imageOutput', rate: 32, strategy: 'fixed', unit: 'millionTokens' },+ ],+ },+ releasedAt: '2025-12-16',+ type: 'image',+ },+ // https://platform.openai.com/docs/models/gpt-image-1+ {+ description: 'ChatGPT native multimodal image generation model.',+ displayName: 'GPT Image 1',+ id: 'gpt-image-1',+ parameters: gptImage1Schema,+ pricing: {+ approximatePricePerImage: 0.042,+ units: [+ { name: 'textInput', rate: 5, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textInput_cacheRead', rate: 1.25, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'imageInput', rate: 10, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'imageInput_cacheRead', rate: 2.5, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'imageOutput', rate: 40, strategy: 'fixed', unit: 'millionTokens' },+ ],+ },+ type: 'image',+ },+ {+ description:+ 'A lower-cost GPT Image 1 variant with native text and image input and image output.',+ displayName: 'GPT Image 1 Mini',+ id: 'gpt-image-1-mini',+ parameters: gptImage1Schema,+ pricing: {+ approximatePricePerImage: 0.011,+ units: [+ { name: 'textInput', rate: 2, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textInput_cacheRead', rate: 0.2, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'imageInput', rate: 2.5, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'imageInput_cacheRead', rate: 0.25, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'imageOutput', rate: 8, strategy: 'fixed', unit: 'millionTokens' },+ ],+ },+ releasedAt: '2025-10-06',+ type: 'image',+ },+];++// GPT-4o and GPT-4o-mini realtime models+export const openaiRealtimeModels: AIRealtimeModelCard[] = [+ {+ abilities: {+ functionCall: true,+ vision: true,+ },+ contextWindowTokens: 32_000,+ description:+ 'A general real-time model supporting real-time text and audio I/O, plus image input.',+ displayName: 'GPT Realtime',+ id: 'gpt-realtime',+ maxOutput: 4096,+ pricing: {+ units: [+ { name: 'audioInput', rate: 32, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'audioOutput', rate: 64, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'audioInput_cacheRead', rate: 0.4, strategy: 'fixed', unit: 'millionTokens' },++ { name: 'textInput', rate: 4, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textOutput', rate: 16, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textInput_cacheRead', rate: 0.4, strategy: 'fixed', unit: 'millionTokens' },++ { name: 'imageInput', rate: 5, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'imageInput_cacheRead', rate: 0.5, strategy: 'fixed', unit: 'millionTokens' },+ ],+ },+ releasedAt: '2025-08-28',+ type: 'realtime',+ },+ {+ contextWindowTokens: 16_000,+ description: 'GPT-4o realtime variant with audio and text real-time I/O.',+ displayName: 'GPT-4o Realtime 241217',+ id: 'gpt-4o-realtime-preview',+ maxOutput: 4096,+ pricing: {+ units: [+ { name: 'audioInput', rate: 40, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'audioOutput', rate: 80, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'audioInput_cacheRead', rate: 2.5, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textInput_cacheRead', rate: 2.5, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textInput', rate: 5, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textOutput', rate: 20, strategy: 'fixed', unit: 'millionTokens' },+ ],+ },+ releasedAt: '2024-12-17',+ type: 'realtime',+ },+ {+ contextWindowTokens: 32_000,+ description: 'GPT-4o realtime variant with audio and text real-time I/O.',+ displayName: 'GPT-4o Realtime 250603',+ id: 'gpt-4o-realtime-preview-2025-06-03',+ maxOutput: 4096,+ pricing: {+ units: [+ { name: 'audioInput', rate: 40, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'audioOutput', rate: 80, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'audioInput_cacheRead', rate: 2.5, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textInput_cacheRead', rate: 2.5, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textInput', rate: 5, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textOutput', rate: 20, strategy: 'fixed', unit: 'millionTokens' },+ ],+ },+ releasedAt: '2025-06-03',+ type: 'realtime',+ },+ {+ contextWindowTokens: 16_000,+ description: 'GPT-4o realtime variant with audio and text real-time I/O.',+ displayName: 'GPT-4o Realtime 241001',+ id: 'gpt-4o-realtime-preview-2024-10-01', // deprecated on 2025-10-10+ maxOutput: 4096,+ pricing: {+ units: [+ { name: 'audioInput', rate: 100, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'audioOutput', rate: 200, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'audioInput_cacheRead', rate: 20, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textInput_cacheRead', rate: 2.5, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textInput', rate: 5, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textOutput', rate: 20, strategy: 'fixed', unit: 'millionTokens' },+ ],+ },+ releasedAt: '2024-10-01',+ type: 'realtime',+ },+ {+ contextWindowTokens: 128_000,+ description: 'GPT-4o-mini realtime variant with audio and text real-time I/O.',+ displayName: 'GPT-4o Mini Realtime',+ id: 'gpt-4o-mini-realtime-preview',+ maxOutput: 4096,+ pricing: {+ units: [+ { name: 'audioInput', rate: 10, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'audioOutput', rate: 20, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'audioInput_cacheRead', rate: 0.3, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textInput_cacheRead', rate: 0.3, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textInput', rate: 0.6, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textOutput', rate: 2.4, strategy: 'fixed', unit: 'millionTokens' },+ ],+ },+ releasedAt: '2024-12-17',+ type: 'realtime',+ },+];++export const openaiVideoModels: AIVideoModelCard[] = [+ {+ description:+ 'Sora 2 is our new powerful media generation model, generating videos with synced audio. It can create richly detailed, dynamic clips from natural language or images.',+ displayName: 'Sora 2',+ enabled: true,+ id: 'sora-2',+ parameters: {+ duration: { default: 4, enum: [4, 8, 12] },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ size: {+ default: '720x1280',+ enum: ['720x1280', '1280x720', '1024x1792', '1792x1024'],+ },+ },+ pricing: {+ units: [{ name: 'videoGeneration', rate: 0.1, strategy: 'fixed', unit: 'second' }],+ },+ releasedAt: '2025-12-08',+ type: 'video',+ },+ {+ description:+ 'Sora 2 Pro is our state-of-the-art, most advanced media generation model, generating videos with synced audio. It can create richly detailed, dynamic clips from natural language or images.',+ displayName: 'Sora 2 Pro',+ enabled: true,+ id: 'sora-2-pro',+ parameters: {+ duration: { default: 4, enum: [4, 8, 12] },+ imageUrl: {+ default: null,+ },+ prompt: { default: '' },+ size: {+ default: '720x1280',+ enum: ['720x1280', '1280x720', '1024x1792', '1792x1024'],+ },+ },+ pricing: {+ units: [{ name: 'videoGeneration', rate: 0.5, strategy: 'fixed', unit: 'second' }],+ },+ releasedAt: '2025-10-06',+ type: 'video',+ },+];diff --git a/packages/model-bank/src/standard-parameters/index.ts b/packages/model-bank/src/standard-parameters/index.tsindex 8425dbfe53c..9eab3ef6de0 100644--- a/packages/model-bank/src/standard-parameters/index.ts+++ b/packages/model-bank/src/standard-parameters/index.ts@@ -64,6 +64,37 @@ export const isAutoGeneratedImageModelId = (modelId: string) => {return IMAGE_GENERATION_MODEL_WHITELIST.some((pattern) => baseModelId.endsWith(pattern));};+/**+ * Chat models that the same provider also serves through a dedicated decision endpoint+ * (OpenAI `POST /v1/decisions`). Model ids must be unique per provider, so the decision card+ * gets a `:decision` suffix that runtimes strip before calling upstream.+ *+ * Matched exactly rather than by suffix like the image whitelist: OpenRouter lists+ * `openai/gpt-6-luna` as a chat model and serves decisions under a different id.+ * @see https://developers.openai.com/api/docs/guides/decisions+ */+export const DECISION_MODEL_WHITELIST = ['gpt-6-luna'] as const;++export const DECISION_MODEL_SUFFIX = ':decision';++export const isAutoGeneratedDecisionModelId = (modelId: string) => {+ if (!modelId.endsWith(DECISION_MODEL_SUFFIX)) return false;++ const baseModelId = modelId.slice(0, -DECISION_MODEL_SUFFIX.length);+ return (DECISION_MODEL_WHITELIST as readonly string[]).includes(baseModelId);+};++/**+ * Returns the source model id of a card generated from a whitelisted chat model+ * (`<id>:image` or `<id>:decision`), or `undefined` for any other id.+ */+export const getAutoGeneratedModelSourceId = (modelId: string): string | undefined => {+ if (isAutoGeneratedImageModelId(modelId)) return modelId.slice(0, -IMAGE_MODEL_SUFFIX.length);+ if (isAutoGeneratedDecisionModelId(modelId)) {+ return modelId.slice(0, -DECISION_MODEL_SUFFIX.length);+ }+};+export const CHAT_MODEL_IMAGE_GENERATION_PARAMS: ModelParamsSchema = {imageUrls: {default: [],diff --git a/packages/model-bank/tsdown.config.ts b/packages/model-bank/tsdown.config.tsindex a081c0fa581..650d20e4e77 100644--- a/packages/model-bank/tsdown.config.ts+++ b/packages/model-bank/tsdown.config.ts@@ -12,6 +12,8 @@ export default defineConfig({'src/modelProviders/lobehub.ts','src/types/index.ts','src/aiModels/*.ts',+ // Providers split into a directory (`openai/`, `google/`, …) export their `index.ts`.+ 'src/aiModels/*/index.ts',],fixedExtension: false,format: ['esm'],diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/decide.openai.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/decide.openai.test.tsnew file mode 100644index 00000000000..db3aa6bb3d5--- /dev/null+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/decide.openai.test.ts@@ -0,0 +1,272 @@+// @vitest-environment node+import { afterEach, describe, expect, it, vi } from 'vitest';++import { LobeOpenAI } from '../../providers/openai';+import type { DecisionPayload } from '../../types';+import { AgentRuntimeErrorType } from '../../types/error';++// Price from the real OpenAI cards so the test also covers the `:decision` card's pricing.+vi.mock('@lobechat/business-model-bank/model-config', async () => {+ const { default: openaiModels } = await import('model-bank/openai');+ return {+ loadModels: async () => openaiModels.map((model) => ({ ...model, providerId: 'openai' })),+ };+});++const createInstance = () => new LobeOpenAI({ apiKey: 'test-key' });++const payload = {+ model: 'gpt-6-luna:decision',+ questions: {+ intent: {+ criteria: { billing: 'Payment problems.', other: null },+ 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 openaiResponse = {+ answers: [+ {+ choice: 'billing',+ confidence: 0.93,+ name: 'intent',+ probabilities: [+ { probability: 0.97, value: 'billing' },+ { probability: 0.03, value: 'other' },+ ],+ type: 'choice',+ },+ { name: 'refund', probability: 0.99, type: 'predicate' },+ {+ confidence: 0.5,+ name: 'urgency',+ probabilities: [+ { label: '0', probability: 0.05, value: 0 },+ { label: '1', probability: 0.25, value: 1 },+ { label: '2', probability: 0.7, value: 2 },+ ],+ score: 1.65,+ type: 'score',+ },+ ],+ model: 'gpt-6-luna-2026-10-06',+ usage: {+ input_tokens: 436,+ input_tokens_details: { cache_write_tokens: 0, cached_tokens: 0 },+ output_tokens: 3,+ output_tokens_details: { reasoning_tokens: 0 },+ total_tokens: 439,+ },+};++describe('decide via the OpenAI Decisions API', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('strips the :decision suffix and sends OpenAI questions without SDK retries', async () => {+ const instance = createInstance();+ const post = vi.spyOn(instance['client'], 'post').mockResolvedValue(openaiResponse as never);++ await instance.decide!(payload, { user: 'user-1' });++ expect(post).toHaveBeenCalledWith(+ '/decisions',+ expect.objectContaining({+ body: {+ input: payload.state,+ model: 'gpt-6-luna',+ questions: [+ {+ choices: [{ description: 'Payment problems.', value: 'billing' }, { value: 'other' }],+ instructions: 'What is the ticket about?',+ name: 'intent',+ type: 'choice',+ },+ {+ instructions:+ 'Is the customer asking for a refund?\n\nTrue when: Asks for money back.\n\nFalse when: No refund requested.',+ name: 'refund',+ type: 'predicate',+ },+ {+ instructions: 'How urgent is the ticket?',+ levels: [+ { description: 'Low', label: '0' },+ { description: 'Medium', label: '1' },+ { description: 'High', label: '2' },+ ],+ name: 'urgency',+ type: 'score',+ },+ ],+ safety_identifier: 'user-1',+ },+ maxRetries: 0,+ }),+ );+ });++ it('maps the answers array back to answers keyed by question name', async () => {+ const instance = createInstance();+ vi.spyOn(instance['client'], 'post').mockResolvedValue(openaiResponse as never);++ const result = await instance.decide!(payload);++ 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' },+ },+ model: 'gpt-6-luna-2026-10-06',+ usage: expect.objectContaining({ totalTokens: 439 }),+ });+ });++ it('prices usage from the :decision card on input tokens only', async () => {+ const instance = createInstance();+ vi.spyOn(instance['client'], 'post').mockResolvedValue(openaiResponse as never);+ const onUsage = vi.fn();+ const onProviderReportedCost = vi.fn();++ const { usage } = await instance.decide!(payload, { onProviderReportedCost, onUsage });++ expect(onUsage).toHaveBeenCalledWith(usage);+ expect(usage).toMatchObject({ inputTextTokens: 436, outputTextTokens: 3, totalTokens: 439 });+ // 436 input tokens × $0.10/M = 43.6 credits, ceiled to whole credits; output tokens are free.+ expect(usage?.cost).toBe(0.000_044);+ // OpenAI reports no charge of its own.+ expect(onProviderReportedCost).not.toHaveBeenCalled();+ });++ it('serializes structured state, instructions and criteria to the strings OpenAI accepts', async () => {+ const instance = createInstance();+ const post = vi.spyOn(instance['client'], 'post').mockResolvedValue({+ answers: [{ name: 'refund', probability: 0.8, type: 'predicate' }],+ model: 'gpt-6-luna',+ } as never);++ const result = await instance.decide!({+ model: 'gpt-6-luna:decision',+ questions: {+ refund: { instructions: { ask: 'Is this a refund request?' }, type: 'boolean' },+ },+ state: { ticket: { body: 'Money back please' } },+ });++ expect(post.mock.calls[0][1]).toMatchObject({+ body: {+ input: '{"ticket":{"body":"Money back please"}}',+ questions: [+ {+ instructions: '{"ask":"Is this a refund request?"}',+ name: 'refund',+ type: 'predicate',+ },+ ],+ },+ });+ expect(result.answers.refund).toEqual({ probability: 0.8, type: 'boolean' });+ expect(result.usage).toBeUndefined();+ });++ it('returns a refusal as an answer, including one without a name', async () => {+ const instance = createInstance();+ vi.spyOn(instance['client'], 'post').mockResolvedValue({+ ...openaiResponse,+ answers: [{ name: null, type: 'refusal' }, ...openaiResponse.answers.slice(1)],+ } as never);++ const result = await instance.decide!(payload);++ expect(result.answers.intent).toEqual({ type: 'refusal' });+ expect(result.answers.refund).toEqual({ probability: 0.99, type: 'boolean' });+ });++ it('omits probabilities when the provider does not report a distribution', async () => {+ const instance = createInstance();+ const [intent, refund, urgency] = openaiResponse.answers;+ const { probabilities: _, ...intentWithout } = intent as typeof intent & {+ probabilities: unknown;+ };+ const { probabilities: __, ...urgencyWithout } = urgency as typeof urgency & {+ probabilities: unknown;+ };+ vi.spyOn(instance['client'], 'post').mockResolvedValue({+ ...openaiResponse,+ answers: [intentWithout, refund, urgencyWithout],+ } 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' });+ });++ const [intentAnswer, refundAnswer, urgencyAnswer] = openaiResponse.answers;++ it.each([+ [+ 'a choice outside the requested options',+ [{ ...intentAnswer, choice: 'shipping' }, refundAnswer, urgencyAnswer],+ ],+ ['a boolean choice value', [{ ...intentAnswer, choice: true }, refundAnswer, urgencyAnswer]],+ [+ 'a choice without a probability for every option',+ [+ { ...intentAnswer, probabilities: [{ probability: 1, value: 'billing' }] },+ refundAnswer,+ urgencyAnswer,+ ],+ ],+ [+ 'a score without a probability for every level',+ [+ intentAnswer,+ refundAnswer,+ {+ ...urgencyAnswer,+ probabilities: [+ { probability: 0.3, value: 0 },+ { probability: 0.7, value: 1 },+ ],+ },+ ],+ ],+ ['an answer of the wrong type', [intentAnswer, intentAnswer, urgencyAnswer]],+ ['a missing answer', [intentAnswer, refundAnswer]],+ ['answers in a different order', [refundAnswer, intentAnswer, urgencyAnswer]],+ ])('rejects %s as a provider error', async (_, answers) => {+ const instance = createInstance();+ vi.spyOn(instance['client'], 'post').mockResolvedValue({+ ...openaiResponse,+ answers,+ } as never);+ const onUsage = vi.fn();++ await expect(instance.decide!(payload, { onUsage })).rejects.toMatchObject({+ errorType: AgentRuntimeErrorType.ProviderBizError,+ provider: 'openai',+ });+ expect(onUsage).not.toHaveBeenCalled();+ });+});diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/decide.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/decide.test.tsindex 73beac2632d..599858d98ef 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/decide.test.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/decide.test.ts@@ -16,7 +16,7 @@ vi.mock('@lobechat/business-model-bank/model-config', async () => {const DecideRuntime = createOpenAICompatibleRuntime({baseURL: 'https://openrouter.ai/api/v1',- decide: { path: '/systemone' },+ decide: { path: '/systemone', protocol: 'systemone' },provider: 'openrouter',});diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/decide.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/decide.tsdeleted file mode 100644index efe28796849..00000000000--- a/packages/model-runtime/src/core/openaiCompatibleFactory/decide.ts+++ /dev/null@@ -1,253 +0,0 @@-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/decide/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/decide/index.tsnew file mode 100644index 00000000000..9dc14aa6b14--- /dev/null+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/decide/index.ts@@ -0,0 +1,144 @@+import type { ModelUsage } from '@lobechat/types';+import { AgentRuntimeErrorType } from '@lobechat/types';+import { isRecord } from '@lobechat/utils/object';+import createDebug from 'debug';+import { DECISION_MODEL_SUFFIX } from 'model-bank';+import type OpenAI from 'openai';++import type { DecisionOptions, DecisionPayload, 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';+import { openaiDecisionAdapter } from './openai';+import type { DecisionWireAdapter } from './shared';+import { InvalidDecisionResponseError } from './shared';+import { systemOneDecisionAdapter } from './systemOne';++const log = createDebug('lobe-model-runtime:decide');++const adapters = {+ openai: openaiDecisionAdapter,+ systemone: systemOneDecisionAdapter,+} satisfies Record<string, DecisionWireAdapter>;++/**+ * Serves decision models through a dedicated endpoint. Only providers that set this expose+ * `decide`, so callers can tell decision support apart from plain chat compatibility.+ */+export interface DecideConfig {+ /** Endpoint path relative to the client base URL, e.g. `/systemone` or `/decisions`. */+ path: string;+ /**+ * Wire format of the endpoint: `systemone` for TypeSafe / OpenRouter System One, `openai`+ * for the OpenAI Decisions API.+ */+ protocol: keyof typeof adapters;+}++const toProviderReportedCost = (value: unknown): number | undefined =>+ typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;++/**+ * `<id>:decision` only keeps a decision card apart from the chat card with the same upstream id+ * (see `DECISION_MODEL_WHITELIST`); upstream never knows the suffix.+ */+const toUpstreamModelId = (model: string) =>+ model.endsWith(DECISION_MODEL_SUFFIX) ? model.slice(0, -DECISION_MODEL_SUFFIX.length) : model;++interface RequestDecisionParams extends DecideConfig {+ provider: string;+ /** Model id sent upstream; may differ from `payload.model` after id mapping. */+ requestModel: string;+}++const requestDecision = async (+ client: OpenAI,+ payload: DecisionPayload,+ options: DecisionOptions | undefined,+ { path, protocol, provider, requestModel }: RequestDecisionParams,+): Promise<DecisionResponse> => {+ const adapter = adapters[protocol];+ 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 protocol=%s model=%s questions=%d', protocol, requestModel, questionEntries.length);++ const raw = await client.post(path, {+ body: adapter.buildBody({ payload, questionEntries, requestModel, 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,+ });++ let parsed: ReturnType<DecisionWireAdapter['parseResponse']>;+ try {+ parsed = adapter.parseResponse(raw, questionEntries);+ } catch (error) {+ if (!(error instanceof InvalidDecisionResponseError)) throw error;+ throw AgentRuntimeError.chat({+ error: { message: `Invalid decision response: ${error.message}` },+ errorType: AgentRuntimeErrorType.ProviderBizError,+ provider,+ });+ }++ const response: DecisionResponse = parsed.response;+ const usage = parsed.usage;+ if (usage) {+ const outputTokens = usage.outputTokens ?? 0;+ const tokens = {+ inputTextTokens: usage.inputTokens,+ // 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.inputTokens,+ totalOutputTokens: outputTokens,+ totalTokens: usage.inputTokens + 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.providerReportedCost);+ if (providerReportedCost !== undefined) {+ await options?.onProviderReportedCost?.(providerReportedCost);+ }+ }++ return response;+};++interface CreateDecisionParams extends DecideConfig {+ /** Maps transport failures (HTTP, network) to the provider's runtime error payload. */+ handleError: (error: unknown) => unknown;+ modelIdMappingOptions?: ModelIdMappingOptions;+ provider: string;+}++export const createDecision = async (+ client: OpenAI,+ payload: DecisionPayload,+ options: DecisionOptions | undefined,+ { handleError, modelIdMappingOptions, ...params }: CreateDecisionParams,+): Promise<DecisionResponse> => {+ try {+ return await requestDecision(client, payload, options, {+ ...params,+ requestModel: toUpstreamModelId(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/decide/openai.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/decide/openai.tsnew file mode 100644index 00000000000..ede0d6d4628--- /dev/null+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/decide/openai.ts@@ -0,0 +1,210 @@+import { z } from 'zod';++import type { DecisionAnswer, DecisionContent, DecisionQuestion } from '../../../types';+import type { DecisionWireAdapter } from './shared';+import {+ assertRequestedChoice,+ InvalidDecisionResponseError,+ pickChoiceProbabilities,+ pickScoreProbabilities,+} from './shared';++/**+ * OpenAI Decisions API wire format (`POST /v1/decisions`). Questions are an ordered array of+ * named `predicate` / `choice` / `score` items and answers come back in the same order.+ * Field shapes follow the `openai` SDK `resources/decisions` types (v7.30+).+ * @see https://developers.openai.com/api/docs/guides/decisions+ */+const ProbabilitySchema = z.number().min(0).max(1);++const OpenAIDecisionAnswerSchema = z.discriminatedUnion('type', [+ z.object({+ name: z.string().nullable(),+ probability: ProbabilitySchema,+ type: z.literal('predicate'),+ }),+ z.object({+ /** Choice values are typed upstream; we only send strings, so a boolean never matches. */+ choice: z.union([z.string(), z.boolean()]),+ confidence: z.number().optional(),+ name: z.string().nullable(),+ probabilities: z+ .array(+ z.object({ probability: ProbabilitySchema, value: z.union([z.string(), z.boolean()]) }),+ )+ .optional(),+ type: z.literal('choice'),+ }),+ z.object({+ confidence: z.number().optional(),+ name: z.string().nullable(),+ probabilities: z+ .array(+ z.object({+ label: z.string().optional(),+ probability: ProbabilitySchema,+ /** Zero-based level index. */+ value: z.number().int().nonnegative(),+ }),+ )+ .optional(),+ score: z.number(),+ type: z.literal('score'),+ }),+ // A refusal carries only the question name; `name` is null for unnamed questions.+ z.object({ name: z.string().nullable(), type: z.literal('refusal') }).passthrough(),+]);++const OpenAIDecisionResponseSchema = z.object({+ answers: z.array(OpenAIDecisionAnswerSchema),+ id: z.string().optional(),+ model: z.string(),+ usage: z+ .object({+ input_tokens: z.number().int().nonnegative(),+ output_tokens: z.number().int().nonnegative().optional(),+ })+ .optional(),+});++type OpenAIDecisionAnswer = z.infer<typeof OpenAIDecisionAnswerSchema>;++/** OpenAI accepts only strings for `input`, `instructions`, and option descriptions. */+const toText = (content: DecisionContent): string =>+ typeof content === 'string' ? content : JSON.stringify(content);++/**+ * `predicate` questions have no criteria field, so the true/false guidance goes into the+ * instructions the model reads.+ */+const toPredicateInstructions = (+ question: Extract<DecisionQuestion, { type: 'boolean' }>,+): string => {+ const instructions = toText(question.instructions);+ if (!question.criteria) return instructions;++ return [+ instructions,+ `True when: ${toText(question.criteria.true)}`,+ `False when: ${toText(question.criteria.false)}`,+ ].join('\n\n');+};++const toOpenAIQuestion = (name: string, question: DecisionQuestion) => {+ switch (question.type) {+ case 'boolean': {+ return { instructions: toPredicateInstructions(question), name, type: 'predicate' };+ }++ case 'choice': {+ return {+ choices: Object.entries(question.criteria).map(([value, description]) => ({+ ...(description !== null && { description: toText(description) }),+ value,+ })),+ instructions: toText(question.instructions),+ name,+ type: 'choice',+ };+ }++ case 'score': {+ return {+ instructions: toText(question.instructions),+ // `label` is required upstream; our rubric has descriptions only, so label by index,+ // which is also the value the response reports per level.+ levels: question.criteria.map((criterion, level) => ({+ description: toText(criterion),+ label: String(level),+ })),+ name,+ type: 'score',+ };+ }+ }+};++const toDecisionAnswer = (+ name: string,+ question: DecisionQuestion,+ answer: OpenAIDecisionAnswer | undefined,+): DecisionAnswer => {+ if (!answer) throw new InvalidDecisionResponseError(`Missing answer for question "${name}"`);+ // Answers are positional; a reported name must still match so a reordered response is caught.+ if (answer.name !== null && answer.name !== name) {+ throw new InvalidDecisionResponseError(+ `Expected the answer to question "${name}" but got "${answer.name}"`,+ );+ }+ if (answer.type === 'refusal') return { type: 'refusal' };++ if (question.type === 'boolean' && answer.type === 'predicate') {+ return { probability: answer.probability, type: 'boolean' };+ }++ if (question.type === 'choice' && answer.type === 'choice') {+ const choice = assertRequestedChoice(name, question, answer.choice);+ const reported = answer.probabilities;+ const probabilities =+ reported &&+ pickChoiceProbabilities(+ name,+ question,+ (option) => reported.find((entry) => entry.value === option)?.probability,+ );+ return { choice, confidence: answer.confidence, probabilities, type: 'choice' };+ }++ if (question.type === 'score' && answer.type === 'score') {+ const reported = answer.probabilities;+ const probabilities =+ reported &&+ pickScoreProbabilities(+ name,+ question,+ (level) => reported.find((entry) => entry.value === level)?.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`,+ );+};++export const openaiDecisionAdapter: DecisionWireAdapter = {+ buildBody: ({ payload, questionEntries, requestModel, user }) => ({+ input: toText(payload.state),+ model: requestModel,+ questions: questionEntries.map(([name, question]) => toOpenAIQuestion(name, question)),+ // The Decisions API takes `safety_identifier` (like Responses) rather than `user`.+ ...(user && { safety_identifier: user }),+ }),++ parseResponse: (raw, questionEntries) => {+ const parsed = OpenAIDecisionResponseSchema.safeParse(raw);+ if (!parsed.success) throw new InvalidDecisionResponseError(parsed.error.message);++ const { answers, id, model, usage } = parsed.data;+ if (answers.length !== questionEntries.length) {+ throw new InvalidDecisionResponseError(+ `Expected ${questionEntries.length} answers but got ${answers.length}`,+ );+ }++ return {+ response: {+ answers: Object.fromEntries(+ questionEntries.map(([name, question], index) => [+ name,+ toDecisionAnswer(name, question, answers[index]),+ ]),+ ),+ id,+ model,+ },+ // OpenAI reports no charge; cost comes from the model card's input-only pricing.+ usage: usage && { inputTokens: usage.input_tokens, outputTokens: usage.output_tokens },+ };+ },+};diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/decide/shared.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/decide/shared.tsnew file mode 100644index 00000000000..4e80d9da282--- /dev/null+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/decide/shared.ts@@ -0,0 +1,94 @@+import type {+ DecisionChoiceQuestion,+ DecisionPayload,+ DecisionQuestion,+ DecisionResponse,+ DecisionScoreQuestion,+} from '../../../types';++/** A response that does not answer what was asked; mapped to `ProviderBizError`. */+export class InvalidDecisionResponseError extends Error {}++export type DecisionQuestionEntries = [name: string, question: DecisionQuestion][];++export interface DecisionWireUsage {+ inputTokens: number;+ outputTokens?: number;+ /** Raw provider charge, validated before it reaches `onProviderReportedCost`. */+ providerReportedCost?: unknown;+}++export interface ParsedDecisionWireResponse {+ response: Omit<DecisionResponse, 'usage'>;+ usage?: DecisionWireUsage;+}++/** Translates the provider-neutral decision protocol to one endpoint's wire format. */+export interface DecisionWireAdapter {+ buildBody: (params: {+ payload: DecisionPayload;+ questionEntries: DecisionQuestionEntries;+ /** Model id sent upstream; may differ from `payload.model` after id mapping. */+ requestModel: string;+ user?: string;+ }) => Record<string, unknown>;+ /**+ * Maps the raw response back to answers keyed by question name.+ * Throws {@link InvalidDecisionResponseError} when it is malformed or incomplete.+ */+ parseResponse: (+ raw: unknown,+ questionEntries: DecisionQuestionEntries,+ ) => ParsedDecisionWireResponse;+}++export const assertRequestedChoice = (+ name: string,+ question: DecisionChoiceQuestion,+ choice: unknown,+): string => {+ // Own keys only: option names such as `toString` would otherwise hit the prototype.+ if (typeof choice !== 'string' || !Object.hasOwn(question.criteria, choice)) {+ throw new InvalidDecisionResponseError(+ `Question "${name}" chose "${String(choice)}", which is not a requested option`,+ );+ }+ return choice;+};++/**+ * The distribution is optional upstream, but a partial one would read a gap as zero, so every+ * requested option must be reported.+ */+export const pickChoiceProbabilities = (+ name: string,+ question: DecisionChoiceQuestion,+ getProbability: (option: string) => number | undefined,+): Record<string, number> =>+ Object.fromEntries(+ Object.keys(question.criteria).map((option) => {+ const probability = getProbability(option);+ if (probability === undefined) {+ throw new InvalidDecisionResponseError(+ `Question "${name}" has no probability for option "${option}"`,+ );+ }+ return [option, probability];+ }),+ );++/** A missing level probability is not evidence of zero, so reject rather than fill it. */+export const pickScoreProbabilities = (+ name: string,+ question: DecisionScoreQuestion,+ getProbability: (level: number) => number | undefined,+): number[] =>+ question.criteria.map((_, level) => {+ const probability = getProbability(level);+ if (probability === undefined) {+ throw new InvalidDecisionResponseError(+ `Question "${name}" has no probability for score level ${level}`,+ );+ }+ return probability;+ });diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/decide/systemOne.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/decide/systemOne.tsnew file mode 100644index 00000000000..e8d368b914f--- /dev/null+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/decide/systemOne.ts@@ -0,0 +1,127 @@+import { z } from 'zod';++import type { DecisionAnswer, DecisionQuestion } from '../../../types';+import type { DecisionWireAdapter } from './shared';+import {+ assertRequestedChoice,+ InvalidDecisionResponseError,+ pickChoiceProbabilities,+ pickScoreProbabilities,+} from './shared';++/**+ * 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 toSystemOneQuestion = (question: DecisionQuestion) =>+ question.type === 'boolean' ? { ...question, type: 'noul' as const } : question;++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') {+ const choice = assertRequestedChoice(name, question, answer.choice);+ const reported = answer.probabilities;+ const probabilities =+ reported &&+ pickChoiceProbabilities(name, question, (option) =>+ Object.hasOwn(reported, option) ? reported[option] : undefined,+ );+ return { choice, confidence: answer.confidence, probabilities, type: 'choice' };+ }++ if (question.type === 'score' && answer.type === 'score') {+ const reported = answer.probabilities;+ const probabilities =+ reported && pickScoreProbabilities(name, question, (level) => reported[String(level)]);+ 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`,+ );+};++export const systemOneDecisionAdapter: DecisionWireAdapter = {+ buildBody: ({ payload, questionEntries, requestModel, user }) => ({+ model: requestModel,+ questions: Object.fromEntries(+ questionEntries.map(([name, question]) => [name, toSystemOneQuestion(question)]),+ ),+ state: payload.state,+ ...(user && { user }),+ }),++ parseResponse: (raw, questionEntries) => {+ const parsed = SystemOneResponseSchema.safeParse(raw);+ if (!parsed.success) throw new InvalidDecisionResponseError(parsed.error.message);++ const { answers, id, model, provider, usage } = parsed.data;+ return {+ response: {+ answers: Object.fromEntries(+ questionEntries.map(([name, question]) => [+ name,+ toDecisionAnswer(name, question, answers[name]),+ ]),+ ),+ id,+ model,+ provider,+ },+ usage: usage && {+ inputTokens: usage.input_tokens,+ outputTokens: usage.output_tokens,+ providerReportedCost: usage.cost,+ },+ };+ },+};diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/factoryOptions.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/factoryOptions.tsindex 232314b14d7..9812658b042 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/factoryOptions.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/factoryOptions.ts@@ -23,7 +23,7 @@ import type {import type { ModelIdMappingOptions } from '../../utils/modelIdMapping';import type { AssertContextWithinWindowOptions } from '../../utils/resolveSafeMaxTokens';import type { ChatPayloadForTransformStream } from '../streams/protocol';-import type { SystemOneDecideConfig } from './decide';+import type { DecideConfig } 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.@@ -142,7 +142,7 @@ export interface OpenAICompatibleFactoryOptions<T extends Record<string, any> =chatCompletion: () => boolean;responses?: () => boolean;};- decide?: SystemOneDecideConfig;+ decide?: DecideConfig;errorType?: {bizError: ILobeAgentRuntimeErrorType;invalidAPIKey: ILobeAgentRuntimeErrorType;diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.tsindex 6b1daf9ed33..02f8cb7c455 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts@@ -74,7 +74,7 @@ import {import { OpenAICompatibleClient } from './client';import { createOpenAICompatibleImage } from './createImage';import { createOpenAICompatibleVideo, pollOpenAICompatibleVideoStatus } from './createVideo';-import { createSystemOneDecision } from './decide';+import { createDecision } from './decide';import type {ChatCompletionCreateParamsWithPromptCacheKey,ConstructorOptions,@@ -253,7 +253,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anif (decideConfig) {this.decide = (payload, decideOptions) =>- createSystemOneDecision(this.client, payload, decideOptions, {+ createDecision(this.client, payload, decideOptions, {...decideConfig,handleError: (error) => this.handleError(error),modelIdMappingOptions: this.modelIdMappingOptions,diff --git a/packages/model-runtime/src/providers/openai/index.test.ts b/packages/model-runtime/src/providers/openai/index.test.tsindex a2d89c8aa30..a0c87b52f8a 100644--- a/packages/model-runtime/src/providers/openai/index.test.ts+++ b/packages/model-runtime/src/providers/openai/index.test.ts@@ -282,6 +282,20 @@ describe('LobeOpenAI', () => {expect(textEmbeddingAda).toBeDefined();expect(textEmbeddingAda?.type).toBe('embedding');});++ it('lists a decision card next to a chat model served by the Decisions API', async () => {+ (instance['client'].models.list as Mock).mockResolvedValue({+ data: [{ created: 1_780_000_000, id: 'gpt-6-luna', object: 'model', owned_by: 'system' }],+ });++ const list = await instance.models();++ expect(list.find((model) => model.id === 'gpt-6-luna')?.type).toBe('chat');+ expect(list.find((model) => model.id === 'gpt-6-luna:decision')).toMatchObject({+ displayName: 'GPT-6 Luna Decisions',+ type: 'decision',+ });+ });});describe('chatCompletion.handlePayload', () => {diff --git a/packages/model-runtime/src/providers/openai/index.ts b/packages/model-runtime/src/providers/openai/index.tsindex 5b064aec999..c749a16e7a9 100644--- a/packages/model-runtime/src/providers/openai/index.ts+++ b/packages/model-runtime/src/providers/openai/index.ts@@ -5,6 +5,7 @@ import type { OpenAICompatibleFactoryOptions } from '../../core/openaiCompatibleimport { createOpenAICompatibleRuntime } from '../../core/openaiCompatibleFactory';import type { ChatStreamPayload } from '../../types';import { processMultiProviderModelList } from '../../utils/modelParse';+import { appendDecisionModels } from '../../utils/postProcessModelList';import {isGPTProResponsesModel,isOpenAIComputerUseModel,@@ -76,6 +77,8 @@ export const params = {},supportsAudioInput: true,},+ /** @see https://developers.openai.com/api/docs/guides/decisions */+ decide: { path: '/decisions', protocol: 'openai' },debug: {chatCompletion: () => process.env.DEBUG_OPENAI_CHAT_COMPLETION === '1',responses: () => process.env.DEBUG_OPENAI_RESPONSES === '1',@@ -85,7 +88,9 @@ export const params = {const modelList: OpenAIModelCard[] = modelsPage.data;// Automatically detect model provider and select corresponding configuration- return processMultiProviderModelList(modelList, 'openai');+ const models = await processMultiProviderModelList(modelList, 'openai');+ // `decide` serves these through `/decisions`, so list their `:decision` cards too.+ return appendDecisionModels(models);},provider: ModelProvider.OpenAI,responses: {diff --git a/packages/model-runtime/src/providers/openrouter/index.ts b/packages/model-runtime/src/providers/openrouter/index.tsindex a3451c02bcb..91b76b72488 100644--- a/packages/model-runtime/src/providers/openrouter/index.ts+++ b/packages/model-runtime/src/providers/openrouter/index.ts@@ -105,7 +105,7 @@ export const params = {debug: {chatCompletion: () => process.env.DEBUG_OPENROUTER_CHAT_COMPLETION === '1',},- decide: { path: '/systemone' },+ decide: { path: '/systemone', protocol: 'systemone' },models: async () => {// The default listing omits decision models; they are only returned when filtering by// their output modality, so fetch both lists.diff --git a/packages/model-runtime/src/utils/postProcessModelList.test.ts b/packages/model-runtime/src/utils/postProcessModelList.test.tsindex 76a0d777c6a..bf64aca161d 100644--- a/packages/model-runtime/src/utils/postProcessModelList.test.ts+++ b/packages/model-runtime/src/utils/postProcessModelList.test.ts@@ -4,7 +4,9 @@ import type * as ModelBankModule from 'model-bank';import { describe, expect, it, vi } from 'vitest';import {+ appendDecisionModels,IMAGE_GENERATION_MODEL_WHITELIST,+ isAutoGeneratedDecisionModelId,isAutoGeneratedImageModelId,postProcessModelList,} from './postProcessModelList';@@ -42,6 +44,66 @@ describe('isAutoGeneratedImageModelId', () => {});});+describe('isAutoGeneratedDecisionModelId', () => {+ it('identifies decision ids generated from whitelisted chat models', () => {+ expect(isAutoGeneratedDecisionModelId('gpt-6-luna:decision')).toBe(true);+ });++ it('rejects base models, prefixed ids and non-whitelisted decision ids', () => {+ expect(isAutoGeneratedDecisionModelId('gpt-6-luna')).toBe(false);+ expect(isAutoGeneratedDecisionModelId('openai/gpt-6-luna:decision')).toBe(false);+ expect(isAutoGeneratedDecisionModelId('custom-decider:decision')).toBe(false);+ });+});++describe('appendDecisionModels', () => {+ const lunaChat: ChatModelCard = {+ contextWindowTokens: 1_050_000,+ displayName: 'GPT-6 Luna',+ enabled: true,+ functionCall: true,+ id: 'gpt-6-luna',+ pricing: { units: [{ name: 'textOutput', rate: 1, strategy: 'fixed', unit: 'millionTokens' }] },+ reasoning: true,+ type: 'chat',+ vision: true,+ };++ it('generates a :decision card from the builtin decision card, not the chat card', () => {+ const result = appendDecisionModels([lunaChat]);++ expect(result).toHaveLength(2);+ expect(result[1]).toEqual({+ contextWindowTokens: 1_050_000,+ description: expect.stringContaining('Decisions API'),+ displayName: 'GPT-6 Luna Decisions',+ enabled: true,+ id: 'gpt-6-luna:decision',+ pricing: {+ units: [expect.objectContaining({ name: 'textInput', strategy: 'tiered' })],+ },+ releasedAt: '2026-10-06',+ type: 'decision',+ });+ });++ it('leaves decision cards out of the generic post-processing other providers use', async () => {+ const result = await postProcessModelList([lunaChat]);++ expect(result.map((model) => model.id)).toEqual(['gpt-6-luna']);+ });++ it('only matches whitelisted chat ids exactly', () => {+ const result = appendDecisionModels([+ { ...lunaChat, id: 'openai/gpt-6-luna' },+ { ...lunaChat, id: 'gpt-6-luna-2026-10-06' },+ { ...lunaChat, type: 'embedding' },+ ]);++ expect(result.some((model) => model.type === 'decision')).toBe(false);+ });+});+describe('postProcessModelList', () => {const mockModels: ChatModelCard[] = [{diff --git a/packages/model-runtime/src/utils/postProcessModelList.ts b/packages/model-runtime/src/utils/postProcessModelList.tsindex ae279b934f1..fcaa5cfd51d 100644--- a/packages/model-runtime/src/utils/postProcessModelList.ts+++ b/packages/model-runtime/src/utils/postProcessModelList.ts@@ -1,9 +1,57 @@import type { ChatModelCard } from '@lobechat/types';import { omit } from 'es-toolkit/compat';import type { AiModelType } from 'model-bank';-import { CHAT_MODEL_IMAGE_GENERATION_PARAMS, IMAGE_GENERATION_MODEL_WHITELIST } from 'model-bank';+import {+ CHAT_MODEL_IMAGE_GENERATION_PARAMS,+ DECISION_MODEL_SUFFIX,+ DECISION_MODEL_WHITELIST,+ IMAGE_GENERATION_MODEL_WHITELIST,+ LOBE_DEFAULT_MODEL_LIST,+} from 'model-bank';-export { IMAGE_GENERATION_MODEL_WHITELIST, isAutoGeneratedImageModelId } from 'model-bank';+export {+ DECISION_MODEL_WHITELIST,+ IMAGE_GENERATION_MODEL_WHITELIST,+ isAutoGeneratedDecisionModelId,+ isAutoGeneratedImageModelId,+} from 'model-bank';++const toDecisionModel = (model: ChatModelCard): ChatModelCard => {+ const id = `${model.id}${DECISION_MODEL_SUFFIX}`;+ // The chat card's abilities and output pricing do not apply to the decision endpoint.+ const builtin = LOBE_DEFAULT_MODEL_LIST.find(+ (card) => card.id === id && card.type === 'decision',+ );++ return {+ contextWindowTokens: builtin?.contextWindowTokens ?? model.contextWindowTokens,+ description: builtin?.description,+ displayName: builtin?.displayName ?? model.displayName,+ enabled: model.enabled,+ id,+ pricing: builtin?.pricing,+ releasedAt: builtin?.releasedAt ?? model.releasedAt,+ type: 'decision',+ };+};++/**+ * Appends a `<id>:decision` card for each whitelisted chat model in the list.+ *+ * Only providers that serve those models through `decide()` call this from their `models()`,+ * so other providers listing the same id (aggregators, proxies) do not get a decision card that+ * would fail with `CapabilityNotSupported`.+ */+export const appendDecisionModels = (models: ChatModelCard[]): ChatModelCard[] => [+ ...models,+ ...models+ .filter(+ (model) =>+ (model.type ?? 'chat') === 'chat' &&+ (DECISION_MODEL_WHITELIST as readonly string[]).includes(model.id),+ )+ .map(toDecisionModel),+];/*** Process model list: ensure type field exists and generate image generation models for whitelisted modelsdiff --git a/src/store/aiInfra/slices/aiModel/utils.test.ts b/src/store/aiInfra/slices/aiModel/utils.test.tsindex 8e49e44ba8e..f2f8d8cd0ec 100644--- a/src/store/aiInfra/slices/aiModel/utils.test.ts+++ b/src/store/aiInfra/slices/aiModel/utils.test.ts@@ -50,6 +50,20 @@ describe('deduplicateRemoteModels', () => {]);});+ it('should keep the last auto-generated decision model with a duplicate id', () => {+ const result = deduplicateRemoteModels([+ { id: 'gpt-6-luna', source: 'base' },+ { id: 'gpt-6-luna:decision', source: 'provider' },+ { id: 'gpt-6-luna:decision', source: 'generated' },+ ]);++ expect(result.models).toEqual([+ { id: 'gpt-6-luna', source: 'base' },+ { id: 'gpt-6-luna:decision', source: 'generated' },+ ]);+ expect(result.duplicateIds).toEqual(['gpt-6-luna:decision']);+ });+it('should count every removed entry while reporting each duplicate id once', () => {const result = deduplicateRemoteModels([{ id: 'duplicate-model', value: 1 },diff --git a/src/store/aiInfra/slices/aiModel/utils.ts b/src/store/aiInfra/slices/aiModel/utils.tsindex cd9998166dc..bf974eb6edd 100644--- a/src/store/aiInfra/slices/aiModel/utils.ts+++ b/src/store/aiInfra/slices/aiModel/utils.ts@@ -1,6 +1,4 @@-import { isAutoGeneratedImageModelId } from 'model-bank/standardParameters';--const IMAGE_MODEL_SUFFIX = ':image';+import { getAutoGeneratedModelSourceId } from 'model-bank/standardParameters';interface ModelWithId {id: string;@@ -31,9 +29,8 @@ export const deduplicateRemoteModels = <T extends ModelWithId>(duplicateIdSet.add(model.id);}- const shouldKeepLast =- isAutoGeneratedImageModelId(model.id) &&- sourceModelIds.has(model.id.slice(0, -IMAGE_MODEL_SUFFIX.length));+ const sourceModelId = getAutoGeneratedModelSourceId(model.id);+ const shouldKeepLast = !!sourceModelId && sourceModelIds.has(sourceModelId);if (shouldKeepLast) {modelMap.delete(model.id);