deepseek.rs

  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        #[serde(default, skip_serializing_if = "Option::is_none")]
159        reasoning_content: Option<String>,
160    },
161    User {
162        content: String,
163    },
164    System {
165        content: String,
166    },
167    Tool {
168        content: String,
169        tool_call_id: String,
170    },
171}
172
173#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
174pub struct ToolCall {
175    pub id: String,
176    #[serde(flatten)]
177    pub content: ToolCallContent,
178}
179
180#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
181#[serde(tag = "type", rename_all = "lowercase")]
182pub enum ToolCallContent {
183    Function { function: FunctionContent },
184}
185
186#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
187pub struct FunctionContent {
188    pub name: String,
189    pub arguments: String,
190}
191
192#[derive(Serialize, Deserialize, Debug)]
193pub struct Response {
194    pub id: String,
195    pub object: String,
196    pub created: u64,
197    pub model: String,
198    pub choices: Vec<Choice>,
199    pub usage: Usage,
200    #[serde(default, skip_serializing_if = "Option::is_none")]
201    pub reasoning_content: Option<String>,
202}
203
204#[derive(Serialize, Deserialize, Debug)]
205pub struct Usage {
206    pub prompt_tokens: u64,
207    pub completion_tokens: u64,
208    pub total_tokens: u64,
209    #[serde(default)]
210    pub prompt_cache_hit_tokens: u64,
211    #[serde(default)]
212    pub prompt_cache_miss_tokens: u64,
213}
214
215#[derive(Serialize, Deserialize, Debug)]
216pub struct Choice {
217    pub index: u32,
218    pub message: RequestMessage,
219    pub finish_reason: Option<String>,
220}
221
222#[derive(Serialize, Deserialize, Debug)]
223pub struct StreamResponse {
224    pub id: String,
225    pub object: String,
226    pub created: u64,
227    pub model: String,
228    pub choices: Vec<StreamChoice>,
229    pub usage: Option<Usage>,
230}
231
232#[derive(Serialize, Deserialize, Debug)]
233pub struct StreamChoice {
234    pub index: u32,
235    pub delta: StreamDelta,
236    pub finish_reason: Option<String>,
237}
238
239#[derive(Serialize, Deserialize, Debug)]
240pub struct StreamDelta {
241    pub role: Option<Role>,
242    pub content: Option<String>,
243    #[serde(default, skip_serializing_if = "Option::is_none")]
244    pub tool_calls: Option<Vec<ToolCallChunk>>,
245    #[serde(default, skip_serializing_if = "Option::is_none")]
246    pub reasoning_content: Option<String>,
247}
248
249#[derive(Serialize, Deserialize, Debug)]
250pub struct ToolCallChunk {
251    pub index: usize,
252    pub id: Option<String>,
253    pub function: Option<FunctionChunk>,
254}
255
256#[derive(Serialize, Deserialize, Debug)]
257pub struct FunctionChunk {
258    pub name: Option<String>,
259    pub arguments: Option<String>,
260}
261
262pub async fn stream_completion(
263    client: &dyn HttpClient,
264    api_url: &str,
265    api_key: &str,
266    request: Request,
267) -> Result<BoxStream<'static, Result<StreamResponse>>> {
268    let uri = format!("{api_url}/chat/completions");
269    let request_builder = HttpRequest::builder()
270        .method(Method::POST)
271        .uri(uri)
272        .header("Content-Type", "application/json")
273        .header("Authorization", format!("Bearer {}", api_key.trim()));
274
275    let request = request_builder.body(AsyncBody::from(serde_json::to_string(&request)?))?;
276    let mut response = client.send(request).await?;
277
278    if response.status().is_success() {
279        let reader = BufReader::new(response.into_body());
280        Ok(reader
281            .lines()
282            .filter_map(|line| async move {
283                match line {
284                    Ok(line) => {
285                        let line = line.strip_prefix("data: ")?;
286                        if line == "[DONE]" {
287                            None
288                        } else {
289                            match serde_json::from_str(line) {
290                                Ok(response) => Some(Ok(response)),
291                                Err(error) => Some(Err(anyhow!(error))),
292                            }
293                        }
294                    }
295                    Err(error) => Some(Err(anyhow!(error))),
296                }
297            })
298            .boxed())
299    } else {
300        let mut body = String::new();
301        response.body_mut().read_to_string(&mut body).await?;
302        anyhow::bail!(
303            "Failed to connect to DeepSeek API: {} {}",
304            response.status(),
305            body,
306        );
307    }
308}