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
//! The non-chat wires, driven from recorded bytes.

use super::super::tests::{recorded, recorded_json};
use super::*;
use crate::error::{ErrorKind, ProviderError};
use crate::providers::doubleword::QWEN3_EMBEDDING_8B;
use crate::providers::mistral::embedding::{CODESTRAL_EMBED, MISTRAL_EMBED};
use crate::providers::openai::embedding::TEXT_EMBEDDING_ADA_002;
use crate::providers::openai::wire::{
    AZURE, DOUBLEWORD, Dialect, LLAMACPP, MISTRAL, OPENAI, OpenAIConfig, TOGETHER,
};
use crate::test_utils::{RecordingHttpClient, json_body};

/// The batch the embedding cassettes were recorded against.
fn documents() -> Vec<String> {
    vec![
        "Rust values memory safety and predictable performance.".to_owned(),
        "Streaming responses arrive incrementally instead of all at once.".to_owned(),
        "Embeddings turn text into numeric vectors for similarity search.".to_owned(),
    ]
}

/// The vectors come back in request order, joined onto the inputs the
/// request carried — which are not on the wire, so only the operation's fold
/// can supply them.
#[tokio::test]
async fn a_recorded_embedding_reply_zips_onto_the_requests_inputs() {
    let reply = recorded(
        "then",
        "embedding_matrix/normalized_response_is_complete.yaml",
    );
    let wire = OpenAIConfig::new("sk-test").embedding("text-embedding-3-small", None);
    let bound = crate::driver::Model::new(wire, RecordingHttpClient::new(reply));

    let response = bound
        .call(documents())
        .await
        .expect("the recorded reply decodes");

    let inputs: Vec<&str> = response
        .embeddings
        .iter()
        .map(|embedding| embedding.document.as_str())
        .collect();
    assert_eq!(
        inputs,
        documents().iter().map(String::as_str).collect::<Vec<_>>(),
        "vectors must stay paired with the input they belong to, in order"
    );
    assert!(
        response
            .embeddings
            .iter()
            .all(|embedding| embedding.vec.len() == 1536),
        "widths: {:?}",
        response
            .embeddings
            .iter()
            .map(|embedding| embedding.vec.len())
            .collect::<Vec<_>>()
    );
    assert_eq!(response.provider, "openai");
    assert_eq!(response.model.as_deref(), Some("text-embedding-3-small"));
    assert!(response.usage.input_tokens.is_some());
}

/// A batch whose reply carries the wrong number of vectors is a provider
/// defect, and the check lives in the operation's fold rather than in this
/// wire.
#[tokio::test]
async fn a_short_embedding_reply_fails_the_call() {
    let reply = r#"{"object":"list","model":"m","data":[{"object":"embedding","index":0,"embedding":[0.5]}],"usage":{"prompt_tokens":1,"total_tokens":1}}"#;
    let bound = crate::driver::Model::new(
        OpenAIConfig::new("sk-test").embedding("text-embedding-3-small", None),
        RecordingHttpClient::new(reply),
    );
    let error = bound
        .call(documents())
        .await
        .expect_err("three inputs and one vector cannot pair up");
    assert!(
        error.to_string().contains('1') && error.to_string().contains('3'),
        "the error names both counts: {error}"
    );
}

/// A requested width goes on the wire in the field the dialect spells it
/// with — and the recorded request is what that looks like.
#[test]
fn a_requested_width_matches_the_recorded_request() {
    let encoded = OpenAIConfig::new("sk-test")
        .embedding("text-embedding-3-small", Some(512))
        .encode(documents(), Mode::Unary)
        .expect("the request encodes");
    let body = json_body(&encoded.request);
    assert_eq!(
        body,
        recorded_json("when", "embedding_matrix/dimensions_request.yaml")
    );
}

/// Mistral takes a width in `output_dimension`, and `llama-server` reads no
/// width field at all — so neither can be expressed by sending `dimensions`
/// unconditionally.
#[test]
fn the_dialect_decides_the_width_field() {
    fn width_field(dialect: &Dialect, model: &str) -> Option<String> {
        let encoded = OpenAIConfig::with_key(dialect, "k")
            .embedding(model, Some(256))
            .encode(documents(), Mode::Unary)
            .expect("the request encodes");
        let body = json_body(&encoded.request);
        ["dimensions", "output_dimension"]
            .into_iter()
            .find(|field| body.get(*field).is_some())
            .map(str::to_owned)
    }

    assert_eq!(
        width_field(&OPENAI, "text-embedding-3-small"),
        Some("dimensions".to_owned())
    );
    assert_eq!(
        width_field(&MISTRAL, "codestral-embed"),
        Some("output_dimension".to_owned())
    );
    assert_eq!(
        width_field(&LLAMACPP, "nomic-embed"),
        None,
        "`llama-server` ignores a width field, so sending one would leave \
         `ndims()` describing vectors it never returned"
    );
    // OpenAI's legacy Ada model rejects the field outright.
    assert_eq!(width_field(&OPENAI, TEXT_EMBEDDING_ADA_002), None);
}

/// Azure addresses a deployment in the URL and therefore sends no `model`.
#[test]
fn azure_sends_no_model_field() {
    let encoded = OpenAIConfig::with_key(&AZURE, "k")
        .with_base_url("https://example.openai.azure.com")
        .with_api_version("2024-10-21")
        .embedding("my-deployment", None)
        .encode(documents(), Mode::Unary)
        .expect("the request encodes");
    let request = &encoded.request;
    assert_eq!(
        request.uri().to_string(),
        "https://example.openai.azure.com/openai/deployments/my-deployment/embeddings?api-version=2024-10-21"
    );
    let body = json_body(request);
    assert!(body.get("model").is_none(), "{body}");
}

/// A dialect that must report usage and does not is a defect, not an
/// embedding with no accounting.
#[tokio::test]
async fn a_usage_less_reply_fails_a_dialect_that_requires_usage() {
    let reply = r#"{"object":"list","model":"m","data":[{"object":"embedding","index":0,"embedding":[0.5]}]}"#;
    let error = crate::driver::Model::new(
        OpenAIConfig::new("sk-test").embedding("text-embedding-3-small", None),
        RecordingHttpClient::new(reply),
    )
    .call(vec!["one".to_owned()])
    .await
    .expect_err("OpenAI always reports usage");
    assert_eq!(error.kind(), ErrorKind::Response, "{error}");
    assert!(
        error
            .to_string()
            .contains("openai embedding response omitted required usage"),
        "{error}"
    );

    // Together does not guarantee it, so the same reply succeeds there.
    let response = crate::driver::Model::new(
        OpenAIConfig::with_key(&TOGETHER, "k")
            .embedding("togethercomputer/m2-bert-80M-8k-retrieval", None),
        RecordingHttpClient::new(reply),
    )
    .call(vec!["one".to_owned()])
    .await
    .expect("Together may omit usage");
    assert_eq!(response.embeddings.len(), 1);
}

/// The catalogue decodes, and Groq's context/output limits land on the
/// normalized model rather than being dropped.
#[tokio::test]
async fn a_recorded_model_listing_decodes() {
    let reply = recorded("then", "models/list_models_smoke.yaml");
    let models = crate::driver::Model::new(
        OpenAIConfig::new("sk-test").models(),
        RecordingHttpClient::new(reply),
    )
    .list()
    .await
    .expect("the recorded catalogue decodes");
    assert!(!models.is_empty(), "the catalogue is not empty");
    assert!(
        models.iter().all(|model| !model.id.is_empty()),
        "every entry names a model"
    );
}

/// The transcription body is multipart, with the model as a form field
/// everywhere but Azure.
#[test]
fn a_transcription_request_is_multipart() {
    let request = crate::transcription::TranscriptionRequest {
        data: b"RIFF".to_vec(),
        filename: "clip.wav".to_owned(),
        language: Some("en".to_owned()),
        prompt: None,
        temperature: None,
        additional_params: Some(serde_json::json!({"response_format": "verbose_json"})),
    };
    let encoded = OpenAIConfig::new("sk-test")
        .transcription("whisper-1")
        .encode(request, Mode::Unary)
        .expect("the request encodes");
    let http_request = &encoded.request;
    let Body::Multipart(form) = http_request.body() else {
        panic!("a transcription body is multipart");
    };
    let names: Vec<&str> = form.parts().iter().map(|part| part.name()).collect();
    assert_eq!(
        names,
        vec!["model", "file", "language", "response_format"],
        "field order is the order these endpoints were always sent in"
    );
    assert_eq!(
        http_request.uri().to_string(),
        "https://api.openai.com/v1/audio/transcriptions"
    );
}

// ── the dialect-specific modality bodies ────────────────────────────────

/// xAI's image endpoint takes no `size` and must be asked for base64, which
/// is the only form this wire decodes.
#[cfg(feature = "image")]
#[tokio::test]
async fn the_xai_image_body_and_reply_differ_from_openais() {
    use crate::providers::xai::DIALECT as XAI;

    let request = || crate::image_generation::ImageGenerationRequest {
        prompt: "a cat".to_owned(),
        width: 1024,
        height: 1024,
        additional_params: None,
    };
    let encoded = OpenAIConfig::with_key(&XAI, "xai-key")
        .image_generation("grok-imagine-image-pro")
        .encode(request(), Mode::Unary)
        .expect("the request encodes");
    let http_request = &encoded.request;
    assert_eq!(
        http_request.uri().to_string(),
        "https://api.x.ai/v1/images/generations"
    );
    let body = json_body(http_request);
    assert_eq!(body["response_format"], "b64_json");
    assert_eq!(body["aspect_ratio"], "1:1");
    assert!(body.get("size").is_none(), "xAI takes no `size`: {body}");

    // OpenAI's own body is the other shape.
    let openai = OpenAIConfig::new("sk")
        .image_generation("gpt-image-1")
        .encode(request(), Mode::Unary)
        .expect("encodes");
    let openai_body = json_body(&openai.request);
    assert_eq!(openai_body["size"], "1024x1024");
    assert!(openai_body.get("aspect_ratio").is_none());

    // xAI's reply carries no `created`, which the shared reply shape used to
    // require — every xAI image call would have failed to decode.
    let reply = r#"{"data":[{"b64_json":"aGk="}]}"#;
    let response = crate::driver::Model::new(
        OpenAIConfig::with_key(&XAI, "k").image_generation("grok-imagine-image-pro"),
        RecordingHttpClient::new(reply),
    )
    .call(request())
    .await
    .expect("a reply without `created` still decodes");
    assert_eq!(response.image, b"hi");
    assert_eq!(response.provider, "xai");
}

/// xAI spells its speech endpoint `/v1/tts` and takes a body of its own.
#[cfg(feature = "audio")]
#[test]
fn the_xai_speech_body_differs_from_openais() {
    use crate::providers::xai::DIALECT as XAI;

    let request = |voice: &str| crate::audio_generation::AudioGenerationRequest {
        text: "hello".to_owned(),
        voice: voice.to_owned(),
        speed: 1.0,
        additional_params: None,
    };
    let encoded = OpenAIConfig::with_key(&XAI, "k")
        .audio_generation("tts-1")
        .encode(request("nova"), Mode::Unary)
        .expect("encodes");
    let http_request = &encoded.request;
    assert_eq!(http_request.uri().to_string(), "https://api.x.ai/v1/tts");
    let body = json_body(&encoded.request);
    assert_eq!(body["voice_id"], "nova");
    assert_eq!(body["text"], "hello");
    assert_eq!(body["language"], "en");
    assert!(body.get("model").is_none(), "xAI's tts takes no model");

    // The voice its client defaulted to when the caller named none.
    let defaulted = OpenAIConfig::with_key(&XAI, "k")
        .audio_generation("tts-1")
        .encode(request(""), Mode::Unary)
        .expect("encodes");
    assert_eq!(json_body(&defaulted.request)["voice_id"], "eve");

    // OpenAI's own body is the other shape, at the other path.
    let openai = OpenAIConfig::new("sk")
        .audio_generation("tts-1")
        .encode(request("nova"), Mode::Unary)
        .expect("encodes");
    let body = json_body(&openai.request);
    assert_eq!(body["voice"], "nova");
    assert_eq!(body["input"], "hello");
    assert_eq!(body["model"], "tts-1");
}

/// Azure versions its speech endpoint separately from every other route, so
/// a speech request must not carry the general `api-version`.
#[cfg(feature = "audio")]
#[test]
fn azure_speech_carries_its_own_api_version() {
    let provider = OpenAIConfig::with_key(&AZURE, "k")
        .with_base_url("https://example.openai.azure.com")
        .with_api_version("2024-10-21")
        .with_audio_api_version("2025-04-01-preview");
    let encoded = provider
        .audio_generation("my-tts")
        .encode(
            crate::audio_generation::AudioGenerationRequest {
                text: "hi".to_owned(),
                voice: "alloy".to_owned(),
                speed: 1.0,
                additional_params: None,
            },
            Mode::Unary,
        )
        .expect("encodes");
    let request = &encoded.request;
    assert_eq!(
        request.uri().to_string(),
        "https://example.openai.azure.com/openai/deployments/my-tts/audio/speech?api-version=2025-04-01-preview"
    );

    // Every other Azure route keeps the general version.
    let embeddings = OpenAIConfig::with_key(&AZURE, "k")
        .with_base_url("https://example.openai.azure.com")
        .with_api_version("2024-10-21")
        .embedding("my-embed", None)
        .encode(vec!["a".to_owned()], Mode::Unary)
        .expect("encodes");
    let request = &embeddings.request;
    assert!(
        request
            .uri()
            .to_string()
            .ends_with("?api-version=2024-10-21"),
        "{}",
        request.uri()
    );
}

// ── reranking ───────────────────────────────────────────────────────────

/// llama.cpp's Jina-shaped reranking: the request it posts and the ranking
/// it folds.
#[tokio::test]
async fn a_recorded_rerank_reply_folds_its_ranking() {
    let reply = r#"{"model":"bge-reranker-v2-m3","object":"list","usage":{"prompt_tokens":37,"total_tokens":37},"results":[{"index":2,"relevance_score":0.98},{"index":0,"relevance_score":0.41},{"index":1,"relevance_score":0.02}]}"#;
    let response = crate::driver::Model::new(
        OpenAIConfig::with_key(&LLAMACPP, "").rerank("bge-reranker-v2-m3"),
        RecordingHttpClient::new(reply),
    )
    .call(crate::operation::RerankRequest {
        query: "which is about cats?".to_owned(),
        documents: vec![
            "dogs bark".to_owned(),
            "the sky is blue".to_owned(),
            "cats purr".to_owned(),
        ],
    })
    .await
    .expect("the reply decodes");

    // Score order is the server's, preserved as sent.
    let ranked: Vec<(usize, f64)> = response
        .results
        .iter()
        .map(|result| (result.index, result.relevance_score))
        .collect();
    assert_eq!(ranked, vec![(2, 0.98), (0, 0.41), (1, 0.02)]);
    assert_eq!(response.provider, "llamacpp");
    assert_eq!(response.model.as_deref(), Some("bge-reranker-v2-m3"));
    assert_eq!(response.usage.input_tokens, Some(37));
    assert_eq!(response.usage.total_tokens, Some(37));
    // llama.cpp never echoes the document text on this path.
    assert!(
        response
            .results
            .iter()
            .all(|result| result.document.is_none())
    );
}

#[test]
fn a_rerank_request_is_the_jina_shape() {
    let encoded = OpenAIConfig::with_key(&LLAMACPP, "")
        .rerank("bge-reranker-v2-m3")
        .with_top_n(2)
        .encode(
            crate::operation::RerankRequest {
                query: "q".to_owned(),
                documents: vec!["a".to_owned(), "b".to_owned(), "c".to_owned()],
            },
            Mode::Unary,
        )
        .expect("encodes");
    let request = &encoded.request;
    assert_eq!(request.uri().to_string(), "http://localhost:8080/v1/rerank");
    let body = json_body(&encoded.request);
    assert_eq!(
        body,
        serde_json::json!({
            "query": "q",
            "documents": ["a", "b", "c"],
            "model": "bge-reranker-v2-m3",
            "top_n": 2,
        })
    );
    // The batching hint the consumer trait asks for.
    assert_eq!(
        OpenAIConfig::with_key(&LLAMACPP, "")
            .rerank("r")
            .describe()
            .capabilities
            .max_documents,
        1024
    );
}

/// Hyperbolic's image endpoint names the model `model_name`, takes the size
/// as two fields, and answers under `images[].image` — none of which the
/// OpenAI shape would have matched.
#[cfg(feature = "image")]
#[tokio::test]
async fn the_hyperbolic_image_body_and_reply_differ_from_openais() {
    use crate::providers::openai::wire::HYPERBOLIC;

    let request = || crate::image_generation::ImageGenerationRequest {
        prompt: "a cat".to_owned(),
        width: 1024,
        height: 768,
        additional_params: None,
    };
    let encoded = OpenAIConfig::with_key(&HYPERBOLIC, "hb")
        .image_generation("SDXL1.0-base")
        .encode(request(), Mode::Unary)
        .expect("the request encodes");
    let http_request = &encoded.request;
    assert_eq!(
        http_request.uri().to_string(),
        "https://api.hyperbolic.xyz/v1/image/generation"
    );
    let body = json_body(&encoded.request);
    assert_eq!(body["model_name"], "SDXL1.0-base");
    assert_eq!(body["width"], 1024);
    assert_eq!(body["height"], 768);
    assert!(
        body.get("model").is_none(),
        "the key is `model_name`: {body}"
    );
    assert!(body.get("size").is_none(), "the size is two fields: {body}");

    // And the reply is keyed `images[].image`, not `data[].b64_json`.
    let response = crate::driver::Model::new(
        OpenAIConfig::with_key(&HYPERBOLIC, "hb").image_generation("SDXL1.0-base"),
        RecordingHttpClient::new(r#"{"images":[{"image":"aGk="}]}"#),
    )
    .call(request())
    .await
    .expect("Hyperbolic's reply shape decodes");
    assert_eq!(response.image, b"hi");
    assert_eq!(response.provider, "hyperbolic");
}

/// Hugging Face's router takes the prompt as `inputs` and the size nested
/// under `parameters`, and the model is the path rather than a body field —
/// the OpenAI body would have been rejected outright.
#[cfg(feature = "image")]
#[test]
fn the_huggingface_image_body_is_the_routers_own_shape() {
    use crate::providers::openai::wire::HUGGINGFACE;

    let encoded = OpenAIConfig::with_key(&HUGGINGFACE, "hf")
        .image_generation("stabilityai/stable-diffusion-3-medium-diffusers")
        .encode(
            crate::image_generation::ImageGenerationRequest {
                prompt: "a cat".to_owned(),
                width: 1024,
                height: 768,
                additional_params: None,
            },
            Mode::Unary,
        )
        .expect("the request encodes");
    let http_request = &encoded.request;
    // The model is the path, at the router root rather than under `/v1`.
    assert_eq!(
        http_request.uri().to_string(),
        "https://router.huggingface.co/stabilityai/stable-diffusion-3-medium-diffusers"
    );
    let body = json_body(&encoded.request);
    assert_eq!(body["inputs"], "a cat");
    assert_eq!(body["parameters"]["width"], 1024);
    assert_eq!(body["parameters"]["height"], 768);
    assert!(
        body.get("prompt").is_none(),
        "the prompt is `inputs`: {body}"
    );
    assert!(body.get("model").is_none(), "the model is the path: {body}");
    assert!(body.get("size").is_none(), "the size is nested: {body}");
    assert!(
        body.get("width").is_none(),
        "the size is under `parameters`: {body}"
    );
}

/// The router answers with the image bytes and no JSON envelope at all, so
/// the reply neither classifies nor decodes as JSON: the frame is the image.
#[cfg(feature = "image")]
#[tokio::test]
async fn the_huggingface_image_reply_is_the_image_bytes() {
    use crate::providers::openai::wire::HUGGINGFACE;

    // A real PNG header: not valid UTF-8, and not valid JSON.
    let png = b"\x89PNG\r\n\x1a\n\xff\xd8not-json";
    let response = crate::driver::Model::new(
        OpenAIConfig::with_key(&HUGGINGFACE, "hf").image_generation("black-forest-labs/FLUX.1-dev"),
        RecordingHttpClient::new(&png[..]),
    )
    .call(crate::image_generation::ImageGenerationRequest {
        prompt: "a cat".to_owned(),
        width: 1024,
        height: 768,
        additional_params: None,
    })
    .await
    .expect("raw image bytes decode");
    assert_eq!(response.image, png);
    assert_eq!(response.provider, "huggingface");
    // There is no reply document, so `raw` is null rather than a re-encoding
    // of the image.
    assert!(response.raw.is_null(), "{}", response.raw);
}

/// Hyperbolic addresses speech by language and answers with base64 in a JSON
/// envelope rather than the audio bytes OpenAI's endpoint returns.
#[cfg(feature = "audio")]
#[tokio::test]
async fn the_hyperbolic_speech_body_and_reply_differ_from_openais() {
    use crate::providers::openai::wire::HYPERBOLIC;

    let request = || crate::audio_generation::AudioGenerationRequest {
        text: "hello".to_owned(),
        voice: "EN-US".to_owned(),
        speed: 1.0,
        additional_params: None,
    };
    let encoded = OpenAIConfig::with_key(&HYPERBOLIC, "hb")
        .audio_generation("EN")
        .encode(request(), Mode::Unary)
        .expect("the request encodes");
    let http_request = &encoded.request;
    assert_eq!(
        http_request.uri().to_string(),
        "https://api.hyperbolic.xyz/v1/audio/generation"
    );
    let body = json_body(&encoded.request);
    // The "model" handle IS the language tag.
    assert_eq!(body["language"], "EN");
    assert_eq!(body["speaker"], "EN-US");
    assert_eq!(body["text"], "hello");
    assert_eq!(body["speed"], 1.0);
    assert!(body.get("model").is_none(), "{body}");
    assert!(body.get("voice").is_none(), "{body}");

    let response = crate::driver::Model::new(
        OpenAIConfig::with_key(&HYPERBOLIC, "hb").audio_generation("EN"),
        RecordingHttpClient::new(r#"{"audio":"aGk="}"#),
    )
    .call(request())
    .await
    .expect("Hyperbolic's base64 envelope decodes");
    assert_eq!(response.audio, b"hi");
    assert_eq!(response.provider, "hyperbolic");

    // OpenAI's own endpoint answers with the bytes themselves, so the same
    // decoder must not go looking for an envelope there.
    let openai = crate::driver::Model::new(
        OpenAIConfig::new("sk").audio_generation("tts-1"),
        RecordingHttpClient::new(&b"ID3\x04raw-mp3"[..]),
    )
    .call(request())
    .await
    .expect("raw bytes decode");
    assert_eq!(openai.audio, b"ID3\x04raw-mp3");
}

/// The width a dialect's own table documents, and the field suppression that
/// comes with it.
///
/// `ndims()` is what a vector store sizes its index from — `rig-neo4j`
/// validates and creates its index from it, `rig-sqlite` sizes its table
/// from it — so a model absent from every table reports 0 and builds an
/// index that cannot hold its own vectors. Doubleword's only embedding model
/// is absent from OpenAI's `text-embedding-*` table, which is why the
/// dialect has to carry its own.
#[test]
fn a_dialects_width_table_supplies_the_default_and_suppresses_the_field() {
    let unasked = OpenAIConfig::with_key(&DOUBLEWORD, "k").embedding(QWEN3_EMBEDDING_8B, None);
    assert_eq!(
        unasked.describe().capabilities.ndims,
        4_096,
        "the dialect's table is the only place this model's width is written down"
    );

    // At the native width the field is redundant: the model emits 4096
    // unasked, so the vector is identical either way.
    for wire in [
        &unasked,
        &OpenAIConfig::with_key(&DOUBLEWORD, "k").embedding(QWEN3_EMBEDDING_8B, Some(4_096)),
    ] {
        let encoded = wire
            .encode(documents(), Mode::Unary)
            .expect("the native width encodes");
        assert!(
            json_body(&encoded.request).get("dimensions").is_none(),
            "{}",
            json_body(&encoded.request)
        );
    }

    // A truncating width is a real request and goes out.
    let encoded = OpenAIConfig::with_key(&DOUBLEWORD, "k")
        .embedding(QWEN3_EMBEDDING_8B, Some(512))
        .encode(documents(), Mode::Unary)
        .expect("a width inside the documented range encodes");
    assert_eq!(
        json_body(&encoded.request)["dimensions"],
        serde_json::json!(512)
    );

    // Mistral's fixed-width model is the same mechanism with a different
    // table: 1024 reported, and no `output_dimension` on the wire.
    let mistral = OpenAIConfig::with_key(&MISTRAL, "k").embedding(MISTRAL_EMBED, None);
    assert_eq!(mistral.describe().capabilities.ndims, 1_024);
    let encoded = mistral
        .encode(documents(), Mode::Unary)
        .expect("the native width encodes");
    assert!(
        json_body(&encoded.request)
            .get("output_dimension")
            .is_none(),
        "{}",
        json_body(&encoded.request)
    );
}

/// A width the dialect cannot honour is refused before the request is built.
///
/// Request-side, because the reply-side check cannot see it: Doubleword
/// answers an over-wide request `200` with a silently clamped 4096-wide
/// vector, so the disagreement never appears in the reply at all.
#[test]
fn an_unhonourable_width_is_refused_before_the_request_is_built() {
    fn refusal(dialect: &Dialect, model: &str, ndims: usize) -> String {
        let error: ProviderError = OpenAIConfig::with_key(dialect, "k")
            .embedding(model, Some(ndims))
            .encode(documents(), Mode::Unary)
            .expect_err("a width the dialect cannot honour must not reach the wire")
            .into();
        assert_eq!(error.kind(), ErrorKind::Request, "{error}");
        error.to_string()
    }

    // The two Doubleword refusals read differently, and both texts are the
    // provider's documented contract rather than prose.
    assert_eq!(
        refusal(&DOUBLEWORD, QWEN3_EMBEDDING_8B, 0),
        "RequestError: doubleword embeddings require `dimensions` to be greater than zero"
    );
    for over_or_under in [8_192, 31] {
        assert_eq!(
            refusal(&DOUBLEWORD, QWEN3_EMBEDDING_8B, over_or_under),
            "RequestError: doubleword embeddings require `dimensions` to be between 32 and 4096"
        );
    }

    // Mistral's ceiling, and its fixed-width model refusing the parameter
    // itself rather than a value.
    assert_eq!(
        refusal(&MISTRAL, CODESTRAL_EMBED, 3_073),
        "RequestError: mistral embeddings require `output_dimension` to be at most 3072 for \
         Codestral Embed"
    );
    assert_eq!(
        refusal(&MISTRAL, MISTRAL_EMBED, 512),
        "RequestError: mistral embeddings do not support the `output_dimension` parameter",
        "a fixed-width model has no width to request"
    );

    // rig polices only the range it has a table for. For a model the dialect
    // does not document, the caller's width is the only width there is: it
    // goes out unvalidated and the provider decides.
    let unknown =
        OpenAIConfig::with_key(&DOUBLEWORD, "k").embedding("Qwen/Qwen4-Unreleased", Some(8_192));
    assert_eq!(unknown.describe().capabilities.ndims, 8_192);
    let encoded = unknown
        .encode(documents(), Mode::Unary)
        .expect("an undocumented model's width is not rig's to refuse");
    assert_eq!(
        json_body(&encoded.request)["dimensions"],
        serde_json::json!(8_192)
    );
}