openai-interface 0.8.1

A low-level Rust interface for the OpenAI API
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
//! Streaming event types for the Responses API.
//!
//! When `stream: true`, the server returns a sequence of semantic SSE
//! events instead of a single response object. Every event carries an
//! incrementing `sequence_number`; the stream ends with
//! `response.completed`, `response.incomplete`, or `response.failed`
//! (there is **no** `data: [DONE]` sentinel).
//!
//! The event set follows the OpenAI Responses streaming events together
//! with the subsets documented by
//! [DeepSeek](https://api-docs.deepseek.com/guides/responses_api#streaming)
//! and
//! [Qwen](https://www.alibabacloud.com/help/zh/model-studio/qwen-api-via-openai-responses).
//! Events not modeled explicitly deserialize to
//! [`ResponseStreamEvent::Other`].

use serde::Deserialize;

use crate::responses::{Response, ResponseOutputItem};

/// One event of a streamed Responses API call.
///
/// Use [`Self::final_response`] to extract the finished [`Response`] from
/// the terminal `response.completed` / `response.incomplete` /
/// `response.failed` events.
#[derive(Debug, Deserialize, Clone)]
#[serde(tag = "type")]
pub enum ResponseStreamEvent {
    /// First event: the response was created, status `in_progress`.
    #[serde(rename = "response.created")]
    ResponseCreated {
        #[serde(default)]
        sequence_number: Option<u64>,
        response: Response,
    },

    /// The response is being generated.
    #[serde(rename = "response.in_progress")]
    ResponseInProgress {
        #[serde(default)]
        sequence_number: Option<u64>,
        response: Response,
    },

    /// The response completed normally; final event with the full
    /// response object including `usage`.
    #[serde(rename = "response.completed")]
    ResponseCompleted {
        #[serde(default)]
        sequence_number: Option<u64>,
        response: Response,
    },

    /// The response was truncated (e.g. `max_output_tokens` reached);
    /// final event with the full response object.
    #[serde(rename = "response.incomplete")]
    ResponseIncomplete {
        #[serde(default)]
        sequence_number: Option<u64>,
        response: Response,
    },

    /// The response failed; final event with the full response object
    /// including the `error` details.
    #[serde(rename = "response.failed")]
    ResponseFailed {
        #[serde(default)]
        sequence_number: Option<u64>,
        response: Response,
    },

    /// An error event emitted mid-stream.
    #[serde(rename = "error")]
    Error {
        #[serde(default)]
        sequence_number: Option<u64>,
        /// A human-readable description of the error.
        #[serde(default)]
        message: Option<String>,
        /// The machine-readable error code.
        #[serde(default)]
        code: Option<String>,
        /// The request parameter that caused the error, if any.
        #[serde(default)]
        param: Option<String>,
    },

    /// An output item (reasoning, message, tool call, ...) started.
    #[serde(rename = "response.output_item.added")]
    OutputItemAdded {
        #[serde(default)]
        sequence_number: Option<u64>,
        /// The index of the item in the `output` array.
        #[serde(default)]
        output_index: Option<u32>,
        /// The item that was added.
        item: ResponseOutputItem,
    },

    /// An output item completed.
    #[serde(rename = "response.output_item.done")]
    OutputItemDone {
        #[serde(default)]
        sequence_number: Option<u64>,
        #[serde(default)]
        output_index: Option<u32>,
        /// The completed item.
        item: ResponseOutputItem,
    },

    /// A content part started within an output item.
    #[serde(rename = "response.content_part.added")]
    ContentPartAdded {
        #[serde(default)]
        sequence_number: Option<u64>,
        /// The ID of the item the content part belongs to.
        #[serde(default)]
        item_id: Option<String>,
        #[serde(default)]
        output_index: Option<u32>,
        /// The index of the content part within the item.
        #[serde(default)]
        content_index: Option<u32>,
        /// The content part that was added.
        part: EventContentPart,
    },

    /// A content part completed.
    #[serde(rename = "response.content_part.done")]
    ContentPartDone {
        #[serde(default)]
        sequence_number: Option<u64>,
        #[serde(default)]
        item_id: Option<String>,
        #[serde(default)]
        output_index: Option<u32>,
        #[serde(default)]
        content_index: Option<u32>,
        /// The completed content part.
        part: EventContentPart,
    },

    /// An incremental text delta of an output message.
    #[serde(rename = "response.output_text.delta")]
    OutputTextDelta {
        #[serde(default)]
        sequence_number: Option<u64>,
        #[serde(default)]
        item_id: Option<String>,
        #[serde(default)]
        output_index: Option<u32>,
        #[serde(default)]
        content_index: Option<u32>,
        /// The incremental text.
        delta: String,
    },

    /// The full output text of a message content part.
    #[serde(rename = "response.output_text.done")]
    OutputTextDone {
        #[serde(default)]
        sequence_number: Option<u64>,
        #[serde(default)]
        item_id: Option<String>,
        #[serde(default)]
        output_index: Option<u32>,
        #[serde(default)]
        content_index: Option<u32>,
        /// The complete text.
        text: String,
    },

    /// An incremental reasoning (chain-of-thought) text delta.
    #[serde(rename = "response.reasoning_text.delta")]
    ReasoningTextDelta {
        #[serde(default)]
        sequence_number: Option<u64>,
        #[serde(default)]
        item_id: Option<String>,
        #[serde(default)]
        output_index: Option<u32>,
        #[serde(default)]
        content_index: Option<u32>,
        /// The incremental reasoning text.
        delta: String,
    },

    /// The full reasoning (chain-of-thought) text of a reasoning item.
    #[serde(rename = "response.reasoning_text.done")]
    ReasoningTextDone {
        #[serde(default)]
        sequence_number: Option<u64>,
        #[serde(default)]
        item_id: Option<String>,
        #[serde(default)]
        output_index: Option<u32>,
        #[serde(default)]
        content_index: Option<u32>,
        /// The complete reasoning text.
        text: String,
    },

    /// An incremental delta of function call arguments.
    #[serde(rename = "response.function_call_arguments.delta")]
    FunctionCallArgumentsDelta {
        #[serde(default)]
        sequence_number: Option<u64>,
        #[serde(default)]
        item_id: Option<String>,
        #[serde(default)]
        output_index: Option<u32>,
        /// The incremental arguments JSON fragment.
        delta: String,
    },

    /// The full arguments of a function call.
    #[serde(rename = "response.function_call_arguments.done")]
    FunctionCallArgumentsDone {
        #[serde(default)]
        sequence_number: Option<u64>,
        #[serde(default)]
        item_id: Option<String>,
        #[serde(default)]
        output_index: Option<u32>,
        /// The complete arguments JSON string.
        arguments: String,
    },

    /// An incremental delta of custom tool call input (e.g. the
    /// `apply_patch` tool).
    #[serde(rename = "response.custom_tool_call_input.delta")]
    CustomToolCallInputDelta {
        #[serde(default)]
        sequence_number: Option<u64>,
        #[serde(default)]
        item_id: Option<String>,
        #[serde(default)]
        output_index: Option<u32>,
        /// The incremental input fragment.
        delta: String,
    },

    /// The full input of a custom tool call.
    #[serde(rename = "response.custom_tool_call_input.done")]
    CustomToolCallInputDone {
        #[serde(default)]
        sequence_number: Option<u64>,
        #[serde(default)]
        item_id: Option<String>,
        #[serde(default)]
        output_index: Option<u32>,
        /// The complete input.
        input: String,
    },

    /// A server-side web search started.
    #[serde(rename = "response.web_search_call.in_progress")]
    WebSearchCallInProgress {
        #[serde(default)]
        sequence_number: Option<u64>,
        #[serde(default)]
        item_id: Option<String>,
        #[serde(default)]
        output_index: Option<u32>,
    },

    /// A server-side web search is searching.
    #[serde(rename = "response.web_search_call.searching")]
    WebSearchCallSearching {
        #[serde(default)]
        sequence_number: Option<u64>,
        #[serde(default)]
        item_id: Option<String>,
        #[serde(default)]
        output_index: Option<u32>,
    },

    /// A server-side web search completed.
    #[serde(rename = "response.web_search_call.completed")]
    WebSearchCallCompleted {
        #[serde(default)]
        sequence_number: Option<u64>,
        #[serde(default)]
        item_id: Option<String>,
        #[serde(default)]
        output_index: Option<u32>,
    },

    /// Qwen: an incremental delta of MCP tool call arguments.
    #[cfg(feature = "qwen")]
    #[serde(rename = "response.mcp_call_arguments.delta")]
    McpCallArgumentsDelta {
        #[serde(default)]
        sequence_number: Option<u64>,
        #[serde(default)]
        item_id: Option<String>,
        #[serde(default)]
        output_index: Option<u32>,
        /// The incremental arguments JSON fragment.
        delta: String,
    },

    /// Qwen: the full arguments of an MCP tool call.
    #[cfg(feature = "qwen")]
    #[serde(rename = "response.mcp_call_arguments.done")]
    McpCallArgumentsDone {
        #[serde(default)]
        sequence_number: Option<u64>,
        #[serde(default)]
        item_id: Option<String>,
        #[serde(default)]
        output_index: Option<u32>,
        /// The complete arguments JSON string.
        arguments: String,
    },

    /// Qwen: an MCP tool call completed.
    #[cfg(feature = "qwen")]
    #[serde(rename = "response.mcp_call.completed")]
    McpCallCompleted {
        #[serde(default)]
        sequence_number: Option<u64>,
        #[serde(default)]
        item_id: Option<String>,
        #[serde(default)]
        output_index: Option<u32>,
    },

    /// Qwen: a knowledge-base search started.
    #[cfg(feature = "qwen")]
    #[serde(rename = "response.file_search_call.in_progress")]
    FileSearchCallInProgress {
        #[serde(default)]
        sequence_number: Option<u64>,
        #[serde(default)]
        item_id: Option<String>,
        #[serde(default)]
        output_index: Option<u32>,
    },

    /// Qwen: a knowledge-base search is searching.
    #[cfg(feature = "qwen")]
    #[serde(rename = "response.file_search_call.searching")]
    FileSearchCallSearching {
        #[serde(default)]
        sequence_number: Option<u64>,
        #[serde(default)]
        item_id: Option<String>,
        #[serde(default)]
        output_index: Option<u32>,
    },

    /// Qwen: a knowledge-base search completed.
    #[cfg(feature = "qwen")]
    #[serde(rename = "response.file_search_call.completed")]
    FileSearchCallCompleted {
        #[serde(default)]
        sequence_number: Option<u64>,
        #[serde(default)]
        item_id: Option<String>,
        #[serde(default)]
        output_index: Option<u32>,
    },

    /// Any event type not covered by the variants above.
    #[serde(other)]
    Other,
}

impl ResponseStreamEvent {
    /// Returns the final response object if this is one of the terminal
    /// events (`response.completed`, `response.incomplete`,
    /// `response.failed`).
    pub fn final_response(&self) -> Option<&Response> {
        match self {
            Self::ResponseCompleted { response, .. }
            | Self::ResponseIncomplete { response, .. }
            | Self::ResponseFailed { response, .. } => Some(response),
            _ => None,
        }
    }
}

/// A content part carried by `response.content_part.added` /
/// `response.content_part.done` events.
#[derive(Debug, Deserialize, Clone)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum EventContentPart {
    /// A text output part.
    OutputText {
        /// The text content.
        #[serde(default)]
        text: Option<String>,
    },
    /// A reasoning text part.
    ReasoningText {
        /// The reasoning text.
        #[serde(default)]
        text: Option<String>,
    },
    /// A refusal part.
    Refusal {
        /// The refusal message.
        #[serde(default)]
        refusal: Option<String>,
    },
    /// Any content part type not covered above.
    #[serde(other)]
    Other,
}

crate::impl_from_str!(ResponseStreamEvent);

#[cfg(test)]
mod tests {
    //! Offline deserialization tests using event payloads copied from the
    //! DeepSeek streaming documentation example.

    use std::str::FromStr;

    use super::*;
    use crate::responses::{ResponseObject, ResponseOutputItem};

    /// From the streaming example at
    /// <https://api-docs.deepseek.com/api/create-response>.
    #[test]
    fn parses_documented_stream_events() {
        let created = ResponseStreamEvent::from_str(
            r#"{"type": "response.created", "sequence_number": 0, "response": {"id": "resp_1", "object": "response", "created_at": 0, "status": "in_progress", "model": "deepseek-v4-flash", "output": []}}"#,
        ).unwrap();
        assert!(matches!(
            created,
            ResponseStreamEvent::ResponseCreated { .. }
        ));

        let delta = ResponseStreamEvent::from_str(
            r#"{"type": "response.reasoning_text.delta", "sequence_number": 4, "item_id": "rs_1", "output_index": 0, "content_index": 0, "delta": "The user"}"#,
        ).unwrap();
        match delta {
            ResponseStreamEvent::ReasoningTextDelta { delta, item_id, .. } => {
                assert_eq!(delta, "The user");
                assert_eq!(item_id.as_deref(), Some("rs_1"));
            }
            other => panic!("unexpected event: {other:?}"),
        }

        let text_delta = ResponseStreamEvent::from_str(
            r#"{"type": "response.output_text.delta", "sequence_number": 11, "item_id": "msg_1", "output_index": 1, "content_index": 0, "delta": "Hello"}"#,
        ).unwrap();
        assert!(matches!(
            text_delta,
            ResponseStreamEvent::OutputTextDelta { .. }
        ));
    }

    #[test]
    fn parses_completed_event_and_extracts_response() {
        let event = ResponseStreamEvent::from_str(
            r#"{"type": "response.completed", "sequence_number": 20, "response": {"id": "resp_1", "object": "response", "created_at": 0, "status": "completed", "model": "deepseek-v4-flash", "output": [{"type": "message", "id": "msg_1", "status": "completed", "role": "assistant", "content": [{"type": "output_text", "text": "Hi!", "annotations": []}]}], "usage": {"input_tokens": 1, "output_tokens": 2, "total_tokens": 3}}}"#,
        ).unwrap();

        let response = event.final_response().expect("terminal event");
        assert_eq!(response.object, ResponseObject::Response);
        assert!(response.is_completed());
        assert_eq!(response.output_text(), "Hi!");
        assert!(matches!(
            response.output.first(),
            Some(ResponseOutputItem::Message(_))
        ));
    }

    #[test]
    fn unknown_event_type_is_preserved() {
        let event = ResponseStreamEvent::from_str(
            r#"{"type": "response.some_future_event", "sequence_number": 3}"#,
        )
        .unwrap();
        assert!(matches!(event, ResponseStreamEvent::Other));
    }
}