🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat: support thinking params for structured output (#15051)
YuTengjing1466d6eb5160
diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.test.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.test.tsindex 8d866d93390..489387aaa18 100644--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.test.ts+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.test.ts@@ -248,6 +248,43 @@ describe('Anthropic generateObject', () => {expect(result).toEqual({ data: 'test' });});+ it('should forward configured request params when provided', async () => {+ const mockClient = {+ messages: {+ create: vi.fn().mockResolvedValue({+ content: [+ {+ input: { data: 'test' },+ name: 'data_extractor',+ type: 'tool_use',+ },+ ],+ usage: { input_tokens: 10, output_tokens: 5 },+ }),+ },+ };++ const payload = {+ messages: [{ content: 'Generate data', role: 'user' as const }],+ model: 'deepseek-v4-pro',+ schema: {+ name: 'data_extractor',+ schema: { properties: { data: { type: 'string' } }, type: 'object' as const },+ },+ };++ await createAnthropicGenerateObject(mockClient as any, payload, undefined, undefined, {+ requestParams: { thinking: { type: 'disabled' } },+ });++ expect(mockClient.messages.create).toHaveBeenCalledWith(+ expect.objectContaining({+ thinking: { type: 'disabled' },+ }),+ expect.any(Object),+ );+ });+it('should return undefined when no tool use found in response', async () => {const mockClient = {messages: {diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.tsindex b9f464efbc8..9c91cc6b36a 100644--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.ts+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.ts@@ -10,7 +10,7 @@ import { withUsageCost } from '../usageConverters/utils/withUsageCost';const log = debug('lobe-model-runtime:anthropic:generate-object');export interface AnthropicGenerateObjectConfig {- requestParams?: Pick<Anthropic.MessageCreateParams, 'thinking'>;+ requestParams?: Pick<Anthropic.MessageCreateParams, 'output_config' | 'thinking'>;schemaToolChoice?: 'any' | 'tool';}diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.tsindex 19200c1a991..03cccd2d097 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts@@ -3116,6 +3116,56 @@ describe('LobeOpenAICompatibleFactory', () => {]);});+ it('should not forward internal thinking to generic OpenAI-compatible generateObject requests', async () => {+ const mockResponse = {+ choices: [+ {+ message: {+ tool_calls: [+ {+ function: {+ arguments: '{"name":"Alice","age":28}',+ name: 'person_extractor',+ },+ type: 'function' as const,+ },+ ],+ },+ },+ ],+ };++ vi.spyOn(instanceWithToolCalling['client'].chat.completions, 'create').mockResolvedValue(+ mockResponse as any,+ );++ const payload = {+ messages: [{ content: 'Extract person info', role: 'user' as const }],+ model: 'deepseek-v4-pro',+ reasoning_effort: 'high' as const,+ schema: {+ name: 'person_extractor',+ schema: {+ properties: { age: { type: 'number' }, name: { type: 'string' } },+ type: 'object' as const,+ },+ },+ thinking: { budget_tokens: 0, type: 'disabled' as const },+ };++ await instanceWithToolCalling.generateObject(payload);++ const requestPayload =+ instanceWithToolCalling['client'].chat.completions.create.mock.calls[0]![0];+ expect(requestPayload).toEqual(+ expect.objectContaining({+ model: 'deepseek-v4-pro',+ }),+ );+ expect(requestPayload).not.toHaveProperty('thinking');+ expect(requestPayload).not.toHaveProperty('reasoning_effort');+ });+it('should return undefined when no tool call found', async () => {const mockResponse = {choices: [diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.tsindex 2c7d9f84d52..df47253441a 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts@@ -80,6 +80,13 @@ export const CHAT_MODELS_BLOCK_LIST = [type ConstructorOptions<T extends Record<string, any> = any> = ClientOptions & 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@@ -90,6 +97,16 @@ export type CreateImageOptions = Omit<ClientOptions, 'apiKey'> & {provider: string;};+const getGenerateObjectReasoningParams = ({+ reasoning_effort,+ thinking,+}: GenerateObjectReasoningParams) => ({+ // `thinking` is a Lobe runtime abstraction, not a generic OpenAI-compatible API field.+ // Use it here only to suppress `reasoning_effort`; providers that support thinking+ // must translate it via `generateObject.handlePayload`.+ ...(reasoning_effort && thinking?.type !== 'disabled' ? { reasoning_effort } : {}),+});+export type CreateVideoOptions = Omit<ClientOptions, 'apiKey'> & {apiKey: string;provider: string;@@ -185,6 +202,14 @@ export interface OpenAICompatibleFactoryOptions<T extends Record<string, any> =* 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*/@@ -395,6 +420,15 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anreturn promptCacheKey ? { prompt_cache_key: promptCacheKey } : {};}+ private handleGenerateObjectPayload(+ payload: GenerateObjectPayload,+ requestPayload: ChatCompletionCreateParamsWithPromptCacheKey,+ ) {+ return generateObjectConfig?.handlePayload+ ? generateObjectConfig.handlePayload(payload, requestPayload, this._options)+ : requestPayload;+ }+async chat({ responseMode, ...payload }: ChatStreamPayload, options?: ChatMethodOptions) {try {const log = debug(`${this.logPrefix}:chat`);@@ -806,14 +840,15 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an};const res = await this.client.chat.completions.create(- {+ this.handleGenerateObjectPayload(payload, {+ ...getGenerateObjectReasoningParams(payload),messages,model,...this.resolvePromptCacheKeyParams(model, options?.user),tool_choice: { function: { name: tool.function.name }, type: 'function' },tools: [tool],user: options?.user,- },+ }) as OpenAI.ChatCompletionCreateParamsNonStreaming,{ headers: options?.headers, signal: options?.signal },);@@ -891,13 +926,14 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anlog('calling chat.completions.create for structured output');const res = await this.client.chat.completions.create(- {+ this.handleGenerateObjectPayload(payload, {+ ...getGenerateObjectReasoningParams(payload),messages,model,response_format: { json_schema: processedSchema, type: 'json_schema' },...this.resolvePromptCacheKeyParams(model, options?.user),user: options?.user,- },+ }) as OpenAI.ChatCompletionCreateParamsNonStreaming,{ headers: options?.headers, signal: options?.signal },);if (res.usage) {@@ -1357,14 +1393,15 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anconst msgs = messages;const res = await this.client.chat.completions.create(- {+ this.handleGenerateObjectPayload(payload, {+ ...getGenerateObjectReasoningParams(payload),messages: msgs,model,...this.resolvePromptCacheKeyParams(model, options?.user),tool_choice: 'required',tools,user: options?.user,- },+ }) as OpenAI.ChatCompletionCreateParamsNonStreaming,{ headers: options?.headers, signal: options?.signal },);diff --git a/packages/model-runtime/src/providers/deepseek/index.test.ts b/packages/model-runtime/src/providers/deepseek/index.test.tsindex 0269bc5105f..f28f3453843 100644--- a/packages/model-runtime/src/providers/deepseek/index.test.ts+++ b/packages/model-runtime/src/providers/deepseek/index.test.ts@@ -255,6 +255,31 @@ describe('LobeDeepSeekAnthropicAI', () => {expect(payload.thinking).toEqual({ type: 'disabled' });expect(payload.tool_choice).toEqual({ name: 'task_topic_handoff', type: 'tool' });});++ it('should map reasoning_effort to output_config.effort', async () => {+ await instance.generateObject({+ ...generateObjectPayload,+ reasoning_effort: 'high',+ });++ const payload = getLastRequestPayload();++ expect(payload.output_config).toEqual({ effort: 'high' });+ expect(payload.tool_choice).toEqual({ type: 'any' });+ });++ it('should omit output_config when thinking is disabled', async () => {+ await instance.generateObject({+ ...generateObjectPayload,+ reasoning_effort: 'high',+ thinking: { type: 'disabled' },+ });++ const payload = getLastRequestPayload();++ expect(payload.output_config).toBeUndefined();+ expect(payload.thinking).toEqual({ type: 'disabled' });+ });});describe('handlePayload', () => {@@ -797,6 +822,48 @@ describe('LobeDeepSeekAI - custom features', () => {expect(openAIParams.generateObject).toBeDefined();expect(openAIParams.generateObject?.useToolsCalling).toBe(true);});++ it('should forward disabled thinking for generateObject DeepSeek requests', () => {+ const requestPayload = {+ messages: [{ role: 'user' as const, content: 'Hello' }],+ model: 'deepseek-v4-pro',+ reasoning_effort: 'high' as const,+ };++ const result = openAIParams.generateObject!.handlePayload!(+ {+ messages: [{ role: 'user', content: 'Hello' }],+ model: 'deepseek-v4-pro',+ thinking: { budget_tokens: 0, type: 'disabled' },+ },+ requestPayload,+ {},+ );++ expect(result).toEqual(expect.objectContaining({ thinking: { type: 'disabled' } }));+ expect(result).not.toHaveProperty('reasoning_effort');+ });++ it('should preserve reasoning_effort when generateObject thinking is enabled', () => {+ const requestPayload = {+ messages: [{ role: 'user' as const, content: 'Hello' }],+ model: 'deepseek-v4-pro',+ reasoning_effort: 'high' as const,+ };++ const result = openAIParams.generateObject!.handlePayload!(+ {+ messages: [{ role: 'user', content: 'Hello' }],+ model: 'deepseek-v4-pro',+ thinking: { budget_tokens: 1024, type: 'enabled' },+ },+ requestPayload,+ {},+ );++ expect(result.reasoning_effort).toBe('high');+ expect(result).toEqual(expect.objectContaining({ thinking: { type: 'enabled' } }));+ });});describe('models', () => {diff --git a/packages/model-runtime/src/providers/deepseek/index.ts b/packages/model-runtime/src/providers/deepseek/index.tsindex 00548d499e8..c4792148303 100644--- a/packages/model-runtime/src/providers/deepseek/index.ts+++ b/packages/model-runtime/src/providers/deepseek/index.ts@@ -9,6 +9,7 @@ import {createAnthropicCompatibleParams,createAnthropicCompatibleRuntime,} from '../../core/anthropicCompatibleFactory';+import type { AnthropicGenerateObjectConfig } from '../../core/anthropicCompatibleFactory/generateObject';import { createAnthropicGenerateObject } from '../../core/anthropicCompatibleFactory/generateObject';import type { OpenAICompatibleFactoryOptions } from '../../core/openaiCompatibleFactory';import { createOpenAICompatibleRuntime } from '../../core/openaiCompatibleFactory';@@ -28,6 +29,9 @@ const DEEPSEEK_ANTHROPIC_BASE_URL_PATTERN = /\/anthropic\/?$/;const DEEPSEEK_ANTHROPIC_MESSAGES_PATH_PATTERN = /\/v1\/messages\/?$/;type DeepSeekSDKType = 'anthropic' | 'openai';+type GenerateObjectHandlePayload = NonNullable<+ NonNullable<OpenAICompatibleFactoryOptions['generateObject']>['handlePayload']+>;const isDeepSeekV4Model = (model: string) => model.startsWith('deepseek-v4');const isEmptyContent = (content: unknown) =>@@ -230,13 +234,42 @@ const createDeepSeekAnthropicGenerateObject = async (// `{ type: "any" }`. If thinking is already disabled, keep the stricter// named tool choice; otherwise use `any` without changing the thinking mode.const thinkingDisabled = isGenerateObjectThinkingDisabled(payload);+ const requestParams: AnthropicGenerateObjectConfig['requestParams'] = {+ ...(!thinkingDisabled && payload.reasoning_effort+ ? {+ output_config: {+ effort: payload.reasoning_effort as NonNullable<+ Anthropic.MessageCreateParams['output_config']+ >['effort'],+ },+ }+ : {}),+ ...(thinkingDisabled ? { thinking: { type: 'disabled' } } : {}),+ };return createAnthropicGenerateObject(client, payload, options, pricing, {- ...(thinkingDisabled ? { requestParams: { thinking: { type: 'disabled' } } } : {}),+ requestParams,schemaToolChoice: thinkingDisabled ? 'tool' : 'any',});};+const buildDeepSeekGenerateObjectPayload: GenerateObjectHandlePayload = (+ payload,+ requestPayload,+) => {+ const { thinking } = payload;+ const thinkingExplicitlyDisabled = thinking?.type === 'disabled';+ const payloadWithoutReasoningEffort = { ...requestPayload };+ delete (payloadWithoutReasoningEffort as { reasoning_effort?: unknown }).reasoning_effort;++ return {+ ...(thinkingExplicitlyDisabled ? payloadWithoutReasoningEffort : requestPayload),+ ...(thinking?.type === 'enabled' || thinkingExplicitlyDisabled+ ? { thinking: { type: thinking.type } }+ : {}),+ };+};+const fetchDeepSeekModels = async ({client,}: {@@ -288,6 +321,7 @@ export const openAIParams = {// Deepseek don't support json format well// use Tools calling to simulategenerateObject: {+ handlePayload: buildDeepSeekGenerateObjectPayload,useToolsCalling: true,},models: fetchDeepSeekModels,diff --git a/packages/model-runtime/src/types/structureOutput.ts b/packages/model-runtime/src/types/structureOutput.tsindex 2eca8a1b0df..0baf481c9cc 100644--- a/packages/model-runtime/src/types/structureOutput.ts+++ b/packages/model-runtime/src/types/structureOutput.ts@@ -1,6 +1,6 @@import type { ModelUsage } from '@lobechat/types';-import type { ChatCompletionTool } from './chat';+import type { ChatCompletionTool, ChatStreamPayload } from './chat';interface GenerateObjectMessage {content: string;@@ -23,8 +23,10 @@ export interface GenerateObjectSchema {export interface GenerateObjectPayload {messages: GenerateObjectMessage[];model: string;+ reasoning_effort?: ChatStreamPayload['reasoning_effort'];responseApi?: boolean;schema?: GenerateObjectSchema;+ thinking?: ChatStreamPayload['thinking'];tools?: ChatCompletionTool[];}