vtcode_core/tools/web_search/
mod.rs1use super::traits::Tool;
18use crate::config::constants::tools;
19use anyhow::{Context, Result, anyhow};
20use async_trait::async_trait;
21use serde::Deserialize;
22use serde_json::{Value, json};
23use std::collections::HashMap;
24use std::sync::{Arc, Mutex};
25use std::time::{Duration, Instant};
26use vtcode_config::WebSearchConfig;
27
28mod parser;
29mod transport;
30
31pub use parser::parse_duckduckgo_html;
32use transport::duckduckgo_search;
33
34const MAX_QUERY_CHARS: usize = 500;
35const MAX_RESULTS_CAP: usize = 20;
36
37pub(crate) const WEB_SEARCH_DESCRIPTION: &str = "Searches the web with keyless DuckDuckGo HTML search and returns ranked results (title, url, snippet). Accepts { query: string (up to 500 characters), max_results?: number }. Results are cached briefly to reduce rate limiting; cooldown and session caps bound requests. Use web_fetch on a promising result URL to read full content, subject to separate approval. Returns { query, provider, count, cached, results: [{ title, url, snippet }] } or a structured error with error_type, retryable, and next_action.";
38
39pub(crate) fn web_search_parameter_schema() -> Value {
41 json!({
42 "type": "object",
43 "properties": {
44 "query": {
45 "type": "string",
46 "description": "A nonblank search query (a topic, question, or keywords), up to 500 characters.",
47 "minLength": 1,
48 "maxLength": MAX_QUERY_CHARS
49 },
50 "max_results": {
51 "type": "integer",
52 "description": "Maximum number of results to return (default: 8, max: 20)."
53 }
54 },
55 "required": ["query"],
56 "additionalProperties": false
57 })
58}
59
60#[derive(Debug, Deserialize)]
61#[serde(deny_unknown_fields)]
62struct WebSearchArgs {
63 query: String,
65 #[serde(default)]
66 max_results: Option<usize>,
67}
68
69pub struct SearchResult {
70 pub title: String,
71 pub url: String,
72 pub snippet: String,
73}
74
75impl SearchResult {
76 pub fn new(title: String, url: String, snippet: String) -> Self {
77 Self { title, url, snippet }
78 }
79}
80
81#[derive(Default)]
85struct SessionState {
86 last_request_at: Option<Instant>,
87 requests_made: u32,
88 cache: HashMap<String, CachedResults>,
89}
90
91struct CachedResults {
92 stored_at: Instant,
93 payload: Value,
94}
95
96impl SessionState {
97 fn cache_get(&self, key: &str, ttl: Duration) -> Option<Value> {
98 let entry = self.cache.get(key)?;
99 if entry.stored_at.elapsed() > ttl {
100 return None;
101 }
102 Some(entry.payload.clone())
103 }
104
105 fn cache_put(&mut self, key: String, payload: Value) {
106 self.cache.insert(key, CachedResults { stored_at: Instant::now(), payload });
107 }
108}
109
110#[derive(Clone, Default)]
114pub struct WebSearchTool {
115 config: Arc<Mutex<WebSearchConfig>>,
116 state: Arc<Mutex<SessionState>>,
117}
118
119impl WebSearchTool {
120 pub fn new() -> Self {
121 Self {
122 config: Arc::new(Mutex::new(WebSearchConfig::default())),
123 state: Arc::new(Mutex::new(SessionState::default())),
124 }
125 }
126
127 pub fn with_config(config: WebSearchConfig) -> Self {
131 Self {
132 config: Arc::new(Mutex::new(config)),
133 state: Arc::new(Mutex::new(SessionState::default())),
134 }
135 }
136
137 pub fn set_config(&self, config: WebSearchConfig) {
139 if let Ok(mut guard) = self.config.lock() {
140 *guard = config;
141 }
142 }
143
144 pub fn reset(&self) {
146 if let Ok(mut guard) = self.state.lock() {
147 *guard = SessionState::default();
148 }
149 }
150
151 fn snapshot_config(&self) -> Result<WebSearchConfig> {
152 self.config
153 .lock()
154 .map(|guard| guard.clone())
155 .map_err(|error| anyhow!("web_search config lock poisoned: {error}"))
156 }
157
158 async fn run(&self, raw_args: Value) -> Result<Value> {
159 let args: WebSearchArgs =
160 serde_json::from_value(raw_args).context("Invalid arguments for web_search. Provide a 'query' string.")?;
161
162 let query = args.query.trim().to_string();
163 if query.is_empty() || query.chars().count() > MAX_QUERY_CHARS {
164 return Err(anyhow!("web_search requires a nonblank query of at most {MAX_QUERY_CHARS} characters"));
165 }
166
167 let snapshot = self.snapshot_config()?;
168 let default_max = snapshot.max_results.clamp(1, MAX_RESULTS_CAP);
169 let max_results = args.max_results.unwrap_or(default_max).clamp(1, MAX_RESULTS_CAP);
170 let cooldown = Duration::from_millis(snapshot.cooldown_ms);
171 let cache_ttl = Duration::from_secs(snapshot.cache_ttl_secs);
172 let session_cap = snapshot.session_max_requests;
173 let provider = snapshot.provider.backend_id();
174
175 let cache_key = format!("{max_results}::{query}");
181
182 let cached = self
184 .state
185 .lock()
186 .map_err(|error| anyhow!("web_search state lock poisoned: {error}"))?
187 .cache_get(&cache_key, cache_ttl);
188 if let Some(cached) = cached {
189 return Ok(mark_cached(cached, provider));
190 }
191
192 if let Some(response) = self.admit_request(&query, provider, cooldown, session_cap)? {
196 return Ok(response);
197 }
198
199 let results = duckduckgo_search(&query, max_results, snapshot.timeout_secs).await;
200
201 match results {
202 Ok(results) => {
203 let payload = results_response(&query, provider, results);
204 self.cache_put(&cache_key, &payload)?;
205 Ok(payload)
206 }
207 Err(e) => {
208 Ok(search_error_response(&query, provider, &e.to_string()))
210 }
211 }
212 }
213
214 fn cache_put(&self, key: &str, payload: &Value) -> Result<()> {
215 let mut state = self
216 .state
217 .lock()
218 .map_err(|error| anyhow!("web_search state lock poisoned: {error}"))?;
219 state.cache_put(key.to_string(), payload.clone());
220 Ok(())
221 }
222
223 fn admit_request(
224 &self,
225 query: &str,
226 provider: &str,
227 cooldown: Duration,
228 session_cap: u32,
229 ) -> Result<Option<Value>> {
230 let mut state = self.state.lock().map_err(|e| anyhow!("web_search state lock poisoned: {e}"))?;
231 if state.requests_made >= session_cap {
232 return Ok(Some(session_cap_reached_response(provider, query, session_cap)));
233 }
234 if let Some(last) = state.last_request_at {
235 let elapsed = last.elapsed();
236 if elapsed < cooldown {
237 return Ok(Some(cooldown_response(provider, query, cooldown.saturating_sub(elapsed))));
238 }
239 }
240 state.requests_made = state.requests_made.saturating_add(1);
241 state.last_request_at = Some(Instant::now());
242 Ok(None)
243 }
244}
245
246#[derive(Debug, Clone, Copy, PartialEq, Eq)]
247struct SearchErrorClassification {
248 error_type: &'static str,
249 next_action: &'static str,
250 retryable: bool,
251}
252
253fn classify_search_error(message: &str) -> SearchErrorClassification {
257 let lower = message.to_lowercase();
258 let status = crate::tools::web_fetch::classify_helpers::extract_http_status(&lower);
259 if matches!(status, Some(202 | 403 | 429)) || lower.contains("anti-bot") || lower.contains("challenge") {
260 return SearchErrorClassification {
261 error_type: "antiban_blocked",
262 next_action: "DuckDuckGo declined this request (likely an anti-bot challenge for this network). Do not retry immediately from this network; pick a result URL from this session's earlier searches and use web_fetch on it instead, or ask the user to confirm a different search provider.",
263 retryable: false,
264 };
265 }
266 if lower.contains("response exceeds") || lower.contains("body exceeded") {
267 return SearchErrorClassification {
268 error_type: "response_too_large",
269 next_action: "DuckDuckGo returned an oversized response. Narrow the query before explicitly retrying.",
270 retryable: false,
271 };
272 }
273 if status.is_some_and(|status| (500..=599).contains(&status)) {
274 return SearchErrorClassification {
275 error_type: "upstream_error",
276 next_action: "The search service is currently unavailable. Retry once after a short delay, or use web_fetch on a known URL as a fallback.",
277 retryable: true,
278 };
279 }
280 if lower.contains("timeout") || lower.contains("timed out") {
281 return SearchErrorClassification {
282 error_type: "network_error",
283 next_action: "DuckDuckGo timed out. Retry once after a short delay, or use web_fetch on a known URL as a fallback.",
284 retryable: true,
285 };
286 }
287 SearchErrorClassification {
288 error_type: "network_error",
289 next_action: "Retry once after a short delay, or use web_fetch directly if you already know a relevant URL.",
290 retryable: true,
291 }
292}
293
294fn results_response(query: &str, provider: &str, results: Vec<SearchResult>) -> Value {
295 let count = results.len();
296 let mut payload = json!({
297 "query": query,
298 "provider": provider,
299 "count": count,
300 "cached": false,
301 "results": results
302 .into_iter()
303 .map(|result| json!({ "title": result.title, "url": result.url, "snippet": result.snippet }))
304 .collect::<Vec<_>>(),
305 });
306
307 if count == 0 {
308 payload["warning"] = json!(
309 "No results were returned. DuckDuckGo may have rate-limited the request or matched nothing. Try a different query, or wait a few seconds and try again."
310 );
311 }
312
313 payload
314}
315
316fn search_error_response(query: &str, provider: &str, message: &str) -> Value {
317 let classification = classify_search_error(message);
318 json!({
319 "error": format!("web_search failed: {message}"),
320 "query": query,
321 "provider": provider,
322 "error_type": classification.error_type,
323 "retryable": classification.retryable,
324 "next_action": classification.next_action,
325 })
326}
327
328fn mark_cached(mut payload: Value, provider: &str) -> Value {
329 if let Value::Object(map) = &mut payload {
330 map.insert("provider".to_string(), Value::String(provider.to_owned()));
331 map.insert("cached".to_string(), Value::Bool(true));
332 }
333 payload
334}
335
336fn cooldown_response(provider: &str, query: &str, wait: Duration) -> Value {
337 let retry_after_ms = wait.as_millis().clamp(1, u64::MAX as u128) as u64;
338 json!({
339 "error": "web_search cooldown active",
340 "query": query,
341 "provider": provider,
342 "error_type": "cooldown",
343 "retryable": true,
344 "retry_after_ms": retry_after_ms,
345 "next_action": format!("Wait at least {retry_after_ms} ms before the next web search to avoid being rate-limited.")
346 })
347}
348
349fn session_cap_reached_response(provider: &str, query: &str, cap: u32) -> Value {
350 json!({
351 "error": "web_search session request cap reached",
352 "query": query,
353 "provider": provider,
354 "error_type": "session_cap",
355 "retryable": false,
356 "session_max_requests": cap,
357 "request_budget_remaining": 0,
358 "next_action": format!("This session has used its {cap} web searches. Use web_fetch on a known URL or restart the session to search again.")
359 })
360}
361
362fn truncate_chars(input: &str, max_chars: usize) -> String {
367 vtcode_commons::formatting::truncate_text(input.trim(), max_chars, "…")
368}
369
370#[async_trait]
371impl Tool for WebSearchTool {
372 async fn execute(&self, args: Value) -> Result<Value> {
373 self.run(args).await
374 }
375
376 fn name(&self) -> &str {
377 tools::WEB_SEARCH
378 }
379
380 fn description(&self) -> &str {
381 WEB_SEARCH_DESCRIPTION
382 }
383}
384
385#[cfg(test)]
386mod tests;