strands/models/anthropic/
bedrock.rs1use std::fmt;
5use std::sync::Arc;
6use std::time::Duration;
7
8use aws_sdk_bedrockruntime::Client;
9use aws_sdk_bedrockruntime::config::http::HttpResponse;
10use aws_sdk_bedrockruntime::error::{DisplayErrorContext, ProvideErrorMetadata, SdkError};
11use aws_sdk_bedrockruntime::primitives::Blob;
12use aws_sdk_bedrockruntime::types::ResponseStream;
13use aws_sdk_bedrockruntime::types::error::ResponseStreamError;
14use futures::future::BoxFuture;
15use tokio::sync::OnceCell;
16
17use super::client::{AnthropicClient, ClientRequest, EventStream};
18use super::{AnthropicClientConfig, AnthropicModel, AnthropicModelOptions, client_betas, prepare_config};
19use crate::error::{Error, Result};
20use crate::models::bedrock::transport::{ClientOptions, build_client};
21use crate::models::bedrock::{DEFAULT_REQUEST_TIMEOUT, SdkConfig, SharedCredentialsProvider};
22use crate::models::http::{ErrorPayload, HttpError, read_env};
23use crate::types::JsonValue;
24
25#[derive(Clone, Default, bon::Builder)]
31pub struct AnthropicBedrockConfig {
32 #[builder(into)]
35 pub region: Option<String>,
36 #[builder(into)]
40 pub endpoint_url: Option<String>,
41 pub credentials_provider: Option<SharedCredentialsProvider>,
44 pub sdk_config: Option<SdkConfig>,
47 pub request_timeout: Option<Duration>,
50 #[builder(into)]
53 pub api_key: Option<String>,
54}
55
56impl fmt::Debug for AnthropicBedrockConfig {
57 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58 let set = |present: bool| present.then_some("<set>");
59 f.debug_struct("AnthropicBedrockConfig")
60 .field("region", &self.region)
61 .field("endpoint_url", &self.endpoint_url)
62 .field("credentials_provider", &set(self.credentials_provider.is_some()))
63 .field("sdk_config", &set(self.sdk_config.is_some()))
64 .field("request_timeout", &self.request_timeout)
65 .field("api_key", &set(self.api_key.is_some()))
66 .finish()
67 }
68}
69
70impl AnthropicModel {
71 pub fn bedrock(options: impl Into<AnthropicModelOptions>, bedrock_config: AnthropicBedrockConfig) -> Result<Self> {
99 Self::bedrock_with_env(options.into(), bedrock_config, &|name| std::env::var(name).ok())
100 }
101
102 pub(super) fn bedrock_with_env(
103 options: AnthropicModelOptions,
104 bedrock_config: AnthropicBedrockConfig,
105 env: &dyn Fn(&str) -> Option<String>,
106 ) -> Result<Self> {
107 let (config, api_key, client_config) = options.into_parts();
108 validate_bedrock_client_options(api_key.as_deref(), &client_config)?;
109 let config = prepare_config(config)?;
110 let AnthropicBedrockConfig {
111 region,
112 endpoint_url,
113 credentials_provider,
114 sdk_config,
115 request_timeout,
116 api_key,
117 } = bedrock_config;
118 let endpoint_url = endpoint_url.or_else(|| read_env(env, "ANTHROPIC_BEDROCK_BASE_URL"));
119 let client = BedrockRuntimeClient::new(ClientOptions {
120 region,
121 endpoint_url,
122 credentials_provider,
123 sdk_config,
124 request_timeout: request_timeout.unwrap_or(DEFAULT_REQUEST_TIMEOUT),
125 api_key,
126 });
127 Ok(Self::from_client(
128 config,
129 Arc::new(client),
130 client_betas(&client_config),
131 None,
132 true,
133 ))
134 }
135}
136
137fn validate_bedrock_client_options(api_key: Option<&str>, client_config: &AnthropicClientConfig) -> Result<()> {
138 if api_key.is_some_and(|key| !key.is_empty()) {
139 return Err(Error::other(
140 "api_key is not used on Bedrock: set AnthropicBedrockConfig::api_key for an Amazon Bedrock API key",
141 ));
142 }
143 if client_config.base_url.is_some() {
144 return Err(Error::other(
145 "client_config.base_url is not used on Bedrock: set AnthropicBedrockConfig::endpoint_url",
146 ));
147 }
148 if client_config.max_retries.is_some() || client_config.timeout.is_some() {
149 return Err(Error::other(
150 "client_config.max_retries and client_config.timeout are not used on Bedrock: the AWS SDK retries, and AnthropicBedrockConfig::request_timeout bounds each attempt",
151 ));
152 }
153 if let Some((name, _)) = client_config
154 .default_headers
155 .iter()
156 .find(|(name, _)| !name.eq_ignore_ascii_case("anthropic-beta"))
157 {
158 return Err(Error::other(format!(
159 "client_config.default_headers['{name}'] is not used on Bedrock: only anthropic-beta is sent, in the request body"
160 )));
161 }
162 Ok(())
163}
164
165struct BedrockRuntimeClient {
167 options: ClientOptions,
168 client: Arc<OnceCell<Client>>,
169}
170
171impl BedrockRuntimeClient {
172 fn new(options: ClientOptions) -> Self {
173 Self {
174 options,
175 client: Arc::new(OnceCell::new()),
176 }
177 }
178}
179
180impl AnthropicClient for BedrockRuntimeClient {
181 fn stream(&self, request: ClientRequest) -> EventStream {
182 let client = Arc::clone(&self.client);
183 let options = self.options.clone();
184 Box::pin(async_stream::stream! {
185 let (model_id, body) = match invoke_model_request(request) {
186 Ok(request) => request,
187 Err(error) => {
188 yield Err(error);
189 return;
190 }
191 };
192 let client = client.get_or_init(|| build_client(&options)).await.clone();
193 let send = client
194 .invoke_model_with_response_stream()
195 .model_id(model_id)
196 .content_type("application/json")
197 .accept("application/json")
198 .body(Blob::new(body))
199 .send();
200 let output = match send.await {
201 Ok(output) => output,
202 Err(error) => {
203 yield Err(send_error(error));
204 return;
205 }
206 };
207 let timeout = options.request_timeout;
208 let mut receiver = output.body;
209 loop {
210 let Ok(received) = tokio::time::timeout(timeout, receiver.recv()).await else {
211 yield Err(HttpError::timeout());
212 return;
213 };
214 match received {
215 Ok(Some(ResponseStream::Chunk(part))) => {
216 let bytes = part.bytes.map(Blob::into_inner).unwrap_or_default();
217 match serde_json::from_slice(&bytes) {
218 Ok(event) => yield Ok(event),
219 Err(error) => {
220 yield Err(HttpError::decode(format!("could not decode a Bedrock stream chunk: {error}"), error));
221 return;
222 }
223 }
224 }
225 Ok(Some(_)) => {}
226 Ok(None) => return,
227 Err(error) => {
228 yield Err(stream_error(error));
229 return;
230 }
231 }
232 }
233 })
234 }
235
236 fn beta_stream(&self, request: ClientRequest) -> Option<EventStream> {
237 Some(self.stream(request))
238 }
239
240 fn count_tokens(
241 &self,
242 _request: ClientRequest,
243 ) -> Option<BoxFuture<'static, std::result::Result<JsonValue, HttpError>>> {
244 None
245 }
246}
247
248fn invoke_model_request(request: ClientRequest) -> std::result::Result<(String, Vec<u8>), HttpError> {
251 let JsonValue::Object(mut body) = request.body else {
252 return Err(HttpError::request(
253 "the Messages request body is not a JSON object",
254 None,
255 ));
256 };
257 let model_id = body
258 .shift_remove("model")
259 .and_then(|model| model.as_str().map(str::to_owned))
260 .unwrap_or_default();
261 body.shift_remove("stream");
262 if let Some(beta) = request.beta.filter(|_| !body.contains_key("anthropic_beta")) {
263 let betas = beta.split(',').map(|beta| JsonValue::String(beta.to_owned())).collect();
264 body.insert("anthropic_beta".to_owned(), JsonValue::Array(betas));
265 }
266 let body = serde_json::to_vec(&body)
267 .map_err(|error| HttpError::request(format!("could not encode the request: {error}"), Some(error.into())))?;
268 Ok((model_id, body))
269}
270
271fn send_error<E>(error: SdkError<E, HttpResponse>) -> HttpError
273where
274 E: ProvideErrorMetadata + std::error::Error + Send + Sync + 'static,
275{
276 match &error {
277 SdkError::ServiceError(context) => {
278 let status = context.raw().status().as_u16();
279 let body = serde_json::json!({"message": context.err().message().unwrap_or_default()});
280 HttpError::status(status, Some(body), "", ErrorPayload::Body)
281 }
282 SdkError::TimeoutError(_) => HttpError::timeout(),
283 SdkError::ConstructionFailure(_) => {
284 HttpError::request(DisplayErrorContext(&error).to_string(), Some(error.into()))
285 }
286 _ => HttpError::connection(error),
287 }
288}
289
290fn stream_error<R>(error: SdkError<ResponseStreamError, R>) -> HttpError
292where
293 R: fmt::Debug + Send + Sync + 'static,
294{
295 let SdkError::ServiceError(context) = &error else {
296 return HttpError::connection(error);
297 };
298 let exception = context.err();
299 exception_event(exception_type(exception), exception.message().unwrap_or_default())
300}
301
302fn exception_event(kind: &str, message: &str) -> HttpError {
303 HttpError::event(&serde_json::json!({"type": kind, "message": message}).to_string())
304}
305
306fn exception_type(error: &ResponseStreamError) -> &str {
308 match error {
309 ResponseStreamError::InternalServerException(_) => "internalServerException",
310 ResponseStreamError::ModelStreamErrorException(_) => "modelStreamErrorException",
311 ResponseStreamError::ValidationException(_) => "validationException",
312 ResponseStreamError::ThrottlingException(_) => "throttlingException",
313 ResponseStreamError::ModelTimeoutException(_) => "modelTimeoutException",
314 ResponseStreamError::ServiceUnavailableException(_) => "serviceUnavailableException",
315 other => other.code().unwrap_or("unknownException"),
316 }
317}
318
319#[cfg(test)]
320mod tests {
321 use aws_sdk_bedrockruntime::types::error::{ModelStreamErrorException, ThrottlingException};
322 use serde_json::json;
323
324 use super::*;
325
326 fn body(bytes: &[u8]) -> JsonValue {
327 serde_json::from_slice(bytes).unwrap()
328 }
329
330 #[test]
331 fn moves_the_model_to_the_path_drops_stream_and_sends_the_betas_in_the_body() {
332 let request = ClientRequest {
333 body: json!({"model": "global.anthropic.claude-opus-5-5", "max_tokens": 10, "messages": [], "stream": true, "anthropic_version": "bedrock-2023-05-31"}),
334 beta: Some("a,thinking-binding-controls-2026-08-01".to_owned()),
335 };
336 let (model_id, bytes) = invoke_model_request(request).unwrap();
337 assert_eq!(model_id, "global.anthropic.claude-opus-5-5");
338 assert_eq!(
339 String::from_utf8(bytes).unwrap(),
340 r#"{"max_tokens":10,"messages":[],"anthropic_version":"bedrock-2023-05-31","anthropic_beta":["a","thinking-binding-controls-2026-08-01"]}"#
341 );
342 }
343
344 #[test]
345 fn keeps_anthropic_beta_set_in_the_body() {
346 let request = ClientRequest {
347 body: json!({"model": "m", "anthropic_beta": ["own"]}),
348 beta: Some("other".to_owned()),
349 };
350 let (_, bytes) = invoke_model_request(request).unwrap();
351 assert_eq!(body(&bytes), json!({"anthropic_beta": ["own"]}));
352 }
353
354 #[test]
355 fn maps_exception_frames_to_their_type_and_message() {
356 let throttle =
357 ResponseStreamError::ThrottlingException(ThrottlingException::builder().message("Too many tokens").build());
358 let stream = ResponseStreamError::ModelStreamErrorException(
359 ModelStreamErrorException::builder().message("broken").build(),
360 );
361 assert_eq!(exception_type(&throttle), "throttlingException");
362 assert_eq!(exception_type(&stream), "modelStreamErrorException");
363 let error = exception_event(exception_type(&throttle), "Too many tokens");
364 assert_eq!(error.message(), "Too many tokens");
365 assert_eq!(
366 error.body(),
367 Some(&json!({"type": "throttlingException", "message": "Too many tokens"}))
368 );
369 }
370
371 #[test]
372 fn rejects_client_options_bedrock_does_not_use() {
373 let env = |_: &str| None;
374 let reject = |options: AnthropicModelOptions, expected: &str| {
375 let error = AnthropicModel::bedrock_with_env(options, AnthropicBedrockConfig::default(), &env).unwrap_err();
376 assert!(error.to_string().contains(expected), "{error}");
377 };
378 reject(
379 AnthropicModel::builder().api_key("key").build_options(),
380 "api_key is not used on Bedrock",
381 );
382 let base_url = AnthropicClientConfig {
383 base_url: Some("https://example.com".to_owned()),
384 ..Default::default()
385 };
386 reject(
387 AnthropicModel::builder().client_config(base_url).build_options(),
388 "client_config.base_url",
389 );
390 let header = AnthropicClientConfig {
391 default_headers: vec![("anthropic-version".to_owned(), "2023-06-01".to_owned())],
392 ..Default::default()
393 };
394 reject(
395 AnthropicModel::builder().client_config(header).build_options(),
396 "default_headers['anthropic-version']",
397 );
398 let betas = AnthropicClientConfig {
399 default_headers: vec![("anthropic-beta".to_owned(), "a".to_owned())],
400 ..Default::default()
401 };
402 AnthropicModel::bedrock_with_env(
403 AnthropicModel::builder()
404 .model_id("m")
405 .client_config(betas)
406 .build_options(),
407 AnthropicBedrockConfig::default(),
408 &env,
409 )
410 .unwrap();
411 }
412
413 #[test]
414 fn redacts_credentials_in_debug_output() {
415 let config = AnthropicBedrockConfig::builder()
416 .region("us-west-2")
417 .api_key("secret")
418 .build();
419 let debug = format!("{config:?}");
420 assert!(
421 debug.contains("us-west-2") && debug.contains("<set>") && !debug.contains("secret"),
422 "{debug}"
423 );
424 }
425}