Skip to content

🤯 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.

✨ feat: support DeepSeek Anthropic runtime (#14312)

YuTengjingb0b6e67d5fb7
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
index 63872e4dbad..905c654f215 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
@@ -212,6 +212,45 @@ describe('createRouterRuntime', () => {
expect(result).toEqual(['model-1', 'model-2']);
expect(mockModels).toHaveBeenCalled();
});
+
+ it('should use the baseURL-matched runtime client for functional model discovery', async () => {
+ class OpenAIRuntime implements LobeRuntimeAI {
+ client = { provider: 'openai-compatible' };
+ models = vi.fn();
+ }
+
+ class AnthropicRuntime implements LobeRuntimeAI {
+ client = { provider: 'anthropic-compatible' };
+ models = vi.fn();
+ }
+
+ const models = vi.fn().mockResolvedValue([]);
+ const Runtime = createRouterRuntime({
+ id: 'test-runtime',
+ models,
+ routers: [
+ {
+ apiType: 'openai',
+ baseURLPattern: /\/v1$/,
+ options: {},
+ runtime: OpenAIRuntime as any,
+ },
+ {
+ apiType: 'anthropic',
+ baseURLPattern: /\/anthropic$/,
+ options: {},
+ runtime: AnthropicRuntime as any,
+ },
+ ],
+ });
+
+ const runtime = new Runtime({ baseURL: 'https://api.example.com/v1' });
+ await runtime.models();
+
+ expect(models).toHaveBeenCalledWith({
+ client: { provider: 'openai-compatible' },
+ });
+ });
});
describe('embeddings method', () => {
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
index 0150494771d..3b1faa56043 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
@@ -461,32 +461,23 @@ export const createRouterRuntime = ({
async models() {
const resolvedRouters = await this.resolveRouters();
- const runtimes = await Promise.all(
- resolvedRouters.map(async (router) => {
- const routerOptions = this.normalizeRouterOptions(router);
- const { id: resolvedApiType, runtime } = await this.createRuntimeFromOption(
- router,
- routerOptions[0],
- );
-
- return {
- id: resolvedApiType,
- models: router.models,
- runtime,
- };
- }),
- );
-
- if (modelsOption && typeof modelsOption === 'function') {
- // If it's a functional configuration, use the last runtime's client to call the function
- const lastRuntime = runtimes.at(-1)?.runtime;
- if (lastRuntime && 'client' in lastRuntime) {
- const modelList = await modelsOption({ client: (lastRuntime as any).client });
- return await postProcessModelList(modelList);
- }
+ const matchedRouter = this._options.baseURL
+ ? (resolvedRouters.find((router) => router.baseURLPattern?.test(this._options.baseURL!)) ??
+ resolvedRouters.at(-1)!)
+ : resolvedRouters.at(-1)!;
+ const routerOptions = this.normalizeRouterOptions(matchedRouter);
+ const { runtime } = await this.createRuntimeFromOption(matchedRouter, routerOptions[0]);
+
+ if (
+ modelsOption &&
+ typeof modelsOption === 'function' && // Use the same baseURL-matched runtime as chat routing for provider model discovery.
+ 'client' in runtime
+ ) {
+ const modelList = await modelsOption({ client: (runtime as any).client });
+ return await postProcessModelList(modelList);
}
- return runtimes.at(-1)?.runtime.models?.();
+ return runtime.models?.();
}
/**
diff --git a/packages/model-runtime/src/providers/deepseek/index.test.ts b/packages/model-runtime/src/providers/deepseek/index.test.ts
index 267e2db40b3..4d35d7a8ca1 100644
--- a/packages/model-runtime/src/providers/deepseek/index.test.ts
+++ b/packages/model-runtime/src/providers/deepseek/index.test.ts
@@ -1,22 +1,243 @@
// @vitest-environment node
-import { ModelProvider } from 'model-bank';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { testProvider } from '../../providerTestUtils';
-import { LobeDeepSeekAI, params } from './index';
-
-const provider = ModelProvider.DeepSeek;
-const defaultBaseURL = 'https://api.deepseek.com/v1';
-
-testProvider({
- Runtime: LobeDeepSeekAI,
- provider,
- defaultBaseURL,
- chatDebugEnv: 'DEBUG_DEEPSEEK_CHAT_COMPLETION',
- chatModel: 'deepseek-r1',
- test: {
- skipAPICall: true,
- },
+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 defaultOpenAIBaseURL = 'https://api.deepseek.com/v1';
+const anthropicBaseURL = 'https://api.deepseek.com/anthropic';
+
+vi.spyOn(console, 'error').mockImplementation(() => {});
+
+describe('LobeDeepSeekAI', () => {
+ const resolveRouter = async (baseURL?: string) => {
+ const runtime = new LobeDeepSeekAI({
+ apiKey: 'test',
+ ...(baseURL ? { baseURL } : {}),
+ });
+
+ return (runtime as any).resolveMatchedRouter('deepseek-v4-pro');
+ };
+
+ 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');
+ });
+ });
+});
+
+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('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(384_000);
+ 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', () => {
@@ -35,7 +256,7 @@ describe('LobeDeepSeekAI - custom features', () => {
model: 'deepseek-r1',
};
- const result = params.chatCompletion!.handlePayload!(payload as any);
+ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);
expect(result.messages).toEqual([
{ role: 'user', content: 'Hello' },
@@ -57,7 +278,7 @@ describe('LobeDeepSeekAI - custom features', () => {
model: 'deepseek-chat',
};
- const result = params.chatCompletion!.handlePayload!(payload as any);
+ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);
expect(result.messages).toEqual(payload.messages);
});
@@ -74,7 +295,7 @@ describe('LobeDeepSeekAI - custom features', () => {
model: 'deepseek-r1',
};
- const result = params.chatCompletion!.handlePayload!(payload as any);
+ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);
expect(result.messages[0]).toEqual({
role: 'assistant',
@@ -88,7 +309,7 @@ describe('LobeDeepSeekAI - custom features', () => {
model: 'deepseek-chat',
};
- const result = params.chatCompletion!.handlePayload!(payload as any);
+ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);
expect(result.stream).toBe(true);
});
@@ -100,7 +321,7 @@ describe('LobeDeepSeekAI - custom features', () => {
stream: false,
};
- const result = params.chatCompletion!.handlePayload!(payload as any);
+ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);
expect(result.stream).toBe(false);
});
@@ -128,7 +349,7 @@ describe('LobeDeepSeekAI - custom features', () => {
model: 'deepseek-reasoner',
};
- const result = params.chatCompletion!.handlePayload!(payload as any);
+ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);
expect(result.messages).toEqual([
{ role: 'user', content: 'Search weather' },
@@ -163,7 +384,7 @@ describe('LobeDeepSeekAI - custom features', () => {
model: 'deepseek-reasoner',
};
- const result = params.chatCompletion!.handlePayload!(payload as any);
+ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);
expect(result.messages).toEqual([
{
@@ -197,7 +418,7 @@ describe('LobeDeepSeekAI - custom features', () => {
model: 'deepseek-v4-flash',
};
- const result = params.chatCompletion!.handlePayload!(payload as any);
+ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);
expect(result.messages[1]).toEqual({
role: 'assistant',
@@ -219,7 +440,7 @@ describe('LobeDeepSeekAI - custom features', () => {
model: 'deepseek-v4-pro',
};
- const result = params.chatCompletion!.handlePayload!(payload as any);
+ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);
expect(result.messages[0]).toEqual({
role: 'assistant',
@@ -235,7 +456,7 @@ describe('LobeDeepSeekAI - custom features', () => {
thinking: { type: 'enabled' },
};
- const result = params.chatCompletion!.handlePayload!(payload as any);
+ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);
expect(result.messages[0]).toEqual({
role: 'assistant',
@@ -251,7 +472,7 @@ describe('LobeDeepSeekAI - custom features', () => {
thinking: { type: 'disabled' },
};
- const result = params.chatCompletion!.handlePayload!(payload as any);
+ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);
expect(result.messages[0]).toEqual({
role: 'assistant',
@@ -267,7 +488,7 @@ describe('LobeDeepSeekAI - custom features', () => {
thinking: { type: 'disabled' },
};
- const result = params.chatCompletion!.handlePayload!(payload as any);
+ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);
expect(result).toEqual({
messages: [{ role: 'user', content: 'hi' }],
@@ -285,7 +506,7 @@ describe('LobeDeepSeekAI - custom features', () => {
thinking: { type: 'enabled' },
};
- const result = params.chatCompletion!.handlePayload!(payload as any);
+ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);
expect(result.reasoning_effort).toBe('high');
});
@@ -302,7 +523,7 @@ describe('LobeDeepSeekAI - custom features', () => {
model: 'deepseek-v4-flash',
};
- const result = params.chatCompletion!.handlePayload!(payload as any);
+ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);
expect(result.messages[0]).toEqual({
role: 'assistant',
@@ -317,7 +538,7 @@ describe('LobeDeepSeekAI - custom features', () => {
model: 'deepseek-chat',
};
- const result = params.chatCompletion!.handlePayload!(payload as any);
+ const result = openAIParams.chatCompletion!.handlePayload!(payload as any);
expect(result.messages[0]).toEqual({
role: 'assistant',
@@ -330,13 +551,13 @@ describe('LobeDeepSeekAI - custom features', () => {
describe('Debug Configuration', () => {
it('should disable debug by default', () => {
delete process.env.DEBUG_DEEPSEEK_CHAT_COMPLETION;
- const result = params.debug.chatCompletion();
+ 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 = params.debug.chatCompletion();
+ const result = openAIParams.debug.chatCompletion();
expect(result).toBe(true);
delete process.env.DEBUG_DEEPSEEK_CHAT_COMPLETION;
});
@@ -344,12 +565,13 @@ describe('LobeDeepSeekAI - custom features', () => {
describe('generateObject configuration', () => {
it('should use tools calling for generateObject', () => {
- expect(params.generateObject).toBeDefined();
- expect(params.generateObject?.useToolsCalling).toBe(true);
+ expect(openAIParams.generateObject).toBeDefined();
+ expect(openAIParams.generateObject?.useToolsCalling).toBe(true);
});
});
describe('models', () => {
+ const fetchModels = params.models as (params: { client: unknown }) => Promise<ChatModelCard[]>;
const mockClient = {
models: {
list: vi.fn(),
@@ -365,7 +587,7 @@ describe('LobeDeepSeekAI - custom features', () => {
data: [{ id: 'deepseek-chat' }, { id: 'deepseek-coder' }, { id: 'deepseek-r1' }],
});
- const models = await params.models({ client: mockClient as any });
+ const models = await fetchModels({ client: mockClient });
expect(mockClient.models.list).toHaveBeenCalledTimes(1);
expect(models).toHaveLength(3);
@@ -379,7 +601,7 @@ describe('LobeDeepSeekAI - custom features', () => {
data: [{ id: 'deepseek-chat' }],
});
- const models = await params.models({ client: mockClient as any });
+ const models = await fetchModels({ client: mockClient });
expect(models).toHaveLength(1);
expect(models[0].id).toBe('deepseek-chat');
@@ -390,7 +612,7 @@ describe('LobeDeepSeekAI - custom features', () => {
data: [],
});
- const models = await params.models({ client: mockClient as any });
+ const models = await fetchModels({ client: mockClient });
expect(models).toEqual([]);
});
@@ -400,7 +622,7 @@ describe('LobeDeepSeekAI - custom features', () => {
data: [{ id: 'deepseek-chat' }],
});
- const models = await params.models({ client: mockClient as any });
+ const models = await fetchModels({ client: mockClient });
// The processModelList function should merge with known model list
expect(models[0]).toHaveProperty('id');
@@ -415,7 +637,7 @@ describe('LobeDeepSeekAI - custom features', () => {
],
});
- const models = await params.models({ client: mockClient as any });
+ const models = await fetchModels({ client: mockClient });
expect(models).toHaveLength(2);
expect(models[0].id).toBe('deepseek-chat');
@@ -432,7 +654,7 @@ describe('LobeDeepSeekAI - custom features', () => {
],
});
- const models = await params.models({ client: mockClient as any });
+ 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.ts
index fbecf4d85f4..230eb6a7650 100644
--- a/packages/model-runtime/src/providers/deepseek/index.ts
+++ b/packages/model-runtime/src/providers/deepseek/index.ts
@@ -1,68 +1,236 @@
+import type Anthropic from '@anthropic-ai/sdk';
+import type { ChatModelCard } from '@lobechat/types';
import { ModelProvider } from 'model-bank';
+import type OpenAI from 'openai';
+import {
+ buildDefaultAnthropicPayload,
+ createAnthropicCompatibleParams,
+ createAnthropicCompatibleRuntime,
+} from '../../core/anthropicCompatibleFactory';
import type { OpenAICompatibleFactoryOptions } from '../../core/openaiCompatibleFactory';
import { createOpenAICompatibleRuntime } from '../../core/openaiCompatibleFactory';
+import type { CreateRouterRuntimeOptions } from '../../core/RouterRuntime';
+import { createRouterRuntime } from '../../core/RouterRuntime';
+import type { ChatStreamPayload } from '../../types';
+import { getModelPropertyWithFallback } from '../../utils/getFallbackModelProperty';
import { MODEL_LIST_CONFIGS, processModelList } from '../../utils/modelParse';
export interface DeepSeekModelCard {
id: string;
}
-export const params = {
- baseURL: 'https://api.deepseek.com/v1',
- chatCompletion: {
- handlePayload: (payload) => {
- // 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' && payload.model.startsWith('deepseek-v4');
- 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, ...restPayload } = payload;
+const DEFAULT_DEEPSEEK_BASE_URL = 'https://api.deepseek.com/v1';
+const DEFAULT_DEEPSEEK_ANTHROPIC_BASE_URL = 'https://api.deepseek.com/anthropic';
+
+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 {
- ...restPayload,
- messages,
- ...(!thinkingExplicitlyDisabled && reasoning_effort && { reasoning_effort }),
- stream: payload.stream ?? true,
- } as any;
- },
+ 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, ...restPayload } = payload;
+
+ return {
+ ...restPayload,
+ messages,
+ ...(!thinkingExplicitlyDisabled && reasoning_effort && { reasoning_effort }),
+ stream: payload.stream ?? true,
+ } as OpenAI.ChatCompletionCreateParamsStreaming;
+};
+
+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: {
+ handlePayload: buildDeepSeekAnthropicPayload,
+ },
+ customClient: {},
+ debug: {
+ chatCompletion: () => process.env.DEBUG_DEEPSEEK_CHAT_COMPLETION === '1',
+ },
+ provider: ModelProvider.DeepSeek,
+});
+
+export const LobeDeepSeekAnthropicAI = createAnthropicCompatibleRuntime(anthropicParams);
+
+export const openAIParams = {
+ baseURL: DEFAULT_DEEPSEEK_BASE_URL,
+ chatCompletion: {
+ handlePayload: buildDeepSeekOpenAIPayload,
},
debug: {
chatCompletion: () => process.env.DEBUG_DEEPSEEK_CHAT_COMPLETION === '1',
@@ -72,13 +240,31 @@ export const params = {
generateObject: {
useToolsCalling: true,
},
- models: async ({ client }) => {
- const modelsPage = (await client.models.list()) as any;
- const modelList: DeepSeekModelCard[] = modelsPage.data;
-
- return processModelList(modelList, MODEL_LIST_CONFIGS.deepseek, 'deepseek');
- },
+ models: fetchDeepSeekModels,
provider: ModelProvider.DeepSeek,
} satisfies OpenAICompatibleFactoryOptions;
-export const LobeDeepSeekAI = createOpenAICompatibleRuntime(params);
+export const LobeDeepSeekOpenAI = createOpenAICompatibleRuntime(openAIParams);
+
+export const params: CreateRouterRuntimeOptions = {
+ id: ModelProvider.DeepSeek,
+ models: fetchDeepSeekModels,
+ routers: [
+ {
+ apiType: 'deepseek',
+ baseURLPattern: /^(?!.*\/anthropic\/?$).+$/,
+ id: 'openai-compatible',
+ options: { remark: 'openai-compatible' },
+ runtime: LobeDeepSeekOpenAI,
+ },
+ {
+ apiType: 'deepseek',
+ baseURLPattern: /\/anthropic\/?$/,
+ id: 'anthropic-compatible',
+ options: { remark: 'anthropic-compatible' },
+ runtime: LobeDeepSeekAnthropicAI,
+ },
+ ],
+};
+
+export const LobeDeepSeekAI = createRouterRuntime(params);