deepseek-sdk 0.3.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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
use super::*;

/// A response object in the OpenAI Responses API format.
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct Response {
    /// A unique identifier for the response.
    pub id: String,

    /// The object type, which is always `response`.
    pub object: String,

    /// The Unix timestamp (in seconds) of when the response was created.
    pub created_at: u64,

    /// The status of the response.
    pub status: ResponseStatus,

    /// The error object when the response failed, with `code` and `message` fields.
    #[serde(default)]
    pub error: Option<ResponseError>,

    /// The details about why the response is incomplete.
    #[serde(default)]
    pub incomplete_details: Option<IncompleteDetails>,

    /// The model used for the response.
    pub model: String,

    /// The list of output items generated by the model. In thinking mode, the chain-of-thought
    /// is returned as a `reasoning` item before the `message` item. Function calls are returned
    /// as `function_call` items, and server-side web search actions as `web_search_call` items.
    #[serde(default)]
    pub output: Vec<OutputItem>,

    /// Token usage statistics for the response.
    /// Present on final events and non-streaming responses; `null` on intermediate stream events.
    #[serde(default)]
    pub usage: Option<Usage>,

    /// Whether the response is stored on the server. DeepSeek is stateless and always returns `false`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub store: Option<bool>,

    /// Whether the model may call multiple tools in parallel. DeepSeek always returns `true`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parallel_tool_calls: Option<bool>,

    /// The ID of the previous response. DeepSeek is stateless and always returns `null`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub previous_response_id: Option<String>,
}

impl Response {
    /// Concatenate the plain-text output of all `output_text` content parts of `message` items.
    pub fn output_text(&self) -> String {
        let mut text = String::new();
        for item in &self.output {
            if let OutputItem::Message { content, .. } = item {
                for part in content {
                    if let ContentPart::OutputText {
                        text: part_text, ..
                    } = part
                    {
                        text.push_str(part_text);
                    }
                }
            }
        }
        text
    }

    /// Concatenate the chain-of-thought text of all `reasoning_text` content parts of `reasoning` items.
    pub fn reasoning_text(&self) -> String {
        let mut text = String::new();
        for item in &self.output {
            if let OutputItem::Reasoning { content, .. } = item {
                for part in content {
                    if let ContentPart::ReasoningText {
                        text: part_text, ..
                    } = part
                    {
                        text.push_str(part_text);
                    }
                }
            }
        }
        text
    }
}

/// The status of a response.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ResponseStatus {
    InProgress,
    Completed,
    Incomplete,
    Failed,
}

/// Error details of a failed response.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct ResponseError {
    #[serde(default)]
    pub code: Option<String>,
    #[serde(default)]
    pub message: Option<String>,
}

/// The details about why a response is incomplete.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct IncompleteDetails {
    /// The reason the response is incomplete.
    pub reason: IncompleteReason,
}

/// Reason why a response is incomplete.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum IncompleteReason {
    MaxOutputTokens,
    ContentFilter,
}

/// An output item generated by the model.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum OutputItem {
    /// A message item. The role is always `assistant`.
    Message {
        /// The unique ID of the output item.
        id: String,
        /// The status of the output item.
        #[serde(default)]
        status: Option<OutputItemStatus>,
        /// The role of the author of this message. Always `assistant`.
        #[serde(default)]
        role: Option<MessageRole>,
        /// A list of `output_text` content parts.
        #[serde(default)]
        content: Vec<ContentPart>,
        /// Annotations attached to the content parts.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        annotations: Vec<serde_json::Value>,
    },
    /// A reasoning (chain-of-thought) item.
    Reasoning {
        /// The unique ID of the output item.
        id: String,
        /// The status of the output item.
        #[serde(default)]
        status: Option<OutputItemStatus>,
        /// A list of `reasoning_text` content parts carrying the chain-of-thought in plain text.
        #[serde(default)]
        content: Vec<ContentPart>,
        /// An optional summary of the reasoning, currently not generated by DeepSeek.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        summary: Vec<serde_json::Value>,
    },
    /// A function call item.
    FunctionCall {
        /// The unique ID of the output item.
        id: String,
        /// An identifier used when passing the function output back to the API.
        #[serde(default)]
        call_id: Option<String>,
        /// The name of the function to call.
        name: String,
        /// The arguments to call the function with, as generated by the model in JSON format.
        arguments: String,
    },
    /// A server-side web search call item.
    WebSearchCall {
        /// The unique ID of the output item.
        id: String,
        /// An object describing the search action executed on the server side.
        #[serde(default)]
        action: Option<WebSearchAction>,
    },
    /// An unrecognized output item type, tolerated during deserialization.
    #[serde(other)]
    Unknown,
}

/// A content part of an output item.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ContentPart {
    /// Visible output text of a `message` item.
    OutputText {
        /// The text content.
        text: String,
        /// Annotations attached to the text.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        annotations: Vec<serde_json::Value>,
    },
    /// Chain-of-thought text of a `reasoning` item.
    ReasoningText {
        /// The text content.
        text: String,
    },
    /// An unrecognized content part type, tolerated during deserialization.
    #[serde(other)]
    Unknown,
}

/// The status of an output item.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum OutputItemStatus {
    InProgress,
    Completed,
    Incomplete,
}

/// Role of a message output item.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum MessageRole {
    Assistant,
    #[serde(other)]
    Unknown,
}

/// A server-side web search action.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct WebSearchAction {
    /// The type of the search action.
    #[serde(rename = "type")]
    pub typ: WebSearchActionType,
}

/// The type of a server-side web search action.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum WebSearchActionType {
    Search,
    OpenPage,
    FindInPage,
    #[serde(other)]
    Unknown,
}

/// Token usage statistics for a response.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct Usage {
    /// Number of input tokens.
    pub input_tokens: u64,

    /// Breakdown of the input tokens.
    #[serde(default)]
    pub input_tokens_details: Option<InputTokensDetails>,

    /// Number of output tokens.
    pub output_tokens: u64,

    /// Breakdown of the output tokens.
    #[serde(default)]
    pub output_tokens_details: Option<OutputTokensDetails>,

    /// Total number of tokens used in the request (input + output).
    pub total_tokens: u64,
}

/// Breakdown of the input tokens.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct InputTokensDetails {
    /// Number of input tokens that hit the context cache.
    #[serde(default)]
    pub cached_tokens: Option<u64>,
}

/// Breakdown of the output tokens.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct OutputTokensDetails {
    /// Number of reasoning (chain-of-thought) tokens generated by the model.
    #[serde(default)]
    pub reasoning_tokens: Option<u64>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn deserialize_response_example() {
        let value = json!({
            "id": "24778070-1c36-4ae0-a4bd-870afc7fc13e",
            "object": "response",
            "created_at": 1753000000,
            "status": "completed",
            "model": "deepseek-v4-flash",
            "output": [
                {
                    "type": "reasoning",
                    "id": "rs_1",
                    "status": "completed",
                    "content": [
                        {"type": "reasoning_text", "text": "The user greets me. I should reply politely."}
                    ],
                    "summary": []
                },
                {
                    "type": "message",
                    "id": "msg_1",
                    "status": "completed",
                    "role": "assistant",
                    "content": [
                        {"type": "output_text", "text": "Hello! How can I help you today?", "annotations": []}
                    ]
                }
            ],
            "usage": {
                "input_tokens": 22,
                "input_tokens_details": {"cached_tokens": 0},
                "output_tokens": 29,
                "output_tokens_details": {"reasoning_tokens": 27},
                "total_tokens": 51
            },
            "store": false,
            "parallel_tool_calls": true,
            "previous_response_id": null,
            "error": null,
            "incomplete_details": null
        });

        let response: Response = serde_json::from_value(value).unwrap();
        assert_eq!(response.id, "24778070-1c36-4ae0-a4bd-870afc7fc13e");
        assert_eq!(response.status, ResponseStatus::Completed);
        assert_eq!(response.output.len(), 2);
        assert_eq!(response.output_text(), "Hello! How can I help you today?");
        assert_eq!(
            response.reasoning_text(),
            "The user greets me. I should reply politely."
        );
        assert_eq!(response.usage.as_ref().unwrap().total_tokens, 51);
        assert_eq!(
            response
                .usage
                .as_ref()
                .unwrap()
                .output_tokens_details
                .as_ref()
                .unwrap()
                .reasoning_tokens,
            Some(27)
        );
    }

    #[test]
    fn deserialize_function_call_and_unknown_items() {
        let value = json!({
            "id": "r_1",
            "object": "response",
            "created_at": 1753000000,
            "status": "completed",
            "model": "deepseek-v4-flash",
            "output": [
                {
                    "type": "function_call",
                    "id": "fc_1",
                    "call_id": "call_1",
                    "name": "get_weather",
                    "arguments": "{\"location\":\"Hangzhou\"}"
                },
                {"type": "mystery_item", "id": "x_1"}
            ],
            "usage": {
                "input_tokens": 10,
                "output_tokens": 20,
                "total_tokens": 30
            }
        });

        let response: Response = serde_json::from_value(value).unwrap();
        assert_eq!(response.output.len(), 2);
        assert!(
            matches!(&response.output[0], OutputItem::FunctionCall { name, .. } if name == "get_weather")
        );
        assert!(matches!(&response.output[1], OutputItem::Unknown));
    }

    #[test]
    fn serde_roundtrip() {
        let response = Response {
            id: "r_1".to_string(),
            object: "response".to_string(),
            created_at: 1753000000,
            status: ResponseStatus::Completed,
            error: None,
            incomplete_details: None,
            model: "deepseek-v4-flash".to_string(),
            output: vec![OutputItem::Message {
                id: "msg_1".to_string(),
                status: Some(OutputItemStatus::Completed),
                role: Some(MessageRole::Assistant),
                content: vec![ContentPart::OutputText {
                    text: "Hi".to_string(),
                    annotations: vec![],
                }],
                annotations: vec![],
            }],
            usage: Some(Usage {
                input_tokens: 1,
                input_tokens_details: None,
                output_tokens: 1,
                output_tokens_details: None,
                total_tokens: 2,
            }),
            store: Some(false),
            parallel_tool_calls: Some(true),
            previous_response_id: None,
        };

        let value = serde_json::to_value(&response).unwrap();
        let back: Response = serde_json::from_value(value).unwrap();
        assert_eq!(back, response);
    }
}