dynamo-protocols 2.0.1

Protocol types for OpenAI-compatible inference APIs with inference-serving extensions.
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
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Re-exports upstream async-openai chat types and defines inference-serving
// extensions on top. Types prefixed with `Dynamo` or entirely absent from the
// upstream spec are documented with the rationale for the extension.

use std::pin::Pin;

use derive_builder::Builder;
use futures::Stream;
use serde::{Deserialize, Serialize};
use url::Url;
use uuid::Uuid;

use crate::error::OpenAIError;

// ---------------------------------------------------------------------------
// Re-exports from upstream async-openai (unchanged types)
// ---------------------------------------------------------------------------
// These types are structurally identical to the upstream definitions.
// Consumers should use them via `dynamo_protocols::types::*` as before.

pub use async_openai::types::chat::{
    ChatChoiceLogprobs,
    ChatCompletionAudio,
    ChatCompletionAudioFormat,
    ChatCompletionAudioVoice,
    ChatCompletionFunctionCall,
    ChatCompletionFunctions,
    ChatCompletionFunctionsArgs,
    ChatCompletionRequestAssistantMessageAudio,
    ChatCompletionRequestAssistantMessageContent,
    ChatCompletionRequestAssistantMessageContentPart,
    ChatCompletionRequestDeveloperMessage,
    ChatCompletionRequestDeveloperMessageArgs,
    ChatCompletionRequestDeveloperMessageContent,
    ChatCompletionRequestFunctionMessage,
    ChatCompletionRequestFunctionMessageArgs,
    ChatCompletionRequestMessageContentPartAudio,
    ChatCompletionRequestMessageContentPartRefusal,
    ChatCompletionRequestMessageContentPartText,
    ChatCompletionRequestSystemMessage,
    // Builder types (generated by derive_builder)
    ChatCompletionRequestSystemMessageArgs,
    ChatCompletionRequestSystemMessageContent,
    ChatCompletionRequestSystemMessageContentPart,
    ChatCompletionRequestToolMessage,
    ChatCompletionRequestToolMessageArgs,
    ChatCompletionRequestToolMessageContent,
    ChatCompletionRequestToolMessageContentPart,
    ChatCompletionResponseMessageAudio,
    ChatCompletionTokenLogprob,
    Choice,
    CompletionFinishReason,
    CompletionTokensDetails,
    CompletionUsage,
    FunctionObject,
    FunctionObjectArgs,
    InputAudio,
    InputAudioFormat,
    Logprobs,
    PredictionContent,
    PredictionContentContent,
    Prompt,
    PromptTokensDetails,
    ResponseFormat,
    ResponseFormatJsonSchema,
    Role,
    ServiceTier,
    TopLogprobs,
    WebSearchContextSize,
    WebSearchLocation,
    WebSearchOptions,
    WebSearchUserLocation,
    WebSearchUserLocationType,
};

/// OpenAI stop configuration, with Dynamo's token-id stop extension.
///
/// The standard OpenAI shape accepts a string or string array. Dynamo also
/// accepts an integer array, e.g. `"stop": [576]`, to express token-id stop
/// conditions for tokenized in/out workflows. Strings like `"token_id:576"`
/// remain ordinary string stops; the `token_id:<id>` format is only an output
/// display format for logprobs.
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
#[serde(untagged)]
pub enum Stop {
    String(String),
    StringArray(Vec<String>),
    TokenIdArray(Vec<u32>),
}

impl Stop {
    pub fn strings(&self) -> Option<Vec<String>> {
        match self {
            Stop::String(s) => Some(vec![s.clone()]),
            Stop::StringArray(arr) => Some(arr.clone()),
            Stop::TokenIdArray(_) => None,
        }
    }

    pub fn token_ids(&self) -> Option<Vec<u32>> {
        match self {
            Stop::TokenIdArray(arr) => Some(arr.clone()),
            Stop::String(_) | Stop::StringArray(_) => None,
        }
    }
}

impl From<String> for Stop {
    fn from(value: String) -> Self {
        Stop::String(value)
    }
}

impl From<&str> for Stop {
    fn from(value: &str) -> Self {
        Stop::String(value.to_string())
    }
}

impl From<Vec<String>> for Stop {
    fn from(value: Vec<String>) -> Self {
        Stop::StringArray(value)
    }
}

impl From<Vec<u32>> for Stop {
    fn from(value: Vec<u32>) -> Self {
        Stop::TokenIdArray(value)
    }
}

impl From<async_openai::types::chat::StopConfiguration> for Stop {
    fn from(value: async_openai::types::chat::StopConfiguration) -> Self {
        match value {
            async_openai::types::chat::StopConfiguration::String(value) => Stop::String(value),
            async_openai::types::chat::StopConfiguration::StringArray(value) => {
                Stop::StringArray(value)
            }
        }
    }
}

// Upstream renamed FinishReason (streaming) -- re-export
pub use async_openai::types::chat::FinishReason;

// Upstream uses FunctionType where we used ChatCompletionToolType.
// Re-export both names for compatibility.
pub use async_openai::types::chat::FunctionType;

/// Reasoning effort values accepted by OpenAI-compatible clients.
///
/// async-openai versions used by some Dynamo builds do not include `max`, but
/// DeepSeek-V4 compatible clients may send it by default. Keep this local enum
/// wire-compatible with upstream values and include `max`.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ReasoningEffort {
    None,
    Minimal,
    Low,
    Medium,
    High,
    Xhigh,
    Max,
}

impl From<async_openai::types::chat::ReasoningEffort> for ReasoningEffort {
    fn from(value: async_openai::types::chat::ReasoningEffort) -> Self {
        match value {
            async_openai::types::chat::ReasoningEffort::None => ReasoningEffort::None,
            async_openai::types::chat::ReasoningEffort::Minimal => ReasoningEffort::Minimal,
            async_openai::types::chat::ReasoningEffort::Low => ReasoningEffort::Low,
            async_openai::types::chat::ReasoningEffort::Medium => ReasoningEffort::Medium,
            async_openai::types::chat::ReasoningEffort::High => ReasoningEffort::High,
            async_openai::types::chat::ReasoningEffort::Xhigh => ReasoningEffort::Xhigh,
        }
    }
}

// ---------------------------------------------------------------------------
// Flexible `arguments` deserialisation helpers
// ---------------------------------------------------------------------------
// Some agent frameworks (e.g. LangChain, custom harnesses) send tool-call
// arguments as a pre-parsed JSON object instead of the canonical JSON
// string.  The helpers below normalise both representations to a `String` so
// downstream code never needs to branch on the wire format.

fn deserialize_arguments<'de, D>(deserializer: D) -> Result<String, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::de::Error;
    let value = serde_json::Value::deserialize(deserializer)?;
    match value {
        serde_json::Value::String(s) => Ok(s),
        v @ serde_json::Value::Object(_) => {
            // serde_json::to_string on a Value is infallible
            Ok(serde_json::to_string(&v).unwrap())
        }
        other => Err(D::Error::custom(format!(
            "expected string or object for `arguments`, got {other}"
        ))),
    }
}

fn deserialize_arguments_opt<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::de::Error;
    let value = Option::<serde_json::Value>::deserialize(deserializer)?;
    match value {
        None => Ok(None),
        Some(serde_json::Value::String(s)) => Ok(Some(s)),
        Some(v @ serde_json::Value::Object(_)) => serde_json::to_string(&v)
            .map(Some)
            .map_err(|e| D::Error::custom(e.to_string())),
        Some(other) => Err(D::Error::custom(format!(
            "expected string or object for `arguments`, got {other}"
        ))),
    }
}

// ---------------------------------------------------------------------------
// FunctionCall / FunctionCallStream — local definitions with flexible deser
// ---------------------------------------------------------------------------
// Upstream `async-openai` only accepts a JSON string for `arguments`.
// We define these locally so we can attach `#[serde(deserialize_with)]` and
// accept both string and object representations on the wire.

/// The name and arguments of a function that should be called.
///
/// Accepts `arguments` as either a JSON string (`"{\"key\":\"value\"}"`) or a
/// JSON object (`{"key": "value"}`); both are normalised to a JSON string
/// on deserialisation so callers always see the canonical form.
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Default)]
pub struct FunctionCall {
    pub name: String,
    #[serde(deserialize_with = "deserialize_arguments")]
    pub arguments: String,
}

/// Streaming variant of [`FunctionCall`] where both fields are optional.
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Default)]
pub struct FunctionCallStream {
    pub name: Option<String>,
    #[serde(default, deserialize_with = "deserialize_arguments_opt")]
    pub arguments: Option<String>,
}

/// Streaming tool-call chunk.
///
/// Defined locally (instead of re-exporting from upstream) because its
/// `function` field references our local [`FunctionCallStream`] with the
/// flexible `arguments` deserialiser.
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Default)]
pub struct ChatCompletionMessageToolCallChunk {
    pub index: u32,
    pub id: Option<String>,
    pub r#type: Option<FunctionType>,
    pub function: Option<FunctionCallStream>,
}

// ---------------------------------------------------------------------------
// Types with structural differences from upstream (kept locally)
// ---------------------------------------------------------------------------

/// Image detail level. Kept locally because upstream uses different field types in ImageUrl.
#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum ImageDetail {
    #[default]
    Auto,
    Low,
    High,
}

/// Image content part -- uses our extended `ImageUrl` with `url::Url` and `uuid`.
#[derive(Debug, Serialize, Deserialize, Clone, Builder, PartialEq)]
#[builder(name = "ChatCompletionRequestMessageContentPartImageArgs")]
#[builder(pattern = "mutable")]
#[builder(setter(into, strip_option))]
#[builder(derive(Debug))]
#[builder(build_fn(error = "OpenAIError"))]
pub struct ChatCompletionRequestMessageContentPartImage {
    pub image_url: ImageUrl,
}

/// Image URL with `url::Url` type and optional UUID.
///
/// Differs from upstream: uses `url::Url` instead of `String`, adds `uuid` field
/// for tracking multimodal assets through the pipeline.
#[derive(Debug, Serialize, Deserialize, Clone, Builder, PartialEq)]
#[builder(name = "ImageUrlArgs")]
#[builder(pattern = "mutable")]
#[builder(setter(into, strip_option))]
#[builder(derive(Debug))]
#[builder(build_fn(error = "OpenAIError"))]
pub struct ImageUrl {
    pub url: Url,
    pub detail: Option<ImageDetail>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uuid: Option<Uuid>,
}

#[derive(Clone, Serialize, Default, Debug, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum ChatCompletionToolType {
    #[default]
    Function,
}

#[derive(Clone, Serialize, Default, Debug, Deserialize, PartialEq)]
pub struct FunctionName {
    pub name: String,
}

#[derive(Clone, Serialize, Default, Debug, Deserialize, PartialEq)]
pub struct ChatCompletionNamedToolChoice {
    pub r#type: ChatCompletionToolType,
    pub function: FunctionName,
}

fn default_function_type() -> FunctionType {
    FunctionType::Function
}

/// Tool call kept locally to preserve `type: "function"` in unary request/response payloads.
///
/// Differs from upstream: `type` is serialized by default and also defaults to
/// `function` when omitted during deserialization, preserving compatibility with
/// both Dynamo's historical wire format and upstream spec-compliant inputs.
#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
pub struct ChatCompletionMessageToolCall {
    pub id: String,
    #[serde(default = "default_function_type")]
    pub r#type: FunctionType,
    pub function: FunctionCall,
}

/// Tool choice enum kept locally because upstream changed variant names.
#[derive(Clone, Serialize, Default, Debug, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum ChatCompletionToolChoiceOption {
    #[default]
    None,
    Auto,
    Required,
    #[serde(untagged)]
    Named(ChatCompletionNamedToolChoice),
}

#[derive(Clone, Serialize, Default, Debug, Builder, Deserialize, PartialEq)]
#[builder(name = "ChatCompletionToolArgs")]
#[builder(pattern = "mutable")]
#[builder(setter(into, strip_option), default)]
#[builder(derive(Debug))]
#[builder(build_fn(error = "OpenAIError"))]
pub struct ChatCompletionTool {
    #[builder(default = "ChatCompletionToolType::Function")]
    pub r#type: ChatCompletionToolType,
    pub function: FunctionObject,
}

// ---------------------------------------------------------------------------
// Inference-serving extensions (not in upstream)
// ---------------------------------------------------------------------------

/// Matched stop condition from the backend.
///
/// Inference backends (vLLM, SGLang) report which stop condition triggered:
/// - `String`: a matched user-provided stop sequence
/// - `Int`: a matched stop token ID
/// - `IntArray`: matched stop token IDs reported as a sequence
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
#[serde(untagged)]
pub enum StopReason {
    String(String),
    Int(i64),
    IntArray(Vec<i64>),
}

/// Reasoning content from a previous assistant turn.
///
/// Deserializes from either:
/// - A plain string: `"reasoning_content": "thinking..."` -> `Text("thinking...")`
/// - An array of strings: `"reasoning_content": ["seg1", "seg2"]` -> `Segments(["seg1", "seg2"])`
///
/// The `Segments` variant preserves interleaved reasoning order needed for KV cache-correct
/// context reconstruction. `segments[i]` is the reasoning that preceded `tool_calls[i]`;
/// `segments[tool_calls.len()]` is any trailing reasoning after the last tool call.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(untagged)]
pub enum ReasoningContent {
    /// Flat string -- single reasoning block or legacy backward-compat form.
    Text(String),
    /// Interleaved segments. segments[i] precedes tool_calls[i];
    /// segments[N] is trailing reasoning after the last tool call.
    Segments(Vec<String>),
}

impl ReasoningContent {
    /// Join all segments (or return text as-is) into a single flat string.
    pub fn to_flat_string(&self) -> String {
        match self {
            ReasoningContent::Text(s) => s.clone(),
            ReasoningContent::Segments(segs) => segs
                .iter()
                .filter(|s| !s.is_empty())
                .cloned()
                .collect::<Vec<_>>()
                .join("\n"),
        }
    }

    /// Returns the segments if this is the `Segments` variant, `None` for `Text`.
    pub fn segments(&self) -> Option<&[String]> {
        match self {
            ReasoningContent::Segments(segs) => Some(segs),
            ReasoningContent::Text(_) => None,
        }
    }
}

// -- Multimodal content types for responses (not in upstream) --

/// Response content part for text in assistant messages
#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
pub struct ChatCompletionResponseContentPartText {
    pub text: String,
}

/// Response content part for image URLs in assistant messages
#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
pub struct ChatCompletionResponseContentPartImageUrl {
    pub image_url: ImageUrlResponse,
}

/// Response content part for video URLs in assistant messages
#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
pub struct ChatCompletionResponseContentPartVideoUrl {
    pub video_url: VideoUrlResponse,
}

/// Response content part for audio URLs in assistant messages
#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
pub struct ChatCompletionResponseContentPartAudioUrl {
    pub audio_url: AudioUrlResponse,
}

#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
pub struct ImageUrlResponse {
    pub url: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
}

#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
pub struct VideoUrlResponse {
    pub url: String,
}

#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
pub struct AudioUrlResponse {
    pub url: String,
}

/// Content parts for assistant responses supporting multiple modalities
#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ChatCompletionResponseContentPart {
    Text(ChatCompletionResponseContentPartText),
    ImageUrl(ChatCompletionResponseContentPartImageUrl),
    VideoUrl(ChatCompletionResponseContentPartVideoUrl),
    AudioUrl(ChatCompletionResponseContentPartAudioUrl),
}

/// Assistant message content -- can be a simple string or multimodal content parts.
///
/// Upstream uses `Option<String>` for the content field. We extend this to
/// support multimodal responses (text + images + video + audio) from backends
/// like vLLM that can return non-text content.
#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum ChatCompletionMessageContent {
    /// Simple text content (backward compatible)
    Text(String),
    /// Array of content parts (for multimodal responses)
    Parts(Vec<ChatCompletionResponseContentPart>),
}

// -- Multimodal input types (video/audio URL support, not in upstream) --

#[derive(Debug, Serialize, Deserialize, Clone, Builder, PartialEq)]
#[builder(name = "VideoUrlArgs")]
#[builder(pattern = "mutable")]
#[builder(setter(into, strip_option))]
#[builder(derive(Debug))]
#[builder(build_fn(error = "OpenAIError"))]
pub struct VideoUrl {
    pub url: Url,
    pub detail: Option<ImageDetail>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uuid: Option<Uuid>,
}

#[derive(Debug, Serialize, Deserialize, Clone, Builder, PartialEq)]
#[builder(name = "ChatCompletionRequestMessageContentPartVideoArgs")]
#[builder(pattern = "mutable")]
#[builder(setter(into, strip_option))]
#[builder(derive(Debug))]
#[builder(build_fn(error = "OpenAIError"))]
pub struct ChatCompletionRequestMessageContentPartVideo {
    pub video_url: VideoUrl,
}

#[derive(Debug, Serialize, Deserialize, Clone, Builder, PartialEq)]
#[builder(name = "AudioUrlArgs")]
#[builder(pattern = "mutable")]
#[builder(setter(into, strip_option))]
#[builder(derive(Debug))]
#[builder(build_fn(error = "OpenAIError"))]
pub struct AudioUrl {
    pub url: Url,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uuid: Option<Uuid>,
}

#[derive(Debug, Serialize, Deserialize, Clone, Builder, PartialEq)]
#[builder(name = "ChatCompletionRequestMessageContentPartAudioUrlArgs")]
#[builder(pattern = "mutable")]
#[builder(setter(into, strip_option))]
#[builder(derive(Debug))]
#[builder(build_fn(error = "OpenAIError"))]
pub struct ChatCompletionRequestMessageContentPartAudioUrl {
    pub audio_url: AudioUrl,
}

// -- Extended request/response types --

/// User message content -- references our extended content part enum.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(untagged)]
pub enum ChatCompletionRequestUserMessageContent {
    Text(String),
    Array(Vec<ChatCompletionRequestUserMessageContentPart>),
}

#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
#[builder(name = "ChatCompletionRequestUserMessageArgs")]
#[builder(pattern = "mutable")]
#[builder(setter(into, strip_option), default)]
#[builder(derive(Debug))]
#[builder(build_fn(error = "OpenAIError"))]
pub struct ChatCompletionRequestUserMessage {
    pub content: ChatCompletionRequestUserMessageContent,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}

impl Default for ChatCompletionRequestUserMessageContent {
    fn default() -> Self {
        Self::Text(String::new())
    }
}

impl From<&str> for ChatCompletionRequestUserMessageContent {
    fn from(value: &str) -> Self {
        Self::Text(value.into())
    }
}

impl From<String> for ChatCompletionRequestUserMessageContent {
    fn from(value: String) -> Self {
        Self::Text(value)
    }
}

impl From<Vec<ChatCompletionRequestUserMessageContentPart>>
    for ChatCompletionRequestUserMessageContent
{
    fn from(value: Vec<ChatCompletionRequestUserMessageContentPart>) -> Self {
        Self::Array(value)
    }
}

/// User message content part with video and audio URL support.
///
/// Extends upstream `ChatCompletionRequestUserMessageContentPart` with:
/// - `VideoUrl`: video input for multimodal models
/// - `AudioUrl`: audio URL input (distinct from base64 InputAudio)
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(tag = "type")]
#[serde(rename_all = "snake_case")]
pub enum ChatCompletionRequestUserMessageContentPart {
    Text(ChatCompletionRequestMessageContentPartText),
    ImageUrl(ChatCompletionRequestMessageContentPartImage),
    VideoUrl(ChatCompletionRequestMessageContentPartVideo),
    AudioUrl(ChatCompletionRequestMessageContentPartAudioUrl),
    InputAudio(ChatCompletionRequestMessageContentPartAudio),
}

/// Assistant message with reasoning content support.
///
/// Extends upstream `ChatCompletionRequestAssistantMessage` with:
/// - `reasoning_content`: interleaved reasoning segments for KV cache correctness
///   (DeepSeek-R1, QwQ models)
#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
#[builder(name = "ChatCompletionRequestAssistantMessageArgs")]
#[builder(pattern = "mutable")]
#[builder(setter(into, strip_option), default)]
#[builder(derive(Debug))]
#[builder(build_fn(error = "OpenAIError"))]
pub struct ChatCompletionRequestAssistantMessage {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<ChatCompletionRequestAssistantMessageContent>,
    /// Reasoning content from a previous assistant turn.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reasoning_content: Option<ReasoningContent>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub refusal: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub audio: Option<ChatCompletionRequestAssistantMessageAudio>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_calls: Option<Vec<ChatCompletionMessageToolCall>>,
    #[deprecated]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub function_call: Option<FunctionCall>,
}

/// Chat completion request message enum.
///
/// Redefined to use our extended `ChatCompletionRequestAssistantMessage`
/// (with reasoning_content) and `ChatCompletionRequestUserMessage`
/// (which references our extended content parts with video/audio).
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(tag = "role")]
#[serde(rename_all = "lowercase")]
pub enum ChatCompletionRequestMessage {
    Developer(ChatCompletionRequestDeveloperMessage),
    System(ChatCompletionRequestSystemMessage),
    User(ChatCompletionRequestUserMessage),
    Assistant(ChatCompletionRequestAssistantMessage),
    Tool(ChatCompletionRequestToolMessage),
    Function(ChatCompletionRequestFunctionMessage),
}

/// Response tier enum for responses (distinct from request `ServiceTier`).
///
/// Not in upstream -- backends report which tier actually served the request.
#[derive(Clone, Serialize, Debug, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum ServiceTierResponse {
    Scale,
    Default,
    Flex,
    Priority,
}

/// Chat completion response message with multimodal content and reasoning.
///
/// Extends upstream `ChatCompletionResponseMessage` with:
/// - `content`: `Option<ChatCompletionMessageContent>` (multimodal) instead of `Option<String>`
/// - `reasoning_content`: model reasoning output (DeepSeek-R1, QwQ)
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
pub struct ChatCompletionResponseMessage {
    /// Always serialized (as `null` when None) so clients can rely on the
    /// `content` key being present alongside `reasoning_content` or
    /// `tool_calls`. Matches the upstream OpenAI API shape (DGH-651).
    pub content: Option<ChatCompletionMessageContent>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub refusal: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_calls: Option<Vec<ChatCompletionMessageToolCall>>,
    pub role: Role,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[deprecated]
    pub function_call: Option<FunctionCall>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub audio: Option<ChatCompletionResponseMessageAudio>,
    /// Reasoning content produced by the model (DeepSeek-R1, QwQ).
    pub reasoning_content: Option<String>,
}

/// Stream options with per-chunk usage reporting.
///
/// Extends upstream `ChatCompletionStreamOptions` with:
/// - `continuous_usage_stats`: emit usage in every chunk, not just the final one
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq)]
pub struct ChatCompletionStreamOptions {
    pub include_usage: bool,
    /// When true, usage statistics are included in every streaming chunk.
    /// Backends like vLLM/SGLang support this for real-time token counting.
    #[serde(default)]
    pub continuous_usage_stats: bool,
}

/// Chat completion request with multimodal processor support.
///
/// Extends upstream `CreateChatCompletionRequest` with:
/// - `mm_processor_kwargs`: multimodal processor configuration (vLLM-specific)
/// - Uses our extended `ChatCompletionRequestMessage` (with reasoning, video/audio)
/// - Uses our extended `ChatCompletionStreamOptions` (with continuous_usage_stats)
#[derive(Clone, Serialize, Default, Debug, Builder, Deserialize, PartialEq)]
#[builder(name = "CreateChatCompletionRequestArgs")]
#[builder(pattern = "mutable")]
#[builder(setter(into, strip_option), default)]
#[builder(derive(Debug))]
#[builder(build_fn(error = "OpenAIError"))]
pub struct CreateChatCompletionRequest {
    pub messages: Vec<ChatCompletionRequestMessage>,
    pub model: String,
    /// Multimodal processor configuration (vLLM-specific)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mm_processor_kwargs: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub store: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reasoning_effort: Option<ReasoningEffort>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub frequency_penalty: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logit_bias: Option<std::collections::HashMap<String, serde_json::Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logprobs: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_logprobs: Option<u8>,
    #[deprecated]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_tokens: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_completion_tokens: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub n: Option<u8>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub modalities: Option<Vec<async_openai::types::chat::ResponseModalities>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prediction: Option<PredictionContent>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub audio: Option<ChatCompletionAudio>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub presence_penalty: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_format: Option<ResponseFormat>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub seed: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub service_tier: Option<ServiceTier>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop: Option<Stop>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stream: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stream_options: Option<ChatCompletionStreamOptions>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_p: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<Vec<ChatCompletionTool>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_choice: Option<ChatCompletionToolChoiceOption>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parallel_tool_calls: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user: Option<String>,
    #[deprecated]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub function_call: Option<ChatCompletionFunctionCall>,
    #[deprecated]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub functions: Option<Vec<ChatCompletionFunctions>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub web_search_options: Option<WebSearchOptions>,
}

/// Chat choice with extended response message.
///
/// Uses our `ChatCompletionResponseMessage` (multimodal content + reasoning).
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
pub struct ChatChoice {
    pub index: u32,
    pub message: ChatCompletionResponseMessage,
    pub finish_reason: Option<FinishReason>,
    pub logprobs: Option<ChatChoiceLogprobs>,
}

/// Non-streaming chat completion response.
#[derive(Debug, Deserialize, Clone, PartialEq, Serialize)]
pub struct CreateChatCompletionResponse {
    pub id: String,
    pub choices: Vec<ChatChoice>,
    pub created: u32,
    pub model: String,
    pub service_tier: Option<ServiceTierResponse>,
    pub system_fingerprint: Option<String>,
    pub object: String,
    pub usage: Option<CompletionUsage>,
}

pub type ChatCompletionResponseStream =
    Pin<Box<dyn Stream<Item = Result<CreateChatCompletionStreamResponse, OpenAIError>> + Send>>;

/// Streaming delta with reasoning content.
///
/// Extends upstream `ChatCompletionStreamResponseDelta` with:
/// - `content`: `Option<ChatCompletionMessageContent>` (multimodal) instead of `Option<String>`
/// - `reasoning_content`: streaming reasoning tokens (DeepSeek-R1, QwQ)
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
pub struct ChatCompletionStreamResponseDelta {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<ChatCompletionMessageContent>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub function_call: Option<ChatCompletionStreamResponseDeltaFunctionCall>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_calls: Option<Vec<ChatCompletionMessageToolCallChunk>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub role: Option<Role>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub refusal: Option<String>,
    /// Streaming reasoning content (DeepSeek-R1, QwQ models).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reasoning_content: Option<String>,
}

#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
pub struct ChatCompletionStreamResponseDeltaFunctionCall {
    pub name: Option<String>,
    #[serde(default, deserialize_with = "deserialize_arguments_opt")]
    pub arguments: Option<String>,
}

/// Streaming chat choice.
#[derive(Debug, Deserialize, Clone, PartialEq, Serialize)]
pub struct ChatChoiceStream {
    pub index: u32,
    pub delta: ChatCompletionStreamResponseDelta,
    pub finish_reason: Option<FinishReason>,
    pub logprobs: Option<ChatChoiceLogprobs>,
}

/// Streaming chat completion response with extended choices.
#[derive(Debug, Deserialize, Clone, PartialEq, Serialize)]
pub struct CreateChatCompletionStreamResponse {
    pub id: String,
    pub choices: Vec<ChatChoiceStream>,
    pub created: u32,
    pub model: String,
    pub service_tier: Option<ServiceTierResponse>,
    pub system_fingerprint: Option<String>,
    pub object: String,
    pub usage: Option<CompletionUsage>,
}

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

    #[test]
    fn stop_accepts_token_id_array() {
        let stop: Stop = serde_json::from_value(serde_json::json!([32, 34])).unwrap();

        assert_eq!(stop, Stop::TokenIdArray(vec![32, 34]));
    }

    #[test]
    fn stop_accepts_string_and_string_array() {
        let stop: Stop = serde_json::from_value(serde_json::json!(" The")).unwrap();

        assert_eq!(stop, Stop::String(" The".to_string()));

        let stop: Stop = serde_json::from_value(serde_json::json!(["A", "B"])).unwrap();

        assert_eq!(
            stop,
            Stop::StringArray(vec!["A".to_string(), "B".to_string()])
        );
    }

    #[test]
    fn stop_token_id_display_string_remains_string_stop() {
        let stop: Stop = serde_json::from_value(serde_json::json!("token_id:576")).unwrap();

        assert_eq!(stop, Stop::String("token_id:576".to_string()));

        let stop: Stop = serde_json::from_value(serde_json::json!(["token_id:576"])).unwrap();

        assert_eq!(stop, Stop::StringArray(vec!["token_id:576".to_string()]));
    }

    #[test]
    fn stop_rejects_single_token_id() {
        let result = serde_json::from_value::<Stop>(serde_json::json!(576));

        assert!(result.is_err());
    }

    #[test]
    fn stop_converts_from_upstream_stop_configuration() {
        let upstream =
            async_openai::types::chat::StopConfiguration::StringArray(vec!["END".to_string()]);

        assert_eq!(
            Stop::from(upstream),
            Stop::StringArray(vec!["END".to_string()])
        );
    }

    #[test]
    fn request_builder_accepts_upstream_reasoning_effort() {
        let request = CreateChatCompletionRequestArgs::default()
            .reasoning_effort(async_openai::types::chat::ReasoningEffort::High)
            .build()
            .unwrap();

        assert_eq!(request.reasoning_effort, Some(ReasoningEffort::High));
    }

    #[test]
    fn tool_call_defaults_type_on_deserialize() {
        let tool_call: ChatCompletionMessageToolCall = serde_json::from_value(serde_json::json!({
            "id": "call_123",
            "function": {
                "name": "get_weather",
                "arguments": "{\"location\":\"SF\"}"
            }
        }))
        .unwrap();

        assert_eq!(tool_call.r#type, FunctionType::Function);
    }

    #[test]
    fn tool_call_serializes_type_for_wire_compat() {
        let tool_call = ChatCompletionMessageToolCall {
            id: "call_123".into(),
            r#type: FunctionType::Function,
            function: FunctionCall {
                name: "get_weather".into(),
                arguments: "{\"location\":\"SF\"}".into(),
            },
        };

        let json = serde_json::to_value(tool_call).unwrap();
        assert_eq!(json["type"], "function");
    }

    // -- dict-format arguments tests --

    #[test]
    fn function_call_accepts_string_arguments() {
        let fc: FunctionCall = serde_json::from_value(serde_json::json!({
            "name": "get_weather",
            "arguments": "{\"location\":\"SF\"}"
        }))
        .unwrap();
        assert_eq!(fc.arguments, "{\"location\":\"SF\"}");
    }

    #[test]
    fn function_call_accepts_dict_arguments() {
        let fc: FunctionCall = serde_json::from_value(serde_json::json!({
            "name": "get_weather",
            "arguments": {"location": "SF"}
        }))
        .unwrap();
        assert_eq!(fc.arguments, "{\"location\":\"SF\"}");
    }

    #[test]
    fn function_call_rejects_integer_arguments() {
        let result = serde_json::from_value::<FunctionCall>(serde_json::json!({
            "name": "f",
            "arguments": 42
        }));
        assert!(result.is_err());
    }

    #[test]
    fn function_call_rejects_boolean_arguments() {
        let result = serde_json::from_value::<FunctionCall>(serde_json::json!({
            "name": "f",
            "arguments": true
        }));
        assert!(result.is_err());
    }

    #[test]
    fn function_call_rejects_null_arguments() {
        let result = serde_json::from_value::<FunctionCall>(serde_json::json!({
            "name": "f",
            "arguments": null
        }));
        assert!(result.is_err());
    }

    #[test]
    fn function_call_rejects_array_arguments() {
        let result = serde_json::from_value::<FunctionCall>(serde_json::json!({
            "name": "f",
            "arguments": [1, 2, 3]
        }));
        assert!(result.is_err());
    }

    #[test]
    fn function_call_stream_null_arguments_produces_none() {
        let fcs: FunctionCallStream = serde_json::from_value(serde_json::json!({
            "name": "f",
            "arguments": null
        }))
        .unwrap();
        assert_eq!(fcs.arguments, None);
    }

    #[test]
    fn function_call_stream_rejects_integer_arguments() {
        let result = serde_json::from_value::<FunctionCallStream>(serde_json::json!({
            "name": "f",
            "arguments": 42
        }));
        assert!(result.is_err());
    }

    #[test]
    fn function_call_stream_rejects_boolean_arguments() {
        let result = serde_json::from_value::<FunctionCallStream>(serde_json::json!({
            "name": "f",
            "arguments": true
        }));
        assert!(result.is_err());
    }

    #[test]
    fn function_call_stream_accepts_dict_arguments() {
        let fcs: FunctionCallStream = serde_json::from_value(serde_json::json!({
            "name": "get_weather",
            "arguments": {"location": "SF"}
        }))
        .unwrap();
        assert_eq!(fcs.arguments.as_deref(), Some("{\"location\":\"SF\"}"));
    }

    #[test]
    fn function_call_stream_accepts_null_arguments() {
        let fcs: FunctionCallStream = serde_json::from_value(serde_json::json!({
            "name": "get_weather"
        }))
        .unwrap();
        assert_eq!(fcs.arguments, None);
    }

    #[test]
    fn tool_call_with_dict_arguments_roundtrip() {
        let tc: ChatCompletionMessageToolCall = serde_json::from_value(serde_json::json!({
            "id": "call_abc",
            "type": "function",
            "function": {
                "name": "search",
                "arguments": {"query": "hello", "limit": 10}
            }
        }))
        .unwrap();
        // Compare as parsed JSON values since key order is non-deterministic
        let parsed: serde_json::Value = serde_json::from_str(&tc.function.arguments).unwrap();
        assert_eq!(parsed, serde_json::json!({"query": "hello", "limit": 10}));
        // Re-serialisation produces a string, not an object
        let json = serde_json::to_value(&tc).unwrap();
        assert!(json["function"]["arguments"].is_string());
    }

    #[test]
    fn stream_delta_function_call_accepts_dict_arguments() {
        let delta: ChatCompletionStreamResponseDeltaFunctionCall =
            serde_json::from_value(serde_json::json!({
                "name": "get_weather",
                "arguments": {"location": "SF"}
            }))
            .unwrap();
        assert_eq!(delta.arguments.as_deref(), Some("{\"location\":\"SF\"}"));
    }
}