1use anyhow::{Result, anyhow};
2use futures::{
3 AsyncBufReadExt, AsyncReadExt,
4 io::BufReader,
5 stream::{BoxStream, StreamExt},
6};
7use http_client::{AsyncBody, HttpClient, Method, Request as HttpRequest};
8use serde::{Deserialize, Serialize};
9use serde_json::Value;
10use std::convert::TryFrom;
11
12pub const DEEPSEEK_API_URL: &str = "https://api.deepseek.com/v1";
13
14#[derive(Clone, Copy, Serialize, Deserialize, Debug, Eq, PartialEq)]
15#[serde(rename_all = "lowercase")]
16pub enum Role {
17 User,
18 Assistant,
19 System,
20 Tool,
21}
22
23impl TryFrom<String> for Role {
24 type Error = anyhow::Error;
25
26 fn try_from(value: String) -> Result<Self> {
27 match value.as_str() {
28 "user" => Ok(Self::User),
29 "assistant" => Ok(Self::Assistant),
30 "system" => Ok(Self::System),
31 "tool" => Ok(Self::Tool),
32 _ => anyhow::bail!("invalid role '{value}'"),
33 }
34 }
35}
36
37impl From<Role> for String {
38 fn from(val: Role) -> Self {
39 match val {
40 Role::User => "user".to_owned(),
41 Role::Assistant => "assistant".to_owned(),
42 Role::System => "system".to_owned(),
43 Role::Tool => "tool".to_owned(),
44 }
45 }
46}
47
48#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
49#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
50pub enum Model {
51 #[serde(rename = "deepseek-chat")]
52 #[default]
53 Chat,
54 #[serde(rename = "deepseek-reasoner")]
55 Reasoner,
56 #[serde(rename = "custom")]
57 Custom {
58 name: String,
59 /// The name displayed in the UI, such as in the assistant panel model dropdown menu.
60 display_name: Option<String>,
61 max_tokens: u64,
62 max_output_tokens: Option<u64>,
63 },
64}
65
66impl Model {
67 pub fn default_fast() -> Self {
68 Model::Chat
69 }
70
71 pub fn from_id(id: &str) -> Result<Self> {
72 match id {
73 "deepseek-chat" => Ok(Self::Chat),
74 "deepseek-reasoner" => Ok(Self::Reasoner),
75 _ => anyhow::bail!("invalid model id {id}"),
76 }
77 }
78
79 pub fn id(&self) -> &str {
80 match self {
81 Self::Chat => "deepseek-chat",
82 Self::Reasoner => "deepseek-reasoner",
83 Self::Custom { name, .. } => name,
84 }
85 }
86
87 pub fn display_name(&self) -> &str {
88 match self {
89 Self::Chat => "DeepSeek Chat",
90 Self::Reasoner => "DeepSeek Reasoner",
91 Self::Custom {
92 name, display_name, ..
93 } => display_name.as_ref().unwrap_or(name).as_str(),
94 }
95 }
96
97 pub fn max_token_count(&self) -> u64 {
98 match self {
99 Self::Chat | Self::Reasoner => 128_000,
100 Self::Custom { max_tokens, .. } => *max_tokens,
101 }
102 }
103
104 pub fn max_output_tokens(&self) -> Option<u64> {
105 match self {
106 Self::Chat => Some(8_192),
107 Self::Reasoner => Some(64_000),
108 Self::Custom {
109 max_output_tokens, ..
110 } => *max_output_tokens,
111 }
112 }
113}
114
115#[derive(Debug, Serialize, Deserialize)]
116pub struct Request {
117 pub model: String,
118 pub messages: Vec<RequestMessage>,
119 pub stream: bool,
120 #[serde(default, skip_serializing_if = "Option::is_none")]
121 pub max_tokens: Option<u64>,
122 #[serde(default, skip_serializing_if = "Option::is_none")]
123 pub temperature: Option<f32>,
124 #[serde(default, skip_serializing_if = "Option::is_none")]
125 pub response_format: Option<ResponseFormat>,
126 #[serde(default, skip_serializing_if = "Vec::is_empty")]
127 pub tools: Vec<ToolDefinition>,
128}
129
130#[derive(Debug, Serialize, Deserialize)]
131#[serde(rename_all = "snake_case")]
132pub enum ResponseFormat {
133 Text,
134 #[serde(rename = "json_object")]
135 JsonObject,
136}
137
138#[derive(Debug, Serialize, Deserialize)]
139#[serde(tag = "type", rename_all = "snake_case")]
140pub enum ToolDefinition {
141 Function { function: FunctionDefinition },
142}
143
144#[derive(Debug, Serialize, Deserialize)]
145pub struct FunctionDefinition {
146 pub name: String,
147 pub description: Option<String>,
148 pub parameters: Option<Value>,
149}
150
151#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
152#[serde(tag = "role", rename_all = "lowercase")]
153pub enum RequestMessage {
154 Assistant {
155 content: Option<String>,
156 #[serde(default, skip_serializing_if = "Vec::is_empty")]
157 tool_calls: Vec<ToolCall>,
158 },
159 User {
160 content: String,
161 },
162 System {
163 content: String,
164 },
165 Tool {
166 content: String,
167 tool_call_id: String,
168 },
169}
170
171#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
172pub struct ToolCall {
173 pub id: String,
174 #[serde(flatten)]
175 pub content: ToolCallContent,
176}
177
178#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
179#[serde(tag = "type", rename_all = "lowercase")]
180pub enum ToolCallContent {
181 Function { function: FunctionContent },
182}
183
184#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
185pub struct FunctionContent {
186 pub name: String,
187 pub arguments: String,
188}
189
190#[derive(Serialize, Deserialize, Debug)]
191pub struct Response {
192 pub id: String,
193 pub object: String,
194 pub created: u64,
195 pub model: String,
196 pub choices: Vec<Choice>,
197 pub usage: Usage,
198 #[serde(default, skip_serializing_if = "Option::is_none")]
199 pub reasoning_content: Option<String>,
200}
201
202#[derive(Serialize, Deserialize, Debug)]
203pub struct Usage {
204 pub prompt_tokens: u64,
205 pub completion_tokens: u64,
206 pub total_tokens: u64,
207 #[serde(default)]
208 pub prompt_cache_hit_tokens: u64,
209 #[serde(default)]
210 pub prompt_cache_miss_tokens: u64,
211}
212
213#[derive(Serialize, Deserialize, Debug)]
214pub struct Choice {
215 pub index: u32,
216 pub message: RequestMessage,
217 pub finish_reason: Option<String>,
218}
219
220#[derive(Serialize, Deserialize, Debug)]
221pub struct StreamResponse {
222 pub id: String,
223 pub object: String,
224 pub created: u64,
225 pub model: String,
226 pub choices: Vec<StreamChoice>,
227 pub usage: Option<Usage>,
228}
229
230#[derive(Serialize, Deserialize, Debug)]
231pub struct StreamChoice {
232 pub index: u32,
233 pub delta: StreamDelta,
234 pub finish_reason: Option<String>,
235}
236
237#[derive(Serialize, Deserialize, Debug)]
238pub struct StreamDelta {
239 pub role: Option<Role>,
240 pub content: Option<String>,
241 #[serde(default, skip_serializing_if = "Option::is_none")]
242 pub tool_calls: Option<Vec<ToolCallChunk>>,
243 #[serde(default, skip_serializing_if = "Option::is_none")]
244 pub reasoning_content: Option<String>,
245}
246
247#[derive(Serialize, Deserialize, Debug)]
248pub struct ToolCallChunk {
249 pub index: usize,
250 pub id: Option<String>,
251 pub function: Option<FunctionChunk>,
252}
253
254#[derive(Serialize, Deserialize, Debug)]
255pub struct FunctionChunk {
256 pub name: Option<String>,
257 pub arguments: Option<String>,
258}
259
260pub async fn stream_completion(
261 client: &dyn HttpClient,
262 api_url: &str,
263 api_key: &str,
264 request: Request,
265) -> Result<BoxStream<'static, Result<StreamResponse>>> {
266 let uri = format!("{api_url}/chat/completions");
267 let request_builder = HttpRequest::builder()
268 .method(Method::POST)
269 .uri(uri)
270 .header("Content-Type", "application/json")
271 .header("Authorization", format!("Bearer {}", api_key.trim()));
272
273 let request = request_builder.body(AsyncBody::from(serde_json::to_string(&request)?))?;
274 let mut response = client.send(request).await?;
275
276 if response.status().is_success() {
277 let reader = BufReader::new(response.into_body());
278 Ok(reader
279 .lines()
280 .filter_map(|line| async move {
281 match line {
282 Ok(line) => {
283 let line = line.strip_prefix("data: ")?;
284 if line == "[DONE]" {
285 None
286 } else {
287 match serde_json::from_str(line) {
288 Ok(response) => Some(Ok(response)),
289 Err(error) => Some(Err(anyhow!(error))),
290 }
291 }
292 }
293 Err(error) => Some(Err(anyhow!(error))),
294 }
295 })
296 .boxed())
297 } else {
298 let mut body = String::new();
299 response.body_mut().read_to_string(&mut body).await?;
300 anyhow::bail!(
301 "Failed to connect to DeepSeek API: {} {}",
302 response.status(),
303 body,
304 );
305 }
306}