deepseek-sdk 0.7.0

DeepSeek API client for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
#![deny(unsafe_code)]

//! DeepSeek API client for Rust.
//!
//! This crate provides:
//! - Chat completions (`/chat/completions`), including function and DeepSeek web tools (`deepseek_web_search`, `deepseek_read_url`)
//! - FIM completions (beta, `/beta/completions`)
//! - Responses API (OpenAI Responses format, `/responses`)
//! - Model listing (`/models`)
//! - Account balance (`/user/balance`)
//! - Files API (`/files`) for uploading and managing images
//! - Web search, web fetch, text-to-speech, OCR, and speech-to-text (`/v1/tools/search`, `/v1/tools/fetch`, `/v1/tools/tts`, `/v1/tools/ocr`, `/v1/tools/asr`)
//!
//! Streaming is supported in both async and blocking forms. The async API returns
//! a `tokio::mpsc::Receiver`, while the blocking API returns an iterator that
//! yields stream items.
//!
//! ```ignore
//! use deepseek_sdk::chat::request::{ChatMessage, ChatRequestBuilder, Thinking};
//! use deepseek_sdk::{DeepSeekClient, DeepSeekRequest, DEFAULT_BASE_URL};
//!
//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
//! let req = ChatRequestBuilder::default()
//!     .client(DeepSeekClient::new("sk-...", DEFAULT_BASE_URL.clone()))
//!     .model("deepseek-flash")
//!     .message(ChatMessage::User { content: "Hi".into(), name: None })
//!     .thinking(Thinking::disabled())
//!     .build()?;
//! let _resp = req.send().await?;
//! # Ok(()) }
//! ```
/// Account balance (`/user/balance`).
#[cfg(feature = "balance")]
pub mod balance;
/// Chat completions (`/chat/completions`).
#[cfg(feature = "chat")]
pub mod chat;
/// Beta completions (FIM, beta chat).
#[cfg(feature = "completion")]
pub mod completion;
pub mod error;
/// Files API (`/files`) for uploading and managing images.
#[cfg(feature = "files")]
pub mod files;
/// Model listing (`/models`).
#[cfg(feature = "models")]
pub mod models;
/// Open AI Responses format
#[cfg(feature = "responses")]
pub mod responses;
/// Web search, web fetch, text-to-speech, OCR, and speech-to-text (`/v1/tools`).
#[cfg(feature = "tools")]
pub mod tools;

use crate::error::{ApiErrorEnvelope, DeepSeekError};

use futures_util::StreamExt;
use reqwest::{Client, Method, RequestBuilder, Response, header::AUTHORIZATION};
use reqwest_eventsource::{Event, EventSource, RequestBuilderExt};
use serde::{Serialize, de::DeserializeOwned};
use std::future::Future;
use std::sync::LazyLock;
use tokio::sync::mpsc;

/// Default base URL for stable API endpoints.
pub static DEFAULT_BASE_URL: LazyLock<String> =
    LazyLock::new(|| String::from("https://api.deepseek.com"));
/// Default base URL for beta endpoints (e.g. FIM completion).
pub static DEFAULT_BETA_BASE_URL: LazyLock<String> =
    LazyLock::new(|| String::from("https://api.deepseek.com/beta"));

/// API credentials for a DeepSeek endpoint.
#[derive(Clone, Debug, Eq, PartialEq)]
struct Credentials {
    pub(crate) api_key: String,
    pub(crate) base_url: String,
}

#[derive(Clone, Debug)]
pub struct DeepSeekClient {
    pub(crate) credentials: Credentials,
    pub client: Client,
}

impl PartialEq for DeepSeekClient {
    fn eq(&self, other: &Self) -> bool {
        self.credentials == other.credentials
    }
}

impl Eq for DeepSeekClient {}

impl DeepSeekClient {
    pub fn new(api_key: impl Into<String>, base_url: impl Into<String>) -> Self {
        DeepSeekClient {
            credentials: Credentials::new(api_key, base_url),
            client: Client::new(),
        }
    }

    pub fn with_client(mut self, client: Client) -> Self {
        self.client = client;
        self
    }

    pub fn with_credentials(
        mut self,
        api_key: impl Into<String>,
        base_url: impl Into<String>,
    ) -> Self {
        self.credentials = Credentials::new(api_key, base_url);
        self
    }
}

impl Credentials {
    /// Create credentials with an API key and base URL.
    pub(crate) fn new(api_key: impl Into<String>, base_url: impl Into<String>) -> Self {
        Credentials {
            api_key: api_key.into(),
            base_url: base_url.into(),
        }
    }
}

/// Unified request interface for DeepSeek endpoints.
///
/// Requests that support streaming should return stream items through `stream`
/// and a blocking iterator through `stream_blocking`.
pub trait DeepSeekRequest: Sized {
    /// Full response type for non-streaming calls.
    type Response;

    /// Item type emitted by streaming calls.
    type StreamItem;
    /// Blocking stream iterator type.
    type BlockingStream: Iterator<Item = Self::StreamItem>;

    /// Send a non-streaming request.
    fn send(self) -> impl Future<Output = Result<Self::Response, DeepSeekError>> + Send;
    /// Send a streaming request (SSE), returning a receiver of stream items.
    fn stream(
        self,
    ) -> impl Future<Output = Result<mpsc::Receiver<Self::StreamItem>, DeepSeekError>> + Send;
    /// Send a streaming request but consume results via a blocking iterator.
    fn stream_blocking(self) -> Result<Self::BlockingStream, DeepSeekError>;
}

async fn api_request_json<F, T>(
    method: Method,
    route: &str,
    builder: F,
    deepseek_client: DeepSeekClient,
) -> Result<T, DeepSeekError>
where
    F: FnOnce(RequestBuilder) -> RequestBuilder,
    T: DeserializeOwned,
{
    let response = api_request(method, route, builder, deepseek_client).await?;
    let response = check_response(response).await?;
    let text = response.text().await?;

    serde_json::from_str::<T>(&text).map_err(|err| DeepSeekError::decode(err.to_string(), text))
}

/// Map a non-success HTTP response to a structured [`DeepSeekError`].
///
/// Returns the response unchanged when the status is successful.
async fn check_response(response: Response) -> Result<Response, DeepSeekError> {
    let status = response.status();
    if status.is_success() {
        return Ok(response);
    }

    let text = response.text().await?;

    if let Ok(envelope) = serde_json::from_str::<ApiErrorEnvelope>(&text) {
        return Err(DeepSeekError::api(
            envelope.error,
            Some(status.as_u16()),
            Some(text),
        ));
    }

    Err(DeepSeekError::http(status.as_u16(), text))
}

async fn api_request<F>(
    method: Method,
    route: &str,
    builder: F,
    deepseek_client: DeepSeekClient,
) -> Result<Response, DeepSeekError>
where
    F: FnOnce(RequestBuilder) -> RequestBuilder,
{
    let client = deepseek_client.client;
    let mut request = client.request(
        method,
        format!("{}{route}", deepseek_client.credentials.base_url),
    );
    request = builder(request);
    let response = request
        .header(
            AUTHORIZATION,
            format!("Bearer {}", deepseek_client.credentials.api_key),
        )
        .send()
        .await?;
    Ok(response)
}

async fn api_request_stream<F>(
    method: Method,
    route: &str,
    builder: F,
    deepseek_client: DeepSeekClient,
) -> Result<EventSource, DeepSeekError>
where
    F: FnOnce(RequestBuilder) -> RequestBuilder,
{
    let mut request = deepseek_client.client.request(
        method,
        format!("{}{route}", deepseek_client.credentials.base_url),
    );
    request = builder(request);
    let stream = request
        .header(
            AUTHORIZATION,
            format!("Bearer {}", deepseek_client.credentials.api_key),
        )
        .eventsource()
        .map_err(|err| DeepSeekError::decode(err.to_string(), String::new()))?;
    Ok(stream)
}

/// Consume an SSE event source, mapping each `data:` payload through `parse`.
///
/// `Ok(Some(item))` forwards the item downstream, `Ok(None)` ends the stream
/// cleanly, and `Err(err)` forwards the error and ends the stream. A clean EOF
/// (which the Responses API uses instead of a `data: [DONE]` message) is treated
/// as normal stream termination.
pub(crate) fn consume_sse<T, F>(
    mut event_source: EventSource,
    mut parse: F,
) -> mpsc::Receiver<Result<T, DeepSeekError>>
where
    T: Send + 'static,
    F: FnMut(String) -> Result<Option<T>, DeepSeekError> + Send + 'static,
{
    let (tx, rx) = mpsc::channel(32);

    tokio::spawn(async move {
        while let Some(event) = event_source.next().await {
            match event {
                Ok(Event::Open) => {}
                Ok(Event::Message(message)) => {
                    if message.data == "[DONE]" {
                        break;
                    }
                    match parse(message.data) {
                        Ok(Some(item)) => {
                            if tx.send(Ok(item)).await.is_err() {
                                break;
                            }
                        }
                        Ok(None) => break,
                        Err(err) => {
                            let _ = tx.send(Err(err)).await;
                            break;
                        }
                    }
                }
                Err(err) => {
                    if matches!(err, reqwest_eventsource::Error::StreamEnded) {
                        break;
                    }
                    let _ = tx
                        .send(Err(DeepSeekError::decode(err.to_string(), String::new())))
                        .await;
                    break;
                }
            }
        }
    });

    rx
}

/// Drive `fut` to a stream receiver on a dedicated std thread with its own Tokio
/// runtime, forwarding items to a blocking `std::sync::mpsc` receiver.
///
/// `T` is the success type of a stream item; the forwarded items are
/// `Result<T, DeepSeekError>`.
pub(crate) fn spawn_blocking_stream<T>(
    fut: impl Future<Output = Result<mpsc::Receiver<Result<T, DeepSeekError>>, DeepSeekError>>
    + Send
    + 'static,
) -> Result<std::sync::mpsc::Receiver<Result<T, DeepSeekError>>, DeepSeekError>
where
    T: Send + 'static,
{
    let (tx, rx) = std::sync::mpsc::channel();

    std::thread::spawn(move || {
        let runtime = match tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
        {
            Ok(runtime) => runtime,
            Err(err) => {
                let _ = tx.send(Err(DeepSeekError::decode(err.to_string(), String::new())));
                return;
            }
        };

        runtime.block_on(async move {
            match fut.await {
                Ok(mut stream_rx) => {
                    while let Some(item) = stream_rx.recv().await {
                        if tx.send(item).is_err() {
                            break;
                        }
                    }
                }
                Err(err) => {
                    let _ = tx.send(Err(err));
                }
            }
        });
    });

    Ok(rx)
}

/// Send a GET request and decode the JSON response.
async fn api_get<T>(route: &str, client: DeepSeekClient) -> Result<T, DeepSeekError>
where
    T: DeserializeOwned,
{
    api_request_json(Method::GET, route, |request| request, client).await
}

/// Send a POST request with JSON body and decode the response.
async fn api_post<J, T>(route: &str, json: &J, client: DeepSeekClient) -> Result<T, DeepSeekError>
where
    J: Serialize + ?Sized,
    T: DeserializeOwned,
{
    api_request_json(Method::POST, route, |request| request.json(json), client).await
}

/// Send a POST request with JSON body and return the raw response bytes.
async fn api_post_bytes<J>(
    route: &str,
    json: &J,
    client: DeepSeekClient,
) -> Result<Vec<u8>, DeepSeekError>
where
    J: Serialize + ?Sized,
{
    let response = api_request(Method::POST, route, |request| request.json(json), client).await?;
    let response = check_response(response).await?;
    Ok(response.bytes().await?.to_vec())
}

/// Send a POST request with JSON body and return the streaming response.
///
/// The caller consumes the body with [`Response::bytes_stream`]; non-success
/// statuses are mapped to [`DeepSeekError`] the same way as [`api_post`].
async fn api_post_byte_stream<J>(
    route: &str,
    json: &J,
    client: DeepSeekClient,
) -> Result<Response, DeepSeekError>
where
    J: Serialize + ?Sized,
{
    let response = api_request(Method::POST, route, |request| request.json(json), client).await?;
    check_response(response).await
}

/// Send a DELETE request and decode the JSON response.
async fn api_delete<T>(route: &str, client: DeepSeekClient) -> Result<T, DeepSeekError>
where
    T: DeserializeOwned,
{
    api_request_json(Method::DELETE, route, |request| request, client).await
}

/// Send a POST request with multipart form body and decode the JSON response.
async fn api_post_multipart<T>(
    route: &str,
    form: reqwest::multipart::Form,
    client: DeepSeekClient,
) -> Result<T, DeepSeekError>
where
    T: DeserializeOwned,
{
    api_request_json(
        Method::POST,
        route,
        |request| request.multipart(form),
        client,
    )
    .await
}