🤯 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: sanitize DeepSeek surrogate payloads (#15086)
YuTengjing736eb570af8c
diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.tsindex 1d67e4045db..91e153a3522 100644--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts@@ -19,8 +19,6 @@ vi.mock('@lobechat/const', () => ({const MockedAnthropic = vi.mocked(Anthropic);const originalAnthropicClientTimeout = process.env.ANTHROPIC_CLIENT_TIMEOUT;-const originalDeepSeekAnthropicPayloadLogUserId =- process.env.DEEPSEEK_ANTHROPIC_PAYLOAD_LOG_USER_ID;afterEach(() => {if (originalAnthropicClientTimeout === undefined) {@@ -28,45 +26,8 @@ afterEach(() => {} else {process.env.ANTHROPIC_CLIENT_TIMEOUT = originalAnthropicClientTimeout;}-- if (originalDeepSeekAnthropicPayloadLogUserId === undefined) {- delete process.env.DEEPSEEK_ANTHROPIC_PAYLOAD_LOG_USER_ID;- } else {- process.env.DEEPSEEK_ANTHROPIC_PAYLOAD_LOG_USER_ID = originalDeepSeekAnthropicPayloadLogUserId;- }});-const createDeepSeekAnthropicJsonParseRuntime = () => {- const apiError = Object.assign(- new Error(- '400 Failed to parse the request body as JSON: messages[0].content: unexpected end of hex escape at line 1 column 7160',- ),- { status: 400 },- );- const messagesCreate = vi.fn().mockRejectedValue(apiError);- const createClient = vi.fn(- (options) =>- ({- baseURL: options.baseURL,- messages: { create: messagesCreate },- }) as unknown as Anthropic,- );- const Runtime = createAnthropicCompatibleRuntime({- baseURL: 'https://api.deepseek.com/anthropic',- chatCompletion: {- handlePayload: () => ({- max_tokens: 1024,- messages: [{ content: 'x'.repeat(8000), role: 'user' }],- model: 'deepseek-v4-pro',- }),- },- customClient: { createClient },- provider: 'deepseek',- });-- return new Runtime({ apiKey: 'test-key' });-};-describe('createDefaultAnthropicClient', () => {it('should include User-Agent header with current version', () => {MockedAnthropic.mockClear();@@ -196,113 +157,4 @@ describe('createAnthropicCompatibleRuntime', () => {);expect(runtime.baseURL).toBe('https://aihubmix.com');});-- it('should log a scoped payload summary for DeepSeek Anthropic JSON parse errors', async () => {- process.env.DEEPSEEK_ANTHROPIC_PAYLOAD_LOG_USER_ID = 'user_target';-- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});- const runtime = createDeepSeekAnthropicJsonParseRuntime();-- try {- await expect(- runtime.chat({ messages: [], model: 'deepseek-v4-pro', provider: 'deepseek' } as any, {- metadata: { traceId: 'trace-1', trigger: 'bot' },- user: 'user_target',- }),- ).rejects.toBeDefined();-- const logCall = logSpy.mock.calls.find(- ([label]) => label === '[deepseekAnthropicPayloadParseError]',- );- const summary = JSON.parse(logCall?.[1] as string);-- expect(summary).toMatchObject({- column: 7160,- errorStatus: 400,- message0ContentSerializedLength: 8002,- message0ContentType: 'string',- model: 'deepseek-v4-pro',- reportedColumn: 7160,- reportedLine: 1,- request: {- maxTokens: 1024,- metadataUserId: 'user_target',- model: 'deepseek-v4-pro',- stream: true,- },- snippetEnd: 7409,- snippetStart: 6909,- traceId: 'trace-1',- trigger: 'bot',- userId: 'user_target',- });- expect(summary.messageSummaries[0]).toMatchObject({- containsColumn: true,- content: {- kind: 'string',- serializedLength: 8002,- textLength: 8000,- },- index: 0,- role: 'user',- });- expect(summary.payloadKeys).toEqual([- 'max_tokens',- 'messages',- 'model',- 'stream',- 'metadata',- ]);- expect(summary.payloadLength).toBeGreaterThan(7400);- expect(summary.snippet).toHaveLength(500);- } finally {- logSpy.mockRestore();- }- });-- it('should skip DeepSeek Anthropic payload summary when the target user env is not configured', async () => {- delete process.env.DEEPSEEK_ANTHROPIC_PAYLOAD_LOG_USER_ID;-- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});- const runtime = createDeepSeekAnthropicJsonParseRuntime();-- try {- await expect(- runtime.chat({ messages: [], model: 'deepseek-v4-pro', provider: 'deepseek' } as any, {- metadata: { traceId: 'trace-1', trigger: 'bot' },- user: 'user_target',- }),- ).rejects.toBeDefined();-- expect(logSpy).not.toHaveBeenCalledWith(- '[deepseekAnthropicPayloadParseError]',- expect.any(String),- );- } finally {- logSpy.mockRestore();- }- });-- it('should skip DeepSeek Anthropic payload summary for other users', async () => {- process.env.DEEPSEEK_ANTHROPIC_PAYLOAD_LOG_USER_ID = 'user_target';-- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});- const runtime = createDeepSeekAnthropicJsonParseRuntime();-- try {- await expect(- runtime.chat({ messages: [], model: 'deepseek-v4-pro', provider: 'deepseek' } as any, {- metadata: { traceId: 'trace-1', trigger: 'bot' },- user: 'user_other',- }),- ).rejects.toBeDefined();-- expect(logSpy).not.toHaveBeenCalledWith(- '[deepseekAnthropicPayloadParseError]',- expect.any(String),- );- } finally {- logSpy.mockRestore();- }- });});diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.tsindex 69ac774ea46..5d33a57919c 100644--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts@@ -45,13 +45,6 @@ type AnthropicTools = Anthropic.Tool | Anthropic.WebSearchTool20250305;export const DEFAULT_ANTHROPIC_BASE_URL = 'https://api.anthropic.com';const ANTHROPIC_CLIENT_TIMEOUT_ENV = 'ANTHROPIC_CLIENT_TIMEOUT';-const DEEPSEEK_ANTHROPIC_PAYLOAD_LOG_DEFAULT_COLUMN = 7160;-const DEEPSEEK_ANTHROPIC_PAYLOAD_LOG_MESSAGE_LIMIT = 30;-const DEEPSEEK_ANTHROPIC_PAYLOAD_LOG_MODEL = 'deepseek-v4-pro';-const DEEPSEEK_ANTHROPIC_PAYLOAD_LOG_SNIPPET_RADIUS = 250;-const DEEPSEEK_ANTHROPIC_PAYLOAD_LOG_TOOL_LIMIT = 30;-const DEEPSEEK_ANTHROPIC_PAYLOAD_LOG_USER_ID_ENV = 'DEEPSEEK_ANTHROPIC_PAYLOAD_LOG_USER_ID';-const ERROR_LOCATION_PATTERN = /line\s+(\d+)\s+column\s+(\d+)/i;/*** Keep Anthropic SDK's timeout explicit so non-streaming structured output* calls with large max_tokens do not hit the SDK's long-request guard before@@ -64,267 +57,6 @@ const ANTHROPIC_SDK_MESSAGES_PATH_PATTERN = /\/v1(?:\/messages)?\/?$/;const normalizeAnthropicCompatibleBaseURL = (baseURL?: string | null) =>baseURL?.replace(ANTHROPIC_SDK_MESSAGES_PATH_PATTERN, '');-const isOfficialDeepSeekAnthropicBaseURL = (baseURL: string) => {- try {- const url = new URL(baseURL);- return url.hostname === 'api.deepseek.com' && url.pathname.replace(/\/$/, '') === '/anthropic';- } catch {- return baseURL.includes('api.deepseek.com/anthropic');- }-};--const getValueKind = (value: unknown) => {- if (Array.isArray(value)) return 'array';- if (value === null) return 'null';- return typeof value;-};--const getMetadataString = (metadata: Record<string, unknown> | undefined, key: string) => {- const value = metadata?.[key];- return typeof value === 'string' ? value : undefined;-};--const getErrorRecord = (error: unknown) =>- typeof error === 'object' && error !== null ? (error as Record<PropertyKey, unknown>) : undefined;--const getErrorMessage = (error: unknown) => {- if (error instanceof Error) return error.message;-- const message = getErrorRecord(error)?.message;- return typeof message === 'string' ? message : String(error);-};--const getErrorStatus = (error: unknown) => {- const status = getErrorRecord(error)?.status;- return typeof status === 'number' || typeof status === 'string' ? status : undefined;-};--const getJSONSerializedLength = (value: unknown) => {- try {- const serialized = JSON.stringify(value);- return typeof serialized === 'string' ? serialized.length : undefined;- } catch {- return undefined;- }-};--const isDeepSeekAnthropicPayloadParseError = (error: unknown) => {- const message = getErrorMessage(error);-- return (- message.includes('Failed to parse the request body as JSON') ||- message.includes('unexpected end of hex escape')- );-};--const shouldLogDeepSeekAnthropicPayloadForUser = (requestUserId: string | undefined) => {- const targetUserId = process.env[DEEPSEEK_ANTHROPIC_PAYLOAD_LOG_USER_ID_ENV]?.trim();-- return !!targetUserId && requestUserId === targetUserId;-};--const parseErrorLocation = (error: unknown) => {- const match = ERROR_LOCATION_PATTERN.exec(getErrorMessage(error));- if (!match) return;-- const line = Number(match[1]);- const column = Number(match[2]);-- return Number.isInteger(line) && Number.isInteger(column) ? { column, line } : undefined;-};--const buildSerializedSnippet = (serializedPayload: string, column: number) => {- const columnIndex = Math.max(0, column - 1);- const snippetStart = Math.max(0, columnIndex - DEEPSEEK_ANTHROPIC_PAYLOAD_LOG_SNIPPET_RADIUS);- const snippetEnd = Math.min(- serializedPayload.length,- columnIndex + DEEPSEEK_ANTHROPIC_PAYLOAD_LOG_SNIPPET_RADIUS,- );- const columnChar = serializedPayload.charAt(columnIndex);-- return {- columnChar: columnChar || undefined,- columnCharCode: columnChar ? columnChar.codePointAt(0) : undefined,- snippet: serializedPayload.slice(snippetStart, snippetEnd),- snippetEnd,- snippetStart,- };-};--const summarizeContentBlock = (block: unknown) => {- const record = getErrorRecord(block);- const input = record?.input;-- return {- id: typeof record?.id === 'string' ? record.id : undefined,- inputSerializedLength: input === undefined ? undefined : getJSONSerializedLength(input),- name: typeof record?.name === 'string' ? record.name : undefined,- textLength: typeof record?.text === 'string' ? record.text.length : undefined,- thinkingLength: typeof record?.thinking === 'string' ? record.thinking.length : undefined,- type: typeof record?.type === 'string' ? record.type : undefined,- };-};--const summarizeContent = (content: unknown) => ({- blocks: Array.isArray(content) ? content.slice(0, 20).map(summarizeContentBlock) : undefined,- blocksCount: Array.isArray(content) ? content.length : undefined,- kind: getValueKind(content),- serializedLength: getJSONSerializedLength(content),- textLength: typeof content === 'string' ? content.length : undefined,-});--const buildSerializedRanges = (items: unknown[], serializedPayload: string) => {- let searchStart = 0;-- return items.map((item) => {- const serializedItem = JSON.stringify(item);- const start = serializedPayload.indexOf(serializedItem, searchStart);-- if (start === -1) {- return {- serializedEnd: undefined,- serializedLength: serializedItem.length,- serializedStart: undefined,- };- }-- const end = start + serializedItem.length;- searchStart = end;-- return {- serializedEnd: end,- serializedLength: serializedItem.length,- serializedStart: start,- };- });-};--const summarizeMessages = (- messages: Anthropic.MessageCreateParams['messages'],- serializedPayload: string,- column: number,-) => {- const ranges = buildSerializedRanges(messages, serializedPayload);- const columnIndex = Math.max(0, column - 1);-- return messages.slice(0, DEEPSEEK_ANTHROPIC_PAYLOAD_LOG_MESSAGE_LIMIT).map((message, index) => {- const record = getErrorRecord(message);- const content = record?.content;- const range = ranges[index];-- return {- containsColumn:- range.serializedStart !== undefined &&- range.serializedEnd !== undefined &&- columnIndex >= range.serializedStart &&- columnIndex < range.serializedEnd,- content: summarizeContent(content),- index,- role: typeof record?.role === 'string' ? record.role : undefined,- serializedEnd: range.serializedEnd,- serializedLength: range.serializedLength,- serializedStart: range.serializedStart,- };- });-};--const summarizeTools = (tools: Anthropic.MessageCreateParams['tools']) =>- tools?.slice(0, DEEPSEEK_ANTHROPIC_PAYLOAD_LOG_TOOL_LIMIT).map((tool) => {- const record = getErrorRecord(tool);- return {- name: typeof record?.name === 'string' ? record.name : undefined,- serializedLength: getJSONSerializedLength(tool),- type: typeof record?.type === 'string' ? record.type : undefined,- };- });--const logDeepSeekAnthropicPayloadParseError = ({- baseURL,- error,- metadata,- payload,- provider,- requestPayload,- requestUserId,-}: {- baseURL: string;- error: unknown;- metadata: Record<string, unknown> | undefined;- payload: ChatStreamPayload;- provider: string;- requestPayload: Anthropic.MessageCreateParams;- requestUserId: string | undefined;-}) => {- if (- provider !== 'deepseek' ||- payload.model !== DEEPSEEK_ANTHROPIC_PAYLOAD_LOG_MODEL ||- !shouldLogDeepSeekAnthropicPayloadForUser(requestUserId) ||- getMetadataString(metadata, 'trigger') !== 'bot' ||- !isOfficialDeepSeekAnthropicBaseURL(baseURL) ||- !isDeepSeekAnthropicPayloadParseError(error)- ) {- return;- }-- const serializedPayload = JSON.stringify(requestPayload);- const reportedLocation = parseErrorLocation(error);- const column = reportedLocation?.column ?? DEEPSEEK_ANTHROPIC_PAYLOAD_LOG_DEFAULT_COLUMN;- const firstMessageContent = requestPayload.messages.at(0)?.content;- const serializedFirstMessageContent = JSON.stringify(firstMessageContent ?? '');- const { columnChar, columnCharCode, snippet, snippetStart, snippetEnd } = buildSerializedSnippet(- serializedPayload,- column,- );-- // Temporary diagnostic for DeepSeek's Anthropic endpoint JSON parser failure.- // eslint-disable-next-line no-console- console.log(- '[deepseekAnthropicPayloadParseError]',- JSON.stringify({- baseURL: desensitizeUrl(baseURL),- column,- columnChar: columnChar || undefined,- columnCharCode,- errorMessage: getErrorMessage(error),- errorStatus: getErrorStatus(error),- message0ContentBlocks: Array.isArray(firstMessageContent)- ? firstMessageContent.length- : undefined,- message0ContentSerializedLength: serializedFirstMessageContent.length,- message0ContentType: getValueKind(firstMessageContent),- messageSummaries: summarizeMessages(requestPayload.messages, serializedPayload, column),- messagesCount: requestPayload.messages.length,- model: payload.model,- payloadKeys: Object.keys(requestPayload),- payloadLength: serializedPayload.length,- reportedColumn: reportedLocation?.column,- reportedLine: reportedLocation?.line,- request: {- maxTokens: requestPayload.max_tokens,- metadataUserId: requestPayload.metadata?.user_id,- model: requestPayload.model,- outputConfig: requestPayload.output_config,- stream: requestPayload.stream,- temperature: requestPayload.temperature,- thinking: requestPayload.thinking,- topP: requestPayload.top_p,- },- snippet,- snippetEnd,- snippetStart,- system: summarizeContent(requestPayload.system),- systemSerializedLength: JSON.stringify(requestPayload.system ?? '').length,- thinking: requestPayload.thinking,- tools: summarizeTools(requestPayload.tools),- toolsCount: requestPayload.tools?.length ?? 0,- topicId: getMetadataString(metadata, 'topicId'),- traceId: getMetadataString(metadata, 'traceId'),- trigger: getMetadataString(metadata, 'trigger'),- userId: requestUserId,- }),- );-};-const resolveDefaultAnthropicTimeout = () => {const timeout = Number(process.env[ANTHROPIC_CLIENT_TIMEOUT_ENV]);@@ -753,7 +485,8 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =baseURL: finalBaseURL,...constructorOptions,...rest,- timeout: rest.timeout ?? constructorOptions?.timeout ?? resolveDefaultAnthropicTimeout(),+ timeout:+ rest.timeout ?? constructorOptions?.timeout ?? resolveDefaultAnthropicTimeout(),};if (customClient?.createClient) {@@ -768,14 +501,6 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =}async chat(payload: ChatStreamPayload, options?: ChatMethodOptions) {- let deepSeekAnthropicPayloadParseErrorContext:- | {- metadata: Record<string, unknown> | undefined;- requestPayload: Anthropic.MessageCreateParams;- requestUserId: string | undefined;- }- | undefined;-try {if (!chatCompletion?.handlePayload) {throw new Error('Anthropic-compatible runtime requires chatCompletion.handlePayload');@@ -789,15 +514,6 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =const postPayload = await chatCompletion.handlePayload(payload, this._options);const shouldStream = postPayload.stream ?? payload.stream ?? true;const finalPayload = { ...postPayload, stream: shouldStream };- const requestPayload = {- ...finalPayload,- metadata: options?.user ? { user_id: options.user } : undefined,- };- deepSeekAnthropicPayloadParseErrorContext = {- metadata: options?.metadata,- requestPayload,- requestUserId: options?.user,- };if (debugParams?.chatCompletion?.()) {// eslint-disable-next-line no-console@@ -806,10 +522,16 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =console.log(JSON.stringify(finalPayload), '\n');}- const response = await this.client.messages.create(requestPayload, {- headers: options?.requestHeaders,- signal: options?.signal,- });+ const response = await this.client.messages.create(+ {+ ...finalPayload,+ metadata: options?.user ? { user_id: options.user } : undefined,+ },+ {+ headers: options?.requestHeaders,+ signal: options?.signal,+ },+ );const pricing = await getModelPricing(payload.model, this.id);const pricingOptions = await chatCompletion?.getPricingOptions?.(payload, postPayload);@@ -933,18 +655,6 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =},);} catch (error) {- if (deepSeekAnthropicPayloadParseErrorContext) {- logDeepSeekAnthropicPayloadParseError({- baseURL: this.baseURL,- error,- metadata: deepSeekAnthropicPayloadParseErrorContext.metadata,- payload,- provider,- requestPayload: deepSeekAnthropicPayloadParseErrorContext.requestPayload,- requestUserId: deepSeekAnthropicPayloadParseErrorContext.requestUserId,- });- }-throw this.handleError(error);}}diff --git a/packages/model-runtime/src/providers/deepseek/__tests__/anthropic.test.ts b/packages/model-runtime/src/providers/deepseek/__tests__/anthropic.test.tsnew file mode 100644index 00000000000..66194954d1c--- /dev/null+++ b/packages/model-runtime/src/providers/deepseek/__tests__/anthropic.test.ts@@ -0,0 +1,219 @@+// @vitest-environment node+import type { Mock } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { LobeDeepSeekAnthropicAI } from '../index';+import {+ expectNoLoneSurrogateEscapes,+ loneHighSurrogate,+ loneLowSurrogate,+ validEmoji,+} from './testUtils';++describe('LobeDeepSeekAnthropicAI handlePayload', () => {+ let instance: InstanceType<typeof LobeDeepSeekAnthropicAI>;++ const getLastRequestPayload = () => {+ const calls = ((instance as any).client.messages.create as Mock).mock.calls;+ return calls.at(-1)?.[0];+ };++ beforeEach(() => {+ instance = new LobeDeepSeekAnthropicAI({ apiKey: 'test' });++ vi.spyOn((instance as any).client.messages, 'create').mockResolvedValue(+ new ReadableStream() as any,+ );+ });++ afterEach(() => {+ vi.clearAllMocks();+ });++ it('should enable thinking by default for deepseek-v4-pro', async () => {+ await instance.chat({+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'deepseek-v4-pro',+ temperature: 0,+ });++ const payload = getLastRequestPayload();++ expect(payload.max_tokens).toBe(393_216);+ expect(payload.thinking).toEqual({+ budget_tokens: 1024,+ type: 'enabled',+ });+ });++ it('should disable thinking when thinking.type is disabled', async () => {+ await instance.chat({+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'deepseek-v4-flash',+ reasoning_effort: 'high',+ thinking: { budget_tokens: 0, type: 'disabled' },+ });++ const payload = getLastRequestPayload();++ expect(payload.thinking).toEqual({ type: 'disabled' });+ expect(payload.output_config).toBeUndefined();+ });++ it('should map reasoning_effort to output_config.effort when thinking is enabled', async () => {+ await instance.chat({+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'deepseek-v4-flash',+ reasoning_effort: 'high',+ thinking: { budget_tokens: 2048, type: 'enabled' },+ });++ const payload = getLastRequestPayload();++ expect(payload.output_config).toEqual({ effort: 'high' });+ expect(payload.thinking).toEqual({+ budget_tokens: 2048,+ type: 'enabled',+ });+ });++ it('should not add thinking params for deepseek-chat by default', async () => {+ await instance.chat({+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'deepseek-chat',+ });++ const payload = getLastRequestPayload();++ expect(payload.thinking).toBeUndefined();+ expect(payload.output_config).toBeUndefined();+ });++ it('should preserve DeepSeek temperature scale for non-thinking Anthropic requests', async () => {+ await instance.chat({+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'deepseek-chat',+ temperature: 1.4,+ });++ const payload = getLastRequestPayload();++ expect(payload.temperature).toBe(1.4);+ });++ it('should convert assistant reasoning to Anthropic thinking block', async () => {+ await instance.chat({+ messages: [+ { content: 'Hello', role: 'user' },+ {+ content: 'Response',+ reasoning: { content: 'My reasoning process' },+ role: 'assistant',+ } as any,+ { content: 'Follow-up', role: 'user' },+ ],+ model: 'deepseek-v4-flash',+ });++ const payload = getLastRequestPayload();+ const assistantMessage = payload.messages.find((message: any) => message.role === 'assistant');++ expect(assistantMessage?.content).toEqual([+ { thinking: 'My reasoning process', type: 'thinking' },+ { text: 'Response', type: 'text' },+ ]);+ });++ it('should convert tool calls to Anthropic tool_use with a thinking placeholder', async () => {+ await instance.chat({+ messages: [+ { content: 'Search weather', role: 'user' },+ {+ content: '',+ role: 'assistant',+ tool_calls: [+ {+ function: { arguments: '{"city":"Beijing"}', name: 'get_weather' },+ id: 'call_1',+ type: 'function',+ },+ ],+ } as any,+ {+ content: '{"temp":20}',+ role: 'tool',+ tool_call_id: 'call_1',+ } as any,+ ],+ model: 'deepseek-v4-flash',+ });++ const payload = getLastRequestPayload();+ const assistantMessage = payload.messages.find((message: any) => message.role === 'assistant');++ expect(assistantMessage?.content).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ thinking: ' ', type: 'thinking' }),+ expect.objectContaining({ name: 'get_weather', type: 'tool_use' }),+ ]),+ );+ });++ it('should remove lone surrogates from converted Anthropic tool_use input', async () => {+ await instance.chat({+ messages: [+ { content: 'Search weather', role: 'user' },+ {+ content: '',+ role: 'assistant',+ tool_calls: [+ {+ function: {+ arguments: `{"city":"${loneHighSurrogate} ${validEmoji}","nested":{"value":"${loneLowSurrogate}"}}`,+ name: 'get_weather',+ },+ id: 'call_1',+ type: 'function',+ },+ ],+ } as any,+ {+ content: '{"temp":20}',+ role: 'tool',+ tool_call_id: 'call_1',+ } as any,+ ],+ model: 'deepseek-v4-flash',+ });++ const payload = getLastRequestPayload();+ const serialized = expectNoLoneSurrogateEscapes(payload);+ const assistantMessage = payload.messages.find((message: any) => message.role === 'assistant');+ const toolUseBlock = assistantMessage?.content.find((block: any) => block.type === 'tool_use');++ expect(serialized).toContain(validEmoji);+ expect(toolUseBlock?.input).toEqual({+ city: ` ${validEmoji}`,+ nested: { value: '' },+ });+ });++ it('should remove lone surrogates from Anthropic chat payload strings', async () => {+ await instance.chat({+ messages: [+ { content: `Hello ${loneHighSurrogate} ${validEmoji}`, role: 'user' },+ {+ content: 'Response',+ reasoning: { content: `Reasoning ${loneLowSurrogate} value` },+ role: 'assistant',+ } as any,+ ],+ model: 'deepseek-v4-flash',+ });++ const payload = getLastRequestPayload();+ const serialized = expectNoLoneSurrogateEscapes(payload);++ expect(serialized).toContain(validEmoji);+ });+});diff --git a/packages/model-runtime/src/providers/deepseek/__tests__/generateObject.test.ts b/packages/model-runtime/src/providers/deepseek/__tests__/generateObject.test.tsnew file mode 100644index 00000000000..9d12dc01b71--- /dev/null+++ b/packages/model-runtime/src/providers/deepseek/__tests__/generateObject.test.ts@@ -0,0 +1,196 @@+// @vitest-environment node+import type { Mock } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { LobeDeepSeekAnthropicAI, openAIParams } from '../index';+import { expectNoLoneSurrogateEscapes, loneHighSurrogate, validEmoji } from './testUtils';++describe('LobeDeepSeekAnthropicAI generateObject', () => {+ let instance: InstanceType<typeof LobeDeepSeekAnthropicAI>;++ 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,+ },+ },+ };++ const getLastRequestPayload = () => {+ const calls = ((instance as any).client.messages.create as Mock).mock.calls;+ return calls.at(-1)?.[0];+ };++ beforeEach(() => {+ instance = new LobeDeepSeekAnthropicAI({ apiKey: 'test' });++ vi.spyOn((instance as any).client.messages, 'create').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,+ },+ } as any);+ });++ afterEach(() => {+ vi.clearAllMocks();+ });++ 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' });+ });++ 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 remove lone surrogates from Anthropic generateObject request payload strings', async () => {+ await instance.generateObject({+ ...generateObjectPayload,+ messages: [+ {+ content: `Generate ${loneHighSurrogate} handoff ${validEmoji}`,+ role: 'user' as const,+ },+ ],+ });++ const payload = getLastRequestPayload();+ const serialized = expectNoLoneSurrogateEscapes(payload);++ expect(serialized).toContain(validEmoji);+ });++ it('should omit output_config when thinking is disabled', async () => {+ await instance.generateObject({+ ...generateObjectPayload,+ reasoning_effort: 'high',+ thinking: { budget_tokens: 0, type: 'disabled' },+ });++ const payload = getLastRequestPayload();++ expect(payload.output_config).toBeUndefined();+ expect(payload.thinking).toEqual({ type: 'disabled' });+ });+});++describe('DeepSeek OpenAI-compatible generateObject configuration', () => {+ it('should use tools calling for generateObject', () => {+ 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' } }));+ });++ it('should remove lone surrogates from generateObject request payload strings', () => {+ const requestPayload = {+ messages: [{ role: 'user' as const, content: `Hello ${loneHighSurrogate} ${validEmoji}` }],+ 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,+ {},+ );+ const serialized = expectNoLoneSurrogateEscapes(result);++ expect(serialized).toContain(validEmoji);+ });+});diff --git a/packages/model-runtime/src/providers/deepseek/__tests__/index.test.ts b/packages/model-runtime/src/providers/deepseek/__tests__/index.test.tsnew file mode 100644index 00000000000..4effb9fcd03--- /dev/null+++ b/packages/model-runtime/src/providers/deepseek/__tests__/index.test.ts@@ -0,0 +1,169 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import {+ LobeDeepSeekAI,+ LobeDeepSeekAnthropicAI,+ LobeDeepSeekOpenAI,+ openAIParams,+} from '../index';+import { anthropicBaseURL, defaultOpenAIBaseURL } from './testUtils';++describe('LobeDeepSeekAI', () => {+ const createRuntime = ({+ baseURL,+ sdkType,+ }: {+ baseURL?: string;+ sdkType?: string;+ } = {}) =>+ new LobeDeepSeekAI({+ apiKey: 'test',+ ...(baseURL ? { baseURL } : {}),+ ...(sdkType ? { sdkType } : {}),+ });++ const resolveRouter = async (baseURL?: string, sdkType?: string) => {+ const runtime = createRuntime({ baseURL, sdkType });++ return (runtime as any).resolveMatchedRouter('deepseek-v4-pro');+ };++ const resolveFirstRouterOption = async (baseURL: string, sdkType: string) => {+ const runtime = createRuntime({ baseURL, sdkType });+ const router = await (runtime as any).resolveMatchedRouter('deepseek-v4-pro');+ const routerOptions = (runtime as any).normalizeRouterOptions(router);++ return {+ option: routerOptions[0],+ router,+ };+ };++ describe('RouterRuntime baseURL routing', () => {+ it('should route to Anthropic format by default', async () => {+ const router = await resolveRouter();++ expect(router.apiType).toBe('deepseek');+ expect(router.id).toBe('anthropic-compatible');+ });++ it('should route to Anthropic format when baseURL ends with /anthropic', async () => {+ const router = await resolveRouter(anthropicBaseURL);++ expect(router.apiType).toBe('deepseek');+ expect(router.id).toBe('anthropic-compatible');+ });++ it('should route to Anthropic format when baseURL ends with /anthropic/', async () => {+ const router = await resolveRouter(`${anthropicBaseURL}/`);++ expect(router.apiType).toBe('deepseek');+ expect(router.id).toBe('anthropic-compatible');+ });++ it('should route to OpenAI format when baseURL ends with /v1', async () => {+ const router = await resolveRouter(defaultOpenAIBaseURL);++ expect(router.apiType).toBe('deepseek');+ expect(router.id).toBe('openai-compatible');+ });++ it('should route custom non-Anthropic baseURL to OpenAI format', async () => {+ const router = await resolveRouter('https://api.deepseek.com');++ expect(router.apiType).toBe('deepseek');+ expect(router.id).toBe('openai-compatible');+ });++ it('should route to Anthropic format when sdkType is anthropic', async () => {+ const router = await resolveRouter('https://aihubmix.com/v1/messages', 'anthropic');++ expect(router.apiType).toBe('deepseek');+ expect(router.id).toBe('anthropic-compatible');+ });++ it('should normalize /v1/messages before creating an Anthropic SDK runtime', async () => {+ const { option } = await resolveFirstRouterOption(+ 'https://aihubmix.com/v1/messages',+ 'anthropic',+ );+ const runtime = new LobeDeepSeekAnthropicAI({ apiKey: 'test', baseURL: option.baseURL });++ expect(option.baseURL).toBe('https://aihubmix.com');+ expect(runtime).toBeInstanceOf(LobeDeepSeekAnthropicAI);+ expect((runtime as any).baseURL).toBe('https://aihubmix.com');+ });++ it('should let Anthropic-compatible runtime normalize /v1 baseURL', async () => {+ const { option } = await resolveFirstRouterOption('https://aihubmix.com/v1', 'anthropic');+ const runtime = new LobeDeepSeekAnthropicAI({ apiKey: 'test', baseURL: option.baseURL });++ expect(option.baseURL).toBe('https://aihubmix.com/v1');+ expect(runtime).toBeInstanceOf(LobeDeepSeekAnthropicAI);+ expect((runtime as any).baseURL).toBe('https://aihubmix.com');+ });++ it('should normalize /anthropic/v1/messages before creating an Anthropic SDK runtime', async () => {+ const { option } = await resolveFirstRouterOption(+ 'https://api.deepseek.com/anthropic/v1/messages',+ 'anthropic',+ );+ const runtime = new LobeDeepSeekAnthropicAI({ apiKey: 'test', baseURL: option.baseURL });++ expect(option.baseURL).toBe(anthropicBaseURL);+ expect(runtime).toBeInstanceOf(LobeDeepSeekAnthropicAI);+ expect((runtime as any).baseURL).toBe(anthropicBaseURL);+ });++ it('should let sdkType override legacy baseURL suffix routing', async () => {+ const router = await resolveRouter(anthropicBaseURL, 'openai');++ expect(router.apiType).toBe('deepseek');+ expect(router.id).toBe('openai-compatible');+ });++ it('should reject unsupported sdkType values', async () => {+ await expect(resolveRouter(defaultOpenAIBaseURL, 'invalid')).rejects.toThrow(+ 'Unsupported DeepSeek sdkType: invalid',+ );+ });+ });+});++describe('LobeDeepSeekOpenAI', () => {+ describe('init', () => {+ it('should correctly initialize with an API key', () => {+ const runtime = new LobeDeepSeekOpenAI({ apiKey: 'test_api_key' });++ expect(runtime).toBeInstanceOf(LobeDeepSeekOpenAI);+ expect((runtime as any).baseURL).toEqual(defaultOpenAIBaseURL);+ });+ });+});++describe('LobeDeepSeekAnthropicAI', () => {+ describe('init', () => {+ it('should correctly initialize with an API key', () => {+ const runtime = new LobeDeepSeekAnthropicAI({ apiKey: 'test_api_key' });++ expect(runtime).toBeInstanceOf(LobeDeepSeekAnthropicAI);+ expect((runtime as any).baseURL).toEqual(anthropicBaseURL);+ });+ });+});++describe('Debug Configuration', () => {+ it('should disable debug by default', () => {+ delete process.env.DEBUG_DEEPSEEK_CHAT_COMPLETION;+ const result = openAIParams.debug.chatCompletion();+ expect(result).toBe(false);+ });++ it('should enable debug when env is set', () => {+ process.env.DEBUG_DEEPSEEK_CHAT_COMPLETION = '1';+ const result = openAIParams.debug.chatCompletion();+ expect(result).toBe(true);+ delete process.env.DEBUG_DEEPSEEK_CHAT_COMPLETION;+ });+});diff --git a/packages/model-runtime/src/providers/deepseek/__tests__/modelFetch.test.ts b/packages/model-runtime/src/providers/deepseek/__tests__/modelFetch.test.tsnew file mode 100644index 00000000000..f777d6b29d0--- /dev/null+++ b/packages/model-runtime/src/providers/deepseek/__tests__/modelFetch.test.ts@@ -0,0 +1,98 @@+// @vitest-environment node+import './testUtils';++import type { ChatModelCard } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { params } from '../index';++describe('DeepSeek models', () => {+ const fetchModels = params.models as (params: { client: unknown }) => Promise<ChatModelCard[]>;+ const mockClient = {+ models: {+ list: vi.fn(),+ },+ };++ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('should fetch and process models successfully', async () => {+ mockClient.models.list.mockResolvedValue({+ data: [{ id: 'deepseek-chat' }, { id: 'deepseek-coder' }, { id: 'deepseek-r1' }],+ });++ const models = await fetchModels({ client: mockClient });++ expect(mockClient.models.list).toHaveBeenCalledTimes(1);+ expect(models).toHaveLength(3);+ expect(models[0].id).toBe('deepseek-chat');+ expect(models[1].id).toBe('deepseek-coder');+ expect(models[2].id).toBe('deepseek-r1');+ });++ it('should handle single model', async () => {+ mockClient.models.list.mockResolvedValue({+ data: [{ id: 'deepseek-chat' }],+ });++ const models = await fetchModels({ client: mockClient });++ expect(models).toHaveLength(1);+ expect(models[0].id).toBe('deepseek-chat');+ });++ it('should handle empty model list', async () => {+ mockClient.models.list.mockResolvedValue({+ data: [],+ });++ const models = await fetchModels({ client: mockClient });++ expect(models).toEqual([]);+ });++ it('should process models with MODEL_LIST_CONFIGS', async () => {+ mockClient.models.list.mockResolvedValue({+ data: [{ id: 'deepseek-chat' }],+ });++ const models = await fetchModels({ client: mockClient });++ // The processModelList function should merge with known model list+ expect(models[0]).toHaveProperty('id');+ expect(models[0].id).toBe('deepseek-chat');+ });++ it('should preserve model properties from API response', async () => {+ mockClient.models.list.mockResolvedValue({+ data: [+ { id: 'deepseek-chat', extra_field: 'value' },+ { id: 'deepseek-coder', another_field: 123 },+ ],+ });++ const models = await fetchModels({ client: mockClient });++ expect(models).toHaveLength(2);+ expect(models[0].id).toBe('deepseek-chat');+ expect(models[1].id).toBe('deepseek-coder');+ });++ it('should handle models with different id patterns', async () => {+ mockClient.models.list.mockResolvedValue({+ data: [+ { id: 'deepseek-chat' },+ { id: 'deepseek-r1' },+ { id: 'deepseek-reasoner' },+ { id: 'deepseek-v3' },+ ],+ });++ const models = await fetchModels({ client: mockClient });++ expect(models).toHaveLength(4);+ expect(models.every((m) => typeof m.id === 'string')).toBe(true);+ });+});diff --git a/packages/model-runtime/src/providers/deepseek/__tests__/openaiPayload.test.ts b/packages/model-runtime/src/providers/deepseek/__tests__/openaiPayload.test.tsnew file mode 100644index 00000000000..d832bc4dca1--- /dev/null+++ b/packages/model-runtime/src/providers/deepseek/__tests__/openaiPayload.test.ts@@ -0,0 +1,412 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import { openAIParams } from '../index';+import {+ expectNoLoneSurrogateEscapes,+ loneHighSurrogate,+ loneLowSurrogate,+ validEmoji,+} from './testUtils';++describe('DeepSeek OpenAI-compatible chatCompletion.handlePayload', () => {+ it('should transform reasoning object to reasoning_content string', () => {+ const payload = {+ messages: [+ { role: 'user', content: 'Hello' },+ {+ role: 'assistant',+ content: 'Hi there',+ reasoning: { content: 'Let me think...', duration: 1000 },+ },+ { role: 'user', content: 'How are you?' },+ ],+ model: 'deepseek-r1',+ };++ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);++ expect(result.messages).toEqual([+ { role: 'user', content: 'Hello' },+ {+ role: 'assistant',+ content: 'Hi there',+ reasoning_content: 'Let me think...',+ },+ { role: 'user', content: 'How are you?' },+ ]);+ });++ it('should not modify messages without reasoning field', () => {+ const payload = {+ messages: [+ { role: 'user', content: 'Hello' },+ { role: 'assistant', content: 'Hi there' },+ ],+ model: 'deepseek-chat',+ };++ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);++ expect(result.messages).toEqual(payload.messages);+ });++ it('should handle empty reasoning content', () => {+ const payload = {+ messages: [+ {+ role: 'assistant',+ content: 'Response',+ reasoning: { duration: 1000 },+ },+ ],+ model: 'deepseek-r1',+ };++ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);++ expect(result.messages[0]).toEqual({+ role: 'assistant',+ content: 'Response',+ });+ });++ it('should set stream to true by default', () => {+ const payload = {+ messages: [{ role: 'user', content: 'Hello' }],+ model: 'deepseek-chat',+ };++ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);++ expect(result.stream).toBe(true);+ });++ it('should remove lone surrogates from OpenAI-compatible chat payload strings', () => {+ const payload = {+ messages: [+ { role: 'user', content: `Hello ${loneHighSurrogate} ${validEmoji}` },+ {+ role: 'assistant',+ content: 'Response',+ reasoning: { content: `Reasoning ${loneLowSurrogate} value` },+ },+ ],+ model: 'deepseek-v4-flash',+ };++ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);+ const serialized = expectNoLoneSurrogateEscapes(result);++ expect(serialized).toContain(validEmoji);+ });++ it('should preserve existing stream value', () => {+ const payload = {+ messages: [{ role: 'user', content: 'Hello' }],+ model: 'deepseek-chat',+ stream: false,+ };++ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);++ expect(result.stream).toBe(false);+ });++ it('should add empty reasoning_content for assistant messages in deepseek-reasoner', () => {+ const payload = {+ messages: [+ { role: 'user', content: 'Search weather' },+ {+ role: 'assistant',+ content: '',+ tool_calls: [+ {+ id: 'call_1',+ type: 'function',+ function: {+ name: 'search',+ arguments: '{"q":"weather"}',+ },+ },+ ],+ },+ { role: 'tool', content: '{"result":"sunny"}', tool_call_id: 'call_1' },+ ],+ model: 'deepseek-reasoner',+ };++ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);++ expect(result.messages).toEqual([+ { role: 'user', content: 'Search weather' },+ {+ role: 'assistant',+ content: '',+ reasoning_content: '',+ tool_calls: [+ {+ id: 'call_1',+ type: 'function',+ function: {+ name: 'search',+ arguments: '{"q":"weather"}',+ },+ },+ ],+ },+ { role: 'tool', content: '{"result":"sunny"}', tool_call_id: 'call_1' },+ ]);+ });++ it('should preserve existing reasoning_content for deepseek-reasoner assistant messages', () => {+ const payload = {+ messages: [+ {+ role: 'assistant',+ content: 'Previous answer',+ reasoning_content: 'existing reasoning',+ },+ ],+ model: 'deepseek-reasoner',+ };++ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);++ expect(result.messages).toEqual([+ {+ role: 'assistant',+ content: 'Previous answer',+ reasoning_content: 'existing reasoning',+ },+ ]);+ });++ // DeepSeek V4 models default to thinking mode unless thinking.type === 'disabled'.+ // In thinking mode the API rejects follow-up turns whose assistant messages omit+ // reasoning_content when tool calls are involved — see chatPayload.ts for details.+ describe('deepseek-v4 thinking mode reasoning_content enforcement', () => {+ it('should force reasoning_content on v4-flash assistant messages by default', () => {+ const payload = {+ messages: [+ { role: 'user', content: 'Search weather' },+ {+ role: 'assistant',+ content: '',+ tool_calls: [+ {+ id: 'call_1',+ type: 'function',+ function: { name: 'search', arguments: '{"q":"weather"}' },+ },+ ],+ },+ ],+ model: 'deepseek-v4-flash',+ };++ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);++ expect(result.messages[1]).toEqual({+ role: 'assistant',+ content: '',+ reasoning_content: '',+ tool_calls: [+ {+ id: 'call_1',+ type: 'function',+ function: { name: 'search', arguments: '{"q":"weather"}' },+ },+ ],+ });+ });++ it('should force reasoning_content on v4-pro assistant messages by default', () => {+ const payload = {+ messages: [{ role: 'assistant', content: 'hi' }],+ model: 'deepseek-v4-pro',+ };++ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);++ expect(result.messages[0]).toEqual({+ role: 'assistant',+ content: 'hi',+ reasoning_content: '',+ });+ });++ it('should force reasoning_content when thinking.type is explicitly enabled', () => {+ const payload = {+ messages: [{ role: 'assistant', content: 'hi' }],+ model: 'deepseek-v4-flash',+ thinking: { type: 'enabled' },+ };++ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);++ expect(result.messages[0]).toEqual({+ role: 'assistant',+ content: 'hi',+ reasoning_content: '',+ });+ });++ it('should NOT force reasoning_content when thinking.type is disabled', () => {+ const payload = {+ messages: [{ role: 'assistant', content: 'hi' }],+ model: 'deepseek-v4-flash',+ thinking: { type: 'disabled' },+ };++ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);++ expect(result.messages[0]).toEqual({+ role: 'assistant',+ content: 'hi',+ });+ });++ it('should remove reasoning_effort when thinking.type is disabled', () => {+ const payload = {+ messages: [{ role: 'user', content: 'hi' }],+ model: 'deepseek-v4-flash',+ reasoning_effort: 'high',+ thinking: { type: 'disabled' },+ };++ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);++ expect(result).toEqual({+ messages: [{ role: 'user', content: 'hi' }],+ model: 'deepseek-v4-flash',+ stream: true,+ thinking: { type: 'disabled' },+ });+ });++ it('should preserve reasoning_effort when thinking is enabled', () => {+ const payload = {+ messages: [{ role: 'user', content: 'hi' }],+ model: 'deepseek-v4-flash',+ reasoning_effort: 'high',+ thinking: { type: 'enabled' },+ };++ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);++ expect(result.reasoning_effort).toBe('high');+ });++ it('should preserve existing reasoning_content on v4 assistant messages', () => {+ const payload = {+ messages: [+ {+ role: 'assistant',+ content: 'answer',+ reasoning_content: 'prior reasoning',+ },+ ],+ model: 'deepseek-v4-flash',+ };++ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);++ expect(result.messages[0]).toEqual({+ role: 'assistant',+ content: 'answer',+ reasoning_content: 'prior reasoning',+ });+ });++ it('should NOT force reasoning_content on non-v4 / non-reasoner models', () => {+ const payload = {+ messages: [{ role: 'assistant', content: 'hi' }],+ model: 'deepseek-chat',+ };++ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);++ expect(result.messages[0]).toEqual({+ role: 'assistant',+ content: 'hi',+ });+ });+ });++ it('should add empty reasoning_content for assistant messages in deepseek-v4-pro thinking mode', () => {+ const payload = {+ messages: [+ { role: 'user', content: 'Call a tool' },+ {+ role: 'assistant',+ content: '',+ tool_calls: [+ {+ id: 'call_1',+ type: 'function',+ function: {+ name: 'lookup',+ arguments: '{"q":"docs"}',+ },+ },+ ],+ },+ ],+ model: 'deepseek-v4-pro',+ };++ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);++ expect(result.messages).toEqual([+ { role: 'user', content: 'Call a tool' },+ {+ role: 'assistant',+ content: '',+ reasoning_content: '',+ tool_calls: [+ {+ id: 'call_1',+ type: 'function',+ function: {+ name: 'lookup',+ arguments: '{"q":"docs"}',+ },+ },+ ],+ },+ ]);+ });++ it('should preserve only supported DeepSeek thinking config fields', () => {+ const payload = {+ messages: [{ role: 'user', content: 'Hello' }],+ model: 'deepseek-v4-flash',+ reasoning_effort: 'high' as const,+ thinking: {+ budget_tokens: 4096,+ type: 'enabled' as const,+ },+ };++ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);++ expect(result.reasoning_effort).toBe('high');+ expect(result).toEqual(expect.objectContaining({ thinking: { type: 'enabled' } }));+ expect(result).not.toEqual(+ expect.objectContaining({ thinking: expect.objectContaining({ budget_tokens: 4096 }) }),+ );+ });++ it('should forward disabled thinking mode for deepseek-v4-pro', () => {+ const payload = {+ messages: [{ role: 'user', content: 'Hello' }],+ model: 'deepseek-v4-pro',+ thinking: { type: 'disabled' as const },+ };++ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);++ expect(result).toEqual(expect.objectContaining({ thinking: { type: 'disabled' } }));+ });+});diff --git a/packages/model-runtime/src/providers/deepseek/__tests__/sanitizePayload.test.ts b/packages/model-runtime/src/providers/deepseek/__tests__/sanitizePayload.test.tsnew file mode 100644index 00000000000..ac4a3d8b367--- /dev/null+++ b/packages/model-runtime/src/providers/deepseek/__tests__/sanitizePayload.test.ts@@ -0,0 +1,78 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import { sanitizeDeepSeekJsonPayload } from '../sanitizePayload';+import { loneHighSurrogate, loneLowSurrogate, validEmoji } from './testUtils';++describe('sanitizeDeepSeekJsonPayload', () => {+ it('should sanitize request text surfaces only', () => {+ const payload = {+ messages: [+ { content: `Hello ${loneHighSurrogate} ${validEmoji}`, role: 'user' },+ {+ content: [{ text: `Block ${loneLowSurrogate} ${validEmoji}`, type: 'text' }],+ role: 'assistant',+ tool_calls: [+ {+ function: {+ arguments: `{"query":"${loneHighSurrogate} ${validEmoji}"}`,+ name: 'search',+ },+ id: 'call_1',+ type: 'function',+ },+ ],+ },+ {+ content: [+ {+ input: {+ nested: { values: [`Nested ${loneLowSurrogate} ${validEmoji}`] },+ query: `Tool ${loneHighSurrogate} ${validEmoji}`,+ },+ name: 'search',+ type: 'tool_use',+ },+ ],+ role: 'assistant',+ },+ ],+ metadata: {+ note: loneHighSurrogate,+ },+ system: [{ text: `System ${loneHighSurrogate} ${validEmoji}`, type: 'text' }],+ tools: [+ {+ description: loneHighSurrogate,+ input_schema: {+ properties: {+ query: { description: loneHighSurrogate, type: 'string' },+ },+ type: 'object',+ },+ name: 'search',+ },+ ],+ };++ const result = sanitizeDeepSeekJsonPayload(payload);++ expect(JSON.stringify(result.messages)).not.toContain('\\ud83d');+ expect(JSON.stringify(result.messages)).not.toContain('\\udc1b');+ expect(JSON.stringify(result.system)).not.toContain('\\ud83d');+ expect(JSON.stringify(result.metadata)).toContain('\\ud83d');+ expect(JSON.stringify(result.tools)).toContain('\\ud83d');+ });++ it('should keep non-plain objects unchanged', () => {+ const createdAt = new Date('2026-05-22T00:00:00.000Z');+ const payload = {+ messages: [{ content: 'Hello', role: 'user' }],+ metadata: { createdAt },+ };++ const result = sanitizeDeepSeekJsonPayload(payload);++ expect(result.metadata.createdAt).toBe(createdAt);+ });+});diff --git a/packages/model-runtime/src/providers/deepseek/__tests__/testUtils.ts b/packages/model-runtime/src/providers/deepseek/__tests__/testUtils.tsnew file mode 100644index 00000000000..d263815938b--- /dev/null+++ b/packages/model-runtime/src/providers/deepseek/__tests__/testUtils.ts@@ -0,0 +1,32 @@+import { expect, vi } from 'vitest';++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,+}));++export const defaultOpenAIBaseURL = 'https://api.deepseek.com/v1';+export const anthropicBaseURL = 'https://api.deepseek.com/anthropic';+export const loneHighSurrogate = '\uD83D';+export const loneLowSurrogate = '\uDC1B';+export const validEmoji = '\uD83D\uDC1B';++export const expectNoLoneSurrogateEscapes = (value: unknown) => {+ const serialized = JSON.stringify(value);++ expect(serialized).not.toContain('\\ud83d');+ expect(serialized).not.toContain('\\udc1b');++ return serialized;+};++vi.spyOn(console, 'error').mockImplementation(() => {});diff --git a/packages/model-runtime/src/providers/deepseek/chatPayload.ts b/packages/model-runtime/src/providers/deepseek/chatPayload.tsnew file mode 100644index 00000000000..b5d3216ab66--- /dev/null+++ b/packages/model-runtime/src/providers/deepseek/chatPayload.ts@@ -0,0 +1,180 @@+import type Anthropic from '@anthropic-ai/sdk';+import { ModelProvider } from 'model-bank';+import type OpenAI from 'openai';++import { buildDefaultAnthropicPayload } from '../../core/anthropicCompatibleFactory';+import type { ChatStreamPayload } from '../../types';+import { getModelPropertyWithFallback } from '../../utils/getFallbackModelProperty';+import { sanitizeDeepSeekJsonPayload } from './sanitizePayload';++const isDeepSeekV4Model = (model: string) => model.startsWith('deepseek-v4');+const isEmptyContent = (content: unknown) =>+ content === '' || content === null || content === undefined;+const hasReasoningContent = (reasoning: any) => typeof reasoning?.content === 'string';++const buildThinkingBlock = (reasoning: any) =>+ hasReasoningContent(reasoning)+ ? { thinking: reasoning.content, type: 'thinking' as const }+ : undefined;++const toContentArray = (content: any) =>+ Array.isArray(content)+ ? content+ : [{ text: isEmptyContent(content) ? ' ' : content, type: 'text' as const }];++const shouldEnableDeepSeekThinking = (payload: ChatStreamPayload) => {+ if (payload.model === 'deepseek-reasoner') return true;+ return isDeepSeekV4Model(payload.model) && payload.thinking?.type !== 'disabled';+};++const resolveDeepSeekThinking = (payload: ChatStreamPayload): ChatStreamPayload['thinking'] => {+ if (payload.model === 'deepseek-reasoner') {+ return {+ budget_tokens: payload.thinking?.budget_tokens ?? 1024,+ type: 'enabled',+ };+ }++ if (isDeepSeekV4Model(payload.model)) {+ if (payload.thinking?.type === 'disabled') {+ return {+ budget_tokens: 0,+ type: 'disabled',+ };+ }++ return {+ budget_tokens: payload.thinking?.budget_tokens ?? 1024,+ type: 'enabled',+ };+ }++ if (payload.thinking?.type === 'enabled' && payload.thinking.budget_tokens === undefined) {+ return {+ budget_tokens: 1024,+ type: 'enabled',+ };+ }++ return payload.thinking;+};++/**+ * DeepSeek's Anthropic-compatible API uses Anthropic content blocks for assistant+ * reasoning history. For V4 thinking mode we keep an explicit placeholder block+ * so follow-up tool-call turns preserve the same reasoning-history guarantee as+ * the OpenAI-compatible API.+ *+ * @see https://api-docs.deepseek.com/guides/anthropic_api+ * @see https://api-docs.deepseek.com/guides/thinking_mode#tool-calls+ */+const normalizeMessagesForAnthropic = (+ messages: ChatStreamPayload['messages'],+ forceThinking = false,+) =>+ messages.map((message: any) => {+ if (message.role !== 'assistant') return message;++ const { reasoning, ...rest } = message;+ const thinkingBlock = buildThinkingBlock(reasoning);+ const effectiveThinkingBlock =+ thinkingBlock || (forceThinking ? { thinking: ' ', type: 'thinking' as const } : undefined);++ if (!effectiveThinkingBlock) return rest;++ return {+ ...rest,+ content: [effectiveThinkingBlock, ...toContentArray(message.content)],+ };+ });++export const buildDeepSeekAnthropicPayload = async (+ payload: ChatStreamPayload,+): Promise<Anthropic.MessageCreateParams> => {+ const resolvedThinking = resolveDeepSeekThinking(payload);+ const isThinkingDisabled = resolvedThinking?.type === 'disabled';+ const resolvedMaxTokens =+ payload.max_tokens ??+ (await getModelPropertyWithFallback<number | undefined>(+ payload.model,+ 'maxOutput',+ ModelProvider.DeepSeek,+ )) ??+ (resolvedThinking?.type === 'enabled' ? 32_000 : 64_000);++ const basePayload = await buildDefaultAnthropicPayload({+ ...payload,+ effort: !isThinkingDisabled ? ((payload.effort ?? payload.reasoning_effort) as any) : undefined,+ max_tokens: resolvedMaxTokens,+ messages: normalizeMessagesForAnthropic(+ payload.messages,+ shouldEnableDeepSeekThinking(payload),+ ),+ thinking: isThinkingDisabled ? undefined : resolvedThinking,+ });++ return sanitizeDeepSeekJsonPayload({+ ...basePayload,+ ...(basePayload.temperature !== undefined && payload.temperature !== undefined+ ? { temperature: payload.temperature }+ : {}),+ ...(isThinkingDisabled ? { thinking: { type: 'disabled' } } : {}),+ } as Anthropic.MessageCreateParams);+};++export const buildDeepSeekOpenAIPayload = (+ payload: ChatStreamPayload,+): OpenAI.ChatCompletionCreateParamsStreaming => {+ // deepseek-v4-* defaults to thinking=enabled unless the caller explicitly+ // sets thinking.type === 'disabled'. In thinking mode the API rejects+ // (HTTP 400) follow-up turns that omit reasoning_content on assistant+ // messages with tool calls — see+ // https://api-docs.deepseek.com/guides/thinking_mode#tool-calls+ const isV4Model = typeof payload.model === 'string' && isDeepSeekV4Model(payload.model);+ const thinkingExplicitlyDisabled = payload.thinking?.type === 'disabled';+ const shouldForceAssistantReasoningContent =+ payload.model === 'deepseek-reasoner' || (isV4Model && !thinkingExplicitlyDisabled);++ // Transform reasoning object to reasoning_content string for multi-turn conversations+ const messages = payload.messages.map((message: any) => {+ const { reasoning, ...rest } = message;++ const reasoningContent =+ typeof rest.reasoning_content === 'string'+ ? rest.reasoning_content+ : typeof reasoning?.content === 'string'+ ? reasoning.content+ : undefined;++ // DeepSeek thinking mode with tool calls requires assistant history+ // messages to carry reasoning_content, or the API returns a 400.+ if (message.role === 'assistant' && shouldForceAssistantReasoningContent) {+ return {+ ...rest,+ reasoning_content: reasoningContent ?? '',+ };+ }++ if (reasoningContent !== undefined) {+ return {+ ...rest,+ reasoning_content: reasoningContent,+ };+ }++ return rest;+ });++ // DeepSeek rejects `reasoning_effort` when thinking is explicitly disabled.+ const { reasoning_effort, thinking, ...restPayload } = payload;++ return sanitizeDeepSeekJsonPayload({+ ...restPayload,+ messages,+ ...(!thinkingExplicitlyDisabled && reasoning_effort && { reasoning_effort }),+ ...(thinking?.type === 'enabled' || thinking?.type === 'disabled'+ ? { thinking: { type: thinking.type } }+ : {}),+ stream: payload.stream ?? true,+ } as OpenAI.ChatCompletionCreateParamsStreaming);+};diff --git a/packages/model-runtime/src/providers/deepseek/generateObject.ts b/packages/model-runtime/src/providers/deepseek/generateObject.tsnew file mode 100644index 00000000000..321e2fe7577--- /dev/null+++ b/packages/model-runtime/src/providers/deepseek/generateObject.ts@@ -0,0 +1,72 @@+import type Anthropic from '@anthropic-ai/sdk';+import type { Pricing } from 'model-bank';++import type { AnthropicGenerateObjectConfig } from '../../core/anthropicCompatibleFactory/generateObject';+import { createAnthropicGenerateObject } from '../../core/anthropicCompatibleFactory/generateObject';+import type { OpenAICompatibleFactoryOptions } from '../../core/openaiCompatibleFactory';+import type { ChatStreamPayload, GenerateObjectOptions, GenerateObjectPayload } from '../../types';+import { sanitizeDeepSeekJsonPayload } from './sanitizePayload';++type GenerateObjectHandlePayload = NonNullable<+ NonNullable<OpenAICompatibleFactoryOptions['generateObject']>['handlePayload']+>;++const isGenerateObjectThinkingDisabled = (payload: GenerateObjectPayload) =>+ (payload as GenerateObjectPayload & { thinking?: ChatStreamPayload['thinking'] }).thinking+ ?.type === 'disabled';++export 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);+ 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' } } : {}),+ };++ const sanitizedClient = {+ ...client,+ messages: {+ ...client.messages,+ create: (params: Anthropic.MessageCreateParams, requestOptions?: Anthropic.RequestOptions) =>+ client.messages.create(sanitizeDeepSeekJsonPayload(params), requestOptions),+ },+ } as Anthropic;++ return createAnthropicGenerateObject(sanitizedClient, payload, options, pricing, {+ requestParams,+ schemaToolChoice: thinkingDisabled ? 'tool' : 'any',+ });+};++export 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 sanitizeDeepSeekJsonPayload({+ ...(thinkingExplicitlyDisabled ? payloadWithoutReasoningEffort : requestPayload),+ ...(thinking?.type === 'enabled' || thinkingExplicitlyDisabled+ ? { thinking: { type: thinking.type } }+ : {}),+ });+};diff --git a/packages/model-runtime/src/providers/deepseek/index.test.ts b/packages/model-runtime/src/providers/deepseek/index.test.tsdeleted file mode 100644index b50dca1b0c6..00000000000--- a/packages/model-runtime/src/providers/deepseek/index.test.ts+++ /dev/null@@ -1,959 +0,0 @@-// @vitest-environment node-import type { ChatModelCard } from '@lobechat/types';-import type { Mock } from 'vitest';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import {- LobeDeepSeekAI,- LobeDeepSeekAnthropicAI,- LobeDeepSeekOpenAI,- openAIParams,- 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';--vi.spyOn(console, 'error').mockImplementation(() => {});--describe('LobeDeepSeekAI', () => {- const createRuntime = ({- baseURL,- sdkType,- }: {- baseURL?: string;- sdkType?: string;- } = {}) =>- new LobeDeepSeekAI({- apiKey: 'test',- ...(baseURL ? { baseURL } : {}),- ...(sdkType ? { sdkType } : {}),- });-- const resolveRouter = async (baseURL?: string, sdkType?: string) => {- const runtime = createRuntime({ baseURL, sdkType });-- return (runtime as any).resolveMatchedRouter('deepseek-v4-pro');- };-- const resolveFirstRouterOption = async (baseURL: string, sdkType: string) => {- const runtime = createRuntime({ baseURL, sdkType });- const router = await (runtime as any).resolveMatchedRouter('deepseek-v4-pro');- const routerOptions = (runtime as any).normalizeRouterOptions(router);-- return {- option: routerOptions[0],- router,- };- };-- describe('RouterRuntime baseURL routing', () => {- it('should route to Anthropic format by default', async () => {- const router = await resolveRouter();-- expect(router.apiType).toBe('deepseek');- expect(router.id).toBe('anthropic-compatible');- });-- it('should route to Anthropic format when baseURL ends with /anthropic', async () => {- const router = await resolveRouter(anthropicBaseURL);-- expect(router.apiType).toBe('deepseek');- expect(router.id).toBe('anthropic-compatible');- });-- it('should route to Anthropic format when baseURL ends with /anthropic/', async () => {- const router = await resolveRouter(`${anthropicBaseURL}/`);-- expect(router.apiType).toBe('deepseek');- expect(router.id).toBe('anthropic-compatible');- });-- it('should route to OpenAI format when baseURL ends with /v1', async () => {- const router = await resolveRouter(defaultOpenAIBaseURL);-- expect(router.apiType).toBe('deepseek');- expect(router.id).toBe('openai-compatible');- });-- it('should route custom non-Anthropic baseURL to OpenAI format', async () => {- const router = await resolveRouter('https://api.deepseek.com');-- expect(router.apiType).toBe('deepseek');- expect(router.id).toBe('openai-compatible');- });-- it('should route to Anthropic format when sdkType is anthropic', async () => {- const router = await resolveRouter('https://aihubmix.com/v1/messages', 'anthropic');-- expect(router.apiType).toBe('deepseek');- expect(router.id).toBe('anthropic-compatible');- });-- it('should normalize /v1/messages before creating an Anthropic SDK runtime', async () => {- const { option } = await resolveFirstRouterOption(- 'https://aihubmix.com/v1/messages',- 'anthropic',- );- const runtime = new LobeDeepSeekAnthropicAI({ apiKey: 'test', baseURL: option.baseURL });-- expect(option.baseURL).toBe('https://aihubmix.com');- expect(runtime).toBeInstanceOf(LobeDeepSeekAnthropicAI);- expect((runtime as any).baseURL).toBe('https://aihubmix.com');- });-- it('should let Anthropic-compatible runtime normalize /v1 baseURL', async () => {- const { option } = await resolveFirstRouterOption('https://aihubmix.com/v1', 'anthropic');- const runtime = new LobeDeepSeekAnthropicAI({ apiKey: 'test', baseURL: option.baseURL });-- expect(option.baseURL).toBe('https://aihubmix.com/v1');- expect(runtime).toBeInstanceOf(LobeDeepSeekAnthropicAI);- expect((runtime as any).baseURL).toBe('https://aihubmix.com');- });-- it('should normalize /anthropic/v1/messages before creating an Anthropic SDK runtime', async () => {- const { option } = await resolveFirstRouterOption(- 'https://api.deepseek.com/anthropic/v1/messages',- 'anthropic',- );- const runtime = new LobeDeepSeekAnthropicAI({ apiKey: 'test', baseURL: option.baseURL });-- expect(option.baseURL).toBe(anthropicBaseURL);- expect(runtime).toBeInstanceOf(LobeDeepSeekAnthropicAI);- expect((runtime as any).baseURL).toBe(anthropicBaseURL);- });-- it('should let sdkType override legacy baseURL suffix routing', async () => {- const router = await resolveRouter(anthropicBaseURL, 'openai');-- expect(router.apiType).toBe('deepseek');- expect(router.id).toBe('openai-compatible');- });-- it('should reject unsupported sdkType values', async () => {- await expect(resolveRouter(defaultOpenAIBaseURL, 'invalid')).rejects.toThrow(- 'Unsupported DeepSeek sdkType: invalid',- );- });- });-});--describe('LobeDeepSeekOpenAI', () => {- describe('init', () => {- it('should correctly initialize with an API key', () => {- const runtime = new LobeDeepSeekOpenAI({ apiKey: 'test_api_key' });-- expect(runtime).toBeInstanceOf(LobeDeepSeekOpenAI);- expect((runtime as any).baseURL).toEqual(defaultOpenAIBaseURL);- });- });-});--describe('LobeDeepSeekAnthropicAI', () => {- let instance: InstanceType<typeof LobeDeepSeekAnthropicAI>;-- const getLastRequestPayload = () => {- const calls = ((instance as any).client.messages.create as Mock).mock.calls;- return calls.at(-1)?.[0];- };-- beforeEach(() => {- instance = new LobeDeepSeekAnthropicAI({ apiKey: 'test' });-- vi.spyOn((instance as any).client.messages, 'create').mockResolvedValue(- new ReadableStream() as any,- );- });-- afterEach(() => {- vi.clearAllMocks();- });-- describe('init', () => {- it('should correctly initialize with an API key', () => {- const runtime = new LobeDeepSeekAnthropicAI({ apiKey: 'test_api_key' });-- expect(runtime).toBeInstanceOf(LobeDeepSeekAnthropicAI);- expect((runtime as any).baseURL).toEqual(anthropicBaseURL);- });- });-- 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' });- });-- 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: { budget_tokens: 0, type: 'disabled' },- });-- const payload = getLastRequestPayload();-- expect(payload.output_config).toBeUndefined();- expect(payload.thinking).toEqual({ type: 'disabled' });- });- });-- describe('handlePayload', () => {- it('should enable thinking by default for deepseek-v4-pro', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'deepseek-v4-pro',- temperature: 0,- });-- const payload = getLastRequestPayload();-- expect(payload.max_tokens).toBe(393_216);- expect(payload.thinking).toEqual({- budget_tokens: 1024,- type: 'enabled',- });- });-- it('should disable thinking when thinking.type is disabled', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'deepseek-v4-flash',- reasoning_effort: 'high',- thinking: { budget_tokens: 0, type: 'disabled' },- });-- const payload = getLastRequestPayload();-- expect(payload.thinking).toEqual({ type: 'disabled' });- expect(payload.output_config).toBeUndefined();- });-- it('should map reasoning_effort to output_config.effort when thinking is enabled', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'deepseek-v4-flash',- reasoning_effort: 'high',- thinking: { budget_tokens: 2048, type: 'enabled' },- });-- const payload = getLastRequestPayload();-- expect(payload.output_config).toEqual({ effort: 'high' });- expect(payload.thinking).toEqual({- budget_tokens: 2048,- type: 'enabled',- });- });-- it('should not add thinking params for deepseek-chat by default', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'deepseek-chat',- });-- const payload = getLastRequestPayload();-- expect(payload.thinking).toBeUndefined();- expect(payload.output_config).toBeUndefined();- });-- it('should preserve DeepSeek temperature scale for non-thinking Anthropic requests', async () => {- await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'deepseek-chat',- temperature: 1.4,- });-- const payload = getLastRequestPayload();-- expect(payload.temperature).toBe(1.4);- });-- it('should convert assistant reasoning to Anthropic thinking block', async () => {- await instance.chat({- messages: [- { content: 'Hello', role: 'user' },- {- content: 'Response',- reasoning: { content: 'My reasoning process' },- role: 'assistant',- } as any,- { content: 'Follow-up', role: 'user' },- ],- model: 'deepseek-v4-flash',- });-- const payload = getLastRequestPayload();- const assistantMessage = payload.messages.find(- (message: any) => message.role === 'assistant',- );-- expect(assistantMessage?.content).toEqual([- { thinking: 'My reasoning process', type: 'thinking' },- { text: 'Response', type: 'text' },- ]);- });-- it('should convert tool calls to Anthropic tool_use with a thinking placeholder', async () => {- await instance.chat({- messages: [- { content: 'Search weather', role: 'user' },- {- content: '',- role: 'assistant',- tool_calls: [- {- function: { arguments: '{"city":"Beijing"}', name: 'get_weather' },- id: 'call_1',- type: 'function',- },- ],- } as any,- {- content: '{"temp":20}',- role: 'tool',- tool_call_id: 'call_1',- } as any,- ],- model: 'deepseek-v4-flash',- });-- const payload = getLastRequestPayload();- const assistantMessage = payload.messages.find(- (message: any) => message.role === 'assistant',- );-- expect(assistantMessage?.content).toEqual(- expect.arrayContaining([- expect.objectContaining({ thinking: ' ', type: 'thinking' }),- expect.objectContaining({ name: 'get_weather', type: 'tool_use' }),- ]),- );- });- });-});--describe('LobeDeepSeekAI - custom features', () => {- describe('chatCompletion.handlePayload', () => {- it('should transform reasoning object to reasoning_content string', () => {- const payload = {- messages: [- { role: 'user', content: 'Hello' },- {- role: 'assistant',- content: 'Hi there',- reasoning: { content: 'Let me think...', duration: 1000 },- },- { role: 'user', content: 'How are you?' },- ],- model: 'deepseek-r1',- };-- const result = openAIParams.chatCompletion!.handlePayload!(payload as any);-- expect(result.messages).toEqual([- { role: 'user', content: 'Hello' },- {- role: 'assistant',- content: 'Hi there',- reasoning_content: 'Let me think...',- },- { role: 'user', content: 'How are you?' },- ]);- });-- it('should not modify messages without reasoning field', () => {- const payload = {- messages: [- { role: 'user', content: 'Hello' },- { role: 'assistant', content: 'Hi there' },- ],- model: 'deepseek-chat',- };-- const result = openAIParams.chatCompletion!.handlePayload!(payload as any);-- expect(result.messages).toEqual(payload.messages);- });-- it('should handle empty reasoning content', () => {- const payload = {- messages: [- {- role: 'assistant',- content: 'Response',- reasoning: { duration: 1000 },- },- ],- model: 'deepseek-r1',- };-- const result = openAIParams.chatCompletion!.handlePayload!(payload as any);-- expect(result.messages[0]).toEqual({- role: 'assistant',- content: 'Response',- });- });-- it('should set stream to true by default', () => {- const payload = {- messages: [{ role: 'user', content: 'Hello' }],- model: 'deepseek-chat',- };-- const result = openAIParams.chatCompletion!.handlePayload!(payload as any);-- expect(result.stream).toBe(true);- });-- it('should preserve existing stream value', () => {- const payload = {- messages: [{ role: 'user', content: 'Hello' }],- model: 'deepseek-chat',- stream: false,- };-- const result = openAIParams.chatCompletion!.handlePayload!(payload as any);-- expect(result.stream).toBe(false);- });-- it('should add empty reasoning_content for assistant messages in deepseek-reasoner', () => {- const payload = {- messages: [- { role: 'user', content: 'Search weather' },- {- role: 'assistant',- content: '',- tool_calls: [- {- id: 'call_1',- type: 'function',- function: {- name: 'search',- arguments: '{"q":"weather"}',- },- },- ],- },- { role: 'tool', content: '{"result":"sunny"}', tool_call_id: 'call_1' },- ],- model: 'deepseek-reasoner',- };-- const result = openAIParams.chatCompletion!.handlePayload!(payload as any);-- expect(result.messages).toEqual([- { role: 'user', content: 'Search weather' },- {- role: 'assistant',- content: '',- reasoning_content: '',- tool_calls: [- {- id: 'call_1',- type: 'function',- function: {- name: 'search',- arguments: '{"q":"weather"}',- },- },- ],- },- { role: 'tool', content: '{"result":"sunny"}', tool_call_id: 'call_1' },- ]);- });-- it('should preserve existing reasoning_content for deepseek-reasoner assistant messages', () => {- const payload = {- messages: [- {- role: 'assistant',- content: 'Previous answer',- reasoning_content: 'existing reasoning',- },- ],- model: 'deepseek-reasoner',- };-- const result = openAIParams.chatCompletion!.handlePayload!(payload as any);-- expect(result.messages).toEqual([- {- role: 'assistant',- content: 'Previous answer',- reasoning_content: 'existing reasoning',- },- ]);- });-- // DeepSeek V4 models default to thinking mode unless thinking.type === 'disabled'.- // In thinking mode the API rejects follow-up turns whose assistant messages omit- // reasoning_content when tool calls are involved — see index.ts for details.- describe('deepseek-v4 thinking mode reasoning_content enforcement', () => {- it('should force reasoning_content on v4-flash assistant messages by default', () => {- const payload = {- messages: [- { role: 'user', content: 'Search weather' },- {- role: 'assistant',- content: '',- tool_calls: [- {- id: 'call_1',- type: 'function',- function: { name: 'search', arguments: '{"q":"weather"}' },- },- ],- },- ],- model: 'deepseek-v4-flash',- };-- const result = openAIParams.chatCompletion!.handlePayload!(payload as any);-- expect(result.messages[1]).toEqual({- role: 'assistant',- content: '',- reasoning_content: '',- tool_calls: [- {- id: 'call_1',- type: 'function',- function: { name: 'search', arguments: '{"q":"weather"}' },- },- ],- });- });-- it('should force reasoning_content on v4-pro assistant messages by default', () => {- const payload = {- messages: [{ role: 'assistant', content: 'hi' }],- model: 'deepseek-v4-pro',- };-- const result = openAIParams.chatCompletion!.handlePayload!(payload as any);-- expect(result.messages[0]).toEqual({- role: 'assistant',- content: 'hi',- reasoning_content: '',- });- });-- it('should force reasoning_content when thinking.type is explicitly enabled', () => {- const payload = {- messages: [{ role: 'assistant', content: 'hi' }],- model: 'deepseek-v4-flash',- thinking: { type: 'enabled' },- };-- const result = openAIParams.chatCompletion!.handlePayload!(payload as any);-- expect(result.messages[0]).toEqual({- role: 'assistant',- content: 'hi',- reasoning_content: '',- });- });-- it('should NOT force reasoning_content when thinking.type is disabled', () => {- const payload = {- messages: [{ role: 'assistant', content: 'hi' }],- model: 'deepseek-v4-flash',- thinking: { type: 'disabled' },- };-- const result = openAIParams.chatCompletion!.handlePayload!(payload as any);-- expect(result.messages[0]).toEqual({- role: 'assistant',- content: 'hi',- });- });-- it('should remove reasoning_effort when thinking.type is disabled', () => {- const payload = {- messages: [{ role: 'user', content: 'hi' }],- model: 'deepseek-v4-flash',- reasoning_effort: 'high',- thinking: { type: 'disabled' },- };-- const result = openAIParams.chatCompletion!.handlePayload!(payload as any);-- expect(result).toEqual({- messages: [{ role: 'user', content: 'hi' }],- model: 'deepseek-v4-flash',- stream: true,- thinking: { type: 'disabled' },- });- });-- it('should preserve reasoning_effort when thinking is enabled', () => {- const payload = {- messages: [{ role: 'user', content: 'hi' }],- model: 'deepseek-v4-flash',- reasoning_effort: 'high',- thinking: { type: 'enabled' },- };-- const result = openAIParams.chatCompletion!.handlePayload!(payload as any);-- expect(result.reasoning_effort).toBe('high');- });-- it('should preserve existing reasoning_content on v4 assistant messages', () => {- const payload = {- messages: [- {- role: 'assistant',- content: 'answer',- reasoning_content: 'prior reasoning',- },- ],- model: 'deepseek-v4-flash',- };-- const result = openAIParams.chatCompletion!.handlePayload!(payload as any);-- expect(result.messages[0]).toEqual({- role: 'assistant',- content: 'answer',- reasoning_content: 'prior reasoning',- });- });-- it('should NOT force reasoning_content on non-v4 / non-reasoner models', () => {- const payload = {- messages: [{ role: 'assistant', content: 'hi' }],- model: 'deepseek-chat',- };-- const result = openAIParams.chatCompletion!.handlePayload!(payload as any);-- expect(result.messages[0]).toEqual({- role: 'assistant',- content: 'hi',- });- });- });-- it('should add empty reasoning_content for assistant messages in deepseek-v4-pro thinking mode', () => {- const payload = {- messages: [- { role: 'user', content: 'Call a tool' },- {- role: 'assistant',- content: '',- tool_calls: [- {- id: 'call_1',- type: 'function',- function: {- name: 'lookup',- arguments: '{"q":"docs"}',- },- },- ],- },- ],- model: 'deepseek-v4-pro',- };-- const result = openAIParams.chatCompletion!.handlePayload!(payload as any);-- expect(result.messages).toEqual([- { role: 'user', content: 'Call a tool' },- {- role: 'assistant',- content: '',- reasoning_content: '',- tool_calls: [- {- id: 'call_1',- type: 'function',- function: {- name: 'lookup',- arguments: '{"q":"docs"}',- },- },- ],- },- ]);- });-- it('should preserve only supported DeepSeek thinking config fields', () => {- const payload = {- messages: [{ role: 'user', content: 'Hello' }],- model: 'deepseek-v4-flash',- reasoning_effort: 'high' as const,- thinking: {- budget_tokens: 4096,- type: 'enabled' as const,- },- };-- const result = openAIParams.chatCompletion!.handlePayload!(payload as any);-- expect(result.reasoning_effort).toBe('high');- expect(result).toEqual(expect.objectContaining({ thinking: { type: 'enabled' } }));- expect(result).not.toEqual(- expect.objectContaining({ thinking: expect.objectContaining({ budget_tokens: 4096 }) }),- );- });-- it('should forward disabled thinking mode for deepseek-v4-pro', () => {- const payload = {- messages: [{ role: 'user', content: 'Hello' }],- model: 'deepseek-v4-pro',- thinking: { type: 'disabled' as const },- };-- const result = openAIParams.chatCompletion!.handlePayload!(payload as any);-- expect(result).toEqual(expect.objectContaining({ thinking: { type: 'disabled' } }));- });- });-- describe('Debug Configuration', () => {- it('should disable debug by default', () => {- delete process.env.DEBUG_DEEPSEEK_CHAT_COMPLETION;- const result = openAIParams.debug.chatCompletion();- expect(result).toBe(false);- });-- it('should enable debug when env is set', () => {- process.env.DEBUG_DEEPSEEK_CHAT_COMPLETION = '1';- const result = openAIParams.debug.chatCompletion();- expect(result).toBe(true);- delete process.env.DEBUG_DEEPSEEK_CHAT_COMPLETION;- });- });-- describe('generateObject configuration', () => {- it('should use tools calling for generateObject', () => {- 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', () => {- const fetchModels = params.models as (params: { client: unknown }) => Promise<ChatModelCard[]>;- const mockClient = {- models: {- list: vi.fn(),- },- };-- beforeEach(() => {- vi.clearAllMocks();- });-- it('should fetch and process models successfully', async () => {- mockClient.models.list.mockResolvedValue({- data: [{ id: 'deepseek-chat' }, { id: 'deepseek-coder' }, { id: 'deepseek-r1' }],- });-- const models = await fetchModels({ client: mockClient });-- expect(mockClient.models.list).toHaveBeenCalledTimes(1);- expect(models).toHaveLength(3);- expect(models[0].id).toBe('deepseek-chat');- expect(models[1].id).toBe('deepseek-coder');- expect(models[2].id).toBe('deepseek-r1');- });-- it('should handle single model', async () => {- mockClient.models.list.mockResolvedValue({- data: [{ id: 'deepseek-chat' }],- });-- const models = await fetchModels({ client: mockClient });-- expect(models).toHaveLength(1);- expect(models[0].id).toBe('deepseek-chat');- });-- it('should handle empty model list', async () => {- mockClient.models.list.mockResolvedValue({- data: [],- });-- const models = await fetchModels({ client: mockClient });-- expect(models).toEqual([]);- });-- it('should process models with MODEL_LIST_CONFIGS', async () => {- mockClient.models.list.mockResolvedValue({- data: [{ id: 'deepseek-chat' }],- });-- const models = await fetchModels({ client: mockClient });-- // The processModelList function should merge with known model list- expect(models[0]).toHaveProperty('id');- expect(models[0].id).toBe('deepseek-chat');- });-- it('should preserve model properties from API response', async () => {- mockClient.models.list.mockResolvedValue({- data: [- { id: 'deepseek-chat', extra_field: 'value' },- { id: 'deepseek-coder', another_field: 123 },- ],- });-- const models = await fetchModels({ client: mockClient });-- expect(models).toHaveLength(2);- expect(models[0].id).toBe('deepseek-chat');- expect(models[1].id).toBe('deepseek-coder');- });-- it('should handle models with different id patterns', async () => {- mockClient.models.list.mockResolvedValue({- data: [- { id: 'deepseek-chat' },- { id: 'deepseek-r1' },- { id: 'deepseek-reasoner' },- { id: 'deepseek-v3' },- ],- });-- const models = await fetchModels({ client: mockClient });-- expect(models).toHaveLength(4);- expect(models.every((m) => typeof m.id === 'string')).toBe(true);- });- });-});diff --git a/packages/model-runtime/src/providers/deepseek/index.ts b/packages/model-runtime/src/providers/deepseek/index.tsindex c4792148303..70b28785902 100644--- a/packages/model-runtime/src/providers/deepseek/index.ts+++ b/packages/model-runtime/src/providers/deepseek/index.ts@@ -1,27 +1,19 @@-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';import {- buildDefaultAnthropicPayload,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';import type { CreateRouterRuntimeOptions } from '../../core/RouterRuntime';import { createRouterRuntime } from '../../core/RouterRuntime';-import type { ChatStreamPayload, GenerateObjectOptions, GenerateObjectPayload } from '../../types';-import { getModelPropertyWithFallback } from '../../utils/getFallbackModelProperty';-import { MODEL_LIST_CONFIGS, processModelList } from '../../utils/modelParse';--export interface DeepSeekModelCard {- id: string;-}+import { buildDeepSeekAnthropicPayload, buildDeepSeekOpenAIPayload } from './chatPayload';+import {+ buildDeepSeekGenerateObjectPayload,+ createDeepSeekAnthropicGenerateObject,+} from './generateObject';+import { fetchDeepSeekModels } from './modelFetch';const DEFAULT_DEEPSEEK_BASE_URL = 'https://api.deepseek.com/v1';const DEFAULT_DEEPSEEK_ANTHROPIC_BASE_URL = 'https://api.deepseek.com/anthropic';@@ -29,24 +21,6 @@ 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) =>- content === '' || content === null || content === undefined;-const hasReasoningContent = (reasoning: any) => typeof reasoning?.content === 'string';--const buildThinkingBlock = (reasoning: any) =>- hasReasoningContent(reasoning)- ? { thinking: reasoning.content, type: 'thinking' as const }- : undefined;--const toContentArray = (content: any) =>- Array.isArray(content)- ? content- : [{ text: isEmptyContent(content) ? ' ' : content, type: 'text' as const }];const normalizeDeepSeekAnthropicBaseURL = (baseURL?: string | null) =>baseURL?.replace(DEEPSEEK_ANTHROPIC_MESSAGES_PATH_PATTERN, '');@@ -62,235 +36,6 @@ const resolveDeepSeekSDKType = (sdkType: unknown): DeepSeekSDKType | undefined =throw new Error(`Unsupported DeepSeek sdkType: ${String(sdkType)}`);};-const shouldEnableDeepSeekThinking = (payload: ChatStreamPayload) => {- if (payload.model === 'deepseek-reasoner') return true;- return isDeepSeekV4Model(payload.model) && payload.thinking?.type !== 'disabled';-};--const resolveDeepSeekThinking = (payload: ChatStreamPayload): ChatStreamPayload['thinking'] => {- if (payload.model === 'deepseek-reasoner') {- return {- budget_tokens: payload.thinking?.budget_tokens ?? 1024,- type: 'enabled',- };- }-- if (isDeepSeekV4Model(payload.model)) {- if (payload.thinking?.type === 'disabled') {- return {- budget_tokens: 0,- type: 'disabled',- };- }-- return {- budget_tokens: payload.thinking?.budget_tokens ?? 1024,- type: 'enabled',- };- }-- if (payload.thinking?.type === 'enabled' && payload.thinking.budget_tokens === undefined) {- return {- budget_tokens: 1024,- type: 'enabled',- };- }-- return payload.thinking;-};--/**- * DeepSeek's Anthropic-compatible API uses Anthropic content blocks for assistant- * reasoning history. For V4 thinking mode we keep an explicit placeholder block- * so follow-up tool-call turns preserve the same reasoning-history guarantee as- * the OpenAI-compatible API.- *- * @see https://api-docs.deepseek.com/guides/anthropic_api- * @see https://api-docs.deepseek.com/guides/thinking_mode#tool-calls- */-const normalizeMessagesForAnthropic = (- messages: ChatStreamPayload['messages'],- forceThinking = false,-) =>- messages.map((message: any) => {- if (message.role !== 'assistant') return message;-- const { reasoning, ...rest } = message;- const thinkingBlock = buildThinkingBlock(reasoning);- const effectiveThinkingBlock =- thinkingBlock || (forceThinking ? { thinking: ' ', type: 'thinking' as const } : undefined);-- if (!effectiveThinkingBlock) return rest;-- return {- ...rest,- content: [effectiveThinkingBlock, ...toContentArray(message.content)],- };- });--const buildDeepSeekAnthropicPayload = async (- payload: ChatStreamPayload,-): Promise<Anthropic.MessageCreateParams> => {- const resolvedThinking = resolveDeepSeekThinking(payload);- const isThinkingDisabled = resolvedThinking?.type === 'disabled';- const resolvedMaxTokens =- payload.max_tokens ??- (await getModelPropertyWithFallback<number | undefined>(- payload.model,- 'maxOutput',- ModelProvider.DeepSeek,- )) ??- (resolvedThinking?.type === 'enabled' ? 32_000 : 64_000);-- const basePayload = await buildDefaultAnthropicPayload({- ...payload,- effort: !isThinkingDisabled ? ((payload.effort ?? payload.reasoning_effort) as any) : undefined,- max_tokens: resolvedMaxTokens,- messages: normalizeMessagesForAnthropic(- payload.messages,- shouldEnableDeepSeekThinking(payload),- ),- thinking: isThinkingDisabled ? undefined : resolvedThinking,- });-- return {- ...basePayload,- ...(basePayload.temperature !== undefined && payload.temperature !== undefined- ? { temperature: payload.temperature }- : {}),- ...(isThinkingDisabled ? { thinking: { type: 'disabled' } } : {}),- } as Anthropic.MessageCreateParams;-};--const buildDeepSeekOpenAIPayload = (- payload: ChatStreamPayload,-): OpenAI.ChatCompletionCreateParamsStreaming => {- // deepseek-v4-* defaults to thinking=enabled unless the caller explicitly- // sets thinking.type === 'disabled'. In thinking mode the API rejects- // (HTTP 400) follow-up turns that omit reasoning_content on assistant- // messages with tool calls — see- // https://api-docs.deepseek.com/guides/thinking_mode#tool-calls- const isV4Model = typeof payload.model === 'string' && isDeepSeekV4Model(payload.model);- const thinkingExplicitlyDisabled = payload.thinking?.type === 'disabled';- const shouldForceAssistantReasoningContent =- payload.model === 'deepseek-reasoner' || (isV4Model && !thinkingExplicitlyDisabled);-- // Transform reasoning object to reasoning_content string for multi-turn conversations- const messages = payload.messages.map((message: any) => {- const { reasoning, ...rest } = message;-- const reasoningContent =- typeof rest.reasoning_content === 'string'- ? rest.reasoning_content- : typeof reasoning?.content === 'string'- ? reasoning.content- : undefined;-- // DeepSeek thinking mode with tool calls requires assistant history- // messages to carry reasoning_content, or the API returns a 400.- if (message.role === 'assistant' && shouldForceAssistantReasoningContent) {- return {- ...rest,- reasoning_content: reasoningContent ?? '',- };- }-- if (reasoningContent !== undefined) {- return {- ...rest,- reasoning_content: reasoningContent,- };- }-- return rest;- });-- // DeepSeek rejects `reasoning_effort` when thinking is explicitly disabled.- const { reasoning_effort, thinking, ...restPayload } = payload;-- return {- ...restPayload,- messages,- ...(!thinkingExplicitlyDisabled && reasoning_effort && { reasoning_effort }),- ...(thinking?.type === 'enabled' || thinking?.type === 'disabled'- ? { thinking: { type: thinking.type } }- : {}),- stream: payload.stream ?? true,- } 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);- 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, {- 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,-}: {- client: OpenAI | unknown;-}): Promise<ChatModelCard[]> => {- const modelClient = client as {- models?: { list?: () => Promise<{ data?: DeepSeekModelCard[] }> };- };-- if (modelClient.models?.list) {- const modelsPage = await modelClient.models.list();- const modelList = modelsPage.data || [];-- return processModelList(modelList, MODEL_LIST_CONFIGS.deepseek, 'deepseek');- }-- const { deepseek } = await import('model-bank');-- return processModelList(deepseek, MODEL_LIST_CONFIGS.deepseek, 'deepseek');-};-export const anthropicParams = createAnthropicCompatibleParams({baseURL: DEFAULT_DEEPSEEK_ANTHROPIC_BASE_URL,chatCompletion: {diff --git a/packages/model-runtime/src/providers/deepseek/modelFetch.ts b/packages/model-runtime/src/providers/deepseek/modelFetch.tsnew file mode 100644index 00000000000..e14a4f4e972--- /dev/null+++ b/packages/model-runtime/src/providers/deepseek/modelFetch.ts@@ -0,0 +1,29 @@+import type { ChatModelCard } from '@lobechat/types';+import type OpenAI from 'openai';++import { MODEL_LIST_CONFIGS, processModelList } from '../../utils/modelParse';++interface DeepSeekModelCard {+ id: string;+}++export const fetchDeepSeekModels = async ({+ client,+}: {+ client: OpenAI | unknown;+}): Promise<ChatModelCard[]> => {+ const modelClient = client as {+ models?: { list?: () => Promise<{ data?: DeepSeekModelCard[] }> };+ };++ if (modelClient.models?.list) {+ const modelsPage = await modelClient.models.list();+ const modelList = modelsPage.data || [];++ return processModelList(modelList, MODEL_LIST_CONFIGS.deepseek, 'deepseek');+ }++ const { deepseek } = await import('model-bank');++ return processModelList(deepseek, MODEL_LIST_CONFIGS.deepseek, 'deepseek');+};diff --git a/packages/model-runtime/src/providers/deepseek/sanitizePayload.ts b/packages/model-runtime/src/providers/deepseek/sanitizePayload.tsnew file mode 100644index 00000000000..7f5428157d5--- /dev/null+++ b/packages/model-runtime/src/providers/deepseek/sanitizePayload.ts@@ -0,0 +1,184 @@+const HIGH_SURROGATE_START = 0xd8_00;+const HIGH_SURROGATE_END = 0xdb_ff;+const LOW_SURROGATE_START = 0xdc_00;+const LOW_SURROGATE_END = 0xdf_ff;++const isHighSurrogate = (codeUnit: number) =>+ codeUnit >= HIGH_SURROGATE_START && codeUnit <= HIGH_SURROGATE_END;++const isLowSurrogate = (codeUnit: number) =>+ codeUnit >= LOW_SURROGATE_START && codeUnit <= LOW_SURROGATE_END;++const sanitizeDeepSeekJsonString = (value: string) => {+ let sanitized = '';+ let index = 0;++ while (index < value.length) {+ const codeUnit = value.charCodeAt(index);+ const nextCodeUnit = value.charCodeAt(index + 1);++ if (isHighSurrogate(codeUnit)) {+ if (isLowSurrogate(nextCodeUnit)) {+ sanitized += value[index] + value[index + 1];+ index += 2;+ continue;+ }++ index += 1;+ continue;+ }++ if (isLowSurrogate(codeUnit)) {+ index += 1;+ continue;+ }++ sanitized += value[index];+ index += 1;+ }++ return sanitized;+};++const isPlainRecord = (value: unknown): value is Record<string, unknown> => {+ if (!value || typeof value !== 'object') return false;++ const prototype = Object.getPrototypeOf(value);+ return prototype === Object.prototype || prototype === null;+};++const setIfChanged = (+ target: Record<string, unknown>,+ source: Record<string, unknown>,+ key: string,+ value: unknown,+) => {+ if (value === source[key]) return target;++ return {+ ...target,+ [key]: value,+ };+};++const sanitizeToolUseInput = (value: unknown): unknown => {+ if (typeof value === 'string') return sanitizeDeepSeekJsonString(value);+ if (Array.isArray(value)) return value.map((item) => sanitizeToolUseInput(item));+ if (!isPlainRecord(value)) return value;++ let sanitized = value;++ for (const [key, item] of Object.entries(value)) {+ sanitized = setIfChanged(sanitized, value, key, sanitizeToolUseInput(item));+ }++ return sanitized;+};++const sanitizeContentSurface = (value: unknown): unknown => {+ if (typeof value === 'string') return sanitizeDeepSeekJsonString(value);+ if (Array.isArray(value)) return value.map((item) => sanitizeContentSurface(item));+ if (!isPlainRecord(value)) return value;++ let sanitized = value;++ if (typeof value.text === 'string') {+ sanitized = setIfChanged(sanitized, value, 'text', sanitizeDeepSeekJsonString(value.text));+ }++ if (typeof value.thinking === 'string') {+ sanitized = setIfChanged(+ sanitized,+ value,+ 'thinking',+ sanitizeDeepSeekJsonString(value.thinking),+ );+ }++ if ('content' in value) {+ sanitized = setIfChanged(sanitized, value, 'content', sanitizeContentSurface(value.content));+ }++ if (value.type === 'tool_use' && 'input' in value) {+ sanitized = setIfChanged(sanitized, value, 'input', sanitizeToolUseInput(value.input));+ }++ return sanitized;+};++const sanitizeToolCalls = (toolCalls: unknown) => {+ if (!Array.isArray(toolCalls)) return toolCalls;++ return toolCalls.map((toolCall) => {+ if (!isPlainRecord(toolCall) || !isPlainRecord(toolCall.function)) return toolCall;++ const sanitizedArguments =+ typeof toolCall.function.arguments === 'string'+ ? sanitizeDeepSeekJsonString(toolCall.function.arguments)+ : toolCall.function.arguments;+ const sanitizedFunction = setIfChanged(+ toolCall.function,+ toolCall.function,+ 'arguments',+ sanitizedArguments,+ );++ return setIfChanged(toolCall, toolCall, 'function', sanitizedFunction);+ });+};++const sanitizeMessage = (message: unknown) => {+ if (!isPlainRecord(message)) return message;++ let sanitized = message;++ if ('content' in message) {+ sanitized = setIfChanged(+ sanitized,+ message,+ 'content',+ sanitizeContentSurface(message.content),+ );+ }++ if (typeof message.reasoning_content === 'string') {+ sanitized = setIfChanged(+ sanitized,+ message,+ 'reasoning_content',+ sanitizeDeepSeekJsonString(message.reasoning_content),+ );+ }++ if ('tool_calls' in message) {+ sanitized = setIfChanged(+ sanitized,+ message,+ 'tool_calls',+ sanitizeToolCalls(message.tool_calls),+ );+ }++ return sanitized;+};++/**+ * DeepSeek's official Anthropic endpoint rejects lone UTF-16 surrogate escapes+ * at the JSON parser layer. Keep this scoped to request text surfaces instead+ * of walking the whole payload, so schema/options objects are not rewritten.+ */+export const sanitizeDeepSeekJsonPayload = <T>(value: T): T => {+ if (!isPlainRecord(value)) return value;++ let sanitized: Record<string, unknown> = value;++ if (Array.isArray(value.messages)) {+ sanitized = setIfChanged(sanitized, value, 'messages', value.messages.map(sanitizeMessage));+ }++ if ('system' in value) {+ sanitized = setIfChanged(sanitized, value, 'system', sanitizeContentSurface(value.system));+ }++ return sanitized as T;+};diff --git a/src/server/utils/__tests__/truncateToolResult.test.ts b/src/server/utils/__tests__/truncateToolResult.test.tsnew file mode 100644index 00000000000..785f7530621--- /dev/null+++ b/src/server/utils/__tests__/truncateToolResult.test.ts@@ -0,0 +1,59 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import { truncateToolResult, truncateToolResultWithState } from '../truncateToolResult';++const validEmoji = '\uD83D\uDC1B';+const familyEmoji = '\uD83D\uDC68\u200D\uD83D\uDC69\u200D\uD83D\uDC67\u200D\uD83D\uDC66';++const getTruncatedPortion = (value: string) => value.split('\n\n[Content truncated')[0];+const endsWithHighSurrogate = (value: string) => {+ const lastCharCode = value.charCodeAt(value.length - 1);++ return lastCharCode >= 0xd8_00 && lastCharCode <= 0xdb_ff;+};++describe('truncateToolResult', () => {+ it('should not split an emoji surrogate pair at the truncation boundary', () => {+ const content = `prefix ${'a'.repeat(10)}${validEmoji} suffix`;+ const limit = 'prefix '.length + 10 + 1;+ const result = truncateToolResult(content, limit);+ const truncatedPortion = getTruncatedPortion(result);++ expect(result).toContain('[Content truncated:');+ expect(truncatedPortion).toBe(`prefix ${'a'.repeat(10)}`);+ expect(endsWithHighSurrogate(truncatedPortion)).toBe(false);+ expect(JSON.stringify({ content: result })).not.toContain('\\ud83d');+ });++ it('should keep a full emoji when the complete surrogate pair fits', () => {+ const content = `prefix ${'a'.repeat(10)}${validEmoji} suffix`;+ const limit = 'prefix '.length + 10 + validEmoji.length;+ const result = truncateToolResult(content, limit);++ expect(result).toContain(validEmoji);+ expect(result).toContain('[Content truncated:');+ });++ it('should never leave a lone high surrogate inside a ZWJ-composed emoji at any cutoff', () => {+ const content = `ab${familyEmoji}cd`;++ for (let cutoff = 1; cutoff < content.length; cutoff += 1) {+ const result = truncateToolResult(content, cutoff);+ const truncatedPortion = getTruncatedPortion(result);++ expect(endsWithHighSurrogate(truncatedPortion)).toBe(false);+ expect(() => JSON.parse(JSON.stringify(result))).not.toThrow();+ }+ });++ it('should preserve state while truncating content safely', () => {+ const result = truncateToolResultWithState(+ { content: `value ${'x'.repeat(4)}${validEmoji} tail`, state: { ok: true } },+ 'value '.length + 4 + 1,+ );++ expect(result.state).toEqual({ ok: true });+ expect(endsWithHighSurrogate(getTruncatedPortion(result.content))).toBe(false);+ });+});diff --git a/src/server/utils/truncateToolResult.ts b/src/server/utils/truncateToolResult.tsindex 7cbc3122435..2703a8ad706 100644--- a/src/server/utils/truncateToolResult.ts+++ b/src/server/utils/truncateToolResult.ts@@ -24,8 +24,17 @@ export function truncateToolResult(content: string, maxLength?: number): stringreturn content;}- const truncated = content.slice(0, limit);- const remainingChars = content.length - limit;+ // Avoid splitting a UTF-16 surrogate pair: if the cutoff lands right after a+ // high surrogate, step back one code unit. Otherwise JSON.stringify emits a+ // lone `\uD83D`-style escape, which DeepSeek rejects at the JSON parser layer.+ let cutoff = limit;+ const lastCharCode = content.charCodeAt(cutoff - 1);+ if (lastCharCode >= 0xd8_00 && lastCharCode <= 0xdb_ff) {+ cutoff -= 1;+ }++ const truncated = content.slice(0, cutoff);+ const remainingChars = content.length - cutoff;// Add truncation noticeconst notice = `\n\n[Content truncated: ${remainingChars.toLocaleString()} characters omitted to prevent context overflow. Original length: ${content.length.toLocaleString()} characters]`;