@hopemyl619/deepseek 0.1.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,66 +1,79 @@
1
- // DeepSeek Provider 工厂
1
+ // DeepSeek Provider - 完全兼容官方 @ai-sdk/deepseek 接口
2
2
 
3
- import { loadApiKey, withoutTrailingSlash } from '@ai-sdk/provider-utils';
4
- import { DeepSeekChatLanguageModel } from './deepseek-chat-language-model';
3
+ import { loadApiKey } from '@ai-sdk/provider-utils';
5
4
  import type { DeepSeekProviderSettings, DeepSeekChatSettings } from './types';
5
+ import { DeepSeekChatLanguageModel } from './deepseek-chat-language-model';
6
6
 
7
- export async function createProvider(options: DeepSeekProviderSettings = {}) {
8
- const baseURL = withoutTrailingSlash(
9
- options.baseURL || 'https://api.deepseek.com/v1'
10
- ) ?? 'https://api.deepseek.com/v1';
7
+ // Provider 接口定义(兼容官方)
8
+ export interface DeepSeekProvider {
9
+ /**
10
+ * 创建 DeepSeek 模型用于文本生成
11
+ */
12
+ (modelId: string, settings?: DeepSeekChatSettings): DeepSeekChatLanguageModel;
11
13
 
12
- const getHeaders = (): Record<string, string> => {
13
- const apiKeyResult = loadApiKey({
14
- apiKey: options.apiKey,
15
- environmentVariableName: 'DEEPSEEK_API_KEY',
16
- description: 'DeepSeek API key',
17
- });
18
- // loadApiKey 可能返回 undefined,使用空字符串作为默认值并确保类型为 string
19
- const apiKey = (apiKeyResult ?? '') as string;
20
- const authHeader: string = 'Bearer ' + apiKey;
21
- const result: Record<string, string> = {
22
- Authorization: authHeader,
23
- };
24
- if (options.headers) {
25
- for (const [key, value] of Object.entries(options.headers)) {
26
- if (typeof value === 'string') {
27
- result[key] = value;
28
- }
29
- }
30
- }
31
- return result;
32
- };
14
+ /**
15
+ * 创建 DeepSeek 模型用于文本生成
16
+ */
17
+ languageModel(modelId: string, settings?: DeepSeekChatSettings): DeepSeekChatLanguageModel;
33
18
 
34
- const createChatModel = (
35
- modelId: string,
36
- settings: DeepSeekChatSettings = {}
37
- ) => {
38
- return new DeepSeekChatLanguageModel(modelId, settings, {
39
- baseURL,
40
- headers: getHeaders,
41
- });
42
- };
19
+ /**
20
+ * 创建 DeepSeek 聊天模型用于文本生成
21
+ */
22
+ chat(modelId: string, settings?: DeepSeekChatSettings): DeepSeekChatLanguageModel;
43
23
 
44
- const provider = {
45
- id: 'deepseek',
46
- name: 'DeepSeek AI',
47
- async initialize() {
48
- // 初始化逻辑:验证配置
49
- try {
50
- await loadApiKey({
51
- apiKey: options.apiKey,
52
- environmentVariableName: 'DEEPSEEK_API_KEY',
53
- description: 'DeepSeek API key',
54
- });
55
- } catch (error) {
56
- throw new Error(`DeepSeek provider initialization failed: ${error}`);
24
+ /**
25
+ * 文本嵌入模型(暂不支持)
26
+ * @deprecated
27
+ */
28
+ textEmbeddingModel(modelId: string): never;
29
+ }
30
+
31
+ /**
32
+ * 创建 DeepSeek Provider
33
+ * 完全兼容官方 @ai-sdk/deepseek 的 createDeepSeek 函数
34
+ */
35
+ export async function createDeepSeek(
36
+ options: DeepSeekProviderSettings = {}
37
+ ): Promise<DeepSeekProvider> {
38
+ // 加载 API Key
39
+ const apiKey = await loadApiKey({
40
+ apiKey: options.apiKey,
41
+ environmentVariableName: 'DEEPSEEK_API_KEY',
42
+ description: 'DeepSeek API key',
43
+ });
44
+
45
+ const baseURL = options.baseURL || 'https://api.deepseek.com';
46
+
47
+ // 创建 provider 函数
48
+ const providerFunction = function(
49
+ modelId: string,
50
+ settings?: DeepSeekChatSettings
51
+ ): DeepSeekChatLanguageModel {
52
+ return new DeepSeekChatLanguageModel(
53
+ modelId,
54
+ settings,
55
+ {
56
+ baseURL,
57
+ headers: () => ({
58
+ Authorization: `Bearer ${apiKey}`,
59
+ ...(options.headers || {}),
60
+ }),
57
61
  }
58
- },
59
- chat: createChatModel,
62
+ );
63
+ } as DeepSeekProvider;
64
+
65
+ // 添加方法到 provider 函数对象
66
+ providerFunction.languageModel = providerFunction;
67
+ providerFunction.chat = providerFunction;
68
+ providerFunction.textEmbeddingModel = () => {
69
+ throw new Error('Text embedding models are not supported for DeepSeek');
60
70
  };
61
71
 
62
- return provider;
72
+ return providerFunction;
63
73
  }
64
74
 
65
- // 默认导出
66
- export const deepseek = createProvider();
75
+ // 默认导出的 provider 实例
76
+ export const deepseek = createDeepSeek();
77
+
78
+ // 为了向后兼容,保留 createProvider 作为别名
79
+ export const createProvider = createDeepSeek;
package/src/index.ts CHANGED
@@ -1,21 +1,18 @@
1
- // 公开导出
1
+ // 公开导出 - 完全兼容官方 @ai-sdk/deepseek
2
2
 
3
- export { createProvider, deepseek } from './deepseek-provider';
3
+ // 主要导出(与官方一致)
4
+ export { createDeepSeek, deepseek, createProvider } from './deepseek-provider';
5
+
6
+ // 内部类型和类的导出
4
7
  export { DeepSeekChatLanguageModel } from './deepseek-chat-language-model';
5
8
  export { validateChatSettings } from './deepseek-chat-settings';
6
- export {
7
- ChineseParamsPreprocessor,
8
- } from './utils/chinese-params-preprocessor';
9
- export {
10
- RequestTransformer,
11
- } from './utils/request-transformer';
12
- export {
13
- ResponseTransformer,
14
- } from './utils/response-transformer';
15
- export {
16
- StreamParser,
17
- } from './utils/stream-parser';
18
9
 
10
+ // 工具类导出
11
+ export { RequestTransformer } from './utils/request-transformer';
12
+ export { ResponseTransformer } from './utils/response-transformer';
13
+ export { StreamParser } from './utils/stream-parser';
14
+
15
+ // 类型导出(与官方一致)
19
16
  export type {
20
17
  DeepSeekProviderSettings,
21
18
  DeepSeekChatSettings,
@@ -28,4 +25,10 @@ export type {
28
25
  DeepSeekResponse,
29
26
  DeepSeekStreamChoice,
30
27
  DeepSeekStreamResponse,
31
- } from './types';
28
+ } from './types';
29
+
30
+ // VERSION 常量(与官方一致)
31
+ export const VERSION = '0.2.0';
32
+
33
+ // DeepSeekProvider 类型导出
34
+ export type { DeepSeekProvider } from './deepseek-provider';
@@ -5,15 +5,8 @@ import type {
5
5
  LanguageModelV1Prompt,
6
6
  } from '@ai-sdk/provider';
7
7
  import type { DeepSeekRequest } from '../types';
8
- import { ChineseParamsPreprocessor } from './chinese-params-preprocessor';
9
8
 
10
9
  export class RequestTransformer {
11
- private preprocessor: ChineseParamsPreprocessor;
12
-
13
- constructor() {
14
- this.preprocessor = new ChineseParamsPreprocessor();
15
- }
16
-
17
10
  transform(modelId: string, options: LanguageModelV1CallOptions): DeepSeekRequest {
18
11
  const transformed: DeepSeekRequest = {
19
12
  model: modelId,
@@ -57,13 +50,18 @@ export class RequestTransformer {
57
50
  toolChoice = mode.toolChoice;
58
51
  }
59
52
 
53
+ // 如果没有通过 mode 传递工具,检查直接传递的 tools 参数(向后兼容)
54
+ if (toolsArray.length === 0 && options.tools && options.tools.length > 0) {
55
+ toolsArray = options.tools;
56
+ toolChoice = options.toolChoice;
57
+ }
58
+
60
59
  if (toolsArray.length > 0) {
61
60
  transformed.tools = this.transformTools(toolsArray);
62
61
  transformed.tool_choice = this.transformToolChoice(toolChoice);
63
62
  }
64
63
 
65
- // 预处理中文参数
66
- return this.preprocessor.process(transformed);
64
+ return transformed;
67
65
  }
68
66
 
69
67
  private transformMessages(messages: LanguageModelV1Prompt): Array<any> {
@@ -150,34 +148,59 @@ export class RequestTransformer {
150
148
  }
151
149
 
152
150
  private transformTools(tools: Array<any>): Array<any> {
153
- return tools.map(tool => ({
154
- type: 'function',
155
- function: {
156
- name: tool.name,
157
- description: tool.description,
158
- parameters: tool.parameters,
159
- },
160
- }));
151
+ return tools.map(tool => {
152
+ // AI SDK V1 格式: { type: 'function', function: { name, description, parameters } }
153
+ if (tool.type === 'function' && tool.function) {
154
+ return {
155
+ type: 'function',
156
+ function: {
157
+ name: tool.function.name,
158
+ description: tool.function.description,
159
+ parameters: tool.function.parameters,
160
+ },
161
+ };
162
+ }
163
+
164
+ // 备用格式(向后兼容)
165
+ return {
166
+ type: 'function',
167
+ function: {
168
+ name: tool.name,
169
+ description: tool.description,
170
+ parameters: tool.parameters,
171
+ },
172
+ };
173
+ });
161
174
  }
162
175
 
163
- private transformToolChoice(toolChoice: any): 'auto' | 'none' | 'required' | string {
176
+ private transformToolChoice(toolChoice: any): any {
177
+ // undefined 或 auto -> 'auto'
164
178
  if (toolChoice === undefined || toolChoice === 'auto') {
165
179
  return 'auto';
166
180
  }
181
+
182
+ // none -> 'none'
167
183
  if (toolChoice === 'none') {
168
184
  return 'none';
169
185
  }
170
- if (toolChoice === 'required') {
186
+
187
+ // required -> 'required' (强制调用至少一个工具)
188
+ if (toolChoice === 'required' || (typeof toolChoice === 'object' && toolChoice.type === 'required')) {
171
189
  return 'required';
172
190
  }
191
+
192
+ // 特定工具: { type: 'tool', toolName: 'function_name' }
173
193
  if (typeof toolChoice === 'object' && toolChoice.type === 'tool') {
174
- return JSON.stringify({
194
+ // DeepSeek API 可能支持的格式
195
+ return {
175
196
  type: 'function',
176
197
  function: {
177
198
  name: toolChoice.toolName,
178
199
  },
179
- });
200
+ };
180
201
  }
202
+
203
+ // 默认: auto
181
204
  return 'auto';
182
205
  }
183
206
  }
@@ -1,28 +1,30 @@
1
- // 响应转换器 - V1 API 兼容版本
1
+ // 响应转换器 - AI SDK 格式
2
2
 
3
3
  import type {
4
- LanguageModelV1,
5
4
  LanguageModelV1FinishReason,
6
5
  LanguageModelV1CallWarning,
7
6
  LanguageModelV1FunctionToolCall,
7
+ LanguageModelV1ContentPart,
8
8
  } from '@ai-sdk/provider';
9
9
  import type { DeepSeekResponse } from '../types';
10
10
 
11
- // V1 API 返回结果类型
11
+ // AI SDK 返回结果类型
12
12
  export interface V1GenerateResult {
13
- text?: string;
14
- reasoning?: string;
13
+ content: LanguageModelV1ContentPart[];
14
+ finishReason: LanguageModelV1FinishReason;
15
15
  usage: {
16
16
  promptTokens: number;
17
17
  completionTokens: number;
18
18
  };
19
- finishReason: LanguageModelV1FinishReason;
20
- toolCalls?: LanguageModelV1FunctionToolCall[];
21
19
  rawCall: {
22
20
  rawPrompt: unknown;
23
21
  rawSettings: Record<string, unknown>;
24
22
  };
25
23
  warnings?: LanguageModelV1CallWarning[];
24
+ // 兼容旧格式的字段
25
+ text?: string;
26
+ toolCalls?: LanguageModelV1FunctionToolCall[];
27
+ reasoning?: string;
26
28
  }
27
29
 
28
30
  export class ResponseTransformer {
@@ -36,8 +38,28 @@ export class ResponseTransformer {
36
38
  message.tool_calls
37
39
  );
38
40
 
41
+ // 转换工具调用
42
+ const toolCalls = this.transformToolCalls(message.tool_calls);
43
+
44
+ // 构建内容数组
45
+ const content: LanguageModelV1ContentPart[] = [];
46
+
47
+ // 添加文本内容
48
+ if (message.content) {
49
+ content.push({
50
+ type: 'text',
51
+ text: message.content,
52
+ });
53
+ }
54
+
55
+ // 添加工具调用
56
+ if (toolCalls.length > 0) {
57
+ content.push(...toolCalls);
58
+ }
59
+
39
60
  return {
40
- text: message.content || '',
61
+ content,
62
+ text: message.content || '', // 兼容旧格式
41
63
  finishReason: finishReason as LanguageModelV1FinishReason,
42
64
  usage: {
43
65
  promptTokens: apiResponse.usage?.prompt_tokens || 0,
@@ -47,7 +69,7 @@ export class ResponseTransformer {
47
69
  rawPrompt: '',
48
70
  rawSettings: {},
49
71
  },
50
- toolCalls: this.transformToolCalls(message.tool_calls),
72
+ toolCalls, // 兼容旧格式
51
73
  warnings: [],
52
74
  };
53
75
  }
@@ -79,6 +101,7 @@ export class ResponseTransformer {
79
101
  }
80
102
 
81
103
  return toolCalls.map((tc: any) => ({
104
+ type: 'tool-call' as const,
82
105
  toolCallType: 'function' as const,
83
106
  toolCallId: tc.id,
84
107
  toolName: tc.function.name,
@@ -87,4 +110,4 @@ export class ResponseTransformer {
87
110
  : JSON.stringify(tc.function.arguments),
88
111
  }));
89
112
  }
90
- }
113
+ }
@@ -28,11 +28,14 @@ interface DeepSeekStreamChunk {
28
28
  }
29
29
 
30
30
  export class StreamParser {
31
+ private hasToolCalls: boolean = false;
32
+
31
33
  async *parse(body: ReadableStream<Uint8Array>): AsyncIterable<LanguageModelV1StreamPart> {
32
34
  const reader = body.getReader();
33
35
  const decoder = new TextDecoder('utf-8');
34
36
  let buffer = '';
35
37
  let partialJson = '';
38
+ this.hasToolCalls = false; // 重置状态
36
39
 
37
40
  try {
38
41
  while (true) {
@@ -95,6 +98,7 @@ export class StreamParser {
95
98
  if (delta?.content) {
96
99
  const toolCallData = this.tryParseToolCall(delta.content);
97
100
  if (toolCallData) {
101
+ this.hasToolCalls = true; // 标记有工具调用
98
102
  yield {
99
103
  type: 'tool-call-delta',
100
104
  toolCallType: 'function',
@@ -113,6 +117,7 @@ export class StreamParser {
113
117
 
114
118
  // 工具调用增量 - 标准 tool_calls 格式
115
119
  if (delta?.tool_calls && delta.tool_calls.length > 0) {
120
+ this.hasToolCalls = true; // 标记有工具调用
116
121
  for (const toolCall of delta.tool_calls) {
117
122
  yield {
118
123
  type: 'tool-call-delta',
@@ -144,6 +149,11 @@ export class StreamParser {
144
149
  }
145
150
 
146
151
  private mapFinishReason(reason: string): 'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'other' | 'unknown' {
152
+ // 修复:如果有工具调用但 finish_reason 是 "stop",改为 "tool-calls"
153
+ if (reason === 'stop' && this.hasToolCalls) {
154
+ return 'tool-calls';
155
+ }
156
+
147
157
  const reasonMap: Record<string, 'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'other' | 'unknown'> = {
148
158
  'stop': 'stop',
149
159
  'length': 'length',
package/dist/index.d.ts DELETED
@@ -1,184 +0,0 @@
1
- import { LanguageModelV1FinishReason, LanguageModelV1FunctionToolCall, LanguageModelV1CallWarning, LanguageModelV1, LanguageModelV1CallOptions, LanguageModelV1StreamPart } from '@ai-sdk/provider';
2
-
3
- interface DeepSeekProviderSettings {
4
- apiKey?: string;
5
- baseURL?: string;
6
- headers?: Record<string, string | undefined>;
7
- }
8
- interface DeepSeekChatSettings {
9
- temperature?: number;
10
- topP?: number;
11
- maxTokens?: number;
12
- presencePenalty?: number;
13
- frequencyPenalty?: number;
14
- }
15
- interface DeepSeekMessage {
16
- role: 'system' | 'user' | 'assistant' | 'tool';
17
- content: string | Array<{
18
- type: 'text' | 'image_url';
19
- text?: string;
20
- image_url?: {
21
- url: string;
22
- };
23
- }>;
24
- tool_calls?: DeepSeekToolCall[];
25
- tool_call_id?: string;
26
- }
27
- interface DeepSeekToolCall {
28
- id: string;
29
- type: 'function';
30
- function: {
31
- name: string;
32
- arguments: string;
33
- };
34
- }
35
- interface DeepSeekTool {
36
- type: 'function';
37
- function: {
38
- name: string;
39
- description?: string;
40
- parameters?: Record<string, any>;
41
- };
42
- }
43
- interface DeepSeekRequest {
44
- model: string;
45
- messages: DeepSeekMessage[];
46
- temperature?: number;
47
- top_p?: number;
48
- max_tokens?: number;
49
- presence_penalty?: number;
50
- frequency_penalty?: number;
51
- stream?: boolean;
52
- tools?: DeepSeekTool[];
53
- tool_choice?: 'auto' | 'none' | 'required' | string;
54
- }
55
- interface DeepSeekChoice {
56
- index: number;
57
- message: {
58
- role: string;
59
- content: string | null;
60
- tool_calls?: DeepSeekToolCall[];
61
- };
62
- finish_reason: string;
63
- }
64
- interface DeepSeekUsage {
65
- prompt_tokens: number;
66
- completion_tokens: number;
67
- total_tokens: number;
68
- }
69
- interface DeepSeekResponse {
70
- id: string;
71
- object: string;
72
- created: number;
73
- model: string;
74
- choices: DeepSeekChoice[];
75
- usage: DeepSeekUsage;
76
- }
77
- interface DeepSeekStreamChoice {
78
- index: number;
79
- delta: {
80
- role?: string;
81
- content?: string;
82
- tool_calls?: DeepSeekToolCall[];
83
- };
84
- finish_reason?: string;
85
- }
86
- interface DeepSeekStreamResponse {
87
- id: string;
88
- object: string;
89
- created: number;
90
- model: string;
91
- choices: DeepSeekStreamChoice[];
92
- }
93
-
94
- interface V1GenerateResult {
95
- text?: string;
96
- reasoning?: string;
97
- usage: {
98
- promptTokens: number;
99
- completionTokens: number;
100
- };
101
- finishReason: LanguageModelV1FinishReason;
102
- toolCalls?: LanguageModelV1FunctionToolCall[];
103
- rawCall: {
104
- rawPrompt: unknown;
105
- rawSettings: Record<string, unknown>;
106
- };
107
- warnings?: LanguageModelV1CallWarning[];
108
- }
109
- declare class ResponseTransformer {
110
- transform(apiResponse: DeepSeekResponse): V1GenerateResult;
111
- private fixFinishReason;
112
- private transformToolCalls;
113
- }
114
-
115
- declare class DeepSeekChatLanguageModel implements LanguageModelV1 {
116
- readonly specificationVersion: "v1";
117
- readonly provider: "deepseek";
118
- readonly modelId: string;
119
- readonly settings: Required<DeepSeekChatSettings>;
120
- readonly defaultObjectGenerationMode: 'json' | 'tool' | undefined;
121
- private baseURL;
122
- private headers;
123
- private requestTransformer;
124
- private responseTransformer;
125
- private streamParser;
126
- constructor(modelId: string, settings: DeepSeekChatSettings | undefined, config: {
127
- baseURL: string;
128
- headers: () => Record<string, string>;
129
- });
130
- doGenerate(options: LanguageModelV1CallOptions): Promise<V1GenerateResult>;
131
- doStream(options: LanguageModelV1CallOptions): Promise<{
132
- stream: any;
133
- rawCall: {
134
- rawPrompt: unknown;
135
- rawSettings: {};
136
- };
137
- warnings: never[];
138
- }>;
139
- }
140
-
141
- declare function createProvider(options?: DeepSeekProviderSettings): Promise<{
142
- id: string;
143
- name: string;
144
- initialize(): Promise<void>;
145
- chat: (modelId: string, settings?: DeepSeekChatSettings) => DeepSeekChatLanguageModel;
146
- }>;
147
- declare const deepseek: Promise<{
148
- id: string;
149
- name: string;
150
- initialize(): Promise<void>;
151
- chat: (modelId: string, settings?: DeepSeekChatSettings) => DeepSeekChatLanguageModel;
152
- }>;
153
-
154
- declare function validateChatSettings(settings?: DeepSeekChatSettings): Required<DeepSeekChatSettings>;
155
-
156
- declare class ChineseParamsPreprocessor {
157
- private cityMap;
158
- process(request: DeepSeekRequest): DeepSeekRequest;
159
- private processMessages;
160
- private processTools;
161
- private processProperties;
162
- private replaceCityNames;
163
- addCityMapping(chinese: string, english: string): void;
164
- addCityMappings(mappings: Record<string, string>): void;
165
- }
166
-
167
- declare class RequestTransformer {
168
- private preprocessor;
169
- constructor();
170
- transform(modelId: string, options: LanguageModelV1CallOptions): DeepSeekRequest;
171
- private transformMessages;
172
- private transformTools;
173
- private transformToolChoice;
174
- }
175
-
176
- declare class StreamParser {
177
- parse(body: ReadableStream<Uint8Array>): AsyncIterable<LanguageModelV1StreamPart>;
178
- private processPartialJson;
179
- private processChunk;
180
- private mapFinishReason;
181
- private tryParseToolCall;
182
- }
183
-
184
- export { ChineseParamsPreprocessor, DeepSeekChatLanguageModel, type DeepSeekChatSettings, type DeepSeekChoice, type DeepSeekMessage, type DeepSeekProviderSettings, type DeepSeekRequest, type DeepSeekResponse, type DeepSeekStreamChoice, type DeepSeekStreamResponse, type DeepSeekTool, type DeepSeekToolCall, type DeepSeekUsage, RequestTransformer, ResponseTransformer, StreamParser, createProvider, deepseek, validateChatSettings };