Skip to main content

strands/models/bedrock/
mod.rs

1//! The Amazon Bedrock model provider, behind the `bedrock` feature (on by default).
2//!
3//! [`BedrockModel`] talks to the Bedrock Converse and ConverseStream APIs through the AWS SDK for
4//! Rust. Requests are built in the Converse JSON shape and converted to the AWS SDK types only at the
5//! transport boundary.
6//!
7//! An agent on a Bedrock model, with credentials and region from the AWS default chain:
8//!
9//! ```no_run
10//! use strands::Agent;
11//! use strands::models::bedrock::BedrockModel;
12//!
13//! # async fn run() -> strands::Result<()> {
14//! let model = BedrockModel::builder()
15//!     .model_id("global.anthropic.claude-sonnet-4-6")
16//!     .max_tokens(4096)
17//!     .build();
18//! let mut agent = Agent::builder().model(model).build()?;
19//! let result = agent.invoke("Why is the sky blue?").await?;
20//! println!("{result}");
21//! # Ok(())
22//! # }
23//! ```
24
25mod format;
26mod parse;
27pub(crate) mod transport;
28mod wire;
29
30#[cfg(test)]
31mod tests;
32
33use std::fmt;
34use std::sync::{Arc, PoisonError, RwLock};
35use std::time::Duration;
36
37use async_trait::async_trait;
38use futures::StreamExt;
39
40use self::format::{FormatOptions, Formatter};
41use self::parse::{StreamState, map_converse_output};
42use self::transport::{BedrockError, BedrockTransport, ChunkStream, SdkTransport};
43use super::bedrock_cache::bedrock_cache_model_info;
44use super::defaults::{MODEL_DEFAULTS, default_max_tokens_warning_message, default_model_warning_message};
45use super::model::{BaseModelConfig, BoxStream, CacheConfig, CacheTtl, CountTokensOptions, Model, ModelRequest};
46use super::model::{base_model_info, estimate_tokens, resolve_config_metadata, resolve_max_tokens};
47use super::model_info::{DeferredToolLoading, ModelCapabilities, ModelInfo, server_side_summary_off};
48use super::native_output::{StructuredOutputMechanism, handle_rejected_mechanism, structured_output_mechanisms};
49use super::streaming::{ANTHROPIC_REASONING_PROVIDER, ModelStreamEvent, tag_signed_reasoning};
50use crate::error::{ContextWindowOverflowError, Error, ModelError, Result};
51use crate::logging::warn_once;
52use crate::types::{JsonValue, Message, ToolChoice};
53
54pub use aws_config::SdkConfig;
55pub use aws_credential_types::Credentials;
56pub use aws_credential_types::provider::SharedCredentialsProvider;
57
58/// Error messages that indicate the input exceeded the model's context window
59/// (`BEDROCK_CONTEXT_WINDOW_OVERFLOW_MESSAGES`).
60const BEDROCK_CONTEXT_WINDOW_OVERFLOW_MESSAGES: [&str; 6] = [
61    "Input is too long for requested model",
62    "input length and `max_tokens` exceed context limit",
63    "too many total text bytes",
64    "prompt is too long",
65    "This model's maximum context length is",
66    "Input Tokens Exceeded",
67];
68
69/// Default per-attempt and stream inactivity timeout (`DEFAULT_REQUEST_TIMEOUT_MS`). The AWS SDK
70/// has none, so a stuck connection would otherwise hang forever.
71pub const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(120);
72
73/// TTL of a Bedrock prompt-cache checkpoint (`BedrockCacheTTL`), such as `"5m"` or `"1h"`.
74///
75/// Bedrock validates the value server-side and requires checkpoint TTLs to be non-increasing
76/// across tools, system and messages.
77pub type BedrockCacheTtl = CacheTtl;
78
79/// Prompt-caching configuration for the Bedrock provider (`BedrockCacheConfig`).
80pub type BedrockCacheConfig = CacheConfig;
81
82/// Whether tool results carry their `status` field.
83#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
84#[non_exhaustive]
85pub enum IncludeToolResultStatus {
86    /// Include it for the models Bedrock documents as accepting it (Amazon Nova and Anthropic
87    /// Claude).
88    #[default]
89    Auto,
90    /// Always (`true`) or never (`false`) include it.
91    Enabled(bool),
92}
93
94impl From<bool> for IncludeToolResultStatus {
95    fn from(enabled: bool) -> Self {
96        Self::Enabled(enabled)
97    }
98}
99
100/// Guardrail trace mode (`BedrockGuardrailConfig.trace`).
101#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
102#[non_exhaustive]
103pub enum BedrockGuardrailTrace {
104    /// `enabled`, the default.
105    #[default]
106    Enabled,
107    /// `disabled`.
108    Disabled,
109    /// `enabled_full`.
110    EnabledFull,
111}
112
113impl BedrockGuardrailTrace {
114    pub(crate) fn as_str(self) -> &'static str {
115        match self {
116            Self::Enabled => "enabled",
117            Self::Disabled => "disabled",
118            Self::EnabledFull => "enabled_full",
119        }
120    }
121}
122
123/// Guardrail stream processing mode (`BedrockGuardrailConfig.streamProcessingMode`).
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125#[non_exhaustive]
126pub enum BedrockGuardrailStreamProcessingMode {
127    /// `sync`.
128    Sync,
129    /// `async`.
130    Async,
131}
132
133impl BedrockGuardrailStreamProcessingMode {
134    pub(crate) fn as_str(self) -> &'static str {
135        match self {
136            Self::Sync => "sync",
137            Self::Async => "async",
138        }
139    }
140}
141
142/// Whether and how content a guardrail blocked is replaced (`BedrockGuardrailRedactionConfig`).
143#[derive(Debug, Clone, Default, PartialEq, Eq, bon::Builder)]
144pub struct BedrockGuardrailRedactionConfig {
145    /// Redact the input when blocked. Default `true`.
146    pub input: Option<bool>,
147    /// Replacement for redacted input. Default `[User input redacted.]`.
148    #[builder(into)]
149    pub input_message: Option<String>,
150    /// Redact the output when blocked. Default `false`.
151    pub output: Option<bool>,
152    /// Replacement for redacted output. Default `[Assistant output redacted.]`.
153    #[builder(into)]
154    pub output_message: Option<String>,
155}
156
157/// Bedrock guardrail configuration (`BedrockGuardrailConfig`).
158///
159/// See <https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails.html>.
160#[derive(Debug, Clone, Default, PartialEq, Eq, bon::Builder)]
161pub struct BedrockGuardrailConfig {
162    /// Guardrail identifier.
163    #[builder(into)]
164    pub guardrail_identifier: String,
165    /// Guardrail version, such as `"1"` or `"DRAFT"`.
166    #[builder(into)]
167    pub guardrail_version: String,
168    /// Trace mode. Default [`BedrockGuardrailTrace::Enabled`].
169    pub trace: Option<BedrockGuardrailTrace>,
170    /// Stream processing mode.
171    pub stream_processing_mode: Option<BedrockGuardrailStreamProcessingMode>,
172    /// Redaction behavior when content is blocked.
173    pub redaction: Option<BedrockGuardrailRedactionConfig>,
174    /// Evaluate only the latest user message: its text and image content is wrapped in guard
175    /// content blocks. The message is the last user message with text or image content, so tool
176    /// result turns after it do not move the target. Default `false`.
177    pub guard_latest_user_message: Option<bool>,
178}
179
180/// Configuration of a [`BedrockModel`] (`BedrockModelConfig`): the [`BaseModelConfig`] fields
181/// plus the Bedrock knobs.
182///
183/// ```
184/// use strands::models::bedrock::BedrockModelConfig;
185///
186/// let config = BedrockModelConfig {
187///     model_id: Some("global.anthropic.claude-sonnet-4-6".into()),
188///     max_tokens: Some(1024),
189///     temperature: Some(0.7),
190///     ..Default::default()
191/// };
192/// assert_eq!(config.to_base().max_tokens, Some(1024));
193/// ```
194#[derive(Debug, Clone, Default, PartialEq, bon::Builder)]
195pub struct BedrockModelConfig {
196    /// The Bedrock model id, inference profile id or ARN. Default
197    /// `global.anthropic.claude-sonnet-4-6`.
198    #[builder(into)]
199    pub model_id: Option<String>,
200    /// Maximum number of tokens to generate. Default: the model's output ceiling from the shared
201    /// model info when known, otherwise unset so Bedrock's per-model default applies.
202    pub max_tokens: Option<u64>,
203    /// Controls randomness in generation.
204    pub temperature: Option<f64>,
205    /// Controls diversity via nucleus sampling.
206    pub top_p: Option<f64>,
207    /// Context window size in tokens; filled from the shared model info when unset.
208    pub context_window_limit: Option<u64>,
209    /// Overrides for what the SDK knows about the model.
210    pub model_info: Option<ModelInfo>,
211    /// Sequences that stop generation.
212    pub stop_sequences: Option<Vec<String>>,
213    /// Prompt caching. Unset, no cache points are added.
214    pub cache_config: Option<BedrockCacheConfig>,
215    /// Extra fields for the model (`additionalModelRequestFields`), such as a `thinking` config.
216    pub additional_request_fields: Option<JsonValue>,
217    /// Paths of extra response fields to return (`additionalModelResponseFieldPaths`).
218    pub additional_response_field_paths: Option<Vec<String>>,
219    /// Extra top-level Converse request fields, merged over the formatted request (for example
220    /// `requestMetadata`, `performanceConfig`, `serviceTier` or `promptVariables`). Keys the
221    /// Converse API does not define are ignored with a warning.
222    pub additional_args: Option<JsonValue>,
223    /// Use ConverseStream (`true`, the default) or Converse (`false`).
224    pub stream: Option<bool>,
225    /// Whether tool results carry their status. Default [`IncludeToolResultStatus::Auto`].
226    #[builder(into)]
227    pub include_tool_result_status: Option<IncludeToolResultStatus>,
228    /// Guardrail configuration.
229    pub guardrail_config: Option<BedrockGuardrailConfig>,
230    /// Count tokens with the Bedrock CountTokens API instead of the heuristic estimate. Default
231    /// `false`.
232    pub use_native_token_count: Option<bool>,
233    /// Send every tool with `strict: true` and a closed copy of its input schema, constraining the
234    /// model to schema-valid tool calls. Bedrock rejects schemas outside its strict subset. Turns
235    /// deferred tool loading off, so `Offload::defer` and the `deferredToolLoading` preset send
236    /// every full spec; a `model_info` override of `deferred_tool_loading` still wins. Default
237    /// `false`.
238    pub strict_tools: Option<bool>,
239}
240
241impl BedrockModelConfig {
242    /// Shallow-merges `update` into `self`: every field `update` sets replaces the current value.
243    pub fn merge(&mut self, update: Self) {
244        let Self {
245            model_id,
246            max_tokens,
247            temperature,
248            top_p,
249            context_window_limit,
250            model_info,
251            stop_sequences,
252            cache_config,
253            additional_request_fields,
254            additional_response_field_paths,
255            additional_args,
256            stream,
257            include_tool_result_status,
258            guardrail_config,
259            use_native_token_count,
260            strict_tools,
261        } = update;
262        replace(&mut self.model_id, model_id);
263        replace(&mut self.max_tokens, max_tokens);
264        replace(&mut self.temperature, temperature);
265        replace(&mut self.top_p, top_p);
266        replace(&mut self.context_window_limit, context_window_limit);
267        replace(&mut self.model_info, model_info);
268        replace(&mut self.stop_sequences, stop_sequences);
269        replace(&mut self.cache_config, cache_config);
270        replace(&mut self.additional_request_fields, additional_request_fields);
271        replace(
272            &mut self.additional_response_field_paths,
273            additional_response_field_paths,
274        );
275        replace(&mut self.additional_args, additional_args);
276        replace(&mut self.stream, stream);
277        replace(&mut self.include_tool_result_status, include_tool_result_status);
278        replace(&mut self.guardrail_config, guardrail_config);
279        replace(&mut self.use_native_token_count, use_native_token_count);
280        replace(&mut self.strict_tools, strict_tools);
281    }
282
283    /// The [`BaseModelConfig`] fields of this configuration.
284    #[must_use]
285    pub fn to_base(&self) -> BaseModelConfig {
286        BaseModelConfig {
287            model_id: self.model_id.clone(),
288            max_tokens: self.max_tokens,
289            temperature: self.temperature,
290            top_p: self.top_p,
291            context_window_limit: self.context_window_limit,
292            model_info: self.model_info.clone(),
293        }
294    }
295
296    fn merge_base(&mut self, update: BaseModelConfig) {
297        let BaseModelConfig {
298            model_id,
299            max_tokens,
300            temperature,
301            top_p,
302            context_window_limit,
303            model_info,
304        } = update;
305        self.merge(Self {
306            model_id,
307            max_tokens,
308            temperature,
309            top_p,
310            context_window_limit,
311            model_info,
312            ..Self::default()
313        });
314    }
315
316    fn model_id_or_default(&self) -> &str {
317        self.model_id.as_deref().unwrap_or(MODEL_DEFAULTS.bedrock.model_id)
318    }
319}
320
321fn replace<T>(slot: &mut Option<T>, update: Option<T>) {
322    if update.is_some() {
323        *slot = update;
324    }
325}
326
327impl From<BaseModelConfig> for BedrockModelConfig {
328    fn from(base: BaseModelConfig) -> Self {
329        let mut config = Self::default();
330        config.merge_base(base);
331        config
332    }
333}
334
335/// Options for creating a [`BedrockModel`] (`BedrockModelOptions`): the [`BedrockModelConfig`]
336/// fields plus how the AWS client is built.
337///
338/// The client is built on first use from the AWS default chain (environment, shared config and
339/// credential files, SSO, IMDS), layered with these options. Without a region from the options,
340/// `sdk_config` or the environment, the region is `us-west-2`. An `AWS_BEARER_TOKEN_BEDROCK`
341/// environment variable selects API key authentication, as in the AWS SDKs.
342///
343/// [`BedrockModel::builder`] starts this builder; its `build()` returns the model and
344/// `build_options()` the options.
345///
346/// ```
347/// use std::time::Duration;
348///
349/// use strands::models::bedrock::BedrockModel;
350///
351/// let model = BedrockModel::builder()
352///     .model_id("us.amazon.nova-lite-v1:0")
353///     .max_tokens(512)
354///     .region("us-east-1")
355///     .request_timeout(Duration::from_secs(300))
356///     .build();
357/// assert_eq!(model.config().model_id.as_deref(), Some("us.amazon.nova-lite-v1:0"));
358/// ```
359#[derive(Clone, Default, bon::Builder)]
360#[builder(finish_fn = build_options)]
361pub struct BedrockModelOptions {
362    /// [`BedrockModelConfig::model_id`].
363    #[builder(into)]
364    pub model_id: Option<String>,
365    /// [`BedrockModelConfig::max_tokens`].
366    pub max_tokens: Option<u64>,
367    /// [`BedrockModelConfig::temperature`].
368    pub temperature: Option<f64>,
369    /// [`BedrockModelConfig::top_p`].
370    pub top_p: Option<f64>,
371    /// [`BedrockModelConfig::context_window_limit`].
372    pub context_window_limit: Option<u64>,
373    /// [`BedrockModelConfig::model_info`].
374    pub model_info: Option<ModelInfo>,
375    /// [`BedrockModelConfig::stop_sequences`].
376    pub stop_sequences: Option<Vec<String>>,
377    /// [`BedrockModelConfig::cache_config`].
378    pub cache_config: Option<BedrockCacheConfig>,
379    /// [`BedrockModelConfig::additional_request_fields`].
380    pub additional_request_fields: Option<JsonValue>,
381    /// [`BedrockModelConfig::additional_response_field_paths`].
382    pub additional_response_field_paths: Option<Vec<String>>,
383    /// [`BedrockModelConfig::additional_args`].
384    pub additional_args: Option<JsonValue>,
385    /// [`BedrockModelConfig::stream`].
386    pub stream: Option<bool>,
387    /// [`BedrockModelConfig::include_tool_result_status`].
388    #[builder(into)]
389    pub include_tool_result_status: Option<IncludeToolResultStatus>,
390    /// [`BedrockModelConfig::guardrail_config`].
391    pub guardrail_config: Option<BedrockGuardrailConfig>,
392    /// [`BedrockModelConfig::use_native_token_count`].
393    pub use_native_token_count: Option<bool>,
394    /// [`BedrockModelConfig::strict_tools`].
395    pub strict_tools: Option<bool>,
396    /// AWS region of the Bedrock endpoint; wins over `sdk_config` and the environment.
397    #[builder(into)]
398    pub region: Option<String>,
399    /// Endpoint URL override, such as a VPC endpoint.
400    #[builder(into)]
401    pub endpoint_url: Option<String>,
402    /// Credentials provider, replacing the default chain. This AWS SDK type is part of the public API
403    /// as an escape hatch.
404    pub credentials_provider: Option<SharedCredentialsProvider>,
405    /// Shared AWS configuration to build the client from instead of loading the default chain: HTTP
406    /// client, retry, timeout and stall settings, credentials and region. This AWS SDK type is part of
407    /// the public API as an escape hatch.
408    pub sdk_config: Option<SdkConfig>,
409    /// Time each attempt may take until the response arrives, and the stream inactivity before a
410    /// request is aborted. It replaces an operation attempt timeout set in `sdk_config` and keeps its
411    /// other timeouts. Default [`DEFAULT_REQUEST_TIMEOUT`].
412    pub request_timeout: Option<Duration>,
413    /// Amazon Bedrock API key: requests use bearer token authentication instead of SigV4.
414    #[builder(into)]
415    pub api_key: Option<String>,
416}
417
418impl<S: bedrock_model_options_builder::IsComplete> BedrockModelOptionsBuilder<S> {
419    /// Builds the [`BedrockModel`].
420    #[must_use]
421    pub fn build(self) -> BedrockModel {
422        BedrockModel::new(self.build_options())
423    }
424}
425
426impl BedrockModelOptions {
427    /// The model configuration part of the options.
428    #[must_use]
429    pub fn to_config(&self) -> BedrockModelConfig {
430        BedrockModelConfig {
431            model_id: self.model_id.clone(),
432            max_tokens: self.max_tokens,
433            temperature: self.temperature,
434            top_p: self.top_p,
435            context_window_limit: self.context_window_limit,
436            model_info: self.model_info.clone(),
437            stop_sequences: self.stop_sequences.clone(),
438            cache_config: self.cache_config.clone(),
439            additional_request_fields: self.additional_request_fields.clone(),
440            additional_response_field_paths: self.additional_response_field_paths.clone(),
441            additional_args: self.additional_args.clone(),
442            stream: self.stream,
443            include_tool_result_status: self.include_tool_result_status,
444            guardrail_config: self.guardrail_config.clone(),
445            use_native_token_count: self.use_native_token_count,
446            strict_tools: self.strict_tools,
447        }
448    }
449}
450
451impl From<BedrockModelConfig> for BedrockModelOptions {
452    fn from(config: BedrockModelConfig) -> Self {
453        let BedrockModelConfig {
454            model_id,
455            max_tokens,
456            temperature,
457            top_p,
458            context_window_limit,
459            model_info,
460            stop_sequences,
461            cache_config,
462            additional_request_fields,
463            additional_response_field_paths,
464            additional_args,
465            stream,
466            include_tool_result_status,
467            guardrail_config,
468            use_native_token_count,
469            strict_tools,
470        } = config;
471        Self {
472            model_id,
473            max_tokens,
474            temperature,
475            top_p,
476            context_window_limit,
477            model_info,
478            stop_sequences,
479            cache_config,
480            additional_request_fields,
481            additional_response_field_paths,
482            additional_args,
483            stream,
484            include_tool_result_status,
485            guardrail_config,
486            use_native_token_count,
487            strict_tools,
488            ..Self::default()
489        }
490    }
491}
492
493impl fmt::Debug for BedrockModelOptions {
494    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
495        f.debug_struct("BedrockModelOptions")
496            .field("config", &self.to_config())
497            .field("region", &self.region)
498            .field("endpoint_url", &self.endpoint_url)
499            .field(
500                "credentials_provider",
501                &self.credentials_provider.as_ref().map(|_| "<set>"),
502            )
503            .field("sdk_config", &self.sdk_config.as_ref().map(|_| "<set>"))
504            .field("request_timeout", &self.request_timeout)
505            .field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))
506            .finish()
507    }
508}
509
510/// The Amazon Bedrock model provider (`BedrockModel`), on the Converse and ConverseStream APIs.
511///
512/// Supports streaming and non-streaming responses, tool use, reasoning, citations, documents and
513/// media, prompt caching ([`BedrockCacheConfig`]), guardrails ([`BedrockGuardrailConfig`]),
514/// native token counting and structured output.
515///
516/// Cheap to clone and to share as `Arc<dyn Model>`: clones share one configuration and one AWS
517/// client, so [`update_config`](Self::update_config) on any clone changes them all.
518///
519/// ```no_run
520/// use strands::models::bedrock::{BedrockModel, BedrockModelConfig};
521/// use strands::models::{Model, ModelRequest};
522/// use strands::{AggregatedEvent, Message};
523/// use futures::StreamExt;
524///
525/// # async fn run() -> strands::Result<()> {
526/// let model = BedrockModel::new(BedrockModelConfig {
527///     model_id: Some("global.anthropic.claude-sonnet-4-6".into()),
528///     max_tokens: Some(1024),
529///     ..Default::default()
530/// });
531/// let request = ModelRequest::builder().messages(vec![Message::user("Hello!")]).build();
532/// let mut stream = model.stream_aggregated(request);
533/// while let Some(item) = stream.next().await {
534///     if let AggregatedEvent::Done(result) = item? {
535///         println!("{}", result.message.text());
536///     }
537/// }
538/// # Ok(())
539/// # }
540/// ```
541#[derive(Clone)]
542pub struct BedrockModel {
543    inner: Arc<Inner>,
544}
545
546struct Inner {
547    config: RwLock<BedrockModelConfig>,
548    transport: Arc<dyn BedrockTransport>,
549    drop_stale_thinking_model_id: Arc<RwLock<Option<String>>>,
550}
551
552impl fmt::Debug for BedrockModel {
553    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
554        f.debug_struct("BedrockModel")
555            .field("config", &self.config())
556            .finish_non_exhaustive()
557    }
558}
559
560impl Default for BedrockModel {
561    fn default() -> Self {
562        Self::new(BedrockModelOptions::default())
563    }
564}
565
566impl From<BedrockModelOptions> for BedrockModel {
567    fn from(options: BedrockModelOptions) -> Self {
568        Self::new(options)
569    }
570}
571
572impl BedrockModel {
573    /// Creates the provider from options or a bare [`BedrockModelConfig`]. The AWS client is built
574    /// on first use.
575    #[must_use]
576    pub fn new(options: impl Into<BedrockModelOptions>) -> Self {
577        let options = options.into();
578        let config = options.to_config();
579        let transport = SdkTransport::new(client_options(options));
580        Self::with_transport(config, Arc::new(transport))
581    }
582
583    /// Starts a [`BedrockModelOptions`] builder whose `build()` returns the provider.
584    pub fn builder() -> BedrockModelOptionsBuilder {
585        BedrockModelOptions::builder()
586    }
587
588    pub(crate) fn with_transport(config: BedrockModelConfig, transport: Arc<dyn BedrockTransport>) -> Self {
589        for warning in construction_warnings(&config) {
590            warn_once(&warning);
591        }
592        let mut stored = config;
593        stored
594            .model_id
595            .get_or_insert_with(|| MODEL_DEFAULTS.bedrock.model_id.to_owned());
596        Self {
597            inner: Arc::new(Inner {
598                config: RwLock::new(stored),
599                transport,
600                drop_stale_thinking_model_id: Arc::default(),
601            }),
602        }
603    }
604
605    /// The configuration with the defaults the provider applies filled in: the model id,
606    /// `max_tokens` from the model's output ceiling and `context_window_limit` from the model info.
607    #[must_use]
608    pub fn config(&self) -> BedrockModelConfig {
609        resolve_config(&self.raw_config())
610    }
611
612    /// Shallow-merges `config` into the configuration: every field it sets replaces the current
613    /// value. Takes a [`BedrockModelConfig`] or a [`BaseModelConfig`]; on the concrete type it
614    /// shadows [`Model::update_config`], which does the same.
615    ///
616    /// # Errors
617    ///
618    /// None today; the `Result` matches the other providers' `update_config`, which validate.
619    pub fn update_config(&self, config: impl Into<BedrockModelConfig>) -> Result<()> {
620        self.inner
621            .config
622            .write()
623            .unwrap_or_else(PoisonError::into_inner)
624            .merge(config.into());
625        Ok(())
626    }
627
628    fn raw_config(&self) -> BedrockModelConfig {
629        self.inner.config.read().unwrap_or_else(PoisonError::into_inner).clone()
630    }
631
632    fn call(&self) -> Call {
633        let config = self.raw_config();
634        Call {
635            model_info: bedrock_model_info(&config),
636            config,
637            transport: Arc::clone(&self.inner.transport),
638            drop_stale_thinking_model_id: Arc::clone(&self.inner.drop_stale_thinking_model_id),
639        }
640    }
641}
642
643/// How the AWS client is built from the options; `request_timeout` falls back to
644/// [`DEFAULT_REQUEST_TIMEOUT`].
645fn client_options(options: BedrockModelOptions) -> transport::ClientOptions {
646    let BedrockModelOptions {
647        region,
648        endpoint_url,
649        credentials_provider,
650        sdk_config,
651        request_timeout,
652        api_key,
653        ..
654    } = options;
655    transport::ClientOptions {
656        region,
657        endpoint_url,
658        credentials_provider,
659        sdk_config,
660        request_timeout: request_timeout.unwrap_or(DEFAULT_REQUEST_TIMEOUT),
661        api_key,
662    }
663}
664
665/// The provider behind an agent built without a model.
666pub(crate) fn default_bedrock_model() -> Arc<dyn Model> {
667    Arc::new(BedrockModel::default())
668}
669
670/// The warnings a new provider logs once: the default model id, and a `max_tokens` that comes
671/// from the shared model info rather than the user (through `max_tokens` or `model_info`).
672fn construction_warnings(config: &BedrockModelConfig) -> Vec<String> {
673    let mut warnings = Vec::new();
674    if config.model_id.is_none() {
675        warnings.push(default_model_warning_message(MODEL_DEFAULTS.bedrock.model_id));
676    }
677    let pinned = config.max_tokens.is_some()
678        || config
679            .model_info
680            .as_ref()
681            .is_some_and(|info| info.limits.max_output_tokens.is_some());
682    if let Some(max_tokens) = resolve_config(config).max_tokens.filter(|_| !pinned) {
683        warnings.push(default_max_tokens_warning_message(max_tokens));
684    }
685    warnings
686}
687
688fn resolve_config(raw: &BedrockModelConfig) -> BedrockModelConfig {
689    let model_id = raw.model_id_or_default().to_owned();
690    let base = raw.to_base();
691    let max_tokens = resolve_max_tokens(&base, &model_id);
692    let resolved = resolve_config_metadata(base, &model_id);
693    let mut config = raw.clone();
694    config.model_id = Some(model_id);
695    config.context_window_limit = resolved.context_window_limit;
696    config.max_tokens = config.max_tokens.or(max_tokens);
697    config
698}
699
700/// Bedrock's model info: the shared info, server-side summary off, how Converse caches the model
701/// where that differs from the shared info, and the user's override on top.
702fn bedrock_model_info(config: &BedrockModelConfig) -> ModelInfo {
703    let mut base = config.to_base();
704    base.model_id
705        .get_or_insert_with(|| MODEL_DEFAULTS.bedrock.model_id.to_owned());
706    let caching = bedrock_cache_model_info(config.model_id_or_default());
707    // Claude-signed reasoning is taken back on a Claude model id, and on one that names no vendor
708    // (an application inference profile ARN); reasoning produced through the latter is not tagged,
709    // so it is not kept from other vendors.
710    let reasoning = takes_claude_reasoning(config.model_id_or_default()).then(|| ModelInfo {
711        capabilities: ModelCapabilities {
712            reasoning_provider: Some(ANTHROPIC_REASONING_PROVIDER.to_owned()),
713            ..ModelCapabilities::default()
714        },
715        ..ModelInfo::default()
716    });
717    // Strict mode needs each tool's full input schema, so it can't take a deferred tool as a stub.
718    let strict = (config.strict_tools == Some(true)).then(|| ModelInfo {
719        capabilities: ModelCapabilities {
720            deferred_tool_loading: Some(DeferredToolLoading::Unsupported),
721            ..ModelCapabilities::default()
722        },
723        ..ModelInfo::default()
724    });
725    ModelInfo::merge([
726        Some(&base_model_info(&base)),
727        Some(&server_side_summary_off()),
728        caching.as_ref(),
729        reasoning.as_ref(),
730        strict.as_ref(),
731        config.model_info.as_ref(),
732    ])
733}
734
735/// Whether a Bedrock model id names an Anthropic model.
736fn names_anthropic(model_id: &str) -> bool {
737    let model_id = model_id.to_lowercase();
738    model_id.contains("anthropic") || model_id.contains("claude")
739}
740
741/// Whether a Bedrock model takes back Claude-signed reasoning: its id names Anthropic, or names no
742/// vendor (no `vendor.` prefix after the last `/`).
743fn takes_claude_reasoning(model_id: &str) -> bool {
744    let names_no_vendor = !model_id.rsplit('/').next().unwrap_or_default().contains('.');
745    names_anthropic(model_id) || names_no_vendor
746}
747
748/// Tags a Claude model's signed or redacted reasoning; a model id that names no vendor stays
749/// untagged.
750fn tag_claude_reasoning(event: ModelStreamEvent, model_id: &str) -> ModelStreamEvent {
751    if !names_anthropic(model_id) {
752        return event;
753    }
754    tag_signed_reasoning(event, ANTHROPIC_REASONING_PROVIDER, model_id)
755}
756
757/// What one model call needs, cloned out of the provider so the stream is `'static`.
758struct Call {
759    config: BedrockModelConfig,
760    model_info: ModelInfo,
761    transport: Arc<dyn BedrockTransport>,
762    drop_stale_thinking_model_id: Arc<RwLock<Option<String>>>,
763}
764
765#[derive(Debug, Clone, Copy, PartialEq, Eq)]
766enum Api {
767    ConverseStream,
768    Converse,
769}
770
771enum Response {
772    Stream(ChunkStream),
773    Converse(crate::types::JsonObject),
774}
775
776impl Call {
777    fn formatter(&self) -> Formatter<'_> {
778        Formatter::new(&self.config, &self.model_info)
779    }
780
781    fn events(self, request: ModelRequest) -> BoxStream<'static, Result<ModelStreamEvent>> {
782        Box::pin(async_stream::try_stream! {
783            let model_id = self.config.model_id_or_default().to_owned();
784            let api = if self.config.stream == Some(false) { Api::Converse } else { Api::ConverseStream };
785            match self.send_request(&request, api).await.map_err(Error::from)? {
786                Response::Stream(mut chunks) => {
787                    let mut state = StreamState::new(self.config.guardrail_config.as_ref());
788                    while let Some(chunk) = chunks.next().await {
789                        let chunk = chunk.map_err(Error::from)?;
790                        for event in state.apply(&chunk)? {
791                            yield tag_claude_reasoning(event, &model_id);
792                        }
793                    }
794                    for event in state.finish() {
795                        yield event;
796                    }
797                }
798                Response::Converse(output) => {
799                    for event in map_converse_output(&output, self.config.guardrail_config.as_ref())? {
800                        yield tag_claude_reasoning(event, &model_id);
801                    }
802                }
803            }
804        })
805    }
806
807    /// Formats and sends the request, with the strongest structured output mechanism the model
808    /// accepts when the call must produce a schema. Rejected mechanisms are
809    /// remembered for the process.
810    async fn send_request(&self, request: &ModelRequest, api: Api) -> Result<Response, SendError> {
811        let options = FormatOptions::from_request(request);
812        let Some(schema) = request.structured_output_schema.as_ref() else {
813            return self
814                .send(self.formatter().format_request(&request.messages, &options)?, api)
815                .await;
816        };
817        let model_id = self.config.model_id_or_default().to_owned();
818        let mechanisms = structured_output_mechanisms(
819            "bedrock",
820            &model_id,
821            request.tool_choice.as_ref(),
822            schema,
823            &self.model_info,
824        );
825        let (fallback, attempts) = mechanisms
826            .split_last()
827            .map_or((StructuredOutputMechanism::Auto, &[][..]), |(last, rest)| (*last, rest));
828        for mechanism in attempts {
829            let formatted = self.structured_output_request(&request.messages, &options, *mechanism, schema)?;
830            match self.send(formatted, api).await {
831                Ok(response) => return Ok(response),
832                Err(SendError::Bedrock(error)) if record_rejected_mechanism(&error, *mechanism, &model_id, schema) => {}
833                Err(error) => return Err(error),
834            }
835        }
836        let formatted = self.structured_output_request(&request.messages, &options, fallback, schema)?;
837        self.send(formatted, api).await
838    }
839
840    /// Formats the request for a structured output mechanism.
841    fn structured_output_request(
842        &self,
843        messages: &[Message],
844        options: &FormatOptions<'_>,
845        mechanism: StructuredOutputMechanism,
846        schema: &JsonValue,
847    ) -> Result<crate::types::JsonObject> {
848        let formatter = self.formatter();
849        if mechanism == StructuredOutputMechanism::Forced {
850            return formatter.format_request(messages, options);
851        }
852        let auto = ToolChoice::Auto;
853        let mut request = formatter.format_request(messages, &options.with_tool_choice(Some(&auto)))?;
854        if mechanism == StructuredOutputMechanism::Native {
855            format::apply_native_output_config(&mut request, schema)?;
856        }
857        Ok(request)
858    }
859
860    /// Sends the request, retrying once with `drop_block` when an edit before replayed thinking
861    /// made it stale (`_send`). An accepted retry turns `drop_block` on for later requests to this
862    /// model.
863    async fn send(&self, request: crate::types::JsonObject, api: Api) -> Result<Response, SendError> {
864        let model_id = request
865            .get("modelId")
866            .and_then(JsonValue::as_str)
867            .unwrap_or_default()
868            .to_owned();
869        let drops_stale = self
870            .drop_stale_thinking_model_id
871            .read()
872            .unwrap_or_else(PoisonError::into_inner)
873            .as_deref()
874            == Some(model_id.as_str());
875        let sent = drops_stale
876            .then(|| format::request_with_drop_block(&request))
877            .flatten()
878            .unwrap_or(request);
879        let error = match self.send_once(sent.clone(), api).await {
880            Ok(response) => return Ok(response),
881            Err(error) => error,
882        };
883        let binding_error =
884            error.name == "ValidationException" && super::thinking_binding::is_thinking_binding_error(&error.message);
885        let Some(retry) = binding_error.then(|| format::request_with_drop_block(&sent)).flatten() else {
886            return Err(error.into());
887        };
888        tracing::warn!(
889            "model_id=<{model_id}> | history edit invalidated replayed thinking blocks, retrying with drop_block"
890        );
891        let response = self.send_once(retry, api).await?;
892        // Latched only once the retry is accepted, so a rejected retry does not alter later requests.
893        *self
894            .drop_stale_thinking_model_id
895            .write()
896            .unwrap_or_else(PoisonError::into_inner) = Some(model_id);
897        Ok(response)
898    }
899
900    async fn send_once(&self, request: crate::types::JsonObject, api: Api) -> Result<Response, BedrockError> {
901        match api {
902            Api::ConverseStream => self.transport.converse_stream(request).await.map(Response::Stream),
903            Api::Converse => self.transport.converse(request).await.map(Response::Converse),
904        }
905    }
906
907    async fn count_tokens(self, messages: &[Message], options: &CountTokensOptions) -> Result<u64, SendError> {
908        let format_options = FormatOptions {
909            system_prompt: options.system_prompt.as_ref(),
910            tool_specs: &options.tool_specs,
911            ..FormatOptions::default()
912        };
913        let request = self.formatter().format_request(messages, &format_options)?;
914        let input: crate::types::JsonObject = ["messages", "system", "toolConfig"]
915            .into_iter()
916            .filter_map(|key| request.get(key).map(|value| (key.to_owned(), value.clone())))
917            .collect();
918        let model_id = self.config.model_id_or_default().to_owned();
919        let tokens = self.transport.count_tokens(model_id, input).await?;
920        let Some(tokens) = tokens else {
921            return Err(Error::from(ModelError::new(
922                "Bedrock CountTokens returned undefined for inputTokens",
923            ))
924            .into());
925        };
926        tracing::debug!("total_tokens=<{tokens}> | native token count");
927        Ok(tokens)
928    }
929}
930
931/// A send failure: the request could not be formatted, or Bedrock rejected it.
932enum SendError {
933    Format(Error),
934    Bedrock(BedrockError),
935}
936
937impl From<Error> for SendError {
938    fn from(error: Error) -> Self {
939        Self::Format(error)
940    }
941}
942
943impl From<BedrockError> for SendError {
944    fn from(error: BedrockError) -> Self {
945        Self::Bedrock(error)
946    }
947}
948
949impl From<SendError> for Error {
950    fn from(error: SendError) -> Self {
951        match error {
952            SendError::Format(error) => error,
953            SendError::Bedrock(error) => error.into(),
954        }
955    }
956}
957
958/// Records a structured output rejection, so the request is resent with the next mechanism.
959fn record_rejected_mechanism(
960    error: &BedrockError,
961    mechanism: StructuredOutputMechanism,
962    model_id: &str,
963    schema: &JsonValue,
964) -> bool {
965    error.name == "ValidationException"
966        && handle_rejected_mechanism("bedrock", model_id, mechanism, schema, &error.message)
967}
968
969/// Turns any error whose message names a context overflow into a [`ContextWindowOverflowError`].
970fn map_stream_error(error: Error) -> Error {
971    let message = error.to_string();
972    if BEDROCK_CONTEXT_WINDOW_OVERFLOW_MESSAGES
973        .iter()
974        .any(|pattern| message.contains(pattern))
975    {
976        return ContextWindowOverflowError::new(message).into();
977    }
978    error
979}
980
981/// Model ids whose CountTokens calls are skipped for the life of the process
982/// (`SKIP_COUNT_TOKENS_MODELS`).
983static SKIP_COUNT_TOKENS_MODELS: std::sync::LazyLock<std::sync::Mutex<std::collections::HashSet<String>>> =
984    std::sync::LazyLock::new(Default::default);
985
986fn skip_count_tokens(model_id: &str) -> bool {
987    SKIP_COUNT_TOKENS_MODELS
988        .lock()
989        .unwrap_or_else(PoisonError::into_inner)
990        .contains(model_id)
991}
992
993fn remember_skip_count_tokens(model_id: &str) {
994    SKIP_COUNT_TOKENS_MODELS
995        .lock()
996        .unwrap_or_else(PoisonError::into_inner)
997        .insert(model_id.to_owned());
998}
999
1000#[async_trait]
1001impl Model for BedrockModel {
1002    fn stream(&self, request: ModelRequest) -> BoxStream<'static, Result<ModelStreamEvent>> {
1003        let cancel_signal = request.cancel_signal.clone();
1004        let mut events = self.call().events(request);
1005        Box::pin(async_stream::stream! {
1006            loop {
1007                let next = match &cancel_signal {
1008                    Some(signal) => tokio::select! {
1009                        biased;
1010                        () = signal.cancelled() => {
1011                            // Closes the connection before the consumer sees the abort.
1012                            drop(events);
1013                            yield Err(ModelError::new("Request aborted").into());
1014                            return;
1015                        }
1016                        next = events.next() => next,
1017                    },
1018                    None => events.next().await,
1019                };
1020                match next {
1021                    Some(Ok(event)) => yield Ok(event),
1022                    Some(Err(error)) => {
1023                        drop(events);
1024                        yield Err(map_stream_error(error));
1025                        return;
1026                    }
1027                    None => return,
1028                }
1029            }
1030        })
1031    }
1032
1033    fn get_config(&self) -> BaseModelConfig {
1034        self.config().to_base()
1035    }
1036
1037    fn update_config(&self, config: BaseModelConfig) -> Result<()> {
1038        Self::update_config(self, config)
1039    }
1040
1041    fn model_info(&self) -> ModelInfo {
1042        bedrock_model_info(&self.raw_config())
1043    }
1044
1045    async fn count_tokens(&self, messages: &[Message], options: CountTokensOptions) -> Result<u64> {
1046        let call = self.call();
1047        if call.config.use_native_token_count != Some(true) {
1048            return Ok(estimate_tokens(messages, &options));
1049        }
1050        let model_id = call.config.model_id_or_default().to_owned();
1051        if skip_count_tokens(&model_id) {
1052            return Ok(estimate_tokens(messages, &options));
1053        }
1054        let error = match call.count_tokens(messages, &options).await {
1055            Ok(tokens) => return Ok(tokens),
1056            Err(error) => error,
1057        };
1058        let (name, message) = match &error {
1059            SendError::Bedrock(error) => (error.name.as_str(), error.message.as_str()),
1060            SendError::Format(_) => ("", ""),
1061        };
1062        if name == "AccessDeniedException" {
1063            warn_once(&format!(
1064                "model_id=<{model_id}> | bedrock:CountTokens permission denied, falling back to heuristic estimation"
1065            ));
1066            remember_skip_count_tokens(&model_id);
1067        } else if name == "ValidationException" && message.contains("doesn't support counting tokens") {
1068            tracing::debug!(
1069                "model_id=<{model_id}> | model does not support CountTokens, caching for future calls, falling back to estimation"
1070            );
1071            remember_skip_count_tokens(&model_id);
1072        } else {
1073            let error = Error::from(error);
1074            tracing::debug!("error=<{error}> | native token counting failed, falling back to estimation");
1075        }
1076        Ok(estimate_tokens(messages, &options))
1077    }
1078}