Skip to main content

agent_sdk_providers/
provider.rs

1//! LLM provider trait and streaming helpers.
2//!
3//! This module defines the [`LlmProvider`] trait that all LLM backends implement,
4//! as well as the [`collect_stream`] helper for consuming a streaming response.
5
6#[cfg(feature = "anthropic")]
7use agent_sdk_foundation::llm::ToolChoice;
8use agent_sdk_foundation::llm::{
9    ChatOutcome, ChatRequest, ChatResponse, ContentBlock, ThinkingConfig, ThinkingMode, Usage,
10};
11use anyhow::Result;
12use async_trait::async_trait;
13use futures::StreamExt;
14use serde::{Deserialize, Serialize};
15
16use crate::model_capabilities::{
17    ModelCapabilities, default_max_output_tokens, get_model_capabilities,
18};
19use crate::model_features::{ModelFeatures, get_model_features};
20use crate::streaming::{StreamAccumulator, StreamBox, StreamDelta, StreamErrorKind};
21
22/// How a provider satisfies a [`ResponseFormat`](agent_sdk_foundation::llm::ResponseFormat)
23/// structured-output request.
24///
25/// The structured-output runner consults this to decide how to shape the
26/// request and where to read the final structured value from the response.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum StructuredOutputSupport {
29    /// The provider applies the schema natively (JSON-mode /
30    /// structured-outputs) when it sees `request.response_format`. The final
31    /// structured value is the JSON in the assistant's text output.
32    Native,
33    /// The provider has no native JSON-schema mode. The runner injects a
34    /// single forced "respond" tool whose `input_schema` is the output schema,
35    /// and reads the structured value from that tool call's input.
36    ToolForcing,
37}
38
39/// A single model entry returned by a provider's live model-listing endpoint.
40///
41/// This is the *dynamic* counterpart to the static
42/// [`ModelCapabilities`] table: it
43/// is populated from the provider's own `/models` API at runtime, so newly
44/// shipped models appear without an SDK code change. Fields beyond `id` are
45/// optional because not every provider's listing endpoint reports them.
46#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
47pub struct ModelInfo {
48    /// The model identifier as the provider's chat endpoint expects it.
49    pub id: String,
50    /// Human-friendly display name, when the listing endpoint provides one.
51    pub display_name: Option<String>,
52    /// Maximum total context window in tokens, when reported.
53    pub context_window: Option<u32>,
54    /// Maximum output tokens per response, when reported.
55    pub max_output_tokens: Option<u32>,
56}
57
58#[async_trait]
59pub trait LlmProvider: Send + Sync {
60    /// Non-streaming chat completion.
61    async fn chat(&self, request: ChatRequest) -> Result<ChatOutcome>;
62
63    /// List the models the provider currently exposes, queried live from the
64    /// provider's own model-listing endpoint.
65    ///
66    /// The default implementation returns an error: model discovery is an
67    /// additive capability, so a provider that has not implemented it stays
68    /// source-compatible while reporting that the operation is unsupported.
69    ///
70    /// # Errors
71    ///
72    /// Returns an error when the provider does not support live model listing,
73    /// or when the underlying HTTP request or response parsing fails.
74    async fn list_models(&self) -> Result<Vec<ModelInfo>> {
75        Err(anyhow::anyhow!(
76            "list_models is not supported for provider {}",
77            self.provider()
78        ))
79    }
80
81    /// Cheaply check whether the provider's endpoint is currently reachable,
82    /// without dispatching a billable request.
83    ///
84    /// Durable runtimes poll this to wait out connectivity loss: after a
85    /// transport-classified stream failure
86    /// ([`StreamErrorKind::is_connectivity`]) they probe until reachability
87    /// returns, then re-dispatch the real call. Only an unreachable answer
88    /// keeps that wait free of charge, so implementations should answer from
89    /// a cheap endpoint — [`probe_http_reachability`] against the API host —
90    /// never a model call.
91    ///
92    /// The default returns `true` ("reachable, or unknown"): a provider that
93    /// cannot observe reachability keeps its callers on the bounded retry
94    /// path instead of parking them in an offline wait it can never end.
95    async fn probe_connectivity(&self) -> bool {
96        true
97    }
98
99    /// Streaming chat completion.
100    ///
101    /// Returns a stream of [`StreamDelta`] events. The default implementation
102    /// calls [`chat()`](Self::chat) and converts the result to a single-chunk stream.
103    ///
104    /// Providers should override this method to provide true streaming support.
105    fn chat_stream(&self, request: ChatRequest) -> StreamBox<'_> {
106        Box::pin(async_stream::stream! {
107            match self.chat(request).await {
108                Ok(outcome) => match outcome {
109                    ChatOutcome::Success(response) => {
110                        // Emit content as deltas
111                        for (idx, block) in response.content.iter().enumerate() {
112                            match block {
113                                ContentBlock::Text { text } => {
114                                    yield Ok(StreamDelta::TextDelta {
115                                        delta: text.clone(),
116                                        block_index: idx,
117                                    });
118                                }
119                                ContentBlock::Thinking { thinking, .. } => {
120                                    yield Ok(StreamDelta::ThinkingDelta {
121                                        delta: thinking.clone(),
122                                        block_index: idx,
123                                    });
124                                }
125                                ContentBlock::RedactedThinking { .. }
126                                | ContentBlock::ToolResult { .. }
127                                | ContentBlock::Image { .. }
128                                | ContentBlock::Document { .. } => {
129                                    // Not streamed in the default implementation
130                                }
131                                ContentBlock::OpaqueReasoning { provider, data } => {
132                                    yield Ok(StreamDelta::OpaqueReasoning {
133                                        provider: provider.clone(),
134                                        data: data.clone(),
135                                        block_index: idx,
136                                    });
137                                }
138                                ContentBlock::ToolUse { id, name, input, thought_signature } => {
139                                    yield Ok(StreamDelta::ToolUseStart {
140                                        id: id.clone(),
141                                        name: name.clone(),
142                                        block_index: idx,
143                                        thought_signature: thought_signature.clone(),
144                                    });
145                                    yield Ok(StreamDelta::ToolInputDelta {
146                                        id: id.clone(),
147                                        delta: serde_json::to_string(input).unwrap_or_default(),
148                                        block_index: idx,
149                                    });
150                                }
151                                // `ContentBlock` is `#[non_exhaustive]`; a future
152                                // block kind we cannot stream is skipped rather than
153                                // panicking the default fallback.
154                                _ => {
155                                    log::warn!(
156                                        "chat_stream fallback skipping unrecognized content block at index {idx}"
157                                    );
158                                }
159                            }
160                        }
161                        yield Ok(StreamDelta::Usage(response.usage));
162                        yield Ok(StreamDelta::Done {
163                            stop_reason: response.stop_reason,
164                        });
165                    }
166                    ChatOutcome::RateLimited(retry_after) => {
167                        yield Ok(StreamDelta::Error {
168                            message: "Rate limited".to_string(),
169                            kind: StreamErrorKind::RateLimited(retry_after),
170                        });
171                    }
172                    ChatOutcome::InvalidRequest(msg) => {
173                        yield Ok(StreamDelta::Error {
174                            message: msg,
175                            kind: StreamErrorKind::InvalidRequest,
176                        });
177                    }
178                    ChatOutcome::ServerError(msg) => {
179                        yield Ok(StreamDelta::Error {
180                            message: msg,
181                            kind: StreamErrorKind::ServerError,
182                        });
183                    }
184                    // `ChatOutcome` is `#[non_exhaustive]`; an outcome this SDK
185                    // version does not model is surfaced as an unclassified
186                    // (non-recoverable) stream error rather than dropped.
187                    _ => {
188                        yield Ok(StreamDelta::Error {
189                            message: "Unrecognized chat outcome".to_string(),
190                            kind: StreamErrorKind::Unknown,
191                        });
192                    }
193                },
194                Err(e) => yield Err(e),
195            }
196        })
197    }
198
199    fn model(&self) -> &str;
200    fn provider(&self) -> &'static str;
201
202    /// Provider-owned thinking configuration, if any.
203    fn configured_thinking(&self) -> Option<&ThinkingConfig> {
204        None
205    }
206
207    /// Canonical capability metadata for this provider/model, if known.
208    fn capabilities(&self) -> Option<&'static ModelCapabilities> {
209        get_model_capabilities(self.provider(), self.model()).or_else(|| match self.provider() {
210            "openai-responses" | "openai-codex" => get_model_capabilities("openai", self.model()),
211            "vertex" if self.model().starts_with("claude-") => {
212                get_model_capabilities("anthropic", self.model())
213            }
214            "vertex" => get_model_capabilities("gemini", self.model()),
215            _ => None,
216        })
217    }
218
219    /// API-shape feature metadata for this provider/model, when known.
220    ///
221    /// This complements [`Self::capabilities`] with endpoint, reasoning,
222    /// caching, and tool-control information that does not fit the legacy
223    /// context/pricing record.
224    fn model_features(&self) -> Option<&'static ModelFeatures> {
225        match self.provider() {
226            "openai" | "openai-responses" | "openai-codex" => get_model_features(self.model()),
227            _ => None,
228        }
229    }
230
231    /// Validate a thinking configuration against the provider/model capabilities.
232    ///
233    /// # Errors
234    ///
235    /// Returns an error when the requested thinking mode is not supported by
236    /// the active provider/model capability set.
237    fn validate_thinking_config(&self, thinking: Option<&ThinkingConfig>) -> Result<()> {
238        let Some(thinking) = thinking else {
239            return Ok(());
240        };
241
242        if self
243            .capabilities()
244            .is_some_and(|caps| !caps.supports_thinking)
245        {
246            return Err(anyhow::anyhow!(
247                "thinking is not supported for provider={} model={}",
248                self.provider(),
249                self.model()
250            ));
251        }
252
253        if matches!(thinking.mode, ThinkingMode::Adaptive)
254            && !self
255                .capabilities()
256                .is_some_and(|caps| caps.supports_adaptive_thinking)
257        {
258            return Err(anyhow::anyhow!(
259                "adaptive thinking is not supported for provider={} model={}",
260                self.provider(),
261                self.model()
262            ));
263        }
264
265        Ok(())
266    }
267
268    /// Resolve the effective thinking configuration for a request.
269    ///
270    /// Request-level thinking overrides provider-owned defaults when present.
271    ///
272    /// # Errors
273    ///
274    /// Returns an error when the resolved thinking configuration is not
275    /// supported by the active provider/model capability set.
276    fn resolve_thinking_config(
277        &self,
278        request_thinking: Option<&ThinkingConfig>,
279    ) -> Result<Option<ThinkingConfig>> {
280        let thinking = request_thinking.or_else(|| self.configured_thinking());
281        self.validate_thinking_config(thinking)?;
282        Ok(thinking.cloned())
283    }
284
285    /// Default maximum output tokens for this provider/model when the caller
286    /// does not explicitly override `AgentConfig.max_tokens`.
287    fn default_max_tokens(&self) -> u32 {
288        self.capabilities()
289            .and_then(|caps| caps.max_output_tokens)
290            .or_else(|| default_max_output_tokens(self.provider(), self.model()))
291            .unwrap_or(4096)
292    }
293
294    /// How this provider satisfies a structured-output
295    /// ([`ResponseFormat`](agent_sdk_foundation::llm::ResponseFormat)) request.
296    ///
297    /// Providers with a native JSON-schema / JSON-mode wire field
298    /// (OpenAI-family, Gemini, Vertex) report
299    /// [`StructuredOutputSupport::Native`] and consume
300    /// `request.response_format` directly. Providers without one (Anthropic)
301    /// report [`StructuredOutputSupport::ToolForcing`] so the runner forces a
302    /// single "respond" tool whose schema is the output schema. The default
303    /// is the conservative [`StructuredOutputSupport::ToolForcing`], which
304    /// works for any tool-capable provider.
305    fn structured_output_support(&self) -> StructuredOutputSupport {
306        match self.provider() {
307            "openai" | "openai-responses" | "openai-codex" | "gemini" => {
308                StructuredOutputSupport::Native
309            }
310            // Vertex multiplexes Anthropic and Gemini models. Only the Gemini
311            // side has a native structured-output field; Claude-on-Vertex uses
312            // the Messages API shape, which has no `response_format`.
313            "vertex" if !self.model().starts_with("claude-") => StructuredOutputSupport::Native,
314            _ => StructuredOutputSupport::ToolForcing,
315        }
316    }
317}
318
319/// Timeout for [`probe_http_reachability`]: long enough for a slow TLS
320/// handshake, short enough that a half-open network cannot stall the
321/// connectivity-wait loop it drives.
322const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
323
324/// `true` when an HTTP response arrives from `url` over a fully-established
325/// (and, for HTTPS, certificate-validated) connection.
326///
327/// The status code is deliberately ignored — a 4xx from the provider's edge
328/// proves the network path exactly as well as a 200 does, and needs no
329/// credentials. Every transport failure (DNS, connect, TLS, timeout) reports
330/// unreachable: this feeds offline-wait loops, where the fail-safe direction
331/// is to keep waiting. A captive portal that hijacks the hostname fails
332/// certificate validation and therefore stays unreachable until the real
333/// endpoint is back.
334pub async fn probe_http_reachability(client: &reqwest::Client, url: &str) -> bool {
335    client.head(url).timeout(PROBE_TIMEOUT).send().await.is_ok()
336}
337
338/// Drop extended thinking when the request forces a specific tool.
339///
340/// Anthropic-family models (native Anthropic and Claude-on-Vertex) reject a
341/// request that pairs extended `thinking` with a `tool_choice` that names a
342/// tool (HTTP 400). The forced-tool constraint is orthogonal to *where* the
343/// thinking came from: clearing `ChatRequest.thinking` upstream is not enough,
344/// because [`resolve_thinking_config`](LlmProvider::resolve_thinking_config)
345/// falls back to the provider-configured default when the request field is
346/// `None` — resurrecting thinking on the wire. The Claude request builders
347/// therefore funnel their already-resolved thinking through this at the wire
348/// boundary so a forced-tool request (e.g. structured-output's `respond` tool)
349/// stays well-formed regardless of the provider's configured thinking default.
350///
351/// `ToolChoice::Auto` (and the absence of any `tool_choice`) keeps thinking,
352/// matching the API's rule that thinking is only incompatible with a
353/// tool-forcing choice.
354#[must_use]
355#[cfg(feature = "anthropic")]
356pub(crate) const fn thinking_for_forced_tool(
357    thinking: Option<ThinkingConfig>,
358    tool_choice: Option<&ToolChoice>,
359) -> Option<ThinkingConfig> {
360    match tool_choice {
361        Some(ToolChoice::Tool(_)) => None,
362        Some(ToolChoice::Auto) | None => thinking,
363    }
364}
365
366/// Helper function to consume a stream and collect it into a `ChatResponse`.
367///
368/// This is useful for providers that want to test their streaming implementation
369/// or for cases where you need the full response after streaming.
370///
371/// # Errors
372///
373/// Returns an error if the stream yields an error result.
374pub async fn collect_stream(mut stream: StreamBox<'_>, model: String) -> Result<ChatOutcome> {
375    let mut accumulator = StreamAccumulator::new();
376    let mut last_error: Option<(String, StreamErrorKind)> = None;
377
378    while let Some(result) = stream.next().await {
379        match result {
380            Ok(delta) => {
381                if let StreamDelta::Error { message, kind } = &delta {
382                    last_error = Some((message.clone(), *kind));
383                }
384                accumulator.apply(&delta);
385            }
386            Err(e) => return Err(e),
387        }
388    }
389
390    // If we encountered an error during streaming, map kind directly
391    // to the corresponding `ChatOutcome` variant.  No string-matching
392    // heuristic is needed because the kind already records the
393    // category at the construction site.
394    if let Some((message, kind)) = last_error {
395        return Ok(match kind {
396            // The rate-limit kind carries whatever retry hint the provider gave
397            // (header or error body), so the reconstructed outcome honours the
398            // server exactly like the non-streaming `chat()` path does.
399            StreamErrorKind::RateLimited(retry_after) => ChatOutcome::RateLimited(retry_after),
400            StreamErrorKind::InvalidRequest => ChatOutcome::InvalidRequest(message),
401            // `StreamErrorKind::ServerError`, plus the `#[non_exhaustive]`
402            // catch-all (`Unknown` / future kinds): an unclassified error is
403            // treated as a (non-recoverable) server error so the caller still
404            // surfaces the failure rather than silently succeeding.
405            _ => ChatOutcome::ServerError(message),
406        });
407    }
408
409    // Extract usage and stop_reason before consuming the accumulator
410    let usage = accumulator.take_usage().unwrap_or(Usage {
411        input_tokens: 0,
412        output_tokens: 0,
413        cached_input_tokens: 0,
414        cache_creation_input_tokens: 0,
415    });
416    let stop_reason = accumulator.take_stop_reason();
417    let content = accumulator.into_content_blocks();
418
419    // Log accumulated response for debugging
420    log::debug!(
421        "Collected stream response: model={} stop_reason={:?} usage={{input_tokens={}, output_tokens={}}} content_blocks={}",
422        model,
423        stop_reason,
424        usage.input_tokens,
425        usage.output_tokens,
426        content.len()
427    );
428    for (i, block) in content.iter().enumerate() {
429        match block {
430            ContentBlock::Text { text } => {
431                log::debug!("  content_block[{}]: Text (len={})", i, text.len());
432            }
433            ContentBlock::Thinking { thinking, .. } => {
434                log::debug!("  content_block[{}]: Thinking (len={})", i, thinking.len());
435            }
436            ContentBlock::RedactedThinking { .. } => {
437                log::debug!("  content_block[{i}]: RedactedThinking");
438            }
439            ContentBlock::OpaqueReasoning { provider, .. } => {
440                log::debug!(
441                    "  content_block[{i}]: OpaqueReasoning provider={provider} payload=<redacted>"
442                );
443            }
444            ContentBlock::ToolUse {
445                id, name, input, ..
446            } => {
447                log::debug!("  content_block[{i}]: ToolUse id={id} name={name} input={input}");
448            }
449            ContentBlock::ToolResult {
450                tool_use_id,
451                content: result_content,
452                is_error,
453            } => {
454                log::debug!(
455                    "  content_block[{}]: ToolResult tool_use_id={} is_error={:?} content_len={}",
456                    i,
457                    tool_use_id,
458                    is_error,
459                    result_content.len()
460                );
461            }
462            ContentBlock::Image { source } => {
463                log::debug!(
464                    "  content_block[{i}]: Image media_type={}",
465                    source.media_type
466                );
467            }
468            ContentBlock::Document { source } => {
469                log::debug!(
470                    "  content_block[{i}]: Document media_type={}",
471                    source.media_type
472                );
473            }
474            // `ContentBlock` is `#[non_exhaustive]`; log unknown future block
475            // kinds generically so the debug dump stays exhaustive.
476            _ => {
477                log::debug!("  content_block[{i}]: <unrecognized block kind>");
478            }
479        }
480    }
481
482    Ok(ChatOutcome::Success(ChatResponse {
483        id: String::new(),
484        content,
485        model,
486        stop_reason,
487        usage,
488    }))
489}
490
491#[cfg(test)]
492mod tests {
493    use super::*;
494    use anyhow::Result;
495    use async_trait::async_trait;
496
497    struct Stub {
498        provider: &'static str,
499        model: &'static str,
500    }
501
502    #[async_trait]
503    impl LlmProvider for Stub {
504        async fn chat(&self, _request: ChatRequest) -> Result<ChatOutcome> {
505            Ok(ChatOutcome::ServerError("unused".to_owned()))
506        }
507
508        fn model(&self) -> &str {
509            self.model
510        }
511
512        fn provider(&self) -> &'static str {
513            self.provider
514        }
515    }
516
517    fn support_for(provider: &'static str, model: &'static str) -> StructuredOutputSupport {
518        Stub { provider, model }.structured_output_support()
519    }
520
521    #[test]
522    fn native_providers_report_native_support() {
523        for provider in ["openai", "openai-responses", "openai-codex", "gemini"] {
524            assert_eq!(
525                support_for(provider, "any-model"),
526                StructuredOutputSupport::Native,
527                "{provider} should be native"
528            );
529        }
530    }
531
532    #[test]
533    fn anthropic_reports_tool_forcing() {
534        assert_eq!(
535            support_for("anthropic", "claude-sonnet-4-5"),
536            StructuredOutputSupport::ToolForcing
537        );
538    }
539
540    #[test]
541    fn vertex_is_native_for_gemini_models_and_tool_forcing_for_claude() {
542        assert_eq!(
543            support_for("vertex", "gemini-3-flash-preview"),
544            StructuredOutputSupport::Native
545        );
546        assert_eq!(
547            support_for("vertex", "claude-sonnet-4-5"),
548            StructuredOutputSupport::ToolForcing
549        );
550    }
551
552    #[test]
553    fn unknown_provider_defaults_to_tool_forcing() {
554        assert_eq!(
555            support_for("some-new-provider", "x"),
556            StructuredOutputSupport::ToolForcing
557        );
558    }
559
560    #[test]
561    #[cfg(feature = "anthropic")]
562    fn thinking_for_forced_tool_drops_thinking_when_a_tool_is_forced() {
563        let cfg = ThinkingConfig::new(10_000);
564        let forced = ToolChoice::Tool("respond".to_owned());
565        assert!(
566            thinking_for_forced_tool(Some(cfg), Some(&forced)).is_none(),
567            "thinking must be dropped when tool_choice names a tool"
568        );
569    }
570
571    #[test]
572    #[cfg(feature = "anthropic")]
573    fn thinking_for_forced_tool_keeps_thinking_for_auto_and_none() {
574        let auto = ToolChoice::Auto;
575        assert!(
576            thinking_for_forced_tool(Some(ThinkingConfig::new(10_000)), Some(&auto)).is_some(),
577            "thinking must survive with ToolChoice::Auto"
578        );
579        assert!(
580            thinking_for_forced_tool(Some(ThinkingConfig::new(10_000)), None).is_some(),
581            "thinking must survive with no tool_choice"
582        );
583    }
584
585    #[test]
586    #[cfg(feature = "anthropic")]
587    fn thinking_for_forced_tool_is_a_noop_when_thinking_absent() {
588        let forced = ToolChoice::Tool("respond".to_owned());
589        assert!(thinking_for_forced_tool(None, Some(&forced)).is_none());
590    }
591
592    fn stream_of(deltas: Vec<StreamDelta>) -> StreamBox<'static> {
593        Box::pin(futures::stream::iter(deltas.into_iter().map(Ok)))
594    }
595
596    #[tokio::test]
597    async fn collect_stream_preserves_the_rate_limit_retry_hint() -> Result<()> {
598        let hint = std::time::Duration::from_secs(30);
599        let outcome = collect_stream(
600            stream_of(vec![StreamDelta::Error {
601                message: "Rate limited".to_owned(),
602                kind: StreamErrorKind::RateLimited(Some(hint)),
603            }]),
604            "test-model".to_owned(),
605        )
606        .await?;
607
608        assert!(
609            matches!(outcome, ChatOutcome::RateLimited(Some(delay)) if delay == hint),
610            "streamed Retry-After must survive reconstruction, got {outcome:?}"
611        );
612        Ok(())
613    }
614
615    #[tokio::test]
616    async fn collect_stream_reports_no_hint_when_the_provider_gave_none() -> Result<()> {
617        let outcome = collect_stream(
618            stream_of(vec![StreamDelta::Error {
619                message: "Rate limited".to_owned(),
620                kind: StreamErrorKind::RateLimited(None),
621            }]),
622            "test-model".to_owned(),
623        )
624        .await?;
625
626        assert!(
627            matches!(outcome, ChatOutcome::RateLimited(None)),
628            "a hintless rate limit must not invent a delay, got {outcome:?}"
629        );
630        Ok(())
631    }
632
633    #[tokio::test]
634    async fn default_chat_stream_carries_the_chat_retry_hint_into_the_error_delta() -> Result<()> {
635        // A provider that only implements `chat()` gets its streaming from the
636        // trait's default adapter; a rate limit's hint must not be lost there.
637        struct RateLimitedStub {
638            model: &'static str,
639        }
640
641        #[async_trait]
642        impl LlmProvider for RateLimitedStub {
643            async fn chat(&self, _request: ChatRequest) -> Result<ChatOutcome> {
644                Ok(ChatOutcome::RateLimited(Some(
645                    std::time::Duration::from_secs(12),
646                )))
647            }
648            fn model(&self) -> &str {
649                self.model
650            }
651            fn provider(&self) -> &'static str {
652                "stub"
653            }
654        }
655
656        let stub = RateLimitedStub {
657            model: "stub-model",
658        };
659        let request = ChatRequest::new("", vec![agent_sdk_foundation::llm::Message::user("hi")]);
660        let outcome =
661            collect_stream(Box::pin(stub.chat_stream(request)), "stub-model".to_owned()).await?;
662
663        assert!(
664            matches!(outcome, ChatOutcome::RateLimited(Some(delay))
665                if delay == std::time::Duration::from_secs(12)),
666            "default chat_stream must forward chat()'s Retry-After, got {outcome:?}"
667        );
668        Ok(())
669    }
670
671    #[tokio::test]
672    async fn collect_stream_maps_other_kinds_without_a_hint() -> Result<()> {
673        let outcome = collect_stream(
674            stream_of(vec![StreamDelta::Error {
675                message: "boom".to_owned(),
676                kind: StreamErrorKind::ServerError,
677            }]),
678            "test-model".to_owned(),
679        )
680        .await?;
681
682        assert!(matches!(outcome, ChatOutcome::ServerError(msg) if msg == "boom"));
683        Ok(())
684    }
685}