strands_harness/tools/web_search/
agentcore.rs1use std::fmt;
4use std::sync::{Arc, OnceLock};
5use std::time::Duration;
6
7use async_trait::async_trait;
8use aws_config::meta::region::ProvideRegion;
9use aws_config::profile::ProfileFileRegionProvider;
10use aws_config::retry::RetryConfig;
11use aws_config::timeout::TimeoutConfig;
12use aws_config::{BehaviorVersion, Region, SdkConfig};
13use aws_credential_types::provider::error::CredentialsError;
14use aws_sdk_bedrockagentcore::Client;
15use aws_sdk_bedrockagentcore::config::http::HttpResponse;
16use aws_sdk_bedrockagentcore::error::{DisplayErrorContext, ProvideErrorMetadata, SdkError};
17use aws_sdk_bedrockagentcore::operation::invoke_web_search::builders::InvokeWebSearchFluentBuilder;
18use aws_sdk_bedrockagentcore::operation::invoke_web_search::{InvokeWebSearchError, InvokeWebSearchOutput};
19use futures::future::BoxFuture;
20use strands::tools::FunctionTool;
21use tokio::sync::OnceCell;
22
23use super::{SNIPPET_CHARS, SearchBackend, SearchResult, WebSearchError, one_line, search_tool};
24use crate::env::Env;
25
26const WEB_SEARCH_ID: &str = "web-search.v1";
27const DEFAULT_REGION: &str = "us-west-2";
29const TIMEOUT: Duration = Duration::from_secs(30);
30const MAX_ATTEMPTS: u32 = 2;
32const ANSWER_WITHOUT_SEARCH: &str = " web_search is unavailable here; answer without it.";
34
35#[derive(Debug, Clone, Default, bon::Builder)]
37#[builder(on(String, into))]
38pub struct MakeAgentCoreWebSearchOptions {
39 pub region: Option<String>,
43 pub sdk_config: Option<SdkConfig>,
46}
47
48#[derive(Debug, Clone, PartialEq, Eq)]
50pub(crate) enum CallFailure {
51 NotInRegion(String),
53 AccessDenied(String),
55 Credentials(String),
57 Other(String),
59}
60
61#[async_trait]
63pub(crate) trait Invoke: Send + Sync {
64 async fn invoke(&self, query: &str, max_results: usize) -> Result<Vec<SearchResult>, CallFailure>;
65}
66
67#[derive(Clone)]
69pub(crate) struct Connection {
70 pub(crate) invoke: Arc<dyn Invoke>,
71 pub(crate) region: String,
72}
73
74type Connect = Arc<dyn Fn() -> BoxFuture<'static, Connection> + Send + Sync>;
75
76pub struct AgentCoreBackend {
80 connect: Connect,
81 connection: OnceCell<Connection>,
82 unavailable: OnceLock<String>,
83}
84
85impl fmt::Debug for AgentCoreBackend {
86 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87 f.debug_struct("AgentCoreBackend")
88 .field(
89 "region",
90 &self.connection.get().map(|connection| connection.region.as_str()),
91 )
92 .field("unavailable", &self.unavailable.get())
93 .finish_non_exhaustive()
94 }
95}
96
97impl Default for AgentCoreBackend {
98 fn default() -> Self {
99 Self::new(MakeAgentCoreWebSearchOptions::default())
100 }
101}
102
103impl AgentCoreBackend {
104 #[must_use]
106 pub fn new(options: MakeAgentCoreWebSearchOptions) -> Self {
107 Self::with_env(options, Env::process())
108 }
109
110 pub(crate) fn with_env(options: MakeAgentCoreWebSearchOptions, env: Env) -> Self {
111 let options = Arc::new(options);
112 Self::with_connect(Arc::new(move || {
113 let options = Arc::clone(&options);
114 let env = env.clone();
115 Box::pin(async move {
116 let region = resolve_region(&options, &env, profile_region()).await;
117 let client = client_for(&options, ®ion).await;
118 Connection {
119 invoke: Arc::new(client),
120 region,
121 }
122 })
123 }))
124 }
125
126 pub(crate) fn with_connect(connect: Connect) -> Self {
127 Self {
128 connect,
129 connection: OnceCell::new(),
130 unavailable: OnceLock::new(),
131 }
132 }
133
134 fn mark_unavailable(&self, reason: &str) -> WebSearchError {
135 let message = self.unavailable.get_or_init(|| {
136 tracing::warn!("web_search: AgentCore web search is unavailable, so every search will fail: {reason}");
137 format!("{reason}{ANSWER_WITHOUT_SEARCH}")
138 });
139 WebSearchError::new(message.clone())
140 }
141}
142
143#[async_trait]
144impl SearchBackend for AgentCoreBackend {
145 async fn search(&self, query: &str, max_results: usize) -> Result<Vec<SearchResult>, WebSearchError> {
146 if let Some(message) = self.unavailable.get() {
147 return Err(WebSearchError::new(message.clone()));
148 }
149 let connection = self.connection.get_or_init(|| (self.connect)()).await;
150 let region = &connection.region;
151 match connection.invoke.invoke(query, max_results).await {
152 Ok(results) => Ok(results),
153 Err(CallFailure::NotInRegion(reason)) => Err(self.mark_unavailable(&format!(
154 "AgentCore web search is not available in {region} ({reason})."
155 ))),
156 Err(CallFailure::AccessDenied(reason)) => Err(self.mark_unavailable(&format!(
157 "{reason} (the caller needs bedrock-agentcore:InvokeWebSearch on arn:aws:bedrock-agentcore:{region}:aws:tool/{WEB_SEARCH_ID})."
158 ))),
159 Err(CallFailure::Credentials(reason)) => Err(self.mark_unavailable(&format!(
160 "{reason} (AgentCore web search is signed with AWS credentials; a Bedrock API key does not cover it)."
161 ))),
162 Err(CallFailure::Other(reason)) => Err(WebSearchError::new(reason)),
163 }
164 }
165}
166
167#[must_use]
178pub fn make_agent_core_web_search(options: MakeAgentCoreWebSearchOptions) -> FunctionTool {
179 search_tool(Arc::new(AgentCoreBackend::new(options)))
180}
181
182pub(crate) fn agent_core_web_search(env: &Env) -> FunctionTool {
183 search_tool(Arc::new(AgentCoreBackend::with_env(
184 MakeAgentCoreWebSearchOptions::default(),
185 env.clone(),
186 )))
187}
188
189fn profile_region() -> BoxFuture<'static, Option<String>> {
190 Box::pin(async {
191 ProfileFileRegionProvider::new()
192 .region()
193 .await
194 .map(|region| region.to_string())
195 })
196}
197
198pub(crate) async fn resolve_region(
201 options: &MakeAgentCoreWebSearchOptions,
202 env: &Env,
203 profile: BoxFuture<'static, Option<String>>,
204) -> String {
205 let configured = options
206 .region
207 .clone()
208 .filter(|region| !region.is_empty())
209 .or_else(|| {
210 options
211 .sdk_config
212 .as_ref()
213 .and_then(SdkConfig::region)
214 .map(ToString::to_string)
215 })
216 .or_else(|| env.get("AWS_REGION"))
217 .or_else(|| env.get("AWS_DEFAULT_REGION"));
218 if let Some(region) = configured {
219 return region;
220 }
221 profile.await.unwrap_or_else(|| DEFAULT_REGION.to_owned())
222}
223
224pub(crate) async fn client_for(options: &MakeAgentCoreWebSearchOptions, region: &str) -> Client {
227 let sdk_config = match &options.sdk_config {
228 Some(config) => config.clone(),
229 None => {
230 aws_config::defaults(BehaviorVersion::latest())
231 .region(Region::new(region.to_owned()))
232 .load()
233 .await
234 }
235 };
236 let timeouts = sdk_config
237 .timeout_config()
238 .map(TimeoutConfig::to_builder)
239 .unwrap_or_default()
240 .operation_timeout(TIMEOUT)
241 .build();
242 let config = aws_sdk_bedrockagentcore::config::Builder::from(&sdk_config)
243 .region(Region::new(region.to_owned()))
244 .retry_config(RetryConfig::standard().with_max_attempts(MAX_ATTEMPTS))
245 .timeout_config(timeouts)
246 .build();
247 Client::from_conf(config)
248}
249
250#[async_trait]
251impl Invoke for Client {
252 async fn invoke(&self, query: &str, max_results: usize) -> Result<Vec<SearchResult>, CallFailure> {
253 let output = request(self, query, max_results)
254 .send()
255 .await
256 .map_err(|error| classify(&error))?;
257 Ok(results(&output))
258 }
259}
260
261#[allow(
262 clippy::cast_possible_truncation,
263 clippy::cast_possible_wrap,
264 reason = "max_results is clamped to 1..=10"
265)]
266pub(crate) fn request(client: &Client, query: &str, max_results: usize) -> InvokeWebSearchFluentBuilder {
267 client
268 .invoke_web_search()
269 .web_search_id(WEB_SEARCH_ID)
270 .search_query(query)
271 .max_results(max_results as i32)
272}
273
274pub(crate) fn results(output: &InvokeWebSearchOutput) -> Vec<SearchResult> {
276 output
277 .results()
278 .iter()
279 .map(|result| {
280 let url = result.url().unwrap_or_default();
281 let title = result.title().filter(|title| !title.is_empty()).unwrap_or(url);
282 let snippet: String = one_line(result.text()).chars().take(SNIPPET_CHARS).collect();
283 SearchResult::new(title, url, snippet)
284 })
285 .collect()
286}
287
288pub(crate) fn classify(error: &SdkError<InvokeWebSearchError, HttpResponse>) -> CallFailure {
292 let service = error.as_service_error();
293 let reason = service
294 .and_then(service_message)
295 .map_or_else(|| DisplayErrorContext(error).to_string(), ToOwned::to_owned);
296 let not_found = service.is_some_and(InvokeWebSearchError::is_resource_not_found_exception);
297 if error.raw_response().is_some_and(|raw| raw.status().as_u16() == 404) && !not_found {
298 return CallFailure::NotInRegion(reason);
299 }
300 if service.is_some_and(InvokeWebSearchError::is_access_denied_exception) {
301 return CallFailure::AccessDenied(reason);
302 }
303 if let Some(credentials) = credentials_failure(error) {
304 return CallFailure::Credentials(credentials);
305 }
306 CallFailure::Other(reason)
307}
308
309fn service_message(error: &InvokeWebSearchError) -> Option<&str> {
311 let message = match error {
312 InvokeWebSearchError::AccessDeniedException(exception) => exception.message(),
313 InvokeWebSearchError::InternalServerException(exception) => exception.message(),
314 InvokeWebSearchError::ResourceNotFoundException(exception) => exception.message(),
315 InvokeWebSearchError::ServiceUnavailableException(exception) => Some(exception.message()),
316 InvokeWebSearchError::ThrottlingException(exception) => exception.message(),
317 InvokeWebSearchError::ValidationException(exception) => Some(exception.message()),
318 _ => None,
319 };
320 message.or_else(|| error.message())
321}
322
323fn credentials_failure(error: &(dyn std::error::Error + 'static)) -> Option<String> {
326 let mut current = Some(error);
327 while let Some(error) = current {
328 if let Some(credentials) = error.downcast_ref::<CredentialsError>() {
329 let text = DisplayErrorContext(credentials).to_string();
330 let first = text.lines().next().unwrap_or_default();
331 return Some(first.trim_end_matches(" Attempted:").to_owned());
332 }
333 current = error.source();
334 }
335 None
336}
337
338#[cfg(test)]
339mod tests;