agent-framework-openai 0.9.0

OpenAI (and OpenAI-compatible) chat client for agent-framework-rs
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
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
//! Conversion between framework types and the OpenAI chat-completions wire
//! format.

use agent_framework_core::tools::ToolKind;
use agent_framework_core::types::{
    ChatOptions, ChatResponse, Content, DataContent, FinishReason, FunctionArguments,
    FunctionCallContent, FunctionResultContent, Message, Role, TextContent, TextReasoningContent,
    ToolMode, UsageDetails,
};
use serde_json::{json, Map, Value};

/// Default filename used for file attachments when the content carries none.
pub(crate) const DEFAULT_FILENAME: &str = "file";

/// The lower-cased top-level media type (the part before `/`), mirroring
/// upstream `_has_top_level_media_type`.
pub(crate) fn top_level_media_type(media_type: &str) -> String {
    let span = match media_type.find('/') {
        Some(i) => &media_type[..i],
        None => media_type,
    };
    span.trim().to_ascii_lowercase()
}

/// The OpenAI audio `format` string for a media type, or `None` if unsupported.
pub(crate) fn audio_format(media_type: &str) -> Option<&'static str> {
    if media_type.contains("wav") {
        Some("wav")
    } else if media_type.contains("mp3") || media_type.contains("mpeg") {
        Some("mp3")
    } else {
        None
    }
}

/// Strip a leading `data:<media-type>;base64,` prefix, returning just the base64
/// payload; a non-`data:` URI is returned unchanged (mirrors upstream).
pub(crate) fn strip_data_uri_prefix(uri: &str) -> &str {
    if uri.starts_with("data:") {
        uri.split_once(',').map_or(uri, |(_, payload)| payload)
    } else {
        uri
    }
}

/// Resolve a [`DataContent`]'s media type, parsing it from the `data:` URI when
/// the explicit field is absent (mirrors upstream, which always populates it
/// from the URI on construction).
pub(crate) fn data_content_media_type(data: &DataContent) -> Option<String> {
    if let Some(mt) = &data.media_type {
        return Some(mt.clone());
    }
    let rest = data.uri.strip_prefix("data:")?;
    let end = rest.find([';', ','])?;
    Some(rest[..end].to_string())
}

/// Maximum length of a sanitized Chat Completions message `name`.
const MAX_AUTHOR_NAME_LENGTH: usize = 64;

/// Sanitize an author name for the Chat Completions message `name` field.
///
/// The API validates `name` against `^[^\s<|\\/>]+$`, so an agent display name
/// containing a space (or any of `< | \ / >`) fails the whole request with a
/// 400. Mirrors upstream's `_sanitize_author_name`
/// (`_chat_completion_client.py`), which in turn mirrors `SanitizeAuthorName`
/// in the .NET client: drop every character outside `[a-zA-Z0-9_]`, return
/// `None` when nothing remains, and truncate to 64 characters.
///
/// Note this is stricter than the API's own regex on purpose — matching
/// upstream keeps a name that round-trips identically across the Python, .NET,
/// and Rust clients.
pub(crate) fn sanitize_author_name(name: &str) -> Option<String> {
    let sanitized: String = name
        .chars()
        .filter(|c| c.is_ascii_alphanumeric() || *c == '_')
        .take(MAX_AUTHOR_NAME_LENGTH)
        .collect();
    (!sanitized.is_empty()).then_some(sanitized)
}

/// Convert framework messages into the OpenAI `messages` array.
pub fn messages_to_openai(messages: &[Message]) -> Vec<Value> {
    let mut out = Vec::with_capacity(messages.len());
    for msg in messages {
        let role = msg.role.as_str();
        // Collect concatenated text, ordered content parts (for multimodal
        // input), tool calls, and tool results.
        let mut text = String::new();
        let mut parts: Vec<Value> = Vec::new();
        let mut has_media_part = false;
        let mut tool_calls: Vec<Value> = Vec::new();
        let mut tool_results: Vec<&FunctionResultContent> = Vec::new();

        // Refusal text replayed as history: the assistant message object
        // carries it in its own `refusal` field, not in `content`. Folding it
        // into `content` presents a decline to the provider as a successful
        // answer on the next turn, which is the distinction the marker exists
        // to keep. Verified against the API's assistant-message request
        // schema, which declares `refusal: Optional[str]`.
        let mut refusal = String::new();

        // The provider's own reasoning payload, replayed verbatim. See
        // `reasoning_details_of` — a reasoning model that requires it rejects
        // the tool-result turn without it.
        //
        // Accumulated across every reasoning content rather than taking the
        // last: a streamed turn splits the payload over several deltas, each
        // parsed into its own `TextReasoningContent`, and `coalesce_text`
        // leaves them separate precisely *because* each carries
        // `protected_data`. Keeping only the last would replay the tail of
        // the reasoning and drop everything before it.
        let mut reasoning_details: Vec<Value> = Vec::new();

        for content in &msg.contents {
            match content {
                Content::TextReasoning(t) => {
                    if let Some(details) = reasoning_details_of(t) {
                        // The payload is an array of reasoning blocks, so
                        // fragments concatenate in stream order. A payload
                        // that is not an array is kept whole rather than
                        // dropped — the provider is the authority on its own
                        // shape.
                        match details {
                            Value::Array(blocks) => reasoning_details.extend(blocks),
                            other => reasoning_details.push(other),
                        }
                    }
                }
                Content::Text(t) if t.refusal => {
                    refusal.push_str(&t.text);
                }
                Content::Text(t) => {
                    text.push_str(&t.text);
                    parts.push(json!({ "type": "text", "text": t.text }));
                }
                Content::FunctionCall(fc) => tool_calls.push(function_call_to_openai(fc)),
                Content::FunctionResult(fr) => tool_results.push(fr),
                Content::Uri(u) => {
                    if let Some(part) = content_part_to_openai(&u.uri, Some(&u.media_type)) {
                        parts.push(part);
                        has_media_part = true;
                    }
                }
                Content::Data(d) => {
                    if let Some(part) =
                        content_part_to_openai(&d.uri, data_content_media_type(d).as_deref())
                    {
                        parts.push(part);
                        has_media_part = true;
                    }
                }
                _ => {}
            }
        }

        // A tool-role message maps each result to its own OpenAI `tool` message.
        if role == Role::TOOL {
            for fr in tool_results {
                out.push(json!({
                    "role": "tool",
                    "tool_call_id": fr.call_id,
                    "content": result_to_string(fr),
                }));
            }
            continue;
        }

        let mut obj = Map::new();
        obj.insert("role".into(), json!(role));
        // When a non-text (image/audio/file) part is present, emit a typed
        // content-parts array with text folded in as `{"type":"text",...}`
        // parts; otherwise keep the plain-string form for wire stability.
        if has_media_part {
            obj.insert("content".into(), Value::Array(parts));
        } else if !text.is_empty() || tool_calls.is_empty() {
            obj.insert("content".into(), json!(text));
        }
        if !refusal.is_empty() {
            obj.insert("refusal".into(), json!(refusal));
        }
        if let Some(name) = msg.author_name.as_deref().and_then(sanitize_author_name) {
            obj.insert("name".into(), json!(name));
        }
        if !tool_calls.is_empty() {
            obj.insert("tool_calls".into(), json!(tool_calls));
        }
        // Only ever emitted when the provider gave us one: OpenAI proper
        // never sets `reasoning_details`, and answers a field its api-version
        // does not know with an error rather than ignoring it.
        if !reasoning_details.is_empty() {
            let details = Value::Array(reasoning_details);
            if obj.contains_key("content") || obj.contains_key("tool_calls") {
                obj.insert("reasoning_details".into(), details);
            }
        }
        out.push(Value::Object(obj));
    }
    out
}

/// Map a URI/data content item to a Chat Completions content part, or `None`
/// when it has no wire mapping (skipped, mirroring upstream
/// `_openai_content_parser`). Handles images (`image_url`), audio
/// (`input_audio`), and `application/*` data URIs (`file`).
fn content_part_to_openai(uri: &str, media_type: Option<&str>) -> Option<Value> {
    let media_type = media_type?;
    match top_level_media_type(media_type).as_str() {
        "image" => Some(json!({ "type": "image_url", "image_url": { "url": uri } })),
        "audio" => {
            let format = audio_format(media_type)?;
            Some(json!({
                "type": "input_audio",
                "input_audio": { "data": strip_data_uri_prefix(uri), "format": format },
            }))
        }
        "application" if uri.starts_with("data:") => Some(json!({
            "type": "file",
            "file": { "file_data": uri, "filename": DEFAULT_FILENAME },
        })),
        _ => None,
    }
}

/// Render a function/tool result as the plain-text/JSON string OpenAI wire
/// formats expect for tool output. Shared by Chat Completions and Responses.
pub(crate) fn result_to_string(fr: &FunctionResultContent) -> String {
    if let Some(exc) = &fr.exception {
        return format!("error: {exc}");
    }
    match &fr.result {
        Some(Value::String(s)) => s.clone(),
        Some(v) => v.to_string(),
        None => String::new(),
    }
}

fn function_call_to_openai(fc: &FunctionCallContent) -> Value {
    json!({
        "id": fc.call_id,
        "type": "function",
        "function": { "name": fc.name, "arguments": function_arguments_to_string(&fc.arguments) }
    })
}

/// Render function-call arguments as the JSON-encoded string the OpenAI wire
/// formats (Chat Completions and Responses alike) expect.
///
/// Public (but hidden) so `responses.rs` in this crate, and any
/// OpenAI-wire-compatible reuse outside it, can share the exact same
/// stringification instead of duplicating it.
#[doc(hidden)]
pub fn function_arguments_to_string(args: &Option<FunctionArguments>) -> String {
    match args {
        Some(FunctionArguments::Raw(s)) => s.clone(),
        Some(FunctionArguments::Object(m)) => {
            serde_json::to_string(m).unwrap_or_else(|_| "{}".into())
        }
        None => "{}".into(),
    }
}

/// Build the tools array and tool_choice for a request.
///
/// Only [`ToolKind::Function`] tools are emitted in `tools`. A hosted
/// web-search tool is surfaced separately as the top-level `web_search_options`
/// field (see [`apply_options`]); any other hosted kind is unsupported on Chat
/// Completions and skipped with a warning. Mirrors upstream
/// `_chat_client._chat_to_tool_spec`.
pub fn tools_to_openai(options: &ChatOptions) -> (Option<Value>, Option<Value>) {
    let tools: Vec<Value> = options
        .tools
        .iter()
        .filter_map(|t| match &t.kind {
            ToolKind::Function => Some(t.to_openai_spec()),
            // Surfaced as `web_search_options`, not a `tools` entry.
            ToolKind::HostedWebSearch => None,
            other => {
                tracing::warn!(
                    tool = %t.name,
                    kind = ?other,
                    "hosted tool is not supported on the Chat Completions API; skipping",
                );
                None
            }
        })
        .collect();
    if tools.is_empty() {
        return (None, None);
    }
    let choice = options.tool_choice.as_ref().map(|tc| match tc {
        ToolMode::Auto => json!("auto"),
        ToolMode::None => json!("none"),
        ToolMode::Required(Some(name)) => {
            json!({ "type": "function", "function": { "name": name } })
        }
        ToolMode::Required(None) => json!("required"),
    });
    (Some(json!(tools)), choice)
}

/// Apply the scalar chat options onto a request body map.
pub fn apply_options(body: &mut Map<String, Value>, options: &ChatOptions) {
    macro_rules! set {
        ($key:literal, $val:expr) => {
            if let Some(v) = $val {
                body.insert($key.into(), json!(v));
            }
        };
    }
    set!("temperature", options.temperature);
    set!("top_p", options.top_p);
    set!("max_tokens", options.max_tokens);
    set!("frequency_penalty", options.frequency_penalty);
    set!("presence_penalty", options.presence_penalty);
    set!("seed", options.seed);
    set!("user", options.user.clone());
    set!("store", options.store);
    if let Some(stop) = &options.stop {
        body.insert("stop".into(), json!(stop));
    }
    if let Some(fmt) = &options.response_format {
        // `ResponseFormat` serializes directly to the Chat Completions
        // `response_format` object for all three variants.
        body.insert("response_format".into(), json!(fmt));
    }
    if let Some(bias) = &options.logit_bias {
        body.insert("logit_bias".into(), json!(bias));
    }
    if let Some(metadata) = &options.metadata {
        body.insert("metadata".into(), json!(metadata));
    }
    // `parallel_tool_calls` is only valid alongside function tools; upstream
    // drops it otherwise (`_chat_client._prepare_options`).
    if let Some(allow) = options.allow_multiple_tool_calls {
        if options.tools.iter().any(|t| t.kind == ToolKind::Function) {
            body.insert("parallel_tool_calls".into(), json!(allow));
        }
    }
    // A hosted web-search tool is expressed as the top-level
    // `web_search_options` request field rather than an entry in `tools`
    // (`_chat_client._process_web_search_tool`). An explicit
    // `ToolMode::None` disables it like every other tool — that field is
    // what *enables* hosted browsing on Chat Completions, and upstream
    // clears the tool list before conversion in that mode
    // (`_clients._prepare_tool_choice`), so nothing would be emitted there
    // either.
    if options.tool_choice != Some(ToolMode::None) {
        if let Some(tool) = options
            .tools
            .iter()
            .find(|t| t.kind == ToolKind::HostedWebSearch)
        {
            let mut ws = Map::new();
            if let Some(loc) = tool.parameters.get("user_location") {
                ws.insert(
                    "user_location".into(),
                    json!({ "type": "approximate", "approximate": loc }),
                );
            }
            body.insert("web_search_options".into(), Value::Object(ws));
        }
    }
    for (k, v) in &options.additional_properties {
        body.entry(k.clone()).or_insert_with(|| v.clone());
    }
}

/// Parse a full (non-streaming) OpenAI chat-completion response.
pub fn parse_response(value: &Value) -> ChatResponse {
    let mut response = ChatResponse {
        response_id: value.get("id").and_then(Value::as_str).map(String::from),
        model: value.get("model").and_then(Value::as_str).map(String::from),
        ..Default::default()
    };

    if let Some(choice) = value
        .get("choices")
        .and_then(|c| c.as_array())
        .and_then(|a| a.first())
    {
        let mut contents: Vec<Content> = Vec::new();
        if let Some(msg) = choice.get("message") {
            if let Some(text) = msg.get("content").and_then(Value::as_str) {
                if !text.is_empty() {
                    contents.push(Content::Text(TextContent::new(text)));
                }
            }
            // A refusal is surfaced as text *marked as a refusal*, so it can
            // never be mistaken for the answer (mirrors upstream #7992). It is
            // emitted whether or not ordinary content is present: the two are
            // separate content items, and dropping the refusal when content
            // happens to accompany it would hide the fact that the model
            // declined part of what was asked.
            if let Some(refusal) = msg.get("refusal").and_then(Value::as_str) {
                if !refusal.is_empty() {
                    contents.push(Content::Text(TextContent::refusal(refusal)));
                }
            }
            if let Some(reasoning) = parse_reasoning_details(msg) {
                contents.push(reasoning);
            }
            if let Some(calls) = msg.get("tool_calls").and_then(Value::as_array) {
                for call in calls {
                    if let Some(fc) = parse_tool_call(call) {
                        contents.push(Content::FunctionCall(fc));
                    }
                }
            }
        }
        let mut message = Message::with_contents(Role::assistant(), contents);
        message.message_id = response.response_id.clone();
        response.messages.push(message);

        if let Some(fr) = choice.get("finish_reason").and_then(Value::as_str) {
            response.finish_reason = Some(FinishReason::new(fr));
        }
    }

    if let Some(usage) = value.get("usage") {
        response.usage_details = Some(parse_usage(usage));
    }
    response
}

/// The provider reasoning payload to replay for a reasoning content, or
/// `None` when it carries none this client can send.
///
/// Reasoning-capable providers on the Chat Completions surface — DeepSeek in
/// thinking mode, OpenRouter, vLLM — return a `reasoning_details` array
/// alongside the answer and **require it back** on the next request of the
/// same turn, which in a tool loop is the tool-result follow-up. Dropping it
/// turns a working conversation into a rejected one at exactly the point the
/// model was about to use its own work (upstream #8382/#8405). It rides in
/// [`TextReasoningContent::protected_data`], the same field the Anthropic
/// thinking signature and the Gemini thought signature use, because it is the
/// same kind of thing: opaque provider state that is replayed, never read.
///
/// A payload that is not JSON is skipped rather than sent: it did not come
/// from this client's parser, and a non-JSON `reasoning_details` is a request
/// the provider rejects — dropping one reasoning block is recoverable, a
/// rejected request is not.
fn reasoning_details_of(content: &TextReasoningContent) -> Option<Value> {
    let raw = content
        .protected_data
        .as_deref()
        .filter(|s| !s.is_empty())?;
    match serde_json::from_str::<Value>(raw) {
        Ok(value) => Some(value),
        Err(e) => {
            tracing::warn!(
                error = %e,
                "dropping a reasoning payload that is not JSON rather than sending it"
            );
            None
        }
    }
}

/// Read a `reasoning_details` payload off a choice's message or delta into a
/// reasoning content. The text stays empty — the payload is opaque provider
/// state, not something to show a user or count as an answer.
pub(crate) fn parse_reasoning_details(message_or_delta: &Value) -> Option<Content> {
    let details = message_or_delta.get("reasoning_details")?;
    if details.is_null() || matches!(details, Value::Array(a) if a.is_empty()) {
        return None;
    }
    Some(Content::TextReasoning(TextReasoningContent {
        text: String::new(),
        protected_data: Some(details.to_string()),
        ..Default::default()
    }))
}

fn parse_tool_call(call: &Value) -> Option<FunctionCallContent> {
    let id = call.get("id").and_then(Value::as_str)?.to_string();
    let func = call.get("function")?;
    let name = func
        .get("name")
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_string();
    let args = func
        .get("arguments")
        .and_then(Value::as_str)
        .unwrap_or("{}")
        .to_string();
    Some(FunctionCallContent::new(
        id,
        name,
        Some(FunctionArguments::Raw(args)),
    ))
}

/// Parse an OpenAI-shaped `usage` object into [`UsageDetails`].
///
/// Detail breakdowns (`completion_tokens_details.*`, `prompt_tokens_details.*`)
/// are folded into [`UsageDetails::additional_counts`] under the same keys
/// upstream uses (`_chat_client._usage_details_from_openai`).
///
/// Public (but hidden) so `agent-framework-azure` can reuse it verbatim.
#[doc(hidden)]
pub fn parse_usage(usage: &Value) -> UsageDetails {
    let mut details = UsageDetails {
        input_token_count: usage.get("prompt_tokens").and_then(Value::as_u64),
        output_token_count: usage.get("completion_tokens").and_then(Value::as_u64),
        total_token_count: usage.get("total_tokens").and_then(Value::as_u64),
        ..Default::default()
    };
    if let Some(ctd) = usage.get("completion_tokens_details") {
        add_usage_detail(
            &mut details,
            ctd,
            "accepted_prediction_tokens",
            "completion/accepted_prediction_tokens",
        );
        add_usage_detail(&mut details, ctd, "audio_tokens", "completion/audio_tokens");
        add_usage_detail(
            &mut details,
            ctd,
            "reasoning_tokens",
            "completion/reasoning_tokens",
        );
        // Mirror upstream: the reasoning count is also surfaced as the typed,
        // cross-language field in addition to the provider-prefixed extra.
        details.reasoning_output_token_count = ctd.get("reasoning_tokens").and_then(Value::as_u64);
        add_usage_detail(
            &mut details,
            ctd,
            "rejected_prediction_tokens",
            "completion/rejected_prediction_tokens",
        );
    }
    if let Some(ptd) = usage.get("prompt_tokens_details") {
        add_usage_detail(&mut details, ptd, "audio_tokens", "prompt/audio_tokens");
        add_usage_detail(&mut details, ptd, "cached_tokens", "prompt/cached_tokens");
        // Mirror upstream: cached prompt tokens also populate the typed field.
        details.cache_read_input_token_count = ptd.get("cached_tokens").and_then(Value::as_u64);
        // Cache *writes* are reported separately from cache reads; surface both
        // the provider-prefixed extra and the typed cross-language field. Absent
        // when the provider does not report it (older API versions).
        if let Some(cache_write) = ptd.get("cache_write_tokens").and_then(Value::as_u64) {
            details
                .additional_counts
                .insert("prompt/cache_write_tokens".into(), cache_write);
            details.cache_creation_input_token_count = Some(cache_write);
        }
    }
    details
}

/// Copy a reported token count from `obj[src]` into `details.additional_counts`
/// under `dest`. An absent (or non-integer) count is skipped; a **reported zero
/// is recorded**, because "the model used none of this" and "the provider did
/// not report this" are different facts and `additional_counts` can only say
/// the second by omission.
///
/// This used to skip zeros, mirroring upstream's truthy `if tokens := ...`
/// guard — Python's walrus is falsy for `0`, so a reported zero vanished.
/// Upstream fixed that to `is not None` (#7964); the port had inherited the
/// bug, test included.
fn add_usage_detail(details: &mut UsageDetails, obj: &Value, src: &str, dest: &str) {
    if let Some(v) = obj.get(src).and_then(Value::as_u64) {
        details.additional_counts.insert(dest.to_string(), v);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use agent_framework_core::tools::{
        hosted_code_interpreter, hosted_web_search, ApprovalMode, ToolDefinition,
    };
    use agent_framework_core::types::{TextReasoningContent, UriContent};
    use std::collections::HashMap;

    fn function_tool(name: &str) -> ToolDefinition {
        ToolDefinition {
            name: name.into(),
            description: "desc".into(),
            parameters: json!({ "type": "object", "properties": {} }),
            kind: ToolKind::Function,
            approval_mode: ApprovalMode::NeverRequire,
            executor: None,
        }
    }

    fn user_with(contents: Vec<Content>) -> Message {
        Message::with_contents(Role::user(), contents)
    }

    // region: multimodal input

    #[test]
    fn text_only_message_stays_a_content_string() {
        let out = messages_to_openai(&[Message::user("hi")]);
        assert_eq!(out[0], json!({ "role": "user", "content": "hi" }));
    }

    #[test]
    fn unsigned_reasoning_text_is_not_sent() {
        // Reasoning *text* has no chat-completions wire mapping — only the
        // opaque `reasoning_details` payload below does — so it is skipped and
        // the message keeps the plain-string content form.
        let msg = user_with(vec![
            Content::Text(TextContent::new("hi")),
            Content::TextReasoning(TextReasoningContent {
                text: "secret".into(),
                annotations: None,
                ..Default::default()
            }),
        ]);
        assert_eq!(
            messages_to_openai(&[msg])[0],
            json!({ "role": "user", "content": "hi" })
        );
    }

    // region: reasoning_details round trip (upstream #8382/#8405)

    #[test]
    fn a_reasoning_payload_rides_back_out_on_the_message_that_carries_the_turn() {
        // DeepSeek-in-thinking-mode and friends reject the tool-result
        // follow-up when the assistant message that carried the turn arrives
        // without the reasoning payload they issued with it.
        let msg = Message::with_contents(
            Role::assistant(),
            vec![
                Content::TextReasoning(TextReasoningContent {
                    text: String::new(),
                    protected_data: Some(r#"[{"type":"reasoning.text","text":"think"}]"#.into()),
                    ..Default::default()
                }),
                Content::Text(TextContent::new("the answer")),
                Content::FunctionCall(FunctionCallContent::new(
                    "c1",
                    "f",
                    Some(FunctionArguments::Raw("{}".into())),
                )),
            ],
        );
        let wire = messages_to_openai(&[msg]);
        // One assistant message carries content, tool_calls and the payload
        // together — splitting them is what left the reasoning on the wrong
        // half upstream.
        assert_eq!(wire.len(), 1);
        assert_eq!(
            wire[0]["reasoning_details"],
            json!([{"type": "reasoning.text", "text": "think"}])
        );
        assert_eq!(wire[0]["content"], json!("the answer"));
        assert!(wire[0]["tool_calls"].is_array());
    }

    #[test]
    fn reasoning_payloads_split_across_a_stream_are_replayed_whole() {
        // A streamed turn emits `reasoning_details` over several deltas, each
        // parsed into its own content — and `coalesce_text` leaves them
        // separate precisely because each carries `protected_data`. Taking
        // the last would replay the tail and drop everything before it, which
        // is exactly what a provider requiring the full payload rejects.
        let msg = Message::with_contents(
            Role::assistant(),
            vec![
                Content::TextReasoning(TextReasoningContent {
                    protected_data: Some(r#"[{"type":"reasoning.text","text":"first"}]"#.into()),
                    ..Default::default()
                }),
                Content::TextReasoning(TextReasoningContent {
                    protected_data: Some(r#"[{"type":"reasoning.text","text":"second"}]"#.into()),
                    ..Default::default()
                }),
                Content::Text(TextContent::new("the answer")),
            ],
        );
        let wire = messages_to_openai(&[msg]);
        assert_eq!(
            wire[0]["reasoning_details"],
            json!([
                {"type": "reasoning.text", "text": "first"},
                {"type": "reasoning.text", "text": "second"},
            ]),
            "fragments concatenate in stream order"
        );
    }

    #[test]
    fn a_non_array_reasoning_payload_is_kept_whole() {
        // The provider is the authority on its own shape; dropping an
        // unexpected one would lose the replay token it needs back.
        let msg = Message::with_contents(
            Role::assistant(),
            vec![
                Content::TextReasoning(TextReasoningContent {
                    protected_data: Some(r#"{"opaque":"blob"}"#.into()),
                    ..Default::default()
                }),
                Content::Text(TextContent::new("the answer")),
            ],
        );
        let wire = messages_to_openai(&[msg]);
        assert_eq!(wire[0]["reasoning_details"], json!([{"opaque": "blob"}]));
    }

    #[test]
    fn a_message_with_no_reasoning_payload_grows_no_field() {
        // OpenAI proper does not know `reasoning_details` and answers an
        // unrecognized request field with an error rather than ignoring it.
        let wire = messages_to_openai(&[Message::user("hi")]);
        assert!(wire[0].get("reasoning_details").is_none());
    }

    #[test]
    fn a_reasoning_payload_that_is_not_json_is_dropped_rather_than_sent() {
        // An Anthropic thinking signature shares the field and is not JSON;
        // sending it would turn a working request into a 400.
        let msg = Message::with_contents(
            Role::assistant(),
            vec![
                Content::TextReasoning(TextReasoningContent {
                    text: String::new(),
                    protected_data: Some("ErUBCkYIBxgCKkA".into()),
                    ..Default::default()
                }),
                Content::Text(TextContent::new("answer")),
            ],
        );
        let wire = messages_to_openai(&[msg]);
        assert!(wire[0].get("reasoning_details").is_none());
        assert_eq!(wire[0]["content"], json!("answer"));
    }

    #[test]
    fn a_reasoning_payload_round_trips_through_the_parser() {
        let response = parse_response(&json!({
            "id": "chatcmpl-1",
            "choices": [{
                "message": {
                    "role": "assistant",
                    "content": "answer",
                    "reasoning_details": [{"type": "reasoning.text", "text": "think"}],
                },
                "finish_reason": "stop",
            }],
        }));
        let reasoning = response.messages[0]
            .contents
            .iter()
            .find_map(|c| match c {
                Content::TextReasoning(t) => Some(t),
                _ => None,
            })
            .expect("the payload is parsed into reasoning content");
        // Empty text: the payload is opaque provider state, not an answer.
        assert!(reasoning.text.is_empty());
        // And it survives a full round trip, which is the property that makes
        // the follow-up request valid.
        let wire = messages_to_openai(&response.messages);
        assert_eq!(
            wire[0]["reasoning_details"],
            json!([{"type": "reasoning.text", "text": "think"}])
        );
    }

    #[test]
    fn an_absent_or_empty_reasoning_payload_parses_to_nothing() {
        for details in [json!(null), json!([])] {
            let response = parse_response(&json!({
                "choices": [{ "message": { "role": "assistant", "content": "a",
                                           "reasoning_details": details } }],
            }));
            assert!(
                !response.messages[0]
                    .contents
                    .iter()
                    .any(|c| matches!(c, Content::TextReasoning(_))),
                "{details} should produce no reasoning content"
            );
        }
    }

    #[test]
    fn image_uri_becomes_content_parts_array() {
        let msg = user_with(vec![
            Content::Text(TextContent::new("look:")),
            Content::Uri(UriContent {
                uri: "https://example.com/cat.png".into(),
                media_type: "image/png".into(),
            }),
        ]);
        assert_eq!(
            messages_to_openai(&[msg])[0],
            json!({
                "role": "user",
                "content": [
                    { "type": "text", "text": "look:" },
                    { "type": "image_url", "image_url": { "url": "https://example.com/cat.png" } },
                ],
            })
        );
    }

    // region: universal-rendering contract

    /// The canonical samples the core contract claims render on every
    /// provider. If this converter stops emitting one of them, the failure
    /// belongs here — next to the converter — not in compaction.
    fn universal_content_samples() -> Vec<Content> {
        use agent_framework_core::types::{
            DataContent, FunctionArguments, FunctionCallContent, FunctionResultContent,
        };
        vec![
            Content::text("hello"),
            Content::FunctionCall(FunctionCallContent::new(
                "contract_call_1",
                "get_weather",
                Some(FunctionArguments::Raw("{\"city\":\"SF\"}".into())),
            )),
            Content::FunctionResult(FunctionResultContent::new(
                "contract_call_1",
                Some(serde_json::json!("sunny")),
            )),
            Content::Data(DataContent::from_bytes(b"png-bytes", "image/png")),
            Content::Data(DataContent::from_bytes(b"jpeg-bytes", "image/jpeg")),
            Content::Data(DataContent::from_bytes(b"webp-bytes", "image/webp")),
            Content::Data(DataContent::from_bytes(b"gif-bytes", "image/gif")),
        ]
    }

    #[test]
    fn every_universal_content_survives_chat_completions_conversion() {
        // messages_to_openai is also the build path for the Ollama, Mistral,
        // Foundry Local and GitHub Copilot crates, so this contract covers all
        // of them at once.
        for content in universal_content_samples() {
            assert!(content.renders_on_every_provider(), "sample not universal");
            let role = if matches!(content, Content::FunctionResult(_)) {
                Role::tool()
            } else if matches!(content, Content::FunctionCall(_)) {
                Role::assistant()
            } else {
                Role::user()
            };
            let msg = Message::with_contents(role, vec![content.clone()]);
            let out = messages_to_openai(&[msg]);
            let emitted = out.iter().any(|m| {
                m.get("tool_calls")
                    .is_some_and(|t| !t.as_array().unwrap().is_empty())
                    || m.get("tool_call_id").is_some()
                    || m.get("content").is_some_and(|c| match c {
                        Value::String(s) => !s.is_empty(),
                        Value::Array(parts) => !parts.is_empty(),
                        _ => false,
                    })
            });
            assert!(
                emitted,
                "core claims this renders everywhere but Chat Completions emits nothing: {content:?}"
            );
        }
    }

    // region: author-name sanitization (upstream #7127)

    #[test]
    fn author_name_is_sanitized_for_the_name_field() {
        // The API validates `name` against `^[^\s<|\\/>]+$`, so a display name
        // with a space used to fail the whole request with a 400.
        assert_eq!(sanitize_author_name("My Agent").as_deref(), Some("MyAgent"));
        assert_eq!(sanitize_author_name("agent_1").as_deref(), Some("agent_1"));
        // Characters the API rejects but that are not whitespace — the previous
        // whitespace-only guard let these through into a 400.
        assert_eq!(sanitize_author_name("a/b|c").as_deref(), Some("abc"));
        // Nothing survives sanitization -> omit the field entirely.
        assert_eq!(sanitize_author_name("***"), None);
        assert_eq!(sanitize_author_name(""), None);
        // Truncated to the 64-character limit.
        assert_eq!(sanitize_author_name(&"a".repeat(100)).unwrap().len(), 64);
    }

    #[test]
    fn messages_to_openai_emits_a_sanitized_name() {
        let mut msg = Message::assistant("hi");
        msg.author_name = Some("My Agent".into());
        let out = messages_to_openai(&[msg]);
        assert_eq!(out[0]["name"], json!("MyAgent"));

        // A name that sanitizes to nothing is omitted rather than sent empty.
        let mut msg = Message::assistant("hi");
        msg.author_name = Some("!!!".into());
        let out = messages_to_openai(&[msg]);
        assert!(out[0].get("name").is_none());
    }

    // region: cache-write tokens (upstream #7369)

    #[test]
    fn additional_properties_carry_request_wide_options_verbatim() {
        // Request-wide options this port has no typed field for — e.g.
        // GPT-5.6's `prompt_cache_options` (upstream #7163) — reach the wire
        // through `ChatOptions::additional_properties`, so no typed surface is
        // needed for them. (The *per-content* `prompt_cache_breakpoint` half of
        // that upstream change is not expressible: it needs
        // `additional_properties` on content items, which this port lacks.)
        let mut options = ChatOptions::new();
        options.additional_properties.insert(
            "prompt_cache_options".into(),
            json!({ "mode": "explicit", "ttl": "30m" }),
        );
        let mut body = Map::new();
        apply_options(&mut body, &options);
        assert_eq!(
            body["prompt_cache_options"],
            json!({ "mode": "explicit", "ttl": "30m" })
        );
    }

    #[test]
    fn usage_parses_cache_write_tokens() {
        let usage = json!({
            "prompt_tokens": 2000,
            "completion_tokens": 60,
            "prompt_tokens_details": { "cached_tokens": 0, "cache_write_tokens": 1024 },
        });
        let d = parse_usage(&usage);
        assert_eq!(d.cache_creation_input_token_count, Some(1024));
        assert_eq!(d.cache_read_input_token_count, Some(0));
        assert_eq!(
            d.additional_counts.get("prompt/cache_write_tokens"),
            Some(&1024)
        );
    }

    #[test]
    fn usage_omits_cache_write_tokens_when_not_reported() {
        let usage = json!({
            "prompt_tokens": 100,
            "completion_tokens": 20,
            "prompt_tokens_details": { "cached_tokens": 40 },
        });
        let d = parse_usage(&usage);
        assert_eq!(d.cache_creation_input_token_count, None);
        assert!(!d
            .additional_counts
            .contains_key("prompt/cache_write_tokens"));
    }

    #[test]
    fn image_data_uri_infers_media_type_from_uri() {
        // media_type is None; it must be parsed from the data URI prefix.
        let msg = user_with(vec![Content::Data(DataContent {
            uri: "data:image/png;base64,AAAA".into(),
            media_type: None,
        })]);
        assert_eq!(
            messages_to_openai(&[msg])[0],
            json!({
                "role": "user",
                "content": [
                    { "type": "image_url", "image_url": { "url": "data:image/png;base64,AAAA" } },
                ],
            })
        );
    }

    #[test]
    fn audio_data_becomes_input_audio_with_stripped_base64() {
        let msg = user_with(vec![Content::Data(DataContent {
            uri: "data:audio/wav;base64,QQQQ".into(),
            media_type: Some("audio/wav".into()),
        })]);
        assert_eq!(
            messages_to_openai(&[msg])[0],
            json!({
                "role": "user",
                "content": [
                    { "type": "input_audio", "input_audio": { "data": "QQQQ", "format": "wav" } },
                ],
            })
        );
    }

    #[test]
    fn audio_mpeg_maps_to_mp3_format() {
        let msg = user_with(vec![Content::Data(DataContent {
            uri: "data:audio/mpeg;base64,SUQz".into(),
            media_type: Some("audio/mpeg".into()),
        })]);
        let out = messages_to_openai(&[msg]);
        assert_eq!(out[0]["content"][0]["input_audio"]["format"], json!("mp3"));
    }

    #[test]
    fn unsupported_audio_format_is_skipped() {
        // ogg has no OpenAI `input_audio` format: the part is dropped, leaving
        // a text-only string message.
        let msg = user_with(vec![
            Content::Text(TextContent::new("clip")),
            Content::Data(DataContent {
                uri: "data:audio/ogg;base64,T2dn".into(),
                media_type: Some("audio/ogg".into()),
            }),
        ]);
        assert_eq!(
            messages_to_openai(&[msg])[0],
            json!({ "role": "user", "content": "clip" })
        );
    }

    #[test]
    fn application_data_becomes_file_part_with_default_filename() {
        let msg = user_with(vec![Content::Data(DataContent {
            uri: "data:application/pdf;base64,JVBERi0x".into(),
            media_type: Some("application/pdf".into()),
        })]);
        assert_eq!(
            messages_to_openai(&[msg])[0],
            json!({
                "role": "user",
                "content": [
                    { "type": "file", "file": {
                        "file_data": "data:application/pdf;base64,JVBERi0x",
                        "filename": "file",
                    } },
                ],
            })
        );
    }

    #[test]
    fn assistant_tool_call_only_still_omits_content() {
        let msg = Message::with_contents(
            Role::assistant(),
            vec![Content::FunctionCall(FunctionCallContent::new(
                "call_1",
                "f",
                Some(FunctionArguments::Raw("{}".into())),
            ))],
        );
        let out = messages_to_openai(&[msg]);
        assert!(out[0].get("content").is_none());
        assert_eq!(out[0]["tool_calls"][0]["function"]["name"], json!("f"));
    }

    // endregion

    // region: tools & hosted tools

    #[test]
    fn only_function_tools_emitted_web_search_excluded() {
        let mut options = ChatOptions::new();
        options.tools = vec![function_tool("get_weather"), hosted_web_search()];
        let (tools, _choice) = tools_to_openai(&options);
        let tools = tools.unwrap();
        assert_eq!(tools.as_array().unwrap().len(), 1);
        assert_eq!(tools[0]["function"]["name"], json!("get_weather"));
    }

    #[test]
    fn other_hosted_tools_are_skipped() {
        let mut options = ChatOptions::new();
        options.tools = vec![hosted_code_interpreter()];
        let (tools, choice) = tools_to_openai(&options);
        assert!(tools.is_none());
        assert!(choice.is_none());
    }

    #[test]
    fn web_search_tool_sets_web_search_options_with_user_location() {
        let mut tool = hosted_web_search();
        tool.parameters = json!({ "user_location": { "city": "Seattle", "country": "US" } });
        let mut options = ChatOptions::new();
        options.tools = vec![tool];
        let mut body = Map::new();
        apply_options(&mut body, &options);
        assert_eq!(
            body["web_search_options"],
            json!({
                "user_location": {
                    "type": "approximate",
                    "approximate": { "city": "Seattle", "country": "US" },
                },
            })
        );
    }

    #[test]
    fn web_search_tool_without_location_sets_empty_options() {
        let mut options = ChatOptions::new();
        options.tools = vec![hosted_web_search()];
        let mut body = Map::new();
        apply_options(&mut body, &options);
        assert_eq!(body["web_search_options"], json!({}));
    }

    #[test]
    fn web_search_options_suppressed_when_tool_choice_is_none() {
        // `web_search_options` is what ENABLES hosted browsing on Chat
        // Completions — an explicit "no tools" run must not emit it.
        let mut options = ChatOptions::new().with_tool_choice(ToolMode::None);
        options.tools = vec![hosted_web_search()];
        let mut body = Map::new();
        apply_options(&mut body, &options);
        assert!(body.get("web_search_options").is_none());
    }

    // endregion

    // region: request options

    #[test]
    fn logit_bias_metadata_and_parallel_tool_calls_are_sent() {
        let mut options = ChatOptions::new();
        options.logit_bias = Some(HashMap::from([("50256".to_string(), -100.0)]));
        options.metadata = Some(HashMap::from([("session".to_string(), "abc".to_string())]));
        options.allow_multiple_tool_calls = Some(true);
        options.tools = vec![function_tool("f")];
        let mut body = Map::new();
        apply_options(&mut body, &options);
        assert_eq!(body["logit_bias"], json!({ "50256": -100.0 }));
        assert_eq!(body["metadata"], json!({ "session": "abc" }));
        assert_eq!(body["parallel_tool_calls"], json!(true));
    }

    #[test]
    fn parallel_tool_calls_omitted_without_function_tools() {
        let mut options = ChatOptions::new();
        options.allow_multiple_tool_calls = Some(true);
        // Only a hosted tool: `parallel_tool_calls` would be an API error.
        options.tools = vec![hosted_web_search()];
        let mut body = Map::new();
        apply_options(&mut body, &options);
        assert!(body.get("parallel_tool_calls").is_none());
    }

    // endregion

    // region: response parsing

    #[test]
    fn a_replayed_refusal_uses_the_assistant_refusal_field_not_content() {
        // Replaying a refusal as ordinary `content` tells the provider the
        // assistant answered, on every subsequent turn — the exact
        // distinction the marker exists to preserve. The API's assistant
        // message object has its own `refusal` field for this.
        let msg = Message::with_contents(
            Role::assistant(),
            vec![
                Content::Text(TextContent::new("here is half")),
                Content::Text(TextContent::refusal("I can't do the rest")),
            ],
        );
        let wire = messages_to_openai(&[msg]);
        assert_eq!(wire[0]["content"], json!("here is half"));
        assert_eq!(wire[0]["refusal"], json!("I can't do the rest"));
    }

    #[test]
    fn a_message_without_a_refusal_carries_no_refusal_field() {
        let wire = messages_to_openai(&[Message::assistant("the answer")]);
        assert_eq!(wire[0]["content"], json!("the answer"));
        assert!(
            wire[0].get("refusal").is_none(),
            "an ordinary turn must not grow a refusal field"
        );
    }

    #[test]
    fn a_refusal_is_marked_and_withheld_from_text() {
        let value = json!({
            "id": "chatcmpl-1",
            "model": "gpt-4o",
            "choices": [{
                "message": { "role": "assistant", "refusal": "I can't help with that." },
                "finish_reason": "stop",
            }],
        });
        let resp = parse_response(&value);

        // The refusal must not read as the answer: a caller doing
        // `resp.text()` (or parse_json over it) would otherwise treat the
        // model's decline as the output it asked for.
        assert_eq!(resp.text(), "");

        let message = &resp.messages[0];
        assert!(message.has_refusal());
        assert_eq!(
            message.refusal_text().as_deref(),
            Some("I can't help with that.")
        );
        // Still carried as content, so nothing is lost — only reclassified.
        assert!(matches!(
            &message.contents[0],
            Content::Text(t) if t.refusal && t.text == "I can't help with that."
        ));
    }

    #[test]
    fn a_refusal_alongside_content_is_kept_rather_than_dropped() {
        // Both halves are real: the model answered part of the request and
        // declined part of it. Returning only the content would hide the
        // decline; returning only the refusal would lose the answer.
        let value = json!({
            "choices": [{
                "message": { "role": "assistant", "content": "answer", "refusal": "nope" },
            }],
        });
        let resp = parse_response(&value);
        let message = &resp.messages[0];

        assert!(message.has_refusal());
        assert_eq!(message.refusal_text().as_deref(), Some("nope"));
        // `text()` is withheld whenever a refusal is present, so a caller
        // cannot silently consume a partial answer as a complete one.
        assert_eq!(resp.text(), "");
        let texts: Vec<&str> = message
            .contents
            .iter()
            .filter_map(|c| match c {
                Content::Text(t) => Some(t.text.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(texts, vec!["answer", "nope"]);
    }

    #[test]
    fn an_empty_refusal_field_marks_nothing() {
        let value = json!({
            "choices": [{
                "message": { "role": "assistant", "content": "answer", "refusal": "" },
            }],
        });
        let resp = parse_response(&value);
        assert!(!resp.messages[0].has_refusal());
        assert_eq!(resp.text(), "answer");
    }

    #[test]
    fn ordinary_text_is_never_marked_as_a_refusal() {
        let value = json!({
            "choices": [{ "message": { "role": "assistant", "content": "answer" } }],
        });
        let resp = parse_response(&value);
        assert!(!resp.messages[0].has_refusal());
        assert_eq!(resp.messages[0].refusal_text(), None);
        assert_eq!(resp.text(), "answer");
    }

    #[test]
    fn usage_detail_breakdowns_are_folded_into_additional_counts() {
        let usage = json!({
            "prompt_tokens": 100,
            "completion_tokens": 50,
            "total_tokens": 150,
            "completion_tokens_details": {
                "reasoning_tokens": 20,
                "audio_tokens": 5,
                "accepted_prediction_tokens": 3,
                "rejected_prediction_tokens": 0,
            },
            "prompt_tokens_details": { "cached_tokens": 40, "audio_tokens": 2 },
        });
        let d = parse_usage(&usage);
        assert_eq!(d.input_token_count, Some(100));
        assert_eq!(d.output_token_count, Some(50));
        assert_eq!(
            d.additional_counts.get("completion/reasoning_tokens"),
            Some(&20)
        );
        assert_eq!(d.additional_counts.get("completion/audio_tokens"), Some(&5));
        assert_eq!(
            d.additional_counts
                .get("completion/accepted_prediction_tokens"),
            Some(&3)
        );
        // A reported zero is a reported count, not an absent one.
        assert_eq!(
            d.additional_counts
                .get("completion/rejected_prediction_tokens"),
            Some(&0)
        );
        assert_eq!(d.additional_counts.get("prompt/cached_tokens"), Some(&40));
        assert_eq!(d.additional_counts.get("prompt/audio_tokens"), Some(&2));
    }

    #[test]
    fn reported_zero_token_counts_are_kept_and_absent_ones_omitted() {
        // The distinction this pins: a provider reporting `0` is saying the
        // model used none of that budget, which is not the same as a provider
        // that does not break the count out at all. `additional_counts` has no
        // way to express the second except by omission, so conflating them
        // loses the first.
        let usage = json!({
            "prompt_tokens": 10,
            "completion_tokens": 0,
            "total_tokens": 10,
            "completion_tokens_details": {
                "audio_tokens": 0,
                "reasoning_tokens": 0,
                // accepted_prediction_tokens deliberately absent
            },
            "prompt_tokens_details": { "cached_tokens": 0 },
        });
        let d = parse_usage(&usage);

        assert_eq!(d.additional_counts.get("completion/audio_tokens"), Some(&0));
        assert_eq!(
            d.additional_counts.get("completion/reasoning_tokens"),
            Some(&0)
        );
        assert_eq!(d.additional_counts.get("prompt/cached_tokens"), Some(&0));
        assert!(!d
            .additional_counts
            .contains_key("completion/accepted_prediction_tokens"));

        // The typed fields never had the truthy guard, so a zero already
        // survived there; asserting it keeps the two paths agreeing.
        assert_eq!(d.reasoning_output_token_count, Some(0));
        assert_eq!(d.cache_read_input_token_count, Some(0));
    }

    #[test]
    fn non_integer_usage_details_are_still_ignored() {
        // Dropping the `> 0` guard must not widen what counts as a count: a
        // string or float is still not a token count.
        let usage = json!({
            "prompt_tokens": 10,
            "completion_tokens_details": { "audio_tokens": "12", "reasoning_tokens": 1.5 },
            "prompt_tokens_details": { "cached_tokens": null },
        });
        let d = parse_usage(&usage);
        assert!(!d.additional_counts.contains_key("completion/audio_tokens"));
        assert!(!d
            .additional_counts
            .contains_key("completion/reasoning_tokens"));
        assert!(!d.additional_counts.contains_key("prompt/cached_tokens"));
    }

    // endregion
}