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";
 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: usize,
 62        max_output_tokens: Option<u32>,
 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) -> usize {
 98        match self {
 99            Self::Chat | Self::Reasoner => 64_000,
100            Self::Custom { max_tokens, .. } => *max_tokens,
101        }
102    }
103
104    pub fn max_output_tokens(&self) -> Option<u32> {
105        match self {
106            Self::Chat => Some(8_192),
107            Self::Reasoner => Some(8_192),
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<u32>,
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: u32,
205    pub completion_tokens: u32,
206    pub total_tokens: u32,
207    #[serde(default)]
208    pub prompt_cache_hit_tokens: u32,
209    #[serde(default)]
210    pub prompt_cache_miss_tokens: u32,
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}
228
229#[derive(Serialize, Deserialize, Debug)]
230pub struct StreamChoice {
231    pub index: u32,
232    pub delta: StreamDelta,
233    pub finish_reason: Option<String>,
234}
235
236#[derive(Serialize, Deserialize, Debug)]
237pub struct StreamDelta {
238    pub role: Option<Role>,
239    pub content: Option<String>,
240    #[serde(default, skip_serializing_if = "Option::is_none")]
241    pub tool_calls: Option<Vec<ToolCallChunk>>,
242    #[serde(default, skip_serializing_if = "Option::is_none")]
243    pub reasoning_content: Option<String>,
244}
245
246#[derive(Serialize, Deserialize, Debug)]
247pub struct ToolCallChunk {
248    pub index: usize,
249    pub id: Option<String>,
250    pub function: Option<FunctionChunk>,
251}
252
253#[derive(Serialize, Deserialize, Debug)]
254pub struct FunctionChunk {
255    pub name: Option<String>,
256    pub arguments: Option<String>,
257}
258
259pub async fn stream_completion(
260    client: &dyn HttpClient,
261    api_url: &str,
262    api_key: &str,
263    request: Request,
264) -> Result<BoxStream<'static, Result<StreamResponse>>> {
265    let uri = format!("{api_url}/v1/chat/completions");
266    let request_builder = HttpRequest::builder()
267        .method(Method::POST)
268        .uri(uri)
269        .header("Content-Type", "application/json")
270        .header("Authorization", format!("Bearer {}", api_key));
271
272    let request = request_builder.body(AsyncBody::from(serde_json::to_string(&request)?))?;
273    let mut response = client.send(request).await?;
274
275    if response.status().is_success() {
276        let reader = BufReader::new(response.into_body());
277        Ok(reader
278            .lines()
279            .filter_map(|line| async move {
280                match line {
281                    Ok(line) => {
282                        let line = line.strip_prefix("data: ")?;
283                        if line == "[DONE]" {
284                            None
285                        } else {
286                            match serde_json::from_str(line) {
287                                Ok(response) => Some(Ok(response)),
288                                Err(error) => Some(Err(anyhow!(error))),
289                            }
290                        }
291                    }
292                    Err(error) => Some(Err(anyhow!(error))),
293                }
294            })
295            .boxed())
296    } else {
297        let mut body = String::new();
298        response.body_mut().read_to_string(&mut body).await?;
299        anyhow::bail!(
300            "Failed to connect to DeepSeek API: {} {}",
301            response.status(),
302            body,
303        );
304    }
305}