1mod 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
58const 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
69pub const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(120);
72
73pub type BedrockCacheTtl = CacheTtl;
78
79pub type BedrockCacheConfig = CacheConfig;
81
82#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
84#[non_exhaustive]
85pub enum IncludeToolResultStatus {
86 #[default]
89 Auto,
90 Enabled(bool),
92}
93
94impl From<bool> for IncludeToolResultStatus {
95 fn from(enabled: bool) -> Self {
96 Self::Enabled(enabled)
97 }
98}
99
100#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
102#[non_exhaustive]
103pub enum BedrockGuardrailTrace {
104 #[default]
106 Enabled,
107 Disabled,
109 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125#[non_exhaustive]
126pub enum BedrockGuardrailStreamProcessingMode {
127 Sync,
129 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#[derive(Debug, Clone, Default, PartialEq, Eq, bon::Builder)]
144pub struct BedrockGuardrailRedactionConfig {
145 pub input: Option<bool>,
147 #[builder(into)]
149 pub input_message: Option<String>,
150 pub output: Option<bool>,
152 #[builder(into)]
154 pub output_message: Option<String>,
155}
156
157#[derive(Debug, Clone, Default, PartialEq, Eq, bon::Builder)]
161pub struct BedrockGuardrailConfig {
162 #[builder(into)]
164 pub guardrail_identifier: String,
165 #[builder(into)]
167 pub guardrail_version: String,
168 pub trace: Option<BedrockGuardrailTrace>,
170 pub stream_processing_mode: Option<BedrockGuardrailStreamProcessingMode>,
172 pub redaction: Option<BedrockGuardrailRedactionConfig>,
174 pub guard_latest_user_message: Option<bool>,
178}
179
180#[derive(Debug, Clone, Default, PartialEq, bon::Builder)]
195pub struct BedrockModelConfig {
196 #[builder(into)]
199 pub model_id: Option<String>,
200 pub max_tokens: Option<u64>,
203 pub temperature: Option<f64>,
205 pub top_p: Option<f64>,
207 pub context_window_limit: Option<u64>,
209 pub model_info: Option<ModelInfo>,
211 pub stop_sequences: Option<Vec<String>>,
213 pub cache_config: Option<BedrockCacheConfig>,
215 pub additional_request_fields: Option<JsonValue>,
217 pub additional_response_field_paths: Option<Vec<String>>,
219 pub additional_args: Option<JsonValue>,
223 pub stream: Option<bool>,
225 #[builder(into)]
227 pub include_tool_result_status: Option<IncludeToolResultStatus>,
228 pub guardrail_config: Option<BedrockGuardrailConfig>,
230 pub use_native_token_count: Option<bool>,
233 pub strict_tools: Option<bool>,
239}
240
241impl BedrockModelConfig {
242 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 #[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#[derive(Clone, Default, bon::Builder)]
360#[builder(finish_fn = build_options)]
361pub struct BedrockModelOptions {
362 #[builder(into)]
364 pub model_id: Option<String>,
365 pub max_tokens: Option<u64>,
367 pub temperature: Option<f64>,
369 pub top_p: Option<f64>,
371 pub context_window_limit: Option<u64>,
373 pub model_info: Option<ModelInfo>,
375 pub stop_sequences: Option<Vec<String>>,
377 pub cache_config: Option<BedrockCacheConfig>,
379 pub additional_request_fields: Option<JsonValue>,
381 pub additional_response_field_paths: Option<Vec<String>>,
383 pub additional_args: Option<JsonValue>,
385 pub stream: Option<bool>,
387 #[builder(into)]
389 pub include_tool_result_status: Option<IncludeToolResultStatus>,
390 pub guardrail_config: Option<BedrockGuardrailConfig>,
392 pub use_native_token_count: Option<bool>,
394 pub strict_tools: Option<bool>,
396 #[builder(into)]
398 pub region: Option<String>,
399 #[builder(into)]
401 pub endpoint_url: Option<String>,
402 pub credentials_provider: Option<SharedCredentialsProvider>,
405 pub sdk_config: Option<SdkConfig>,
409 pub request_timeout: Option<Duration>,
413 #[builder(into)]
415 pub api_key: Option<String>,
416}
417
418impl<S: bedrock_model_options_builder::IsComplete> BedrockModelOptionsBuilder<S> {
419 #[must_use]
421 pub fn build(self) -> BedrockModel {
422 BedrockModel::new(self.build_options())
423 }
424}
425
426impl BedrockModelOptions {
427 #[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#[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 #[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 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 #[must_use]
608 pub fn config(&self) -> BedrockModelConfig {
609 resolve_config(&self.raw_config())
610 }
611
612 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
643fn 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
665pub(crate) fn default_bedrock_model() -> Arc<dyn Model> {
667 Arc::new(BedrockModel::default())
668}
669
670fn 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
700fn 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 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 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
735fn 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
741fn 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
748fn 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
757struct 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 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 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 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 *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
931enum 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
958fn 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
969fn 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
981static 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 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}