rig-core 0.44.0

An opinionated library for building LLM powered applications.
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
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
//! Embedding, transcription, image, speech, listing, reranking, and verification wires.
//! Each operation consumes a whole reply, using its dialect's JSON or binary format.
//!
//! ```
//! use rig_core::providers::openai::{OpenAI, TEXT_EMBEDDING_3_SMALL};
//! let wire = OpenAI::new("key").embedding(TEXT_EMBEDDING_3_SMALL, None);
//! ```

use crate::wire::Flow;
use serde::{Deserialize, Serialize};

use crate::embeddings;
use crate::error::EncodeError;
use crate::error::ProviderError;
use crate::model::{ModelInfo, ModelList};
use crate::operation::{
    Embedding, ModelListing, ModelPage, Rerank as RerankOp, Transcription, Verify as VerifyOp,
};
use crate::providers::internal::wire::classify_untyped_line;
use crate::providers::openai::embedding::Usage;
use crate::providers::openai::embedding::{
    CompatibleEmbeddingResponse, EncodingFormat, model_dimensions_from_identifier,
};
use crate::transcription::TranscriptionRequest;
use crate::wire::{
    Body, Capabilities, Decoder, Descriptor, Encoded, Framing, Mode, Out, Wire, WireEvent,
    WireFrame,
};

use super::OpenAIConfig;

/// Paired request and response formats for image generation.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ImageBody {
    /// `{model, prompt, size}`, answered with `data[].b64_json`.
    #[default]
    OpenAi,
    /// xAI: `{model, prompt, response_format, aspect_ratio}` and no `size`,
    /// answered with `data[].b64_json` and no `created`.
    Xai,
    /// `{model_name, prompt, height, width}`, answered with `images[].image`.
    Hyperbolic,
    /// `{model, prompt, width, height}`, answered with base64 strings in `images`.
    Venice,
    /// `{inputs, parameters: {width, height}}`, answered with raw image bytes.
    /// The model is addressed through the URL path.
    HuggingFace,
}

/// Which body a speech endpoint takes.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SpeechBody {
    /// OpenAI: `{model, input, voice, speed}`.
    #[default]
    OpenAi,
    /// xAI: `{text, voice_id, language}`, with `eve` as the default voice.
    Xai,
    /// Hyperbolic: `{language, speaker, text, speed}`, answered with
    /// `{"audio": "<base64>"}` rather than the audio bytes themselves.
    ///
    /// It addresses this endpoint by *language*, so the identifier a caller
    /// passes as the model is the language tag (`"EN"`).
    Hyperbolic,
}

/// Which body a transcription endpoint takes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TranscriptionBody {
    /// OpenAI: a `multipart/form-data` upload with the audio as a file part
    /// beside `model`, `language`, `prompt` and `temperature`.
    Multipart,
    /// OpenRouter: a JSON body whose audio rides base64-encoded under
    /// `input_audio`, with its container format beside it
    /// (`{"input_audio": {"data": "…", "format": "mp3"}, "model": …}`).
    /// The gateway's speech-to-text route serves only this shape, and has no
    /// top-level `prompt` field at all.
    InputAudioJson,
}

/// Which field a dialect takes an embedding width in.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DimensionsField {
    /// The OpenAI-compatible `dimensions` field.
    Dimensions,
    /// Mistral's `output_dimension`.
    OutputDimension,
    /// The server ignores any width field, so none is sent (`llama-server`
    /// reads no such field and would answer 200 with the native width).
    Ignored,
}

impl DimensionsField {
    /// The body field a requested width goes in, or `None` when the dialect
    /// reads no width field at all.
    ///
    /// The encoder puts a width in this field and a refusal names it, so
    /// both spell it from here rather than from two matching literals.
    pub const fn name(self) -> Option<&'static str> {
        match self {
            Self::Dimensions => Some("dimensions"),
            Self::OutputDimension => Some("output_dimension"),
            Self::Ignored => None,
        }
    }
}

/// Which widths a request may name for one embedding model.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AcceptedWidths {
    /// The model emits one width and reads no width field, so any value but
    /// its own native width is a request for a parameter the provider does
    /// not accept there, and is refused as a request error.
    Fixed,
    /// The model truncates to any width in `min..=max`, and anything else is
    /// refused with [`requirement`](Self::Range::requirement).
    Range {
        /// Narrowest width the provider honours.
        min: usize,
        /// Widest width the provider honours.
        max: usize,
        /// Static error clause describing the accepted bounds.
        /// Must agree with `min` and `max`.
        requirement: &'static str,
    },
}

/// One embedding model's width contract: the width it returns unasked, and
/// the widths it will honour when asked.
///
/// Stated per model rather than per dialect because a dialect serves models
/// of different widths, and a model's default is not always its maximum.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ModelWidth {
    /// The model identifier, as the `model` field spells it.
    pub model: &'static str,
    /// Default width reported when no width is requested, or `None` if unknown.
    /// Unknown widths report zero as the embedding model's `ndims`.
    pub default: Option<usize>,
    /// The widths a request may name.
    pub accepted: AcceptedWidths,
}

/// Reranking endpoint policy. An empty [`Self::path`] disables reranking.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct RerankQuirks {
    /// The rerank path, or empty when the dialect offers none.
    pub path: &'static str,
    /// Most documents the provider accepts in one request.
    pub max_documents: usize,
    /// Whether the model is a body field.
    pub sends_model_field: bool,
}

impl RerankQuirks {
    /// The signal for a dialect with no reranking endpoint.
    pub const fn unsupported() -> Self {
        Self {
            path: "",
            max_documents: 0,
            sends_model_field: true,
        }
    }
}

/// What a dialect's embeddings endpoint accepts.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct EmbeddingQuirks {
    /// Most inputs the provider embeds in one request.
    pub max_documents: usize,
    /// Whether a successful reply must carry usage.
    pub requires_usage: bool,
    /// Whether the provider accepts `encoding_format`.
    pub supports_encoding_format: bool,
    /// Whether the provider accepts `user`.
    pub supports_user: bool,
    /// Whether the model is a body field (false for Azure, which addresses a
    /// deployment through the URL).
    pub sends_model_field: bool,
    /// Which field a requested width goes in.
    pub dimensions: DimensionsField,
    /// Model width contracts used for capability reporting and request validation.
    /// Consulted before the shared OpenAI model-width table.
    pub widths: &'static [ModelWidth],
    /// The `requirement` clause refusing a declared width of zero, or
    /// `None` for a dialect that lets zero through as rig's own "unknown"
    /// sentinel rather than a claim.
    pub refuse_zero_width: Option<&'static str>,
}

impl EmbeddingQuirks {
    /// OpenAI's own embeddings contract, which most dialects inherit.
    pub const fn openai() -> Self {
        Self {
            max_documents: 1024,
            requires_usage: true,
            supports_encoding_format: true,
            supports_user: true,
            sends_model_field: true,
            dimensions: DimensionsField::Dimensions,
            // Shared OpenAI model widths are resolved separately.
            widths: &[],
            // Zero represents an unknown width, not a requested dimension.
            refuse_zero_width: None,
        }
    }
}

impl super::SubRoute {
    /// Whether this sub-provider serves the endpoints that address the model
    /// through the URL (transcription, image generation).
    pub fn serves_model_routed_endpoints(&self) -> bool {
        matches!(self, Self::HFInference)
    }
}

impl OpenAIConfig {
    /// Set the `api-version` Azure's speech endpoint is versioned by.
    pub fn with_audio_api_version(mut self, api_version: impl Into<String>) -> Self {
        self.audio_api_version = Some(api_version.into());
        self
    }

    /// The embeddings wire for `model`.
    pub(crate) fn embedding(&self, model: impl Into<String>, ndims: Option<usize>) -> Embeddings {
        Embeddings::new(self.clone(), model, ndims)
    }

    /// The rerank wire for `model`.
    pub(crate) fn rerank(&self, model: impl Into<String>) -> Rerank {
        Rerank::new(self.clone(), model)
    }

    /// The transcription wire for `model`.
    pub(crate) fn transcription(&self, model: impl Into<String>) -> Transcriptions {
        Transcriptions::new(self.clone(), model)
    }

    /// The model-listing wire.
    pub(crate) fn models(&self) -> Models {
        Models::new(self.clone())
    }

    /// The credential-check wire.
    pub(crate) fn verify(&self) -> Verify {
        Verify::new(self.clone())
    }

    /// The image-generation wire for `model`.
    #[cfg(feature = "image")]
    pub(crate) fn image_generation(&self, model: impl Into<String>) -> Images {
        Images::new(self.clone(), model)
    }

    /// The speech wire for `model`.
    #[cfg(feature = "audio")]
    pub(crate) fn audio_generation(&self, model: impl Into<String>) -> Speech {
        Speech::new(self.clone(), model)
    }

    /// The `api-version` a speech request carries.
    #[cfg(feature = "audio")]
    pub(crate) fn speech_api_version(&self) -> Option<&str> {
        self.audio_api_version
            .as_deref()
            .or(self.api_version.as_deref())
    }

    /// Resolve a fixed or model-addressed modality URL.
    /// Return an error if the selected sub-route does not serve model-routed endpoints.
    pub(crate) fn modality_uri(
        &self,
        endpoint: &str,
        fixed: &'static str,
        model: &str,
    ) -> Result<String, String> {
        if !self.dialect.quirks.model_is_modality_path {
            return Ok(self.uri(fixed, self.deployment(model)));
        }
        let route = self.route();
        if !route.serves_model_routed_endpoints() {
            return Err(format!(
                "{endpoint} endpoint is not supported yet for {route}"
            ));
        }
        Ok(format!(
            "{}/{}",
            self.base_url.trim_end_matches('/'),
            model.trim_start_matches('/')
        ))
    }
}

/// The width contract of Mistral's embedding models.
///
/// `mistral-embed` is fixed at 1024 and reads no width field: Mistral
/// answers any other value with an error rather than truncating, so a
/// request naming one is refused before it is built. Codestral Embed is
/// configurable up to 3072 and takes its width as `output_dimension`.
///
/// The dated aliases are listed beside their rolling names because a caller
/// pinning `mistral-embed-2312` gets the same model, and a model absent from
/// this table reports `ndims() == 0`.
pub(super) const MISTRAL_EMBEDDING_WIDTHS: &[ModelWidth] = &[
    ModelWidth {
        model: crate::providers::mistral::embedding::MISTRAL_EMBED,
        default: Some(1_024),
        accepted: AcceptedWidths::Fixed,
    },
    ModelWidth {
        model: "mistral-embed-2312",
        default: Some(1_024),
        accepted: AcceptedWidths::Fixed,
    },
    ModelWidth {
        model: crate::providers::mistral::embedding::CODESTRAL_EMBED,
        // Configurable with no documented native width, so a handle that
        // names none reports 0 rather than inventing one.
        default: None,
        accepted: AcceptedWidths::Range {
            // Mistral documents only a ceiling. The floor is rig's own
            // "unknown" sentinel, which never reaches the wire.
            min: 0,
            max: 3_072,
            requirement: "to be at most 3072 for Codestral Embed",
        },
    },
    ModelWidth {
        model: "codestral-embed-2505",
        default: None,
        accepted: AcceptedWidths::Range {
            min: 0,
            max: 3_072,
            requirement: "to be at most 3072 for Codestral Embed",
        },
    },
];

/// Doubleword embedding widths: 32 through 4096, defaulting to 4096.
/// Validate both bounds locally because out-of-range requests can be clamped or
/// inconsistently rejected by the service.
pub(super) const DOUBLEWORD_EMBEDDING_WIDTHS: &[ModelWidth] = &[ModelWidth {
    model: crate::providers::doubleword::QWEN3_EMBEDDING_8B,
    default: Some(4_096),
    accepted: AcceptedWidths::Range {
        min: 32,
        max: 4_096,
        requirement: "to be between 32 and 4096",
    },
}];

/// Encode an authenticated JSON POST with whole-response framing.
fn json_post(
    provider: &OpenAIConfig,
    path: &str,
    deployment: Option<&str>,
    body: &serde_json::Value,
) -> Result<Encoded, EncodeError> {
    json_post_to(provider, provider.uri(path, deployment), body)
}

/// [`json_post`] against an already-resolved URL, for the endpoints whose
/// URL is derived rather than a fixed path under the base.
fn json_post_to(
    provider: &OpenAIConfig,
    uri: String,
    body: &serde_json::Value,
) -> Result<Encoded, EncodeError> {
    let bytes = serde_json::to_vec(body)?;
    let builder = http::Request::post(uri).header("Content-Type", "application/json");
    encoded(provider, builder, Body::Bytes(bytes))
}

/// The `GET` whose status is the answer, for the two endpoints that send no
/// body: the model catalogue and the credential check.
fn get(provider: &OpenAIConfig, path: &str) -> Result<Encoded, EncodeError> {
    encoded(
        provider,
        http::Request::get(provider.uri(path, None)),
        Body::empty(),
    )
}

/// Authenticate and build a request, then apply its modality envelope hook.
/// Return construction or hook errors. Use whole-response framing and the
/// dialect's request-ID header.
fn encoded(
    provider: &OpenAIConfig,
    builder: http::request::Builder,
    body: Body,
) -> Result<Encoded, EncodeError> {
    let mut request = provider.authenticate(builder).body(body)?;
    if let Some(envelope) = provider
        .dialect
        .quirks
        .hooks
        .and_then(|hooks| hooks.modality_envelope)
    {
        envelope(provider, &mut request)?;
    }
    Ok(Encoded::new(request, Framing::Whole)
        .with_request_id_header(provider.dialect.request_id_header))
}

/// Refuse an embeddings request parameter the dialect does not accept.
fn unsupported_parameter(provider: &str, parameter: &str) -> EncodeError {
    EncodeError::request(format!(
        "{provider} embeddings do not support the `{parameter}` parameter"
    ))
}

/// The embeddings wire.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Embeddings {
    /// Which provider, and how to reach it.
    pub provider: OpenAIConfig,
    /// The embedding model.
    pub model: String,
    /// The width the caller asked for, when they named one rather than
    /// taking the model's default.
    pub ndims: Option<usize>,
    /// The encoding the caller asked the provider to answer in.
    pub encoding_format: Option<EncodingFormat>,
    /// The end-user identifier the provider attributes the call to.
    pub user: Option<String>,
}

impl Embeddings {
    /// The embeddings wire for `model`.
    pub fn new(provider: OpenAIConfig, model: impl Into<String>, ndims: Option<usize>) -> Self {
        Self {
            provider,
            model: model.into(),
            ndims,
            encoding_format: None,
            user: None,
        }
    }

    /// Ask the provider to answer in `encoding_format`.
    pub fn with_encoding_format(mut self, encoding_format: EncodingFormat) -> Self {
        self.encoding_format = Some(encoding_format);
        self
    }

    /// Attribute the call to an end user.
    pub fn with_user(mut self, user: impl Into<String>) -> Self {
        self.user = Some(user.into());
        self
    }

    /// This model's width contract on this dialect, or `None` for a model
    /// the dialect does not document.
    fn model_width(&self) -> Option<&'static ModelWidth> {
        self.provider
            .dialect
            .quirks
            .embedding
            .widths
            .iter()
            .find(|width| width.model == self.model)
    }

    /// Resolve width from the caller, dialect table, then shared model table.
    /// Return zero when all are absent.
    fn resolved_ndims(&self) -> usize {
        self.ndims
            .or_else(|| self.model_width().and_then(|width| width.default))
            .or_else(|| model_dimensions_from_identifier(&self.model))
            .unwrap_or_default()
    }

    /// Validate declared widths against the dialect's zero-width and model policies.
    /// Return a request error for unsupported widths; unknown models are unchecked.
    fn refuse_unhonourable_width(&self) -> Result<(), EncodeError> {
        let quirks = &self.provider.dialect.quirks.embedding;
        let provider = self.provider.dialect.name;
        let invalid = |requirement, parameter| {
            EncodeError::request(format!(
                "{provider} embeddings require `{parameter}` {requirement}"
            ))
        };
        // A dialect that reads no width field has nothing to refuse: the
        // caller's number never reaches the wire, and the shared driver
        // catches the disagreement against the reply instead.
        let Some(parameter) = quirks.dimensions.name() else {
            return Ok(());
        };
        let Some(declared) = self.ndims else {
            return Ok(());
        };
        if declared == 0 {
            return match quirks.refuse_zero_width {
                Some(requirement) => Err(invalid(requirement, parameter)),
                None => Ok(()),
            };
        }
        // A model the dialect does not document: the caller's width is the
        // only width there is, so it goes out unvalidated and the API rules.
        let Some(width) = self.model_width() else {
            return Ok(());
        };
        // Native widths require no truncation parameter.
        if width.default == Some(declared) {
            return Ok(());
        }
        match width.accepted {
            AcceptedWidths::Fixed => Err(unsupported_parameter(provider, parameter)),
            AcceptedWidths::Range { min, max, .. } if (min..=max).contains(&declared) => Ok(()),
            AcceptedWidths::Range { requirement, .. } => Err(invalid(requirement, parameter)),
        }
    }

    /// The width to send, in the field this dialect spells it with.
    ///
    /// OpenAI's legacy Ada model does not accept a width at all, and
    /// `llama-server` reads no width field, so neither is sent one.
    fn requested_width(&self) -> Option<(&'static str, usize)> {
        let field = self.provider.dialect.quirks.embedding.dimensions.name()?;
        if self.model == crate::providers::openai::embedding::TEXT_EMBEDDING_ADA_002 {
            return None;
        }
        // Unknown widths are metadata sentinels, not request parameters.
        let ndims = match self.resolved_ndims() {
            0 => return None,
            ndims => ndims,
        };
        // At a documented model's native width, send nothing: that width is
        // what the model emits unasked, so the field would only restate the
        // default and the vector is identical either way.
        if self
            .model_width()
            .is_some_and(|width| width.default == Some(ndims))
        {
            return None;
        }
        Some((field, ndims))
    }
}

/// Decode embedding vectors and usage, enforcing the dialect's usage requirement.
#[derive(Default)]
pub struct EmbeddingsDecoder {
    /// Whether this dialect's reply must carry usage.
    requires_usage: bool,
    provider: &'static str,
    model: String,
}

impl<'id> Decoder<'id, Embedding> for EmbeddingsDecoder {
    type Event = CompatibleEmbeddingResponse;

    fn classify(&self, frame: WireFrame) -> WireEvent<Self::Event> {
        classify_untyped_line(frame.as_str().as_bytes())
    }

    fn decode(
        &mut self,
        event: Self::Event,
        out: Out<'id, Embedding>,
    ) -> Result<Flow, ProviderError> {
        if event.usage.is_none() && self.requires_usage {
            return Err(ProviderError::Response(format!(
                "{} embedding response omitted required usage",
                self.provider
            )));
        }
        let usage = event
            .usage
            .as_ref()
            .map(Usage::to_normalized)
            .unwrap_or_default();
        let vectors = event.data.into_iter().map(|datum| {
            datum
                .embedding
                .into_iter()
                .filter_map(|number| number.as_f64())
                .collect()
        });
        let model = if event.model.is_empty() {
            self.model.clone()
        } else {
            event.model
        };
        Ok(out.end(embeddings::EmbeddingResponse {
            model: Some(model),
            usage,
            ..embeddings::EmbeddingResponse::from_vectors(vectors)
        }))
    }
}

impl Wire for Embeddings {
    type Op = Embedding;
    type Payload = crate::wire::Encoded;
    type Frame = crate::wire::WireFrame;
    type Decoder<'id> = EmbeddingsDecoder;
    type Reassembler = crate::wire::document::Unreassembled;

    /// Only an explicit nonzero declaration permits reply-width mismatch checks.
    fn describe(&self) -> Descriptor<'_> {
        Descriptor::new(self.provider.dialect.name)
            .model(self.model.as_str())
            .capabilities(
                Capabilities::embedding(
                    self.provider.dialect.quirks.embedding.max_documents,
                    self.resolved_ndims(),
                )
                .declaring(self.ndims),
            )
    }

    fn encode(&self, request: Vec<String>, _mode: Mode) -> Result<Encoded, EncodeError> {
        let quirks = &self.provider.dialect.quirks.embedding;
        // Base64 vectors are not decoded anywhere, so asking for them would
        // answer 200 with a payload rig cannot read.
        if self.encoding_format == Some(EncodingFormat::Base64) {
            return Err(EncodeError::request(format!(
                "Rig cannot decode {} embedding responses encoded as `base64`",
                self.provider.dialect.name
            )));
        }
        if self.encoding_format.is_some() && !quirks.supports_encoding_format {
            return Err(unsupported_parameter(
                self.provider.dialect.name,
                "encoding_format",
            ));
        }
        if self.user.is_some() && !quirks.supports_user {
            return Err(unsupported_parameter(self.provider.dialect.name, "user"));
        }
        self.refuse_unhonourable_width()?;

        let mut body = serde_json::json!({ "input": request });
        let Some(object) = body.as_object_mut() else {
            return Err(EncodeError::request(
                "embedding request body must be an object",
            ));
        };
        if quirks.sends_model_field {
            object.insert("model".to_owned(), serde_json::json!(self.model));
        }
        if let Some((field, ndims)) = self.requested_width() {
            object.insert(field.to_owned(), serde_json::json!(ndims));
        }
        if let Some(encoding_format) = self.encoding_format {
            object.insert(
                "encoding_format".to_owned(),
                serde_json::to_value(encoding_format)?,
            );
        }
        if let Some(user) = &self.user {
            object.insert("user".to_owned(), serde_json::json!(user));
        }

        json_post(
            &self.provider,
            self.provider.dialect.quirks.embeddings_path,
            self.provider.deployment(&self.model),
            &body,
        )
    }

    fn decoder<'id>(&self) -> Self::Decoder<'id> {
        EmbeddingsDecoder {
            requires_usage: self.provider.dialect.quirks.embedding.requires_usage,
            provider: self.provider.dialect.name,
            model: self.model.clone(),
        }
    }
}

/// Transcription requests encoded as multipart or input-audio JSON.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Transcriptions {
    /// Which provider, and how to reach it.
    pub provider: OpenAIConfig,
    /// Transcription model or Azure deployment identifier.
    pub model: String,
}

impl Transcriptions {
    /// The transcription wire for `model`.
    pub fn new(provider: OpenAIConfig, model: impl Into<String>) -> Self {
        Self {
            provider,
            model: model.into(),
        }
    }

    /// OpenAI's multipart upload: the audio as a file part beside the
    /// per-request options.
    fn multipart_body(&self, request: TranscriptionRequest) -> Result<Body, EncodeError> {
        use crate::http_client::MultipartForm;
        use crate::http_client::multipart::Part;

        let mut form = MultipartForm::new();
        // Azure addresses its deployment through the URL rather than the form.
        if self.provider.deployment(&self.model).is_none() {
            form = form.text("model", self.model.clone());
        }
        form = form.part(Part::bytes("file", request.data).filename(request.filename));
        if let Some(language) = request.language {
            form = form.text("language", language);
        }
        if let Some(prompt) = request.prompt {
            form = form.text("prompt", prompt);
        }
        if let Some(temperature) = request.temperature {
            form = form.text("temperature", temperature.to_string());
        }
        if let Some(additional_params) = request.additional_params {
            for (name, value) in additional_params_object(&additional_params)? {
                // Form strings must not acquire JSON quotation marks.
                let value = match value {
                    serde_json::Value::String(value) => value.clone(),
                    other => other.to_string(),
                };
                form = form.text(name.clone(), value);
            }
        }
        Ok(Body::Multipart(form))
    }

    /// Encode base64 audio under `input_audio`, inferring format from the filename.
    /// Reject top-level prompts and non-object additional parameters.
    fn input_audio_body(&self, request: TranscriptionRequest) -> Result<Body, EncodeError> {
        use base64::Engine;

        if request.prompt.is_some() {
            return Err(EncodeError::request(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "OpenRouter STT does not support a top-level prompt field. \
                     Provider-specific prompt options can be passed via `additional_params`. \
                     Example: {\"provider\": {\"options\": {\"<provider>\": {\"prompt\": \"<text>\"}}}}",
            )));
        }

        let mut body = serde_json::Map::new();
        body.insert("model".to_owned(), serde_json::json!(self.model));
        body.insert(
            "input_audio".to_owned(),
            serde_json::json!({
                "data": base64::engine::general_purpose::STANDARD.encode(&request.data),
                "format": audio_format_of(&request.filename),
            }),
        );
        if let Some(language) = request.language {
            body.insert("language".to_owned(), serde_json::json!(language));
        }
        if let Some(temperature) = request.temperature {
            body.insert("temperature".to_owned(), serde_json::json!(temperature));
        }
        if let Some(additional_params) = request.additional_params {
            for (name, value) in additional_params_object(&additional_params)? {
                body.insert(name.clone(), value.clone());
            }
        }
        Ok(Body::Bytes(serde_json::to_vec(
            &serde_json::Value::Object(body),
        )?))
    }
}

/// A transcription request's `additional_params`, as an object.
fn additional_params_object(
    params: &serde_json::Value,
) -> Result<&serde_json::Map<String, serde_json::Value>, EncodeError> {
    params.as_object().ok_or_else(|| {
        EncodeError::request(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "additional transcription parameters must be a JSON object",
        ))
    })
}

/// Infer the audio container from a case-insensitive filename extension.
/// Unknown or absent extensions default to `wav`.
fn audio_format_of(filename: &str) -> &'static str {
    let extension = std::path::Path::new(filename)
        .extension()
        .and_then(std::ffi::OsStr::to_str)
        .map(str::to_ascii_lowercase);
    match extension.as_deref() {
        Some("mp3") => "mp3",
        Some("flac") => "flac",
        Some("m4a") => "m4a",
        Some("ogg") => "ogg",
        Some("webm") => "webm",
        Some("aac") => "aac",
        _ => "wav",
    }
}

/// The transcription decoder.
#[derive(Default)]
pub struct TranscriptionsDecoder;

impl<'id> Decoder<'id, Transcription> for TranscriptionsDecoder {
    type Event = crate::providers::openai::transcription::TranscriptionResponse;

    fn classify(&self, frame: WireFrame) -> WireEvent<Self::Event> {
        classify_untyped_line(frame.as_str().as_bytes())
    }

    fn decode(
        &mut self,
        event: Self::Event,
        out: Out<'id, Transcription>,
    ) -> Result<Flow, ProviderError> {
        Ok(out.end(event.normalize()?))
    }
}

impl Wire for Transcriptions {
    type Op = Transcription;
    type Payload = crate::wire::Encoded;
    type Frame = crate::wire::WireFrame;
    type Decoder<'id> = TranscriptionsDecoder;
    type Reassembler = crate::wire::document::Unreassembled;

    fn describe(&self) -> Descriptor<'_> {
        Descriptor::new(self.provider.dialect.name).model(self.model.as_str())
    }

    fn encode(&self, request: TranscriptionRequest, _mode: Mode) -> Result<Encoded, EncodeError> {
        let uri = self
            .provider
            .modality_uri(
                "transcription",
                self.provider.dialect.quirks.transcription_path,
                &self.model,
            )
            .map_err(EncodeError::request)?;
        let builder = http::Request::post(uri);
        let (builder, body) = match self.provider.dialect.quirks.transcription_body {
            TranscriptionBody::Multipart => (builder, self.multipart_body(request)?),
            TranscriptionBody::InputAudioJson => (
                builder.header(http::header::CONTENT_TYPE, "application/json"),
                self.input_audio_body(request)?,
            ),
        };
        encoded(&self.provider, builder, body)
    }

    fn decoder<'id>(&self) -> Self::Decoder<'id> {
        TranscriptionsDecoder
    }
}

/// The image-generation wire.
#[cfg(feature = "image")]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Images {
    /// Which provider, and how to reach it.
    pub provider: OpenAIConfig,
    /// The image model.
    pub model: String,
}

#[cfg(feature = "image")]
impl Images {
    /// The image-generation wire for `model`.
    pub fn new(provider: OpenAIConfig, model: impl Into<String>) -> Self {
        Self {
            provider,
            model: model.into(),
        }
    }
}

/// The image-generation decoder.
///
/// Carries the dialect's [`ImageBody`] because the request shape names the
/// reply shape: most of this family answers with a JSON envelope, and
/// Hugging Face's router answers with the image bytes themselves.
#[cfg(feature = "image")]
#[derive(Default)]
pub struct ImagesDecoder {
    /// Which reply shape this dialect answers with.
    body: ImageBody,
}

/// One generated image, as every dialect on this wire returns it.
#[cfg(feature = "image")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageDatum {
    /// The image, base64-encoded.
    pub b64_json: String,
}

/// Base64 image represented as a string or an object with an `image` field.
#[cfg(feature = "image")]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ImagesReplyImage {
    /// Hyperbolic: `{"image": "<base64>"}`.
    Keyed {
        /// The image, base64-encoded.
        image: String,
    },
    /// Venice: the base64 payload itself.
    Bare(String),
}

#[cfg(feature = "image")]
impl ImagesReplyImage {
    /// The image's base64 payload, whichever form the dialect sent.
    pub fn base64(&self) -> &str {
        match self {
            Self::Keyed { image } => image,
            Self::Bare(image) => image,
        }
    }
}

/// JSON image reply accepting `data` and `images` arrays with optional metadata.
#[cfg(feature = "image")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImagesReply {
    /// The generated images, as OpenAI and xAI key them.
    #[serde(default)]
    pub data: Vec<ImageDatum>,
    /// The generated images, as Hyperbolic and Venice key them.
    #[serde(default)]
    pub images: Vec<ImagesReplyImage>,
    /// Whatever else the dialect sent (`created`, Venice's `id`/`timing`, and
    /// any field this build does not model), so the raw payload loses
    /// nothing.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, serde_json::Value>,
}

#[cfg(feature = "image")]
impl ImagesReply {
    /// The first image's base64 payload, whichever key the dialect used.
    pub fn first_base64(&self) -> Option<&str> {
        self.data
            .first()
            .map(|image| image.b64_json.as_str())
            .or_else(|| self.images.first().map(ImagesReplyImage::base64))
            .filter(|encoded| !encoded.is_empty())
    }
}

/// Generated images in a decoded JSON envelope or as raw bytes.
#[cfg(feature = "image")]
#[derive(Debug, Clone)]
pub enum ImagesEvent {
    /// A JSON envelope, as OpenAI, xAI and Hyperbolic answer.
    Json(ImagesReply),
    /// The image bytes themselves, with no envelope at all.
    Raw(Vec<u8>),
}

#[cfg(feature = "image")]
impl<'id> Decoder<'id, crate::operation::ImageGeneration> for ImagesDecoder {
    type Event = ImagesEvent;

    fn classify(&self, frame: WireFrame) -> WireEvent<Self::Event> {
        match self.body {
            // Preserve raw image bytes even when framing recognized valid UTF-8.
            ImageBody::HuggingFace => WireEvent::Known(ImagesEvent::Raw(match frame {
                WireFrame::Text(text) => text.into_bytes(),
                WireFrame::Bytes(bytes) => bytes,
            })),
            ImageBody::OpenAi | ImageBody::Xai | ImageBody::Hyperbolic | ImageBody::Venice => {
                classify_untyped_line(frame.as_str().as_bytes()).map(ImagesEvent::Json)
            }
        }
    }

    fn decode(
        &mut self,
        event: Self::Event,
        out: Out<'id, crate::operation::ImageGeneration>,
    ) -> Result<Flow, ProviderError> {
        use crate::image_generation::ImageGenerationResponse;
        use base64::Engine;

        let reply = match event {
            // The image is already the payload, and the reply is not a
            // document, so `raw` stays null rather than restating the bytes.
            ImagesEvent::Raw(image) => {
                return Ok(out.end(ImageGenerationResponse::new(image)));
            }
            ImagesEvent::Json(reply) => reply,
        };
        let Some(encoded) = reply.first_base64() else {
            return Err(ProviderError::Response("missing image data".to_owned()));
        };
        let image = match base64::prelude::BASE64_STANDARD.decode(encoded) {
            Ok(image) => image,
            Err(error) => {
                return Err(ProviderError::Response(error.to_string()));
            }
        };
        Ok(out.end(ImageGenerationResponse::new(image)))
    }
}

#[cfg(feature = "image")]
impl Wire for Images {
    type Op = crate::operation::ImageGeneration;
    type Payload = crate::wire::Encoded;
    type Frame = crate::wire::WireFrame;
    type Decoder<'id> = ImagesDecoder;
    type Reassembler = crate::wire::document::Unreassembled;

    fn describe(&self) -> Descriptor<'_> {
        Descriptor::new(self.provider.dialect.name).model(self.model.as_str())
    }

    fn encode(
        &self,
        request: crate::image_generation::ImageGenerationRequest,
        _mode: Mode,
    ) -> Result<Encoded, EncodeError> {
        let mut body = match self.provider.dialect.quirks.image_body {
            // `response_format` is deliberately absent: it is no longer part
            // of OpenAI's request schema, which rejects it before it even
            // looks at the model. A compatible endpoint that still takes the
            // field gets it through `additional_params`.
            ImageBody::OpenAi => serde_json::json!({
                "model": self.model,
                "prompt": request.prompt,
                "size": format!("{}x{}", request.width, request.height),
            }),
            // xAI takes no `size` and answers with a URL unless asked for
            // base64, which is the only form this wire decodes.
            ImageBody::Xai => serde_json::json!({
                "model": self.model,
                "prompt": request.prompt,
                "response_format": "b64_json",
                "aspect_ratio": "1:1",
            }),
            ImageBody::Hyperbolic => serde_json::json!({
                "model_name": self.model,
                "prompt": request.prompt,
                "height": request.height,
                "width": request.width,
            }),
            ImageBody::Venice => serde_json::json!({
                "model": self.model,
                "prompt": request.prompt,
                "width": request.width,
                "height": request.height,
            }),
            // The model is addressed through the URL, not the body.
            ImageBody::HuggingFace => serde_json::json!({
                "inputs": request.prompt,
                "parameters": {
                    "width": request.width,
                    "height": request.height,
                },
            }),
        };
        // Merged last, so a caller can reach the endpoint's other parameters
        // and override what is derived above.
        if let Some(additional_params) = request.additional_params {
            crate::json_utils::merge_inplace(&mut body, additional_params);
        }

        let uri = self
            .provider
            .modality_uri(
                "image generation",
                self.provider.dialect.quirks.image_generation_path,
                &self.model,
            )
            .map_err(EncodeError::request)?;
        json_post_to(&self.provider, uri, &body)
    }

    fn decoder<'id>(&self) -> Self::Decoder<'id> {
        ImagesDecoder {
            body: self.provider.dialect.quirks.image_body,
        }
    }
}

/// The speech wire.
#[cfg(feature = "audio")]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Speech {
    /// Which provider, and how to reach it.
    pub provider: OpenAIConfig,
    /// The speech model.
    pub model: String,
}

#[cfg(feature = "audio")]
impl Speech {
    /// The speech wire for `model`.
    pub fn new(provider: OpenAIConfig, model: impl Into<String>) -> Self {
        Self {
            provider,
            model: model.into(),
        }
    }
}

/// Decode raw audio or the dialect's base64 JSON envelope.
#[cfg(feature = "audio")]
#[derive(Default)]
pub struct SpeechDecoder {
    /// Which reply shape this dialect answers with.
    body: SpeechBody,
}

/// Hyperbolic's speech reply: base64 in a JSON envelope rather than the
/// audio bytes themselves.
#[cfg(feature = "audio")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpeechReply {
    /// The audio, base64-encoded.
    pub audio: String,
}

#[cfg(feature = "audio")]
impl<'id> Decoder<'id, crate::operation::AudioGeneration> for SpeechDecoder {
    type Event = Vec<u8>;

    fn classify(&self, frame: WireFrame) -> WireEvent<Self::Event> {
        // Interpretation selects raw audio or JSON decoding from the dialect.
        WireEvent::Known(match frame {
            WireFrame::Text(text) => text.into_bytes(),
            WireFrame::Bytes(bytes) => bytes,
        })
    }

    fn decode(
        &mut self,
        event: Self::Event,
        out: Out<'id, crate::operation::AudioGeneration>,
    ) -> Result<Flow, ProviderError> {
        use base64::Engine;

        let audio = match self.body {
            // OpenAI and xAI answer with the audio itself.
            SpeechBody::OpenAi | SpeechBody::Xai => event,
            // Hyperbolic wraps it, base64-encoded, in a JSON envelope.
            SpeechBody::Hyperbolic => {
                let reply = match serde_json::from_slice::<SpeechReply>(&event) {
                    Ok(reply) => reply,
                    Err(error) => {
                        return Err(ProviderError::Response(error.to_string()));
                    }
                };
                match base64::prelude::BASE64_STANDARD.decode(&reply.audio) {
                    Ok(audio) => audio,
                    Err(error) => {
                        return Err(ProviderError::Response(error.to_string()));
                    }
                }
            }
        };
        Ok(out.end(crate::audio_generation::AudioGenerationResponse::new(audio)))
    }
}

#[cfg(feature = "audio")]
impl Wire for Speech {
    type Op = crate::operation::AudioGeneration;
    type Payload = crate::wire::Encoded;
    type Frame = crate::wire::WireFrame;
    type Decoder<'id> = SpeechDecoder;
    type Reassembler = crate::wire::document::Unreassembled;

    fn describe(&self) -> Descriptor<'_> {
        Descriptor::new(self.provider.dialect.name).model(self.model.as_str())
    }

    fn encode(
        &self,
        request: crate::audio_generation::AudioGenerationRequest,
        _mode: Mode,
    ) -> Result<Encoded, EncodeError> {
        let mut body = match self.provider.dialect.quirks.speech_body {
            SpeechBody::OpenAi => serde_json::json!({
                "model": self.model,
                "input": request.text,
                "voice": request.voice,
                "speed": request.speed,
            }),
            // xAI requires a default voice when the caller leaves it empty.
            SpeechBody::Xai => serde_json::json!({
                "text": request.text,
                "voice_id": if request.voice.is_empty() { "eve" } else { request.voice.as_str() },
                "language": "en",
            }),
            // Hyperbolic addresses this endpoint by language, so the
            // identifier the caller passes as the model IS the language tag.
            SpeechBody::Hyperbolic => serde_json::json!({
                "language": self.model,
                "speaker": request.voice,
                "text": request.text,
                "speed": request.speed,
            }),
        };
        // Caller parameters take precedence, including response format and instructions.
        if let Some(additional_params) = request.additional_params {
            crate::json_utils::merge_inplace(&mut body, additional_params);
        }

        // Azure versions its speech endpoint separately from every other
        // route, so this one request carries its own `api-version`.
        let uri = self.provider.uri_versioned(
            self.provider.dialect.quirks.audio_generation_path,
            self.provider.deployment(&self.model),
            self.provider.speech_api_version(),
        );
        json_post_to(&self.provider, uri, &body)
    }

    fn decoder<'id>(&self) -> Self::Decoder<'id> {
        SpeechDecoder {
            body: self.provider.dialect.quirks.speech_body,
        }
    }
}

/// The model-listing wire.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Models {
    /// Which provider, and how to reach it.
    pub provider: OpenAIConfig,
}

impl Models {
    /// The model-listing wire.
    pub fn new(provider: OpenAIConfig) -> Self {
        Self { provider }
    }
}

/// Model-list entry with required `id` and optional metadata.
/// Context length prefers `context_window`, then `context_length`, then
/// `max_context_length`. Top-level output limits take precedence over `top_provider`.
#[derive(Debug, Deserialize)]
pub struct ModelEntry {
    pub id: String,
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub description: Option<String>,
    /// Mistral labels the model kind `type` (`base`, `fine-tuned`).
    #[serde(default, rename = "type")]
    pub kind: Option<String>,
    #[serde(default)]
    pub created: Option<u64>,
    #[serde(default)]
    pub owned_by: Option<String>,
    #[serde(default)]
    pub context_window: Option<u32>,
    #[serde(default)]
    pub context_length: Option<u32>,
    #[serde(default)]
    pub max_context_length: Option<u32>,
    #[serde(default)]
    pub max_completion_tokens: Option<u32>,
    #[serde(default)]
    pub top_provider: Option<TopProvider>,
}

/// OpenRouter's per-entry routing block. Only the output ceiling is read;
/// the rest of the block is routing detail [`ModelInfo`] has no slot for.
#[derive(Debug, Deserialize)]
pub struct TopProvider {
    #[serde(default)]
    pub max_completion_tokens: Option<u32>,
}

impl From<ModelEntry> for ModelInfo {
    fn from(entry: ModelEntry) -> Self {
        let mut model = ModelInfo::from_id(entry.id);
        model.name = entry.name;
        model.description = entry.description;
        model.r#type = entry.kind;
        model.created_at = entry.created;
        model.owned_by = entry.owned_by;
        model.context_length = entry
            .context_window
            .or(entry.context_length)
            .or(entry.max_context_length);
        model.max_output_tokens = entry.max_completion_tokens.or_else(|| {
            entry
                .top_provider
                .and_then(|provider| provider.max_completion_tokens)
        });
        model
    }
}

/// The `{ "data": [...] }` envelope.
#[derive(Debug, Deserialize)]
pub struct ModelsReply {
    #[serde(default)]
    pub data: Vec<ModelEntry>,
}

/// Decode a complete model catalogue without pagination.
#[derive(Default)]
pub struct ModelsDecoder;

impl<'id> Decoder<'id, ModelListing> for ModelsDecoder {
    type Event = ModelsReply;

    fn classify(&self, frame: WireFrame) -> WireEvent<Self::Event> {
        classify_untyped_line(frame.as_str().as_bytes())
    }

    fn decode(
        &mut self,
        event: Self::Event,
        out: Out<'id, ModelListing>,
    ) -> Result<Flow, ProviderError> {
        let models = event.data.into_iter().map(ModelInfo::from).collect();
        Ok(out.end(ModelPage {
            models: ModelList::new(models),
            next: None,
        }))
    }
}

impl Wire for Models {
    type Op = ModelListing;
    type Payload = crate::wire::Encoded;
    type Frame = crate::wire::WireFrame;
    type Decoder<'id> = ModelsDecoder;
    type Reassembler = crate::wire::document::Unreassembled;

    fn describe(&self) -> Descriptor<'_> {
        Descriptor::new(self.provider.dialect.name)
    }

    /// The catalogue is one page, so a cursor never follows.
    fn encode(&self, _cursor: Option<String>, _mode: Mode) -> Result<Encoded, EncodeError> {
        get(&self.provider, self.provider.dialect.quirks.models_path)
    }

    fn decoder<'id>(&self) -> Self::Decoder<'id> {
        ModelsDecoder
    }
}

/// Rerank documents with `{model, query, documents, top_n}` requests.
/// The dialect must configure a nonempty reranking path.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Rerank {
    /// Which provider, and how to reach it.
    pub provider: OpenAIConfig,
    /// The reranker model.
    pub model: String,
    /// Return only the `top_n` highest-scoring documents, when the caller
    /// asked for a cut.
    pub top_n: Option<usize>,
}

impl Rerank {
    /// The rerank wire for `model`.
    pub fn new(provider: OpenAIConfig, model: impl Into<String>) -> Self {
        Self {
            provider,
            model: model.into(),
            top_n: None,
        }
    }

    /// Ask the server to return only the `top_n` highest-scoring documents.
    pub fn with_top_n(mut self, top_n: usize) -> Self {
        self.top_n = Some(top_n);
        self
    }
}

/// Scored input document accepting `relevance_score` or `score` as its score key.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RerankResultEntry {
    /// Which input document this scored.
    pub index: usize,
    /// The score.
    #[serde(alias = "score")]
    pub relevance_score: f64,
    /// Present only on servers that echo the document back; llama.cpp does
    /// not on this path.
    #[serde(default, alias = "text")]
    pub document: Option<String>,
}

/// What a rerank reply reports besides its ranking.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct RerankUsage {
    /// Tokens the query and documents cost.
    #[serde(default)]
    pub prompt_tokens: u64,
    /// Total tokens, as the provider reported them.
    #[serde(default)]
    pub total_tokens: u64,
}

/// The rerank reply.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RerankReply {
    /// The model the server ranked with, when it named one.
    #[serde(default)]
    pub model: Option<String>,
    /// The ranking.
    pub results: Vec<RerankResultEntry>,
    /// What it cost.
    #[serde(default)]
    pub usage: Option<RerankUsage>,
}

/// The rerank decoder.
#[derive(Default)]
pub struct RerankDecoder;

impl<'id> Decoder<'id, RerankOp> for RerankDecoder {
    type Event = RerankReply;

    fn classify(&self, frame: WireFrame) -> WireEvent<Self::Event> {
        classify_untyped_line(frame.as_str().as_bytes())
    }

    fn decode(
        &mut self,
        event: Self::Event,
        out: Out<'id, RerankOp>,
    ) -> Result<Flow, ProviderError> {
        let usage = event
            .usage
            .map(|usage| crate::completion::Usage {
                input_tokens: Some(usage.prompt_tokens),
                total_tokens: Some(usage.total_tokens),
                ..Default::default()
            })
            .unwrap_or_default();
        let results = event
            .results
            .into_iter()
            .map(|result| crate::rerank::RerankResult {
                index: result.index,
                document: result.document,
                relevance_score: result.relevance_score,
            })
            .collect();
        Ok(out.end(crate::rerank::RerankResponse {
            model: event.model,
            usage,
            ..crate::rerank::RerankResponse::new(results)
        }))
    }
}

impl Wire for Rerank {
    type Op = RerankOp;
    type Payload = crate::wire::Encoded;
    type Frame = crate::wire::WireFrame;
    type Decoder<'id> = RerankDecoder;
    type Reassembler = crate::wire::document::Unreassembled;

    fn describe(&self) -> Descriptor<'_> {
        Descriptor::new(self.provider.dialect.name)
            .model(self.model.as_str())
            .capabilities(Capabilities::rerank(
                self.provider.dialect.quirks.rerank.max_documents,
            ))
    }

    fn encode(
        &self,
        request: crate::operation::RerankRequest,
        _mode: Mode,
    ) -> Result<Encoded, EncodeError> {
        let quirks = &self.provider.dialect.quirks.rerank;
        // An empty path explicitly disables reranking.
        if quirks.path.is_empty() {
            return Err(EncodeError::request(format!(
                "{} offers no reranking endpoint",
                self.provider.dialect.name
            )));
        }
        let mut body = serde_json::json!({
            "query": request.query,
            "documents": request.documents,
        });
        let Some(object) = body.as_object_mut() else {
            return Err(EncodeError::request(
                "rerank request body must be an object",
            ));
        };
        if quirks.sends_model_field {
            object.insert("model".to_owned(), serde_json::json!(self.model));
        }
        if let Some(top_n) = self.top_n {
            object.insert("top_n".to_owned(), serde_json::json!(top_n));
        }

        json_post(
            &self.provider,
            quirks.path,
            self.provider.deployment(&self.model),
            &body,
        )
    }

    fn decoder<'id>(&self) -> Self::Decoder<'id> {
        RerankDecoder
    }
}

/// The credential-check wire: a `GET` whose status is the answer.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Verify {
    /// Which provider, and how to reach it.
    pub provider: OpenAIConfig,
}

impl Verify {
    /// The credential-check wire.
    pub fn new(provider: OpenAIConfig) -> Self {
        Self { provider }
    }
}

pub use crate::operation::VerifyDecoder;

impl Wire for Verify {
    type Op = VerifyOp;
    type Payload = crate::wire::Encoded;
    type Frame = crate::wire::WireFrame;
    type Decoder<'id> = VerifyDecoder;
    type Reassembler = crate::wire::document::Unreassembled;

    fn describe(&self) -> Descriptor<'_> {
        Descriptor::new(self.provider.dialect.name)
    }

    fn encode(&self, _request: (), _mode: Mode) -> Result<Encoded, EncodeError> {
        let path = self.provider.dialect.quirks.verify_path;
        if path.is_empty() {
            return Err(EncodeError::request(format!(
                "{} offers no endpoint that checks a credential without consuming tokens",
                self.provider.dialect.name
            )));
        }
        get(&self.provider, path)
    }

    fn decoder<'id>(&self) -> Self::Decoder<'id> {
        VerifyDecoder
    }
}

#[cfg(test)]
mod tests;