🤯 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
🐛 fix: support DeepSeek generateObject tool choice (#15054)
YuTengjingba358bf3fc74
diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.test.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.test.tsindex 1651c834c49..8d866d93390 100644--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.test.ts+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.test.ts@@ -83,6 +83,54 @@ describe('Anthropic generateObject', () => {expect(result).toEqual({ age: 30, name: 'John' });});+ it('should allow schema structured output to require any tool', async () => {+ const mockClient = {+ messages: {+ create: vi.fn().mockResolvedValue({+ content: [+ {+ input: { summary: 'Task completed', title: 'Done' },+ name: 'task_topic_handoff',+ type: 'tool_use',+ },+ ],+ }),+ },+ };++ const payload = {+ messages: [{ content: 'Generate a task handoff', role: 'user' as const }],+ model: 'claude-3-5-sonnet-20241022',+ schema: {+ name: 'task_topic_handoff',+ schema: {+ properties: { summary: { type: 'string' }, title: { type: 'string' } },+ required: ['title', 'summary'],+ type: 'object' as const,+ },+ },+ };++ const result = await createAnthropicGenerateObject(+ mockClient as any,+ payload,+ undefined,+ undefined,+ { schemaToolChoice: 'any' },+ );++ expect(mockClient.messages.create).toHaveBeenCalledWith(+ expect.objectContaining({+ tool_choice: {+ type: 'any',+ },+ }),+ expect.objectContaining({}),+ );++ expect(result).toEqual({ summary: 'Task completed', title: 'Done' });+ });+it('should ignore whitespace-only system prompts', async () => {const mockClient = {messages: {diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.tsindex 7dcd7c60f59..b9f464efbc8 100644--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.ts+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.ts@@ -9,6 +9,11 @@ import { withUsageCost } from '../usageConverters/utils/withUsageCost';const log = debug('lobe-model-runtime:anthropic:generate-object');+export interface AnthropicGenerateObjectConfig {+ requestParams?: Pick<Anthropic.MessageCreateParams, 'thinking'>;+ schemaToolChoice?: 'any' | 'tool';+}+/*** Generate structured output using Anthropic Claude API with Function Calling*/@@ -17,6 +22,7 @@ export const createAnthropicGenerateObject = async (payload: GenerateObjectPayload,options?: GenerateObjectOptions,pricing?: Pricing,+ config?: AnthropicGenerateObjectConfig,) => {const { schema, messages, model, tools } = payload;@@ -45,6 +51,7 @@ export const createAnthropicGenerateObject = async (let finalTools;let tool_choice: Anthropic.ToolChoiceAny | Anthropic.ToolChoiceTool;+ let schemaToolName: string | undefined;if (tools) {finalTools = buildAnthropicTools(tools);tool_choice = { type: 'any' };@@ -59,7 +66,9 @@ export const createAnthropicGenerateObject = async (log('converted tool: %O', tool);finalTools = [tool];- tool_choice = { name: tool.name, type: 'tool' };+ schemaToolName = tool.name;+ tool_choice =+ config?.schemaToolChoice === 'any' ? { type: 'any' } : { name: tool.name, type: 'tool' };} else {throw new Error('tools or schema is required');}@@ -73,6 +82,7 @@ export const createAnthropicGenerateObject = async (messages: anthropicMessages,model,system: systemPrompts,+ ...config?.requestParams,tool_choice,tools: finalTools,},@@ -88,13 +98,13 @@ export const createAnthropicGenerateObject = async (}// Extract the tool use result- if (tool_choice.type === 'tool') {+ if (schemaToolName) {const toolUseBlock = response.content.find(- (block) => block.type === 'tool_use' && block.name === tool_choice.name,+ (block) => block.type === 'tool_use' && block.name === schemaToolName,);if (!toolUseBlock || toolUseBlock.type !== 'tool_use') {- log('no tool use found in response (expected tool: %s)', tool_choice.name);+ log('no tool use found in response (expected tool: %s)', schemaToolName);return undefined;}diff --git a/packages/model-runtime/src/providers/deepseek/index.test.ts b/packages/model-runtime/src/providers/deepseek/index.test.tsindex a31a3da47c2..0269bc5105f 100644--- a/packages/model-runtime/src/providers/deepseek/index.test.ts+++ b/packages/model-runtime/src/providers/deepseek/index.test.ts@@ -11,6 +11,20 @@ import {params,} from './index';+const loadModelsMock = vi.hoisted(() =>+ vi.fn().mockResolvedValue([+ {+ id: 'deepseek-v4-pro',+ maxOutput: 393_216,+ providerId: 'deepseek',+ },+ ]),+);++vi.mock('@lobechat/business-model-bank/model-config', () => ({+ loadModels: loadModelsMock,+}));+const defaultOpenAIBaseURL = 'https://api.deepseek.com/v1';const anthropicBaseURL = 'https://api.deepseek.com/anthropic';@@ -178,6 +192,71 @@ describe('LobeDeepSeekAnthropicAI', () => {});});+ describe('generateObject', () => {+ const generateObjectPayload = {+ messages: [{ content: 'Generate a handoff', role: 'user' as const }],+ model: 'deepseek-v4-pro',+ schema: {+ name: 'task_topic_handoff',+ schema: {+ additionalProperties: false,+ properties: { summary: { type: 'string' }, title: { type: 'string' } },+ required: ['title', 'summary'],+ type: 'object' as const,+ },+ },+ };++ beforeEach(() => {+ ((instance as any).client.messages.create as Mock).mockResolvedValue({+ content: [+ {+ id: 'call_1',+ input: { summary: 'Task completed', title: 'Done' },+ name: 'task_topic_handoff',+ type: 'tool_use',+ },+ ],+ usage: {+ input_tokens: 3,+ output_tokens: 4,+ },+ });+ });++ it('should use any tool choice by default to keep DeepSeek thinking mode enabled', async () => {+ const result = await instance.generateObject(generateObjectPayload);++ const payload = getLastRequestPayload();++ expect(payload.thinking).toBeUndefined();+ expect(payload.tool_choice).toEqual({ type: 'any' });+ expect(payload.tools).toEqual([+ expect.objectContaining({+ input_schema: expect.objectContaining({+ additionalProperties: false,+ required: ['title', 'summary'],+ type: 'object',+ }),+ name: 'task_topic_handoff',+ }),+ ]);+ expect(result).toEqual({ summary: 'Task completed', title: 'Done' });+ });++ it('should keep named tool choice when thinking is disabled', async () => {+ await instance.generateObject({+ ...generateObjectPayload,+ thinking: { type: 'disabled' },+ } as any);++ const payload = getLastRequestPayload();++ expect(payload.thinking).toEqual({ type: 'disabled' });+ expect(payload.tool_choice).toEqual({ name: 'task_topic_handoff', type: 'tool' });+ });+ });+describe('handlePayload', () => {it('should enable thinking by default for deepseek-v4-pro', async () => {await instance.chat({diff --git a/packages/model-runtime/src/providers/deepseek/index.ts b/packages/model-runtime/src/providers/deepseek/index.tsindex c7bde32550c..00548d499e8 100644--- a/packages/model-runtime/src/providers/deepseek/index.ts+++ b/packages/model-runtime/src/providers/deepseek/index.ts@@ -1,5 +1,6 @@import type Anthropic from '@anthropic-ai/sdk';import type { ChatModelCard } from '@lobechat/types';+import type { Pricing } from 'model-bank';import { deepseek as deepseekChatModels, ModelProvider } from 'model-bank';import type OpenAI from 'openai';@@ -8,11 +9,12 @@ import {createAnthropicCompatibleParams,createAnthropicCompatibleRuntime,} from '../../core/anthropicCompatibleFactory';+import { createAnthropicGenerateObject } from '../../core/anthropicCompatibleFactory/generateObject';import type { OpenAICompatibleFactoryOptions } from '../../core/openaiCompatibleFactory';import { createOpenAICompatibleRuntime } from '../../core/openaiCompatibleFactory';import type { CreateRouterRuntimeOptions } from '../../core/RouterRuntime';import { createRouterRuntime } from '../../core/RouterRuntime';-import type { ChatStreamPayload } from '../../types';+import type { ChatStreamPayload, GenerateObjectOptions, GenerateObjectPayload } from '../../types';import { getModelPropertyWithFallback } from '../../utils/getFallbackModelProperty';import { MODEL_LIST_CONFIGS, processModelList } from '../../utils/modelParse';@@ -213,6 +215,28 @@ const buildDeepSeekOpenAIPayload = (} as OpenAI.ChatCompletionCreateParamsStreaming;};+const isGenerateObjectThinkingDisabled = (payload: GenerateObjectPayload) =>+ (payload as GenerateObjectPayload & { thinking?: ChatStreamPayload['thinking'] }).thinking+ ?.type === 'disabled';++const createDeepSeekAnthropicGenerateObject = async (+ client: Anthropic,+ payload: GenerateObjectPayload,+ options?: GenerateObjectOptions,+ pricing?: Pricing,+) => {+ // DeepSeek V4 thinking mode rejects Anthropic's named schema tool choice,+ // e.g. `{ type: "tool", name: "task_topic_handoff" }`, but accepts+ // `{ 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);++ return createAnthropicGenerateObject(client, payload, options, pricing, {+ ...(thinkingDisabled ? { requestParams: { thinking: { type: 'disabled' } } } : {}),+ schemaToolChoice: thinkingDisabled ? 'tool' : 'any',+ });+};+const fetchDeepSeekModels = async ({client,}: {@@ -243,6 +267,7 @@ export const anthropicParams = createAnthropicCompatibleParams({debug: {chatCompletion: () => process.env.DEBUG_DEEPSEEK_CHAT_COMPLETION === '1',},+ generateObject: createDeepSeekAnthropicGenerateObject,provider: ModelProvider.DeepSeek,});