openai-interface 0.10.0

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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
//! The Responses API: create model responses and retrieve stored ones.
//!
//! The Responses API is the successor of the Chat Completions API. Instead
//! of `messages` it takes an `input` that is either a plain string or a list
//! of input items (`message`, `function_call`, `function_call_output`,
//! `reasoning`, ...), and instead of `choices` it returns a list of output
//! items.
//!
//! Request types live in [`create::request`], the shared response object and
//! the streaming event types in this module and [`create`], and the retrieve
//! endpoint in [`retrieve`].
//!
//! Provider support is partial — see
//! [the DeepSeek Responses API guide](https://api-docs.deepseek.com/guides/responses_api)
//! and
//! [the Qwen Responses API reference](https://www.alibabacloud.com/help/zh/model-studio/qwen-api-via-openai-responses).
//! Notably DeepSeek's implementation is stateless (`store`,
//! `previous_response_id` and retrieval are not supported there), while Qwen
//! supports multi-turn conversations via `previous_response_id`.
//!
//! # Example
//!
//! ```rust,no_run
//! use openai_interface::responses::create::request::{Input, RequestBody};
//! use openai_interface::rest::{default_client, post::PostNoStream};
//!
//! const DEEPSEEK_URL: &'static str = "https://api.deepseek.com";
//! const DEEPSEEK_MODEL: &'static str = "deepseek-v4-flash";
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     // Needs the `ferritls` cargo feature; drop this line if you install
//!     // your own rustls crypto provider (see `openai_interface::rest`).
//!     # #[cfg(feature = "ferritls")]
//!     openai_interface::rest::install_crypto_provider().ok();
//!
//!     let request = RequestBody {
//!         model: DEEPSEEK_MODEL.to_string(),
//!         input: Input::Text("Hello!".to_string()),
//!         ..Default::default()
//!     };
//!
//!     let response = request
//!         .get_response(&default_client(), DEEPSEEK_URL, "YOUR_API_KEY")
//!         .await?;
//!     println!("{}", response.output_text());
//!     Ok(())
//! }
//! ```

pub mod cancel;
pub mod create;
pub mod delete;
pub mod input_items;
pub mod retrieve;

use std::collections::HashMap;

use serde::Deserialize;

use crate::chat::ServiceTier;
use crate::responses::create::request::Truncation;

/// The response object returned by the Responses API (non-streaming create,
/// the final streaming events, and retrieve).
#[derive(Debug, Deserialize, Clone)]
pub struct Response {
    /// Unique identifier for this response.
    pub id: String,

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

    /// An error object returned when the model fails to generate a response.
    #[serde(default)]
    pub error: Option<ResponseError>,

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

    /// The system (or developer) message inserted into the model's context,
    /// echoed back when one was supplied.
    #[serde(default)]
    pub instructions: Option<String>,

    /// Set of key-value pairs attached to the response, echoed back when
    /// `metadata` was supplied in the request.
    #[serde(default)]
    pub metadata: Option<HashMap<String, String>>,

    /// The model that generated the response.
    pub model: String,

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

    /// The output items generated by the model (messages, reasoning, tool
    /// calls, ...).
    #[serde(default)]
    pub output: Vec<ResponseOutputItem>,

    /// Whether the model ran tool calls in parallel.
    #[serde(default)]
    pub parallel_tool_calls: Option<bool>,

    /// The unique ID of the previous response this one builds upon, when
    /// `previous_response_id` was used.
    #[serde(default)]
    pub previous_response_id: Option<String>,

    /// The sampling temperature used.
    #[serde(default)]
    pub temperature: Option<f32>,

    /// The nucleus sampling threshold used.
    #[serde(default)]
    pub top_p: Option<f32>,

    /// Whether the response is stored for later retrieval.
    #[serde(default)]
    pub store: Option<bool>,

    /// The status of the response generation.
    #[serde(default)]
    pub status: Option<ResponseStatus>,

    /// Usage statistics for the request.
    #[serde(default)]
    pub usage: Option<ResponseUsage>,

    /// Whether the response ran in the background (echo of the request
    /// parameter).
    #[serde(default)]
    pub background: Option<bool>,

    /// Unix timestamp (in seconds) of when this response completed. Only
    /// present when the status is `completed`.
    #[serde(default)]
    pub completed_at: Option<u64>,

    /// Upper bound for the number of tokens that could be generated (echo
    /// of the request parameter).
    #[serde(default)]
    pub max_output_tokens: Option<u32>,

    /// Maximum number of built-in tool calls processed in this response
    /// (echo of the request parameter).
    #[serde(default)]
    pub max_tool_calls: Option<u32>,

    /// Number of most likely tokens returned at each output position (echo
    /// of the request parameter).
    #[serde(default)]
    pub top_logprobs: Option<u32>,

    /// The truncation strategy used for the response (echo of the request
    /// parameter).
    #[serde(default)]
    pub truncation: Option<Truncation>,

    /// The service tier actually used to serve the request. May differ from
    /// the value requested.
    #[serde(default)]
    pub service_tier: Option<ServiceTier>,

    /// End-user identifier (echo of the request parameter).
    #[serde(default)]
    pub user: Option<String>,

    /// Stable identifier used for usage-policy violation detection (echo of
    /// the request parameter).
    #[serde(default)]
    pub safety_identifier: Option<String>,

    /// Prompt cache key (echo of the request parameter).
    #[serde(default)]
    pub prompt_cache_key: Option<String>,
}

impl Response {
    /// Whether this response completed successfully.
    pub fn is_completed(&self) -> bool {
        matches!(self.status, Some(ResponseStatus::Completed))
    }

    /// Aggregates all `output_text` content of the output `message` items
    /// into a single string, like the `output_text` property of the official
    /// SDKs. Returns an empty string when there is no text output.
    pub fn output_text(&self) -> String {
        let mut text = String::new();
        for item in &self.output {
            if let ResponseOutputItem::Message(message) = item {
                for part in &message.content {
                    if let OutputContent::OutputText { text: t, .. } = part {
                        text.push_str(t);
                    }
                }
            }
        }
        text
    }

    /// Aggregates the plain-text reasoning content of the output `reasoning`
    /// items into a single string. Returns an empty string when there is no
    /// plaintext reasoning content (e.g. when the provider only returns
    /// reasoning summaries or encrypted content).
    pub fn reasoning_text(&self) -> String {
        let mut text = String::new();
        for item in &self.output {
            if let ResponseOutputItem::Reasoning(reasoning) = item {
                for part in reasoning.content.as_deref().unwrap_or_default() {
                    let ReasoningContent::ReasoningText { text: t } = part;
                    text.push_str(t);
                }
            }
        }
        text
    }
}

/// The `object` field of a response object, always `response`.
#[derive(Debug, Deserialize, Clone, PartialEq, Eq)]
pub enum ResponseObject {
    #[serde(rename = "response")]
    Response,
}

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

/// An error object returned when the model fails to generate a response.
#[derive(Debug, Deserialize, Clone)]
pub struct ResponseError {
    /// The machine-readable error code, if the provider sends one.
    #[serde(default)]
    pub code: Option<String>,
    /// A human-readable description of the error.
    #[serde(default)]
    pub message: Option<String>,
}

/// Details about why the response is incomplete.
#[derive(Debug, Deserialize, Clone)]
pub struct IncompleteDetails {
    /// The reason why the response is incomplete.
    #[serde(default)]
    pub reason: Option<IncompleteReason>,
}

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

/// An item in the `output` array of a [`Response`].
///
/// Item types not modeled explicitly are preserved as
/// [`ResponseOutputItem::Other`] so that unknown or provider-specific items
/// do not break deserialization.
#[derive(Debug, Deserialize, Clone)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ResponseOutputItem {
    /// A message output from the model.
    Message(ResponseOutputMessage),
    /// A reasoning item from the model (chain-of-thought and/or summaries).
    Reasoning(ResponseReasoningItem),
    /// A call to a user-defined function.
    FunctionCall(ResponseFunctionCall),
    /// A web search performed by the server-side web search tool.
    WebSearchCall(ResponseWebSearchCall),
    /// Qwen: a call to a tool on an MCP server.
    #[cfg(feature = "qwen")]
    McpCall(McpCall),
    /// Qwen: a knowledge-base (file search) tool call.
    #[cfg(feature = "qwen")]
    FileSearchCall(FileSearchCall),
    /// Qwen: a code interpreter tool call.
    #[cfg(feature = "qwen")]
    CodeInterpreterCall(CodeInterpreterCall),
    /// Qwen: a web page extraction tool call.
    #[cfg(feature = "qwen")]
    WebExtractorCall(WebExtractorCall),
    /// Qwen: a text-to-image search tool call.
    #[cfg(feature = "qwen")]
    WebSearchImageCall(WebSearchImageCall),
    /// Qwen: an image-to-image search tool call.
    #[cfg(feature = "qwen")]
    ImageSearchCall(ImageSearchCall),
    /// Any item type not covered by the variants above.
    #[serde(other)]
    Other,
}

/// A message output from the model.
#[derive(Debug, Deserialize, Clone)]
pub struct ResponseOutputMessage {
    /// The unique ID of the message.
    #[serde(default)]
    pub id: Option<String>,
    /// The entity that produced the message. Always `assistant`.
    #[serde(default)]
    pub role: Option<String>,
    /// The content of the message (`output_text` and/or `refusal` parts).
    #[serde(default)]
    pub content: Vec<OutputContent>,
    /// The status of the message item.
    #[serde(default)]
    pub status: Option<ItemStatus>,
}

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

/// A content part of an output [`ResponseOutputMessage`].
#[derive(Debug, Deserialize, Clone)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum OutputContent {
    /// A text output part.
    OutputText {
        /// The text content.
        text: String,
        /// Annotations for the text, e.g. citations from web search.
        #[serde(default)]
        annotations: Vec<Annotation>,
    },
    /// A refusal output part.
    Refusal {
        /// The refusal message.
        refusal: String,
    },
}

/// An annotation on an output text part.
#[derive(Debug, Deserialize, Clone)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Annotation {
    /// A citation of a web page returned by the web search tool.
    UrlCitation {
        /// The URL of the cited web page.
        url: String,
        /// The title of the cited web page.
        #[serde(default)]
        title: Option<String>,
        /// The index of the cited web page in the search results.
        #[serde(default)]
        url_citation_index: Option<u32>,
        /// The start index of the cited text in the output.
        #[serde(default)]
        start_index: Option<u32>,
        /// The end index of the cited text in the output.
        #[serde(default)]
        end_index: Option<u32>,
    },
}

/// A call to a user-defined function.
#[derive(Debug, Deserialize, Clone)]
pub struct ResponseFunctionCall {
    /// The unique ID of the function call.
    #[serde(default)]
    pub id: Option<String>,
    /// The ID used to pair this call with its `function_call_output` when
    /// passing the result back in a follow-up request.
    #[serde(default)]
    pub call_id: Option<String>,
    /// The name of the function to call.
    #[serde(default)]
    pub name: Option<String>,
    /// The arguments to call the function with, as a JSON string.
    #[serde(default)]
    pub arguments: Option<String>,
    /// The status of the function call item.
    #[serde(default)]
    pub status: Option<ItemStatus>,
}

/// A reasoning item (chain-of-thought and/or summaries) from the model.
#[derive(Debug, Deserialize, Clone)]
pub struct ResponseReasoningItem {
    /// The unique ID of the reasoning item.
    #[serde(default)]
    pub id: Option<String>,
    /// The reasoning content. Providers that expose chain-of-thought text
    /// (e.g. DeepSeek, Qwen) return `reasoning_text` parts here; OpenAI
    /// omits it unless requested.
    #[serde(default)]
    pub content: Option<Vec<ReasoningContent>>,
    /// Summaries of the reasoning content.
    #[serde(default)]
    pub summary: Vec<ReasoningSummary>,
    /// The status of the reasoning item.
    #[serde(default)]
    pub status: Option<ItemStatus>,
}

/// A content part of a [`ResponseReasoningItem`].
///
/// Currently only the plaintext `reasoning_text` part is modeled; OpenAI
/// also defines `summary_text` parts here, but this crate carries summaries
/// in [`ResponseReasoningItem::summary`] instead.
#[derive(Debug, Deserialize, Clone)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ReasoningContent {
    /// Plaintext chain-of-thought text.
    ReasoningText {
        /// The reasoning text.
        text: String,
    },
}

/// A summary part of a [`ResponseReasoningItem`].
#[derive(Debug, Deserialize, Clone)]
pub struct ReasoningSummary {
    /// The type of the summary part, always `summary_text`.
    #[serde(rename = "type")]
    pub summary_type: Option<String>,
    /// The summary text.
    #[serde(default)]
    pub text: Option<String>,
}

/// A web search performed by the server-side web search tool.
#[derive(Debug, Deserialize, Clone)]
pub struct ResponseWebSearchCall {
    /// The unique ID of the web search call.
    #[serde(default)]
    pub id: Option<String>,
    /// The status of the web search call.
    #[serde(default)]
    pub status: Option<ItemStatus>,
    /// The search action performed by the server.
    #[serde(default)]
    pub action: Option<WebSearchAction>,
}

/// The search action of a [`ResponseWebSearchCall`].
#[derive(Debug, Deserialize, Clone)]
pub struct WebSearchAction {
    /// The type of the action, e.g. `search`.
    #[serde(rename = "type")]
    pub action_type: Option<String>,
    /// The search query.
    #[serde(default)]
    pub query: Option<String>,
    /// The sources cited by the search.
    #[serde(default)]
    pub sources: Vec<WebSearchSource>,
}

/// A source cited by a web search.
#[derive(Debug, Deserialize, Clone)]
pub struct WebSearchSource {
    /// The type of the source.
    #[serde(rename = "type")]
    pub source_type: Option<String>,
    /// The URL of the source.
    #[serde(default)]
    pub url: Option<String>,
}

/// Qwen: a call to a tool on an MCP server.
#[cfg(feature = "qwen")]
#[derive(Debug, Deserialize, Clone)]
pub struct McpCall {
    /// The unique ID of the MCP call.
    #[serde(default)]
    pub id: Option<String>,
    /// The name of the MCP tool that was called.
    #[serde(default)]
    pub name: Option<String>,
    /// The label of the MCP server running the tool.
    #[serde(default)]
    pub server_label: Option<String>,
    /// The call arguments, as a JSON string.
    #[serde(default)]
    pub arguments: Option<String>,
    /// The result returned by the MCP server, as a JSON string.
    #[serde(default)]
    pub output: Option<String>,
    /// The status of the MCP call.
    #[serde(default)]
    pub status: Option<ItemStatus>,
}

/// Qwen: a knowledge-base (file search) tool call.
#[cfg(feature = "qwen")]
#[derive(Debug, Deserialize, Clone)]
pub struct FileSearchCall {
    /// The unique ID of the file search call.
    #[serde(default)]
    pub id: Option<String>,
    /// The search queries generated by the model.
    #[serde(default)]
    pub queries: Vec<String>,
    /// The knowledge-base search results.
    #[serde(default)]
    pub results: Vec<serde_json::Value>,
    /// The status of the file search call.
    #[serde(default)]
    pub status: Option<ItemStatus>,
}

/// Qwen: a code interpreter tool call.
#[cfg(feature = "qwen")]
#[derive(Debug, Deserialize, Clone)]
pub struct CodeInterpreterCall {
    /// The unique ID of the code interpreter call.
    #[serde(default)]
    pub id: Option<String>,
    /// The code generated and executed by the model.
    #[serde(default)]
    pub code: Option<String>,
    /// The outputs of the code execution.
    #[serde(default)]
    pub outputs: Vec<serde_json::Value>,
    /// The identifier of the code interpreter container.
    #[serde(default)]
    pub container_id: Option<String>,
    /// The status of the code interpreter call.
    #[serde(default)]
    pub status: Option<ItemStatus>,
}

/// Qwen: a web page extraction tool call.
#[cfg(feature = "qwen")]
#[derive(Debug, Deserialize, Clone)]
pub struct WebExtractorCall {
    /// The unique ID of the web extractor call.
    #[serde(default)]
    pub id: Option<String>,
    /// A description of what information should be extracted from the page.
    #[serde(default)]
    pub goal: Option<String>,
    /// The extracted page content.
    #[serde(default)]
    pub output: Option<String>,
    /// The URLs that were extracted.
    #[serde(default)]
    pub urls: Vec<String>,
    /// The status of the web extractor call.
    #[serde(default)]
    pub status: Option<ItemStatus>,
}

/// Qwen: a text-to-image search tool call.
#[cfg(feature = "qwen")]
#[derive(Debug, Deserialize, Clone)]
pub struct WebSearchImageCall {
    /// The unique ID of the image search call.
    #[serde(default)]
    pub id: Option<String>,
    /// The tool name, fixed to `web_search_image`.
    #[serde(default)]
    pub name: Option<String>,
    /// The call arguments, as a JSON string containing the search keywords.
    #[serde(default)]
    pub arguments: Option<String>,
    /// The image search results, as a JSON string.
    #[serde(default)]
    pub output: Option<String>,
    /// The status of the image search call.
    #[serde(default)]
    pub status: Option<ItemStatus>,
}

/// Qwen: an image-to-image search tool call.
#[cfg(feature = "qwen")]
#[derive(Debug, Deserialize, Clone)]
pub struct ImageSearchCall {
    /// The unique ID of the image search call.
    #[serde(default)]
    pub id: Option<String>,
    /// The tool name, fixed to `image_search`.
    #[serde(default)]
    pub name: Option<String>,
    /// The call arguments, as a JSON string containing the image index and
    /// bounding box.
    #[serde(default)]
    pub arguments: Option<String>,
    /// The image search results, as a JSON string.
    #[serde(default)]
    pub output: Option<String>,
    /// The status of the image search call.
    #[serde(default)]
    pub status: Option<ItemStatus>,
}

/// Token usage statistics of a [`Response`].
#[derive(Debug, Deserialize, Clone)]
pub struct ResponseUsage {
    /// The number of input tokens.
    pub input_tokens: usize,
    /// A breakdown of the input tokens.
    #[serde(default)]
    pub input_tokens_details: Option<InputTokensDetails>,
    /// The number of output tokens.
    pub output_tokens: usize,
    /// A breakdown of the output tokens.
    #[serde(default)]
    pub output_tokens_details: Option<OutputTokensDetails>,
    /// The total number of tokens used (input + output).
    pub total_tokens: usize,
    /// Qwen: per-segment token usage details, including the billing type of
    /// each segment.
    #[cfg(feature = "qwen")]
    #[serde(default)]
    pub x_details: Option<Vec<serde_json::Value>>,
    /// Qwen: built-in tool usage statistics, e.g.
    /// `{"file_search": {"count": 1}}`.
    #[cfg(feature = "qwen")]
    #[serde(default)]
    pub x_tools: Option<serde_json::Value>,
}

/// A breakdown of the input tokens.
#[derive(Debug, Deserialize, Clone)]
pub struct InputTokensDetails {
    /// The number of input tokens retrieved from the cache.
    #[serde(default)]
    pub cached_tokens: Option<usize>,
    /// The number of input tokens written to the cache.
    #[serde(default)]
    pub cache_write_tokens: Option<usize>,
}

/// A breakdown of the output tokens.
#[derive(Debug, Deserialize, Clone)]
pub struct OutputTokensDetails {
    /// The number of reasoning tokens generated by the model.
    #[serde(default)]
    pub reasoning_tokens: Option<usize>,
}

crate::impl_from_str!(Response);

#[cfg(test)]
mod tests {
    //! Offline deserialization tests. The fixtures below are copied from the
    //! documented examples of the respective providers, not invented.

    use std::str::FromStr;

    use super::*;

    /// Documented DeepSeek response example, from
    /// <https://api-docs.deepseek.com/api/create-response>.
    const DEEPSEEK_RESPONSE_JSON: &str = r#"
    {
      "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
    }"#;

    #[test]
    fn parses_documented_deepseek_response() {
        let response = Response::from_str(DEEPSEEK_RESPONSE_JSON).unwrap();
        assert_eq!(response.object, ResponseObject::Response);
        assert_eq!(response.model, "deepseek-v4-flash");
        assert!(response.is_completed());
        assert_eq!(response.store, Some(false));
        assert_eq!(response.parallel_tool_calls, Some(true));
        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."
        );
        let usage = response.usage.unwrap();
        assert_eq!(usage.total_tokens, 51);
        assert_eq!(usage.input_tokens_details.unwrap().cached_tokens, Some(0));
        assert_eq!(
            usage.output_tokens_details.unwrap().reasoning_tokens,
            Some(27)
        );
    }

    #[test]
    fn unknown_output_item_type_is_preserved() {
        let json = r#"{
            "id": "resp_1",
            "object": "response",
            "created_at": 0,
            "status": "completed",
            "model": "m",
            "output": [{"type": "something_future"}]
        }"#;
        let response = Response::from_str(json).unwrap();
        assert!(matches!(
            response.output.first(),
            Some(ResponseOutputItem::Other)
        ));
    }
}

#[cfg(test)]
mod integration {
    //! Integration tests against the DeepSeek and Qwen Responses
    //! implementations. They self-skip when the API key environment
    //! variable is absent; `keys/key_env.sh` provides the keys.
    //!
    //! All assertions are based on the documented behavior of the two
    //! providers, not on assumed server responses.

    use futures_util::StreamExt;

    use crate::responses::create::request::{Input, RequestBody};
    use crate::responses::create::response::ResponseStreamEvent;
    use crate::rest::{
        default_client,
        delete::DeleteNoStream,
        get::GetNoStream,
        post::{PostNoStream, PostStream},
    };

    use super::{Response, ResponseObject};

    const DEEPSEEK_URL: &str = "https://api.deepseek.com";
    const DEEPSEEK_MODEL: &str = "deepseek-v4-flash";

    const QWEN_URL: &str = "https://dashscope.aliyuncs.com/compatible-mode/v1";
    const QWEN_MODEL: &str = "qwen3-max";

    fn deepseek_api_key() -> Option<String> {
        std::env::var("DEEPSEEK_API_KEY")
            .ok()
            .map(|key| key.trim().to_string())
            .filter(|key| !key.is_empty())
    }

    fn qwen_api_key() -> Option<String> {
        std::env::var("QWEN_API_KEY")
            .ok()
            .map(|key| key.trim().to_string())
            .filter(|key| !key.is_empty())
    }

    async fn run_stream(
        request: &RequestBody,
        client: &reqwest::Client,
        base_url: &str,
        api_key: &str,
    ) -> anyhow::Result<Response> {
        let mut stream = request
            .get_stream_response(client, base_url, api_key)
            .await?;

        let mut final_response: Option<Response> = None;
        while let Some(event) = stream.next().await {
            let event: ResponseStreamEvent = event?;
            println!(
                "responses stream event: {:?}",
                std::mem::discriminant(&event)
            );
            if let Some(response) = event.final_response() {
                final_response = Some(response.clone());
            }
        }

        let response =
            final_response.expect("the stream should end with a terminal response event");
        Ok(response)
    }

    /// DeepSeek non-streaming create. Documented at
    /// <https://api-docs.deepseek.com/api/create-response>.
    #[tokio::test]
    async fn test_deepseek_response_no_stream() -> Result<(), anyhow::Error> {
        let Some(api_key) = deepseek_api_key() else {
            println!("Skipping: set DEEPSEEK_API_KEY to run this test");
            return Ok(());
        };

        let request = RequestBody {
            model: DEEPSEEK_MODEL.to_string(),
            input: Input::Text("用一句话介绍你自己。".to_string()),
            instructions: Some("You are a helpful assistant.".to_string()),
            ..Default::default()
        };

        let response = request
            .get_response(&default_client(), DEEPSEEK_URL, &api_key)
            .await?;

        println!("deepseek responses no-stream: {response:#?}");
        assert_eq!(response.object, ResponseObject::Response);
        assert!(response.is_completed());
        // DeepSeek's Responses API is stateless: it never stores.
        assert_eq!(response.store, Some(false));
        assert!(!response.output_text().is_empty());
        Ok(())
    }

    /// DeepSeek streaming create: the stream ends with
    /// `response.completed` (no `data: [DONE]` sentinel).
    #[tokio::test]
    async fn test_deepseek_response_stream() -> Result<(), anyhow::Error> {
        let Some(api_key) = deepseek_api_key() else {
            println!("Skipping: set DEEPSEEK_API_KEY to run this test");
            return Ok(());
        };

        let request = RequestBody {
            model: DEEPSEEK_MODEL.to_string(),
            input: Input::Text("用一句话介绍你自己。".to_string()),
            stream: Some(true),
            ..Default::default()
        };

        let response = run_stream(&request, &default_client(), DEEPSEEK_URL, &api_key).await?;

        println!("deepseek responses stream final: {response:#?}");
        assert!(response.is_completed());
        assert!(!response.output_text().is_empty());
        Ok(())
    }

    /// Qwen non-streaming create. Documented at
    /// <https://help.aliyun.com/zh/model-studio/qwen-api-via-openai-responses>.
    #[tokio::test]
    async fn test_qwen_response_no_stream() -> Result<(), anyhow::Error> {
        let Some(api_key) = qwen_api_key() else {
            println!("Skipping: set QWEN_API_KEY to run this test");
            return Ok(());
        };

        let request = RequestBody {
            model: QWEN_MODEL.to_string(),
            input: Input::Text("用一句话介绍你自己。".to_string()),
            instructions: Some("You are a helpful assistant.".to_string()),
            // Do not store this response; the store/retrieve/delete cycle
            // has its own dedicated test.
            store: Some(false),
            ..Default::default()
        };

        let response = request
            .get_response(&default_client(), QWEN_URL, &api_key)
            .await?;

        println!("qwen responses no-stream: {response:#?}");
        assert_eq!(response.object, ResponseObject::Response);
        assert!(response.is_completed());
        assert!(!response.output_text().is_empty());
        Ok(())
    }

    /// Qwen streaming create.
    #[tokio::test]
    async fn test_qwen_response_stream() -> Result<(), anyhow::Error> {
        let Some(api_key) = qwen_api_key() else {
            println!("Skipping: set QWEN_API_KEY to run this test");
            return Ok(());
        };

        let request = RequestBody {
            model: QWEN_MODEL.to_string(),
            input: Input::Text("用一句话介绍你自己。".to_string()),
            stream: Some(true),
            store: Some(false),
            ..Default::default()
        };

        let response = run_stream(&request, &default_client(), QWEN_URL, &api_key).await?;

        println!("qwen responses stream final: {response:#?}");
        assert!(response.is_completed());
        assert!(!response.output_text().is_empty());
        Ok(())
    }

    /// Qwen multi-turn conversation via `previous_response_id`.
    #[tokio::test]
    async fn test_qwen_response_previous_response_id() -> Result<(), anyhow::Error> {
        let Some(api_key) = qwen_api_key() else {
            println!("Skipping: set QWEN_API_KEY to run this test");
            return Ok(());
        };

        let client = default_client();

        // The first response must be stored so that it can be referenced
        // via `previous_response_id` in the second turn.
        let first = RequestBody {
            model: QWEN_MODEL.to_string(),
            input: Input::Text("法国的首都是哪里?".to_string()),
            ..Default::default()
        }
        .get_response(&client, QWEN_URL, &api_key)
        .await?;
        assert!(first.is_completed());

        let second = RequestBody {
            model: QWEN_MODEL.to_string(),
            input: Input::Text("它的人口大约是多少?".to_string()),
            previous_response_id: Some(first.id.clone()),
            store: Some(false),
            ..Default::default()
        }
        .get_response(&client, QWEN_URL, &api_key)
        .await?;

        println!("qwen responses second turn: {second:#?}");
        assert!(second.is_completed());
        assert_eq!(
            second.previous_response_id.as_deref(),
            Some(first.id.as_str())
        );
        assert!(!second.output_text().is_empty());
        Ok(())
    }

    /// Qwen store / retrieve / delete cycle.
    #[tokio::test]
    async fn test_qwen_response_store_retrieve_delete() -> Result<(), anyhow::Error> {
        let Some(api_key) = qwen_api_key() else {
            println!("Skipping: set QWEN_API_KEY to run this test");
            return Ok(());
        };

        let client = default_client();

        let created = RequestBody {
            model: QWEN_MODEL.to_string(),
            input: Input::Text("说一个法语单词。".to_string()),
            store: Some(true),
            ..Default::default()
        }
        .get_response(&client, QWEN_URL, &api_key)
        .await?;
        assert!(created.is_completed());

        // Retrieve the stored response.
        let retrieved = crate::responses::retrieve::RetrieveRequest {
            response_id: &created.id,
        }
        .get_response(&client, QWEN_URL, &api_key)
        .await?;
        assert_eq!(retrieved.id, created.id);
        assert_eq!(retrieved.output_text(), created.output_text());

        // Delete it again.
        let deleted = crate::responses::delete::DeleteRequest {
            response_id: &created.id,
        }
        .get_response(&client, QWEN_URL, &api_key)
        .await?;
        assert_eq!(deleted.id, created.id);
        assert!(deleted.deleted);

        Ok(())
    }
}