aboutsummaryrefslogtreecommitdiffstats
path: root/crates/asist-tools/src/search.rs
blob: c5b7e830969fbfbee716d5f48ded9b557db0d789 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
//! Web search.
//!
//! The result will be read aloud, so what matters is not a list of links but
//! an answer. That is why a search engine that summarizes is preferred
//! (Tavily returns an already written paragraph), and the headlines only come
//! along as a fallback when there is no summary.

use std::path::PathBuf;
use std::time::{Duration, Instant};

use asist_core::error::{Error, Result};
use asist_core::proc;
use asist_core::tools::Tool;
use serde_json::{json, Value};

/// Where the results come from.
#[derive(Debug, Clone)]
pub enum SearchBackend {
    /// Tavily API. It returns an already written answer besides the
    /// results, which is exactly what is needed to speak it.
    Tavily { api_key: String },
    /// SearXNG instance, your own or a trusted one. No key, but it only
    /// returns results: the model has to do the summary.
    SearxNG { base_url: String },
    /// An external program that prints the results as JSON.
    ///
    /// It is the keyless path: `scripts/search-ddgs.sh` queries DuckDuckGo and
    /// friends through the `ddgs` library. It works for anything else that writes
    /// JSON to standard output (a bridge to an MCP server, an internal search
    /// engine), so it is also the extension point of the search feature.
    ///
    /// In `args`, `{query}` and `{max}` are substituted before running.
    Command { program: PathBuf, args: Vec<String> },
}

impl SearchBackend {
    /// Default keyless backend: the script that wraps ddgs.
    pub fn ddgs(script: impl Into<PathBuf>) -> Self {
        SearchBackend::Command {
            program: script.into(),
            args: vec!["{query}".into(), "{max}".into()],
        }
    }
}

impl SearchBackend {
    pub fn label(&self) -> &'static str {
        match self {
            SearchBackend::Tavily { .. } => "Tavily",
            SearchBackend::SearxNG { .. } => "SearXNG",
            SearchBackend::Command { .. } => "command",
        }
    }
}

pub struct WebSearch {
    backend: SearchBackend,
    max_results: usize,
    timeout: Duration,
}

impl WebSearch {
    pub fn new(backend: SearchBackend, max_results: usize, timeout: Duration) -> Self {
        Self {
            backend,
            max_results: max_results.clamp(1, 10),
            timeout,
        }
    }

    pub fn backend(&self) -> &SearchBackend {
        &self.backend
    }

    fn agent(&self) -> ureq::Agent {
        ureq::Agent::config_builder()
            .timeout_global(Some(self.timeout))
            .build()
            .into()
    }

    fn fail(message: impl Into<String>) -> Error {
        Error::Tool {
            tool: "buscar_en_internet".into(),
            message: message.into(),
        }
    }

    fn tavily(&self, key: &str, query: &str) -> Result<String> {
        let body = json!({
            "query": query,
            "max_results": self.max_results,
            "search_depth": "basic",
            // The written answer is the reason to use this engine: without it
            // another model round would be spent summarizing.
            "include_answer": true,
        });
        let mut response = self
            .agent()
            .post("https://api.tavily.com/search")
            .header("Authorization", &format!("Bearer {key}"))
            .send_json(&body)
            .map_err(|e| Self::fail(describe_ureq(&e)))?;

        let parsed: Value = response
            .body_mut()
            .read_json()
            .map_err(|e| Self::fail(format!("respuesta ilegible: {e}")))?;

        let (answer, results) = extract(&parsed, self.max_results);
        compose(&answer, &results)
    }

    /// Runs the configured program and translates whatever it prints.
    fn command(&self, program: &std::path::Path, args: &[String], query: &str) -> Result<String> {
        let rendered: Vec<String> = args
            .iter()
            .map(|arg| {
                arg.replace("{query}", query)
                    .replace("{max}", &self.max_results.to_string())
            })
            .collect();

        // The arguments go to `execve` as they are: the query comes from what
        // the microphone heard, and it must never end up interpreted by a
        // shell.
        let output = proc::run(program, &rendered, self.timeout, None)
            .map_err(|e| Self::fail(e.to_string()))?;
        if !output.success() {
            return Err(Self::fail(format!(
                "el buscador falló: {}",
                output.last_error_line()
            )));
        }

        let parsed: Value = serde_json::from_slice(&output.stdout)
            .map_err(|e| Self::fail(format!("el buscador no devolvió JSON válido: {e}")))?;
        let (answer, results) = extract(&parsed, self.max_results);
        compose(&answer, &results)
    }

    fn searxng(&self, base_url: &str, query: &str) -> Result<String> {
        let url = format!(
            "{}/search?q={}&format=json&language=es",
            base_url.trim_end_matches('/'),
            urlencode(query)
        );
        let mut response = self
            .agent()
            .get(&url)
            .call()
            .map_err(|e| Self::fail(describe_ureq(&e)))?;

        let parsed: Value = response
            .body_mut()
            .read_json()
            .map_err(|e| Self::fail(format!("respuesta ilegible: {e}")))?;

        let (answer, results) = extract(&parsed, self.max_results);
        compose(&answer, &results)
    }
}

impl Tool for WebSearch {
    fn name(&self) -> &str {
        "buscar_en_internet"
    }

    fn description(&self) -> &str {
        "Busca información actual en internet y devuelve un resumen. Úsala para \
         noticias, precios, resultados, el tiempo o cualquier cosa posterior a tu \
         entrenamiento, en vez de responder de memoria."
    }

    fn parameters(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "consulta": {
                    "type": "string",
                    "description": "Qué buscar, en lenguaje natural. Por ejemplo: tiempo en Buenos Aires mañana"
                }
            },
            "required": ["consulta"]
        })
    }

    fn acknowledgement(&self) -> Option<&str> {
        Some("Déjame que lo busque.")
    }

    fn call(&self, args: &Value) -> Result<String> {
        let query = args
            .get("consulta")
            .and_then(Value::as_str)
            .map(str::trim)
            .filter(|q| !q.is_empty())
            .ok_or_else(|| Self::fail("falta «consulta»"))?;

        let started = Instant::now();
        let result = match &self.backend {
            SearchBackend::Tavily { api_key } => self.tavily(api_key, query),
            SearchBackend::SearxNG { base_url } => self.searxng(base_url, query),
            SearchBackend::Command { program, args } => self.command(program, args, query),
        };
        tracing::info!(
            target: "tools",
            backend = self.backend.label(),
            query = query,
            ms = started.elapsed().as_millis(),
            ok = result.is_ok(),
            "search"
        );
        result
    }
}

/// Pulls the answer and results out of a JSON without requiring a specific
/// shape.
///
/// Each engine names the fields its own way (`href` or `url`, `body` or
/// `content`, a bare list or inside `results`), and what matters here is that
/// a new script works without touching Rust.
fn extract(parsed: &Value, max: usize) -> (String, Vec<String>) {
    let answer = parsed
        .get("answer")
        .and_then(Value::as_str)
        .unwrap_or("")
        .trim()
        .to_string();

    let rows = parsed
        .as_array()
        .or_else(|| parsed.get("results").and_then(Value::as_array));

    let results = rows
        .map(|items| {
            items
                .iter()
                .take(max)
                .filter_map