sermo 0.2.4

A Rust client library for interacting with various LLM provider APIs
Documentation
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
// Copyright 2025 Aquila Labs of Alberta, Canada <matt@cicero.sh>
// Licensed under either the Apache License, Version 2.0 OR the MIT License, at your option.
// You may not use this file except in compliance with one of the Licenses.
// Apache License text: https://www.apache.org/licenses/LICENSE-2.0
// MIT License text: https://opensource.org/licenses/MIT

use super::http::build_browser_client;
use super::{Tool, ToolDefinition, FunctionDefinition, arg_str, arg_usize};
use std::io;
use serde_json::Value;
use atlas_http::HttpSyncClient;
use scraper::{Html, Selector};
use url::Url;

const DDG_ENDPOINT: &str = "https://duckduckgo.com/html/";
const MARGINALIA_ENDPOINT: &str = "https://old-search.marginalia.nu/search";
const MARGINALIA_MAX_ATTEMPTS: usize = 4;
const DEFAULT_COUNT: usize = 8;
const MAX_COUNT: usize = 15;
const OLLAMA_ENDPOINT: &str = "https://ollama.com/api/web_search";
const TAVILY_ENDPOINT: &str = "https://api.tavily.com/search";

/// A single search result.
#[derive(Clone)]
pub struct SearchHit {
    pub title: String,
    pub url: String,
    pub snippet: String,
}

/// A web search backend. Implementations return the raw hits for a query.
pub trait SearchBackend {
    fn search(&self, query: &str, count: usize) -> Result<Vec<SearchHit>, io::Error>;
}

/// DuckDuckGo HTML endpoint backend (keyless).
pub struct DuckDuckGoBackend;

impl SearchBackend for DuckDuckGoBackend {
    fn search(&self, query: &str, count: usize) -> Result<Vec<SearchHit>, io::Error> {
        let mut url = Url::parse(DDG_ENDPOINT).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e.to_string()))?;
        url.query_pairs_mut().append_pair("q", query);
        let url_str = url.to_string();

        let mut client = build_browser_client();
        let res = client.get(&url_str).map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string()))?;

        if res.status_code() != 200 {
            return Err(io::Error::new(io::ErrorKind::Other, format!("search failed with status {}", res.status_code())));
        }

        match parse_results(&res.body()) {
            Some(hits) => Ok(hits.into_iter().take(count).collect()),
            None => Err(io::Error::new(io::ErrorKind::Other, "unexpected page".to_string())),
        }
    }
}

/// Marginalia Search backend (old text-friendly interface).
///
/// A small independent search engine that does not require an API key. The
/// public endpoint occasionally returns a soft "wait a moment" throttle page
/// that redirects via a JS `sst` token; we follow that token and retry.
pub struct MarginaliaBackend;

impl SearchBackend for MarginaliaBackend {
    fn search(&self, query: &str, count: usize) -> Result<Vec<SearchHit>, io::Error> {
        let mut url = Url::parse(MARGINALIA_ENDPOINT).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e.to_string()))?;
        url.query_pairs_mut().append_pair("query", query);

        let mut client = build_browser_client();
        let html = fetch_marginalia(&mut client, url.as_str())?;

        match parse_marginalia(&html) {
            Some(hits) => Ok(hits.into_iter().take(count).collect()),
            None => Err(io::Error::new(io::ErrorKind::Other, "unexpected page".to_string())),
        }
    }
}

/// Request a Marginalia results page, following any soft-throttle redirect.
fn fetch_marginalia(client: &mut HttpSyncClient, url: &str) -> Result<String, io::Error> {
    let base = Url::parse(url).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e.to_string()))?;
    let query = base.query_pairs().find(|(k, _)| k == "query").map(|(_, v)| v.into_owned()).unwrap_or_default();

    let mut current = base;
    for _ in 0..MARGINALIA_MAX_ATTEMPTS {
        let res = client.get(current.as_str()).map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string()))?;
        if res.status_code() != 200 {
            return Err(io::Error::new(io::ErrorKind::Other, format!("search failed with status {}", res.status_code())));
        }
        let body = res.body();

        // A real results page has `section.search-result` cards; a throttle page
        // does not but carries a non-empty `sst` redirect token instead.
        if parse_marginalia(&body).is_some() {
            return Ok(body);
        }
        match extract_sst_token(&body) {
            Some(token) => {
                // Soft throttle: wait a moment, then follow the redirect token.
                std::thread::sleep(std::time::Duration::from_millis(1500));
                let mut next = Url::parse(MARGINALIA_ENDPOINT).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e.to_string()))?;
                next.query_pairs_mut().append_pair("query", &query);
                next.query_pairs_mut().append_pair("sst", &token);
                current = next;
            }
            None => return Ok(body),
        }
    }
    Err(io::Error::new(io::ErrorKind::Other, "search engine rate limit".to_string()))
}

/// Extract the throttle-redirect token from a Marginalia "wait" page.
fn extract_sst_token(html: &str) -> Option<String> {
    for part in html.split("sst=").skip(1) {
        let token: String = part.chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '-').collect();
        if !token.is_empty() {
            return Some(token);
        }
    }
    None
}

/// Parse the Marginalia old-interface results page.
fn parse_marginalia(html: &str) -> Option<Vec<SearchHit>> {
    let document = Html::parse_document(html);

    let card = Selector::parse("section.search-result").expect("static selector is valid");
    if document.select(&card).next().is_none() {
        return None;
    }

    let title = Selector::parse("h2 a.title").expect("static selector is valid");
    let desc = Selector::parse("p.description").expect("static selector is valid");

    let mut hits = Vec::new();
    for res in document.select(&card) {
        let anchor = match res.select(&title).next() {
            Some(a) => a,
            None => continue,
        };
        let title_text = node_text(anchor);
        let url = anchor.attr("href").unwrap_or("").to_string();
        if title_text.is_empty() || url.is_empty() {
            continue;
        }
        let snippet = res.select(&desc).next().map(node_text).unwrap_or_default();
        hits.push(SearchHit { title: title_text, url, snippet });
    }

    Some(hits)
}

/// Ollama Web Search API backend. Activated when an API key is provided.
pub struct OllamaSearchBackend {
    api_key: String,
    api_url: String,
}

impl SearchBackend for OllamaSearchBackend {
    fn search(&self, query: &str, count: usize) -> Result<Vec<SearchHit>, io::Error> {
        let body = serde_json::json!({
            "query": query,
            "max_results": count.min(10),
        });

        let mut client = build_browser_client();
        let auth_header = format!("Authorization: Bearer {}", self.api_key);
        let headers: Vec<&str> = vec![
            "Content-Type: application/json",
            &auth_header,
        ];
        let req_body = atlas_http::HttpBody::from_raw_str(&body.to_string());
        let req = atlas_http::HttpRequest::new("POST", &self.api_url, &headers, &req_body);
        let res = client.send(&req).map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string()))?;

        if res.status_code() != 200 {
            return Err(io::Error::new(io::ErrorKind::Other, format!("search failed with status {}", res.status_code())));
        }

        let v: Value = serde_json::from_str(&res.body()).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;
        let results = match v.get("results") {
            Some(Value::Array(arr)) => arr.iter().map(|r| SearchHit {
                title: r.get("title").and_then(|v| v.as_str()).unwrap_or("").to_string(),
                url: r.get("url").and_then(|v| v.as_str()).unwrap_or("").to_string(),
                snippet: r.get("content").and_then(|v| v.as_str()).unwrap_or("").to_string(),
            }).filter(|h| !h.title.is_empty()).collect(),
            _ => Vec::new(),
        };

        Ok(results)
    }
}

/// Tavily Search API backend. Paid API with a free tier.
pub struct TavilySearchBackend {
    api_key: String,
}

impl SearchBackend for TavilySearchBackend {
    fn search(&self, query: &str, count: usize) -> Result<Vec<SearchHit>, io::Error> {
        let body = serde_json::json!({
            "query": query,
            "max_results": count,
            "search_depth": "basic",
        });

        let mut client = build_browser_client();
        let headers: Vec<&str> = vec!["Content-Type: application/json"];
        let req_body = atlas_http::HttpBody::from_raw_str(&body.to_string());
        let req = atlas_http::HttpRequest::new("POST", TAVILY_ENDPOINT, &headers, &req_body);
        let res = client.send(&req).map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string()))?;

        if res.status_code() != 200 {
            return Err(io::Error::new(io::ErrorKind::Other, format!("search failed with status {}", res.status_code())));
        }

        let v: Value = serde_json::from_str(&res.body()).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;
        let results = match v.get("results") {
            Some(Value::Array(arr)) => arr.iter().map(|r| SearchHit {
                title: r.get("title").and_then(|v| v.as_str()).unwrap_or("").to_string(),
                url: r.get("url").and_then(|v| v.as_str()).unwrap_or("").to_string(),
                snippet: r.get("content").and_then(|v| v.as_str()).unwrap_or("").to_string(),
            }).filter(|h| !h.title.is_empty()).collect(),
            _ => Vec::new(),
        };

        Ok(results)
    }
}

/// The `web_search` tool. Delegates to a backend chosen based on the API key.
///
/// When an API key is provided the keyless DuckDuckGo + Marginalia backends are
/// still kept as a fallback chain, so search keeps working even if the API is
/// down or the key is invalid.
pub struct WebSearchTool {
    backends: Vec<Box<dyn SearchBackend>>,
}

impl WebSearchTool {
    pub fn new(ollama_api_key: String) -> Self {
        let mut backends: Vec<Box<dyn SearchBackend>> = Vec::new();
        if !ollama_api_key.is_empty() {
            backends.push(Box::new(OllamaSearchBackend { api_key: ollama_api_key, api_url: OLLAMA_ENDPOINT.to_string() }));
        }
        backends.push(Box::new(DuckDuckGoBackend));
        backends.push(Box::new(MarginaliaBackend));
        Self { backends }
    }

    pub fn get_definition(&self) -> ToolDefinition {
        ToolDefinition {
            tool_type: "function".to_string(),
            function: FunctionDefinition {
                name: self.name().to_string(),
                description: self.description().to_string(),
                parameters: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "query": {
                            "type": "string",
                            "description": "Search query."
                        },
                        "count": {
                            "type": "integer",
                            "description": "Maximum number of results (default 8, max 15)."
                        }
                    },
                    "required": ["query"]
                }),
            },
        }
    }
}

impl Tool for WebSearchTool {
    fn name(&self) -> &str {
        "web_search"
    }

    fn description(&self) -> &str {
        "Search the web for a query and return a list of results. Supports operators such as site: and \"quoted phrases\". The count argument is optional."
    }

    fn execute(&self, arguments: &str) -> Result<String, io::Error> {
        let data: Value = serde_json::from_str(arguments).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, format!("Invalid arguments: {}", e)))?;
        let query = arg_str(&data, "query")?;
        let count = arg_usize(&data, "count", DEFAULT_COUNT).clamp(1, MAX_COUNT);

        let mut last_err: Option<String> = None;
        for backend in &self.backends {
            match backend.search(query, count) {
                Ok(hits) if !hits.is_empty() => return Ok(format_results(&hits)),
                Ok(_) => last_err = Some("no results found".to_string()),
                Err(e) => last_err = Some(e.to_string()),
            }
        }

        match last_err {
            Some(msg) => Ok(format!("search failed: {}. Try again later or use web_fetch on a known URL.", msg)),
            None => Ok("search failed.".to_string()),
        }
    }
}

/// Parse the DuckDuckGo HTML results page.
fn parse_results(html: &str) -> Option<Vec<SearchHit>> {
    let document = Html::parse_document(html);

    let container = Selector::parse("div.results").expect("static selector is valid");
    if document.select(&container).next().is_none() {
        return None;
    }

    let result = Selector::parse("div.result").expect("static selector is valid");
    let link = Selector::parse("a.result__a").expect("static selector is valid");
    let snippet = Selector::parse(".result__snippet").expect("static selector is valid");

    let mut hits = Vec::new();
    for res in document.select(&result) {
        let href = match res.select(&link).next().and_then(|a| a.attr("href")) {
            Some(h) => h,
            None => continue,
        };
        let title = res.select(&link).next().map(node_text).unwrap_or_default();
        let url = unwrap_uddg(href);
        if is_ad_url(&url) {
            continue;
        }
        if url.is_empty() || title.is_empty() {
            continue;
        }
        let snippet_text = res.select(&snippet).next().map(node_text).unwrap_or_default();
        hits.push(SearchHit { title, url, snippet: snippet_text });
    }

    Some(hits)
}

fn node_text(el: scraper::ElementRef<'_>) -> String {
    el.text().collect::<Vec<_>>().join(" ").split_whitespace().collect::<Vec<_>>().join(" ")
}

fn unwrap_uddg(href: &str) -> String {
    let candidate = if href.starts_with("//") {
        format!("https:{}", href)
    } else {
        href.to_string()
    };

    let Ok(url) = Url::parse(&candidate) else {
        return href.to_string();
    };

    if let Some(real) = url.query_pairs().find_map(|(k, v)| (k == "uddg").then(|| v.into_owned())) {
        return real;
    }

    candidate
}

fn is_ad_url(url: &str) -> bool {
    let Ok(parsed) = Url::parse(url) else {
        return false;
    };
    let is_ddg = parsed.host_str().map(|h| h == "duckduckgo.com" || h.ends_with(".duckduckgo.com")).unwrap_or(false);
    is_ddg && parsed.path().contains("/y.js")
}

fn format_results(hits: &[SearchHit]) -> String {
    let mut out = String::new();
    for (i, hit) in hits.iter().enumerate() {
        if i > 0 {
            out.push('\n');
        }
        out.push_str(&format!("{}. {}\n   {}\n   {}", i + 1, hit.title, hit.url, hit.snippet));
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    const DDG_FIXTURE: &str = r#"<html><body>
        <div class="results" id="links">
          <div class="result results_links results_links_deep web-result">
            <a rel="nofollow" class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.com%2Fpage&amp;rut=abc">Example Title</a>
            <a class="result__snippet" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.com%2Fpage&amp;rut=abc">This is a snippet.</a>
          </div>
          <div class="result result--ad">
            <a class="result__a" href="//duckduckgo.com/y.js?u3=ad&amp;u2=example.com">Ad Title</a>
            <a class="result__snippet" href="//duckduckgo.com/y.js">Ad snippet</a>
          </div>
        </div>
        </body></html>"#;

    #[test]
    fn parses_ddg_results_page() {
        let hits = parse_results(DDG_FIXTURE).expect("fixture should be a results page");
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].title, "Example Title");
        assert_eq!(hits[0].url, "https://example.com/page");
        assert_eq!(hits[0].snippet, "This is a snippet.");
    }

    #[test]
    fn detects_unexpected_page() {
        let hits = parse_results("<html><body>Challenge required</body></html>");
        assert!(hits.is_none());
    }

    #[test]
    fn empty_results_container_is_no_results() {
        let hits = parse_results("<html><body><div class=\"results\"></div></body></html>");
        assert!(hits.is_some());
        assert!(hits.unwrap().is_empty());
    }

    #[test]
    fn unwraps_uddg() {
        let real = unwrap_uddg("//duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.com%2Fpath%3Fx%3D1");
        assert_eq!(real, "https://example.com/path?x=1");
    }

    #[test]
    fn uddg_passthrough_when_no_uddg_param() {
        let url = unwrap_uddg("https://example.com/plain");
        assert_eq!(url, "https://example.com/plain");
    }

    #[test]
    fn detects_ad_links() {
        assert!(is_ad_url("https://duckduckgo.com/y.js?u3=x"));
        assert!(!is_ad_url("https://example.com/y.js"));
    }

    #[test]
    fn formats_results_with_blank_lines() {
        let hits = vec![
            SearchHit { title: "A".into(), url: "https://a.example".into(), snippet: "snippet a".into() },
            SearchHit { title: "B".into(), url: "https://b.example".into(), snippet: "snippet b".into() },
        ];
        let out = format_results(&hits);
        assert_eq!(out, "1. A\n   https://a.example\n   snippet a\n2. B\n   https://b.example\n   snippet b");
    }

    const MARGINALIA_FIXTURE: &str = r#"<html><body>
        <section data-ms-rank="1" class="card search-result">
          <div class="url"><a rel="nofollow external" href="https://example.com/page">https://example.com/page</a></div>
          <h2> <a tabindex="-1" class="title" rel="nofollow external" href="https://example.com/page">Example Title</a> </h2>
          <p class="description">This is a description snippet.</p>
        </section>
        <section data-ms-rank="2" class="card search-result">
          <div class="url"><a rel="nofollow external" href="https://second.example/x">https://second.example/x</a></div>
          <h2> <a tabindex="-1" class="title" rel="nofollow external" href="https://second.example/x">Second Result</a> </h2>
          <p class="description">Another snippet.</p>
        </section>
        </body></html>"#;

    #[test]
    fn parses_marginalia_results_page() {
        let hits = parse_marginalia(MARGINALIA_FIXTURE).expect("fixture should be a results page");
        assert_eq!(hits.len(), 2);
        assert_eq!(hits[0].title, "Example Title");
        assert_eq!(hits[0].url, "https://example.com/page");
        assert_eq!(hits[0].snippet, "This is a description snippet.");
    }

    #[test]
    fn marginalia_detects_unexpected_page() {
        let hits = parse_marginalia("<html><body>Wait a moment</body></html>");
        assert!(hits.is_none());
    }

    #[test]
    fn extracts_sst_token_from_wait_page() {
        let html = "window.setTimeout(()=> { location.replace('/search?query=rust&sst=S-082e652404d5c7a7'); }, 1*1000);";
        assert_eq!(extract_sst_token(html).as_deref(), Some("S-082e652404d5c7a7"));
    }

    #[test]
    fn ignores_empty_sst_pagination_params() {
        let html = "<a href=\"/search?query=rust&page=2&sst=\" class=\"page-link\">2</a>";
        assert!(extract_sst_token(html).is_none());
    }
}