| 1 | import { OUTBOUND_MAX_BYTES, readBoundedBody } from "./bounded-body"; |
| 2 | |
| 3 | const FALLBACK_BASE = "https://api.deepseek.com"; |
| 4 | const FALLBACK_MODEL = "deepseek-flash"; |
| 5 | |
| 6 | export interface ChatMessage { |
| 7 | role: "system" | "user" | "assistant"; |
| 8 | content: string; |
| 9 | } |
| 10 | |
| 11 | interface ChatResponse { |
| 12 | choices: { message: { content: string } }[]; |
| 13 | usage?: { prompt_tokens?: number; completion_tokens?: number }; |
| 14 | } |
| 15 | |
| 16 | export interface DeepSeekEnv { |
| 17 | baseUrl?: string; |
| 18 | model?: string; |
| 19 | } |
| 20 | |
| 21 | export async function chat( |
| 22 | messages: ChatMessage[], |
| 23 | apiKey: string, |
| 24 | jsonMode = false, |
| 25 | dsEnv?: DeepSeekEnv |
| 26 | ): Promise<string> { |
| 27 | const data = await requestChat(messages, apiKey, jsonMode, dsEnv, { temperature: 0.4, maxTokens: 4096 }); |
| 28 | return data.choices[0]?.message?.content ?? ""; |
| 29 | } |
| 30 | |
| 31 | export async function requestChat( |
| 32 | messages: ChatMessage[], |
| 33 | apiKey: string, |
| 34 | jsonMode: boolean, |
| 35 | dsEnv: DeepSeekEnv | undefined, |
| 36 | options: { temperature: number; maxTokens: number }, |
| 37 | ): Promise<ChatResponse> { |
| 38 | const base = dsEnv?.baseUrl ?? process.env.DEEPSEEK_BASE_URL ?? FALLBACK_BASE; |
| 39 | const model = dsEnv?.model ?? process.env.DEEPSEEK_MODEL ?? FALLBACK_MODEL; |
| 40 | const res = await fetch(`${base}/v1/chat/completions`, { |
| 41 | method: "POST", |
| 42 | signal: AbortSignal.timeout(180_000), |
| 43 | headers: { |
| 44 | "Content-Type": "application/json", |
| 45 | Authorization: `Bearer ${apiKey}`, |
| 46 | }, |
| 47 | body: JSON.stringify({ |
| 48 | model, |
| 49 | messages, |
| 50 | temperature: options.temperature, |
| 51 | max_tokens: options.maxTokens, |
| 52 | reasoning_effort: "high", |
| 53 | ...(jsonMode ? { response_format: { type: "json_object" } } : {}), |
| 54 | }), |
| 55 | }); |
| 56 | let bytes: Uint8Array; |
| 57 | try { |
| 58 | bytes = await readBoundedBody(res, res.ok ? OUTBOUND_MAX_BYTES : 4096); |
| 59 | } catch (cause) { |
| 60 | throw new Error(`DeepSeek ${res.status}: ${cause instanceof Error ? cause.message : "body read failed"}`, { cause }); |
| 61 | } |
| 62 | const text = new TextDecoder().decode(bytes); |
| 63 | if (!res.ok) throw new Error(`DeepSeek ${res.status}: ${text}`); |
| 64 | return JSON.parse(text) as ChatResponse; |
| 65 | } |
| 66 |