|
1 | | -import { OpenAiHandler, OpenAiHandlerOptions } from "./openai" |
2 | | -import { ModelInfo } from "../../shared/api" |
3 | | -import { deepSeekModels, deepSeekDefaultModelId } from "../../shared/api" |
4 | | - |
5 | | -export class DeepSeekHandler extends OpenAiHandler { |
6 | | - constructor(options: OpenAiHandlerOptions) { |
7 | | - super({ |
8 | | - ...options, |
9 | | - openAiApiKey: options.deepSeekApiKey ?? "not-provided", |
10 | | - openAiModelId: options.apiModelId ?? deepSeekDefaultModelId, |
11 | | - openAiBaseUrl: options.deepSeekBaseUrl ?? "https://api.deepseek.com/v1", |
12 | | - openAiStreamingEnabled: true, |
13 | | - includeMaxTokens: true, |
| 1 | +import { Anthropic } from "@anthropic-ai/sdk" |
| 2 | +import { ApiHandlerOptions, ModelInfo, deepSeekModels, deepSeekDefaultModelId } from "../../shared/api" |
| 3 | +import { ApiHandler, SingleCompletionHandler } from "../index" |
| 4 | +import { convertToR1Format } from "../transform/r1-format" |
| 5 | +import { convertToOpenAiMessages } from "../transform/openai-format" |
| 6 | +import { ApiStream } from "../transform/stream" |
| 7 | + |
| 8 | +interface DeepSeekUsage { |
| 9 | + prompt_tokens: number |
| 10 | + completion_tokens: number |
| 11 | + prompt_cache_miss_tokens?: number |
| 12 | + prompt_cache_hit_tokens?: number |
| 13 | +} |
| 14 | + |
| 15 | +export class DeepSeekHandler implements ApiHandler, SingleCompletionHandler { |
| 16 | + private options: ApiHandlerOptions |
| 17 | + |
| 18 | + constructor(options: ApiHandlerOptions) { |
| 19 | + if (!options.deepSeekApiKey) { |
| 20 | + throw new Error("DeepSeek API key is required. Please provide it in the settings.") |
| 21 | + } |
| 22 | + this.options = options |
| 23 | + } |
| 24 | + |
| 25 | + private get baseUrl(): string { |
| 26 | + return this.options.deepSeekBaseUrl ?? "https://api.deepseek.com/v1" |
| 27 | + } |
| 28 | + |
| 29 | + async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream { |
| 30 | + const modelInfo = this.getModel().info |
| 31 | + const modelId = this.options.apiModelId ?? deepSeekDefaultModelId |
| 32 | + const isReasoner = modelId.includes("deepseek-reasoner") |
| 33 | + |
| 34 | + const systemMessage = { role: "system", content: systemPrompt } |
| 35 | + const formattedMessages = isReasoner |
| 36 | + ? convertToR1Format([{ role: "user", content: systemPrompt }, ...messages]) |
| 37 | + : [systemMessage, ...convertToOpenAiMessages(messages)] |
| 38 | + |
| 39 | + const response = await fetch(`${this.baseUrl}/chat/completions`, { |
| 40 | + method: "POST", |
| 41 | + headers: { |
| 42 | + "Content-Type": "application/json", |
| 43 | + Authorization: `Bearer ${this.options.deepSeekApiKey}`, |
| 44 | + }, |
| 45 | + body: JSON.stringify({ |
| 46 | + model: modelId, |
| 47 | + messages: formattedMessages, |
| 48 | + temperature: 0, |
| 49 | + stream: true, |
| 50 | + max_tokens: modelInfo.maxTokens, |
| 51 | + }), |
14 | 52 | }) |
| 53 | + |
| 54 | + if (!response.ok) { |
| 55 | + throw new Error(`DeepSeek API error: ${response.statusText}`) |
| 56 | + } |
| 57 | + |
| 58 | + if (!response.body) { |
| 59 | + throw new Error("No response body received from DeepSeek API") |
| 60 | + } |
| 61 | + |
| 62 | + const reader = response.body.getReader() |
| 63 | + const decoder = new TextDecoder() |
| 64 | + let buffer = "" |
| 65 | + |
| 66 | + try { |
| 67 | + while (true) { |
| 68 | + const { done, value } = await reader.read() |
| 69 | + if (done) break |
| 70 | + |
| 71 | + buffer += decoder.decode(value, { stream: true }) |
| 72 | + const lines = buffer.split("\n") |
| 73 | + buffer = lines.pop() || "" |
| 74 | + |
| 75 | + for (const line of lines) { |
| 76 | + if (line.trim() === "") continue |
| 77 | + if (!line.startsWith("data: ")) continue |
| 78 | + |
| 79 | + const data = line.slice(6) |
| 80 | + if (data === "[DONE]") continue |
| 81 | + |
| 82 | + try { |
| 83 | + const chunk = JSON.parse(data) |
| 84 | + const delta = chunk.choices[0]?.delta ?? {} |
| 85 | + |
| 86 | + if (delta.content) { |
| 87 | + yield { |
| 88 | + type: "text", |
| 89 | + text: delta.content, |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + if ("reasoning_content" in delta && delta.reasoning_content) { |
| 94 | + yield { |
| 95 | + type: "reasoning", |
| 96 | + text: delta.reasoning_content, |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + if (chunk.usage) { |
| 101 | + const usage = chunk.usage as DeepSeekUsage |
| 102 | + let inputTokens = (usage.prompt_tokens || 0) - (usage.prompt_cache_hit_tokens || 0) |
| 103 | + yield { |
| 104 | + type: "usage", |
| 105 | + inputTokens: inputTokens, |
| 106 | + outputTokens: usage.completion_tokens || 0, |
| 107 | + cacheReadTokens: usage.prompt_cache_hit_tokens || 0, |
| 108 | + cacheWriteTokens: usage.prompt_cache_miss_tokens || 0, |
| 109 | + } |
| 110 | + } |
| 111 | + } catch (error) { |
| 112 | + console.error("Error parsing DeepSeek response:", error) |
| 113 | + } |
| 114 | + } |
| 115 | + } |
| 116 | + } finally { |
| 117 | + reader.releaseLock() |
| 118 | + } |
15 | 119 | } |
16 | 120 |
|
17 | | - override getModel(): { id: string; info: ModelInfo } { |
| 121 | + getModel(): { id: string; info: ModelInfo } { |
18 | 122 | const modelId = this.options.apiModelId ?? deepSeekDefaultModelId |
19 | 123 | return { |
20 | 124 | id: modelId, |
21 | 125 | info: deepSeekModels[modelId as keyof typeof deepSeekModels] || deepSeekModels[deepSeekDefaultModelId], |
22 | 126 | } |
23 | 127 | } |
| 128 | + |
| 129 | + async completePrompt(prompt: string): Promise<string> { |
| 130 | + try { |
| 131 | + const response = await fetch(`${this.baseUrl}/chat/completions`, { |
| 132 | + method: "POST", |
| 133 | + headers: { |
| 134 | + "Content-Type": "application/json", |
| 135 | + Authorization: `Bearer ${this.options.deepSeekApiKey}`, |
| 136 | + }, |
| 137 | + body: JSON.stringify({ |
| 138 | + model: this.getModel().id, |
| 139 | + messages: [{ role: "user", content: prompt }], |
| 140 | + temperature: 0, |
| 141 | + stream: false, |
| 142 | + }), |
| 143 | + }) |
| 144 | + |
| 145 | + if (!response.ok) { |
| 146 | + throw new Error(`DeepSeek API error: ${response.statusText}`) |
| 147 | + } |
| 148 | + |
| 149 | + const data = await response.json() |
| 150 | + return data.choices[0]?.message?.content || "" |
| 151 | + } catch (error) { |
| 152 | + if (error instanceof Error) { |
| 153 | + throw new Error(`DeepSeek completion error: ${error.message}`) |
| 154 | + } |
| 155 | + throw error |
| 156 | + } |
| 157 | + } |
24 | 158 | } |
0 commit comments