ailoy 0.3.0

Agents that drive a language model through tool-augmented turns, in a virtx console.
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
use futures::{StreamExt as _, stream::BoxStream};
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};

use super::{LangModelAPISchema, LangModelProviderElem};
use crate::{
    datatype::Value,
    lang_model::{
        LangModelOptions, get_lm_providers,
        r#impl::{api, framing::Framing},
    },
    message::{
        Delta as _, FinishReason, Marshaled, Message, MessageDeltaOutput, MessageOutput, Role,
    },
    tool::ToolDesc,
};

/// A model id bound to its resolved provider endpoint.
pub struct LangModel {
    model: String,
    provider: LangModelProviderElem,
}

pub(super) struct LangModelRequest<'a> {
    pub model: &'a str,
    pub messages: &'a [Message],
    pub tools: &'a [ToolDesc],
    pub provider: &'a LangModelProviderElem,
    pub options: &'a LangModelOptions,
    /// When true, the marshal requests a streamed response.
    pub stream: bool,
}

impl LangModel {
    /// [`try_from_provider`](Self::try_from_provider) on the `"default"` provider.
    pub fn try_new(model: String) -> anyhow::Result<Self> {
        Self::try_from_provider(model, "default")
    }

    /// Resolve `model` against the [`LangModelProvider`](super::LangModelProvider)
    /// registered under `provider` in [`get_lm_providers`] (exact, then glob).
    ///
    /// The API-side id drops the `provider/` prefix (`"openai/gpt-6-astra"` →
    /// `"gpt-6-astra"`). Errors if `provider` is not registered or no entry matches.
    pub fn try_from_provider(model: String, provider: impl AsRef<str>) -> anyhow::Result<Self> {
        let provider_name = provider.as_ref();
        let registry = get_lm_providers();
        let lmp = registry.get(provider_name).ok_or_else(|| {
            anyhow::anyhow!("lang_model_provider '{}' not registered", provider_name)
        })?;
        let provider_elem = lmp
            .get(&model)
            .ok_or_else(|| {
                anyhow::anyhow!(
                    "no entry for model '{}' in lang_model_provider '{}'",
                    model,
                    provider_name
                )
            })?
            .clone();
        let api_model_id = lmp.resolve_model_id(&model)?;
        Ok(Self {
            model: api_model_id,
            provider: provider_elem,
        })
    }

    pub fn model_id(&self) -> &str {
        &self.model
    }

    pub async fn run(
        &self,
        messages: &[Message],
        tools: &[ToolDesc],
        options: &LangModelOptions,
    ) -> anyhow::Result<MessageOutput> {
        let req = LangModelRequest {
            model: &self.model,
            messages,
            tools,
            provider: &self.provider,
            options,
            stream: false,
        };
        let LangModelProviderElem::API { schema, .. } = &self.provider;
        let (url, header_map, body) = marshal_request(schema, &req)?;

        let provider = api::provider_api(schema);
        let client = reqwest::Client::new();
        let response = send_with_retry(&client, &url, header_map, &body, provider.as_ref()).await?;
        let response_text = response.text().await?;

        let response_value: Value =
            serde_json::from_str::<serde_json::Value>(&response_text)?.into();

        let delta_output = provider.unmarshal_response(response_value)?;

        // A non-streamed response is one complete delta.
        delta_output.finish()
    }

    /// Streaming counterpart to [`run`](Self::run): yields one
    /// [`MessageDeltaOutput`] per incremental update. Callers
    /// accumulate the deltas (via [`Delta::accumulate`](crate::message::Delta::accumulate)) to build the final
    /// message. The stream ends when the response body ends (after the terminal
    /// SSE event), not at the first `finish_reason` — some providers send usage
    /// in a final chunk after it.
    ///
    /// Contract: every message ends with a delta carrying a `finish_reason`. If
    /// a provider closes the stream without one, a terminal `Stop` delta is
    /// synthesized so this holds, letting consumers detect message boundaries by
    /// `finish_reason` alone (`finish()` promotes `Stop` to `ToolCall` if tool
    /// calls were produced).
    pub fn run_stream(
        &self,
        messages: &[Message],
        tools: &[ToolDesc],
        options: &LangModelOptions,
    ) -> BoxStream<'static, anyhow::Result<MessageDeltaOutput>> {
        // Marshal up front so the stream owns only wire artifacts. It must stay
        // `'static`: callers mutate their history (e.g. rolling back a failed
        // turn) while the stream is alive.
        let req = LangModelRequest {
            model: &self.model,
            messages,
            tools,
            provider: &self.provider,
            options,
            stream: true,
        };
        let LangModelProviderElem::API { schema, .. } = &self.provider;
        let (url, header_map, body) = match marshal_request(schema, &req) {
            Ok(parts) => parts,
            // A marshal failure surfaces as a one-shot error stream.
            Err(e) => {
                return Box::pin(futures::stream::once(async move {
                    Err::<MessageDeltaOutput, anyhow::Error>(e)
                }));
            }
        };
        let mut provider = api::provider_api(schema);
        let mut framing = Framing::for_schema(schema);

        Box::pin(async_stream::try_stream! {
            let client = reqwest::Client::new();
            let response =
                send_with_retry(&client, &url, header_map, &body, provider.as_ref()).await?;

            // Network chunks don't align with event boundaries, so events are
            // framed out of a buffer; role/finish tracking closes the contract at EOF.
            let mut seen_role: Option<Role> = None;
            let mut saw_finish = false;

            let mut byte_stream = response.bytes_stream();
            let mut buf: Vec<u8> = Vec::new();
            while let Some(chunk) = byte_stream.next().await {
                buf.extend_from_slice(&chunk?);
                for data in framing.drain(&mut buf)? {
                    if let Some(output) = provider.unmarshal_event(&data)? {
                        if seen_role.is_none() {
                            seen_role = output.delta.role.clone();
                        }
                        saw_finish |= output.finish_reason.is_some();
                        yield output;
                    }
                }
            }

            // Whatever is left at EOF is the last event for framings that allow
            // an unterminated final event (SSE without a trailing blank line).
            for data in framing.flush(&buf)? {
                if let Some(output) = provider.unmarshal_event(&data)? {
                    if seen_role.is_none() {
                        seen_role = output.delta.role.clone();
                    }
                    saw_finish |= output.finish_reason.is_some();
                    yield output;
                }
            }

            // No finish_reason arrived: synthesize a terminal Stop (nothing to
            // close if no role was seen). Must follow the EOF flush, which may
            // carry the real finish, or both would emit. A mid-stream error ends
            // the generator before here, so a failed turn never gets a fake Stop.
            // Not a let-chain: `try_stream!` rejects them (Rust 2024).
            #[allow(clippy::collapsible_if)]
            if !saw_finish {
                if let Some(role) = seen_role {
                    let mut closer = MessageDeltaOutput::new();
                    closer.delta.role = Some(role);
                    closer.finish_reason = Some(FinishReason::Stop {});
                    yield closer;
                }
            }
        })
    }
}

/// Marshals a [`LangModelRequest`] for `schema` into the wire `(url, headers,
/// body)` tuple shared by the blocking and streaming paths.
fn marshal_request(
    schema: &LangModelAPISchema,
    req: &LangModelRequest,
) -> anyhow::Result<(String, HeaderMap, serde_json::Value)> {
    if matches!(schema, LangModelAPISchema::Bedrock) {
        api::bedrock::validate_request(req)?;
    }
    let marshaled = match schema {
        LangModelAPISchema::Anthropic => Value::from(Marshaled::<
            LangModelRequest,
            api::AnthropicMarshal,
        >::new(req)),
        LangModelAPISchema::Bedrock => {
            Value::from(Marshaled::<LangModelRequest, api::BedrockMarshal>::new(req))
        }
        LangModelAPISchema::ChatCompletion => {
            Value::from(Marshaled::<LangModelRequest, api::ChatCompletionMarshal>::new(req))
        }
        LangModelAPISchema::Gemini => {
            Value::from(Marshaled::<LangModelRequest, api::GeminiMarshal>::new(req))
        }
        LangModelAPISchema::OpenAI => {
            Value::from(Marshaled::<LangModelRequest, api::OpenAIMarshal>::new(req))
        }
    };
    let obj = marshaled
        .as_object()
        .ok_or_else(|| anyhow::anyhow!("Invalid Marshal"))?;

    let url = obj
        .get("url")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("No URL in marshaled request"))?
        .to_owned();

    let mut header_map = HeaderMap::new();
    if let Some(header_obj) = obj.get("header").and_then(|v| v.as_object()) {
        for (key, value) in header_obj.iter() {
            if let Some(val_str) = value.as_str() {
                header_map.insert(
                    HeaderName::from_bytes(key.as_bytes())?,
                    HeaderValue::from_str(val_str)?,
                );
            }
        }
    }

    let body = obj
        .get("body")
        .ok_or_else(|| anyhow::anyhow!("No body in marshaled request"))?;
    let body: serde_json::Value = body.clone().into();

    Ok((url, header_map, body))
}

/// POSTs the request, retrying transient 429s with backoff, and returns the
/// successful (2xx) response **unconsumed** so the caller decides whether to
/// read it whole (`run`) or stream it (`run_stream`). Bails on a non-2xx
/// response or exhausted retries.
async fn send_with_retry(
    client: &reqwest::Client,
    url: &str,
    headers: HeaderMap,
    body: &serde_json::Value,
    provider: &(dyn api::ProviderApi + Send + Sync),
) -> anyhow::Result<reqwest::Response> {
    const MAX_RETRIES: u32 = 3;
    const MAX_WAIT_SECS: u64 = 10;
    for attempt in 0..=MAX_RETRIES {
        let response = client
            .post(url)
            .headers(headers.clone())
            .json(body)
            .send()
            .await?;
        let status = response.status();
        if status.is_success() {
            return Ok(response);
        }
        if status.as_u16() == 429 && attempt < MAX_RETRIES {
            let wait_secs = response
                .headers()
                .get("retry-after")
                .and_then(|v| v.to_str().ok())
                .and_then(|v| v.parse::<u64>().ok())
                .unwrap_or(1u64 << attempt)
                .min(MAX_WAIT_SECS);
            let text = response.text().await?;
            // Permanent quota/credit exhaustion never recovers; don't retry.
            if provider.is_permanent_quota_error(&text) {
                log::warn!("Quota exhausted (429), not retrying: {text}");
                anyhow::bail!("API request failed with status {status}: {text}");
            }
            log::warn!(
                "Rate limited (429). Retrying after {}s (attempt {}/{}): {}",
                wait_secs,
                attempt + 1,
                MAX_RETRIES,
                text
            );
            tokio::time::sleep(std::time::Duration::from_secs(wait_secs)).await;
            continue;
        }
        let text = response.text().await.unwrap_or_default();
        anyhow::bail!("API request failed with status {status}: {text}");
    }
    unreachable!("retry loop returns or bails on every path")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        lang_model::{LangModelProvider, ResponseFormat, get_lm_providers_mut},
        message::{FinishReason, Part, Role, into_messages},
        to_value,
        tool::{ToolDesc, ToolDescBuilder},
    };

    fn stored_schema(fmt: ResponseFormat) -> Value {
        match fmt {
            ResponseFormat::JsonSchema(s) => s,
        }
    }

    #[test]
    fn test_response_format_invalid_schema_rejected() {
        assert!(ResponseFormat::json_schema(to_value!({"type": 123})).is_err());
    }

    #[test]
    fn test_response_format_non_object_rejected() {
        assert!(ResponseFormat::json_schema(to_value!("not an object")).is_err());
    }

    #[test]
    fn test_response_format_stores_raw_schema() {
        let schema = to_value!({"type": "object", "properties": {"x": {"type": "string"}}});
        let fmt = ResponseFormat::json_schema(schema.clone()).unwrap();
        let stored = stored_schema(fmt);
        assert_eq!(stored, schema, "stored schema must equal input");
        assert!(
            stored.pointer("/additionalProperties").is_none(),
            "ResponseFormat must not mutate the schema at construction time"
        );
    }

    #[test]
    fn test_response_format_serde_round_trip() {
        let schema = to_value!({"type": "object", "properties": {"name": {"type": "string"}}});
        let original = ResponseFormat::json_schema(schema).unwrap();
        let json = serde_json::to_string(&original).expect("should serialize");
        let restored: ResponseFormat = serde_json::from_str(&json).expect("should deserialize");
        assert_eq!(original, restored);
    }

    /// Register a one-off [`LangModelProvider`] under a unique key in the
    /// global registry and build a [`LangModel`] from it via
    /// [`LangModel::try_from_provider`].
    fn build_test_model(
        provider_name: &str,
        model: &str,
        elem: LangModelProviderElem,
    ) -> LangModel {
        let mut lmp = LangModelProvider::new();
        lmp.insert(model.into(), elem);
        get_lm_providers_mut().insert(provider_name.into(), lmp);
        LangModel::try_from_provider(model.to_string(), provider_name).unwrap()
    }

    fn openai_chat_completion(model: &str, api_key: String) -> LangModel {
        let elem = LangModelProvider::chat_completion(
            "https://api.openai.com/v1/chat/completions",
            Some(api_key),
        )
        .unwrap();
        build_test_model("test_openai_chat_completion", model, elem)
    }

    /// Verifies that the POST request is sent and response is parsed.
    #[tokio::test]
    async fn test_run_lang_model_api_simple() {
        dotenvy::dotenv().ok();
        let api_key = std::env::var("OPENAI_API_KEY").expect("OPENAI_API_KEY must be set in .env");

        let model = openai_chat_completion("gpt-5.4-mini", api_key);
        let messages = vec![Message::new(Role::User).with_contents([Part::text("Hi")])];
        let tools: Vec<ToolDesc> = vec![];

        let resp = model
            .run(&messages, &tools, &LangModelOptions::default())
            .await
            .unwrap();
        assert!(
            !resp.message.contents.is_empty(),
            "Expected at least one message content"
        );
        assert!(
            resp.message.contents.first().unwrap().is_text(),
            "Expected a text type content"
        );
    }

    /// Verifies that the API returns tool calls when tools are provided.
    #[tokio::test]
    async fn test_run_lang_model_api_tool_call() {
        dotenvy::dotenv().ok();
        let api_key = std::env::var("OPENAI_API_KEY").expect("OPENAI_API_KEY must be set in .env");

        let model = openai_chat_completion("gpt-5.4-mini", api_key);
        let messages = vec![
            Message::new(Role::User)
                .with_contents([Part::text("What is the current temperature in Seoul?")]),
        ];
        let tools = vec![
            ToolDescBuilder::new("get_temperature")
                .description("Get the current temperature for a given city")
                .parameters(to_value!({
                    "type": "object",
                    "properties": {
                        "location": {
                            "type": "string",
                            "description": "The city name"
                        },
                        "unit": {
                            "type": "string",
                            "description": "Temperature unit",
                            "enum": ["celsius", "fahrenheit"]
                        }
                    },
                    "required": ["location"]
                }))
                .build(),
        ];

        let resp = model
            .run(&messages, &tools, &LangModelOptions::default())
            .await
            .unwrap();

        assert_eq!(resp.finish_reason, FinishReason::ToolCall {});
        let tool_calls = resp
            .message
            .tool_calls
            .as_ref()
            .expect("Expected tool_calls in response");
        assert!(!tool_calls.is_empty(), "Expected at least one tool call");

        let (_, name, arguments) = tool_calls[0]
            .as_function()
            .expect("Expected function part in tool call");
        assert_eq!(name, "get_temperature");
        assert!(
            arguments.pointer("/location").is_some(),
            "Expected 'location' argument in tool call"
        );
    }

    /// Verifies that token usage is populated in the response from the real API.
    #[tokio::test]
    async fn test_run_returns_usage() {
        dotenvy::dotenv().ok();
        let api_key = std::env::var("OPENAI_API_KEY").expect("OPENAI_API_KEY must be set in .env");
        let model = openai_chat_completion("gpt-5.4-mini", api_key);
        let messages = vec![Message::new(Role::User).with_contents([Part::text("Hi")])];

        let resp = model
            .run(&messages, &[], &LangModelOptions::default())
            .await
            .unwrap();
        let usage = resp
            .usage
            .expect("usage must be present in real API response");
        assert!(usage.input_tokens > 0, "input_tokens must be > 0");
        assert!(usage.output_tokens > 0, "output_tokens must be > 0");
    }

    /// Verifies that the runtime retries on 429 and succeeds when the server recovers.
    /// Uses an axum mock server that returns 429 for the first two requests, then 200.
    #[tokio::test]
    async fn test_run_retries_on_429() {
        use std::sync::{Arc, Mutex};

        use axum::{Router, body::Body, response::Response, routing::post};

        let call_count = Arc::new(Mutex::new(0u32));

        let count = call_count.clone();
        let app = Router::new().route(
            "/",
            post(move || {
                let count = count.clone();
                async move {
                    let mut n = count.lock().unwrap();
                    *n += 1;
                    let current = *n;
                    drop(n);

                    if current <= 2 {
                        // Return 429 with retry-after: 0 so the sleep is instant.
                        Response::builder()
                            .status(429)
                            .header("retry-after", "0")
                            .body(Body::from(r#"{"error":"rate limited"}"#))
                            .unwrap()
                    } else {
                        Response::builder()
                            .status(200)
                            .header("content-type", "application/json")
                            .body(Body::from(r#"{"choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}]}"#))
                            .unwrap()
                    }
                }
            }),
        );

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            axum::serve(listener, app).await.unwrap();
        });

        let elem = LangModelProvider::chat_completion(&format!("http://{}/", addr), None).unwrap();
        let model = build_test_model("test_run_lang_model_mock", "test-model", elem);
        let messages = vec![Message::new(Role::User).with_contents([Part::text("hi")])];

        let resp = model
            .run(&messages, &[], &LangModelOptions::default())
            .await
            .unwrap();

        assert_eq!(
            *call_count.lock().unwrap(),
            3,
            "should have made 3 total attempts (2x 429 retried + 1 success)"
        );
        assert!(!resp.message.contents.is_empty());
    }
    /// Verifies a permanent quota 429 (`insufficient_quota`) is not retried.
    #[tokio::test]
    async fn test_run_does_not_retry_on_permanent_429() {
        use std::sync::{Arc, Mutex};

        use axum::{Router, body::Body, response::Response, routing::post};

        let call_count = Arc::new(Mutex::new(0u32));
        let count = call_count.clone();
        let app = Router::new().route(
            "/",
            post(move || {
                let count = count.clone();
                async move {
                    *count.lock().unwrap() += 1;
                    Response::builder()
                        .status(429)
                        .body(Body::from(
                            r#"{"error":{"type":"insufficient_quota","code":"insufficient_quota","message":"You exceeded your current quota"}}"#,
                        ))
                        .unwrap()
                }
            }),
        );

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            axum::serve(listener, app).await.unwrap();
        });

        let elem = LangModelProviderElem::API {
            schema: LangModelAPISchema::OpenAI,
            url: format!("http://{}/", addr).parse().unwrap(),
            api_key: None,
        };
        let model = build_test_model("test_permanent_429_mock", "test-model", elem);
        let messages = vec![Message::new(Role::User).with_contents([Part::text("hi")])];

        let result = model
            .run(&messages, &[], &LangModelOptions::default())
            .await;

        assert!(result.is_err(), "permanent quota 429 must fail");
        assert_eq!(
            *call_count.lock().unwrap(),
            1,
            "permanent quota 429 must not be retried (1 attempt only)"
        );
    }

    /// Bedrock requests are validated before marshaling, and the Converse
    /// envelope comes out of the shared path with the bearer header lower-cased
    /// by `HeaderMap`.
    #[test]
    fn marshal_request_bedrock_envelope_and_guard() {
        let messages = vec![Message::new(Role::User).with_contents([Part::text("hi")])];
        let provider = LangModelProvider::bedrock("us-east-1".parse().unwrap(), "k".into());
        let options = LangModelOptions::default();
        let req = |options| LangModelRequest {
            model: "m",
            messages: &messages,
            tools: &[],
            provider: &provider,
            options,
            stream: false,
        };

        let (url, headers, body) =
            marshal_request(&LangModelAPISchema::Bedrock, &req(&options)).unwrap();
        assert!(url.ends_with("/model/m/converse"), "{url}");
        assert_eq!(headers["authorization"], "Bearer k");
        assert!(body.get("model").is_none());

        let url_image = vec![
            Message::new(Role::User)
                .with_contents([Part::image_url("https://example.com/a.png".into()).unwrap()]),
        ];
        let rejected = LangModelRequest {
            messages: &url_image,
            ..req(&options)
        };
        assert!(marshal_request(&LangModelAPISchema::Bedrock, &rejected).is_err());
    }

    /// A streamed response that never carries a finish_reason still ends with a
    /// synthesized terminal Stop delta, so consumers can detect the message
    /// boundary by finish_reason alone (the run_stream contract).
    #[tokio::test]
    async fn test_run_stream_synthesizes_terminal_finish_reason() {
        use axum::{Router, body::Body, response::Response, routing::post};

        let app = Router::new().route(
            "/",
            // Content deltas but NO finish_reason anywhere, then [DONE].
            post(|| async {
                let sse = "data: {\"choices\":[{\"delta\":{\"role\":\"assistant\",\"content\":\"Hi\"}}]}\n\n\
                           data: {\"choices\":[{\"delta\":{\"content\":\"!\"}}]}\n\n\
                           data: [DONE]\n\n";
                Response::builder()
                    .status(200)
                    .header("content-type", "text/event-stream")
                    .body(Body::from(sse))
                    .unwrap()
            }),
        );

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            axum::serve(listener, app).await.unwrap();
        });

        let elem = LangModelProvider::chat_completion(&format!("http://{}/", addr), None).unwrap();
        let model = build_test_model("test_stream_synthesizes_mock", "test-model", elem);
        let messages = vec![Message::new(Role::User).with_contents([Part::text("hi")])];

        let deltas: Vec<_> = model
            .run_stream(&messages, &[], &LangModelOptions::default())
            .collect::<Vec<_>>()
            .await
            .into_iter()
            .map(|d| d.unwrap())
            .collect();

        let last = deltas.last().expect("at least one delta");
        assert_eq!(last.finish_reason, Some(FinishReason::Stop {}));
        assert_eq!(last.delta.role, Some(Role::Assistant));
        assert!(last.delta.contents.is_empty());
        assert_eq!(
            deltas.iter().filter(|d| d.finish_reason.is_some()).count(),
            1,
            "exactly one finish_reason (the synthesized closer)"
        );

        // Accumulating the whole stream still reconstructs the message.
        let msgs: Vec<_> = into_messages(futures::stream::iter(deltas.into_iter().map(anyhow::Ok)))
            .map(|m| m.unwrap())
            .collect()
            .await;
        assert_eq!(msgs.len(), 1);
        assert_eq!(msgs[0].message.contents[0].as_text(), Some("Hi!"));
    }

    /// The terminal finish_reason may arrive in the EOF-terminated final event
    /// (no trailing blank line — Gemini's finish + usage chunk). The closer must
    /// see that finish and NOT append a second one. Locks the ordering: the
    /// closer check runs after the EOF-flush.
    #[tokio::test]
    async fn test_run_stream_no_double_finish_when_finish_in_eof_event() {
        use axum::{Router, body::Body, response::Response, routing::post};

        let app = Router::new().route(
            "/",
            post(|| async {
                let sse = "data: {\"choices\":[{\"delta\":{\"role\":\"assistant\",\"content\":\"Hi\"}}]}\n\n\
                           data: {\"choices\":[{\"delta\":{\"content\":\"!\"}}]}\n\n\
                           data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\"}]}";
                Response::builder()
                    .status(200)
                    .header("content-type", "text/event-stream")
                    .body(Body::from(sse))
                    .unwrap()
            }),
        );

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            axum::serve(listener, app).await.unwrap();
        });

        let elem = LangModelProvider::chat_completion(&format!("http://{}/", addr), None).unwrap();
        let model = build_test_model("test_stream_no_double_finish_mock", "test-model", elem);
        let messages = vec![Message::new(Role::User).with_contents([Part::text("hi")])];

        let deltas: Vec<_> = model
            .run_stream(&messages, &[], &LangModelOptions::default())
            .collect::<Vec<_>>()
            .await
            .into_iter()
            .map(|d| d.unwrap())
            .collect();

        assert_eq!(
            deltas.iter().filter(|d| d.finish_reason.is_some()).count(),
            1,
            "exactly one finish_reason — the provider's, no synthesized closer"
        );
    }

    /// A mid-stream error ends the stream WITHOUT a synthesized closer; a fake
    /// Stop on a failed turn would make the agent commit it to history instead
    /// of rolling it back.
    #[tokio::test]
    async fn test_run_stream_error_yields_no_closer() {
        use axum::{Router, body::Body, response::Response, routing::post};

        let app = Router::new().route(
            "/",
            // A valid role delta, then a malformed event (invalid JSON) with no
            // finish_reason — unmarshal_event errors and `?` ends the stream.
            post(|| async {
                let sse = "data: {\"choices\":[{\"delta\":{\"role\":\"assistant\",\"content\":\"Hi\"}}]}\n\n\
                           data: {not json}\n\n";
                Response::builder()
                    .status(200)
                    .header("content-type", "text/event-stream")
                    .body(Body::from(sse))
                    .unwrap()
            }),
        );

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            axum::serve(listener, app).await.unwrap();
        });

        let elem = LangModelProvider::chat_completion(&format!("http://{}/", addr), None).unwrap();
        let model = build_test_model("test_stream_error_mock", "test-model", elem);
        let messages = vec![Message::new(Role::User).with_contents([Part::text("hi")])];

        let results: Vec<_> = model
            .run_stream(&messages, &[], &LangModelOptions::default())
            .collect()
            .await;

        assert!(
            results.last().is_some_and(|r| r.is_err()),
            "stream must terminate with the error"
        );
        // No Ok delta ever carries a finish_reason: the error path appends no closer.
        assert!(
            !results
                .iter()
                .any(|r| r.as_ref().is_ok_and(|d| d.finish_reason.is_some())),
            "no synthesized closer on the error path"
        );
    }
}