websearch 0.1.1

High-performance Rust library and CLI tool for multi-provider web search. Supports Google, ArXiv, DuckDuckGo, Tavily AI, and more with aggregation strategies.
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
//! WebSearch CLI - Command-line interface for the websearch SDK
//!
//! A powerful CLI tool for searching across multiple search providers including
//! Google, Tavily, Exa, SerpAPI, DuckDuckGo, Brave, SearXNG, and ArXiv.

use clap::{Parser, Subcommand, ValueEnum};
use colored::*;
use std::env;
use websearch::{
    multi_provider::{MultiProviderConfig, MultiProviderSearch, MultiProviderStrategy, SearchOptionsMulti},
    providers::*,
    types::{DebugOptions, SafeSearch, SearchOptions, SortBy, SortOrder},
    web_search,
};

#[derive(Parser)]
#[command(name = "websearch")]
#[command(about = "Multi-provider web search CLI")]
#[command(version)]
struct Cli {
    #[command(subcommand)]
    command: Option<Commands>,

    /// Search query (when not using subcommands)
    #[arg(value_name = "QUERY")]
    query: Option<String>,

    /// Search provider
    #[arg(short, long, value_enum, default_value = "duckduckgo")]
    provider: Option<Provider>,

    /// Maximum number of results
    #[arg(short, long, default_value = "10")]
    max_results: Option<u32>,

    /// Language code (e.g., en, es, fr)
    #[arg(short, long)]
    language: Option<String>,

    /// Region code (e.g., US, UK, DE)
    #[arg(short, long)]
    region: Option<String>,

    /// Safe search setting
    #[arg(short, long, value_enum)]
    safe_search: Option<SafeSearchCli>,

    /// ArXiv paper IDs (comma-separated, for ArXiv provider)
    #[arg(long)]
    arxiv_ids: Option<String>,

    /// Sort by field (for ArXiv)
    #[arg(long, value_enum)]
    sort_by: Option<SortByCli>,

    /// Sort order (for ArXiv)
    #[arg(long, value_enum)]
    sort_order: Option<SortOrderCli>,

    /// Enable debug output
    #[arg(short, long)]
    debug: bool,

    /// Show raw provider response
    #[arg(long)]
    raw: bool,

    /// Output format
    #[arg(short, long, value_enum, default_value = "table")]
    format: OutputFormat,
}

#[derive(Subcommand)]
enum Commands {
    /// Search using multiple providers with advanced strategies
    Multi {
        /// Search query
        query: String,

        /// Multi-provider strategy
        #[arg(short, long, value_enum, default_value = "aggregate")]
        strategy: StrategyCli,

        /// Providers to use (if not specified, uses available providers)
        #[arg(short, long, value_enum)]
        providers: Vec<Provider>,

        /// Maximum number of results per provider
        #[arg(short, long, default_value = "5")]
        max_results: u32,

        /// Enable debug output
        #[arg(short, long)]
        debug: bool,

        /// Output format
        #[arg(short, long, value_enum, default_value = "table")]
        format: OutputFormat,

        /// Show provider statistics
        #[arg(long)]
        stats: bool,
    },
    /// List available providers and their status
    Providers,
}

#[derive(ValueEnum, Clone, Debug)]
enum Provider {
    Google,
    Tavily,
    Exa,
    Serpapi,
    Duckduckgo,
    Brave,
    Searxng,
    Arxiv,
}

#[derive(ValueEnum, Clone, Debug)]
enum StrategyCli {
    Failover,
    LoadBalance,
    Aggregate,
    Race,
}

#[derive(ValueEnum, Clone, Debug)]
enum SafeSearchCli {
    Off,
    Moderate,
    Strict,
}

#[derive(ValueEnum, Clone, Debug)]
enum SortByCli {
    Relevance,
    SubmittedDate,
    LastUpdatedDate,
}

#[derive(ValueEnum, Clone, Debug)]
enum SortOrderCli {
    Ascending,
    Descending,
}

#[derive(ValueEnum, Clone, Debug)]
enum OutputFormat {
    Table,
    Json,
    Simple,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let cli = Cli::parse();

    match cli.command {
        Some(Commands::Multi {
            query,
            strategy,
            providers,
            max_results,
            debug,
            format,
            stats,
        }) => {
            handle_multi_search(query, strategy, providers, max_results, debug, format, stats).await?;
        }
        Some(Commands::Providers) => {
            handle_list_providers().await?;
        }
        None => {
            // Default search behavior
            if let Some(query) = cli.query {
                let provider = cli.provider.unwrap_or(Provider::Duckduckgo);
                let max_results = cli.max_results.unwrap_or(10);

                handle_search(
                    query,
                    provider,
                    max_results,
                    cli.language,
                    cli.region,
                    cli.safe_search,
                    cli.arxiv_ids,
                    cli.sort_by,
                    cli.sort_order,
                    cli.debug,
                    cli.raw,
                    cli.format,
                )
                .await?;
            } else {
                eprintln!("{}", "Error: Search query is required".red());
                eprintln!("Usage: websearch \"your search query\" --provider duckduckgo");
                eprintln!("Try: websearch --help");
                std::process::exit(1);
            }
        }
    }

    Ok(())
}

async fn handle_search(
    query: String,
    provider: Provider,
    max_results: u32,
    language: Option<String>,
    region: Option<String>,
    safe_search: Option<SafeSearchCli>,
    arxiv_ids: Option<String>,
    sort_by: Option<SortByCli>,
    sort_order: Option<SortOrderCli>,
    debug: bool,
    raw: bool,
    format: OutputFormat,
) -> Result<(), Box<dyn std::error::Error>> {
    let provider_name = format!("{:?}", provider).to_lowercase();
    let provider_box = create_provider(provider).await?;

    // For ArXiv, use either query or IDs
    let (search_query, id_list) = if provider_name == "arxiv" {
        if let Some(ids) = arxiv_ids {
            ("".to_string(), Some(ids))
        } else {
            (query.clone(), None)
        }
    } else {
        (query.clone(), None)
    };

    let options = SearchOptions {
        query: search_query,
        id_list,
        max_results: Some(max_results),
        language,
        region,
        safe_search: safe_search.map(|s| match s {
            SafeSearchCli::Off => SafeSearch::Off,
            SafeSearchCli::Moderate => SafeSearch::Moderate,
            SafeSearchCli::Strict => SafeSearch::Strict,
        }),
        sort_by: sort_by.map(|s| match s {
            SortByCli::Relevance => SortBy::Relevance,
            SortByCli::SubmittedDate => SortBy::SubmittedDate,
            SortByCli::LastUpdatedDate => SortBy::LastUpdatedDate,
        }),
        sort_order: sort_order.map(|s| match s {
            SortOrderCli::Ascending => SortOrder::Ascending,
            SortOrderCli::Descending => SortOrder::Descending,
        }),
        debug: if debug {
            Some(DebugOptions {
                enabled: true,
                log_requests: true,
                log_responses: false,
            })
        } else {
            None
        },
        provider: provider_box,
        ..Default::default()
    };

    let results = web_search(options).await?;

    display_results(&results, &format, raw, Some(&provider_name));
    Ok(())
}

async fn handle_multi_search(
    query: String,
    strategy: StrategyCli,
    providers: Vec<Provider>,
    max_results: u32,
    debug: bool,
    format: OutputFormat,
    stats: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    let strategy = match strategy {
        StrategyCli::Failover => MultiProviderStrategy::Failover,
        StrategyCli::LoadBalance => MultiProviderStrategy::LoadBalance,
        StrategyCli::Aggregate => MultiProviderStrategy::Aggregate,
        StrategyCli::Race => MultiProviderStrategy::Aggregate, // Use Aggregate as Race strategy
    };

    let mut config = MultiProviderConfig::new(strategy);

    // If no providers specified, try to add all available ones
    let providers_to_use = if providers.is_empty() {
        get_available_providers().await
    } else {
        providers
    };

    for provider in providers_to_use {
        if let Ok(provider_box) = create_provider(provider).await {
            config = config.add_provider(provider_box);
        }
    }

    let mut multi_search = MultiProviderSearch::new(config);

    let options = SearchOptionsMulti {
        query: query.clone(),
        max_results: Some(max_results),
        debug: if debug {
            Some(DebugOptions {
                enabled: true,
                log_requests: true,
                log_responses: false,
            })
        } else {
            None
        },
        ..Default::default()
    };

    let results = multi_search.search(&options).await?;

    display_results(&results, &format, false, None);

    if stats {
        display_provider_stats(&multi_search);
    }

    Ok(())
}

async fn handle_list_providers() -> Result<(), Box<dyn std::error::Error>> {
    println!("{}", "Available Search Providers:".bold().blue());
    println!();

    let providers = [
        ("Google", "Requires GOOGLE_API_KEY and GOOGLE_CX"),
        ("Tavily", "Requires TAVILY_API_KEY (AI-powered search)"),
        ("Exa", "Requires EXA_API_KEY (semantic search)"),
        ("SerpAPI", "Requires SERPAPI_API_KEY"),
        ("DuckDuckGo", "No API key required"),
        ("Brave", "Requires BRAVE_API_KEY"),
        ("SearXNG", "Requires SEARXNG_URL"),
        ("ArXiv", "No API key required"),
    ];

    for (name, requirement) in providers {
        let status = check_provider_availability(name).await;
        let status_color = if status { "".green() } else { "".red() };
        println!("{} {} - {}", status_color, name.bold(), requirement.italic());
    }

    println!();
    println!("{}", "Set environment variables to enable providers:".bold());
    println!("export GOOGLE_API_KEY=your_key");
    println!("export GOOGLE_CX=your_search_engine_id");
    println!("export TAVILY_API_KEY=tvly-dev-your_key");
    println!("export EXA_API_KEY=your_key");
    println!("export SERPAPI_API_KEY=your_key");
    println!("export BRAVE_API_KEY=your_key");
    println!("export SEARXNG_URL=https://your-searxng-instance.com");

    Ok(())
}

async fn create_provider(provider: Provider) -> Result<Box<dyn websearch::types::SearchProvider>, Box<dyn std::error::Error>> {
    match provider {
        Provider::Google => {
            let api_key = env::var("GOOGLE_API_KEY")?;
            let cx = env::var("GOOGLE_CX")?;
            Ok(Box::new(GoogleProvider::new(&api_key, &cx)?))
        }
        Provider::Tavily => {
            let api_key = env::var("TAVILY_API_KEY")?;
            Ok(Box::new(TavilyProvider::new(&api_key)?))
        }
        Provider::Exa => {
            let api_key = env::var("EXA_API_KEY")?;
            Ok(Box::new(ExaProvider::new(&api_key)?))
        }
        Provider::Serpapi => {
            let api_key = env::var("SERPAPI_API_KEY")?;
            Ok(Box::new(SerpApiProvider::new(&api_key)?))
        }
        Provider::Duckduckgo => Ok(Box::new(DuckDuckGoProvider::new())),
        Provider::Brave => {
            let api_key = env::var("BRAVE_API_KEY")?;
            Ok(Box::new(BraveProvider::new(&api_key)?))
        }
        Provider::Searxng => {
            let url = env::var("SEARXNG_URL")?;
            Ok(Box::new(SearxNGProvider::new(&url)?))
        }
        Provider::Arxiv => Ok(Box::new(ArxivProvider::new())),
    }
}

async fn get_available_providers() -> Vec<Provider> {
    let mut available = Vec::new();

    if env::var("GOOGLE_API_KEY").is_ok() && env::var("GOOGLE_CX").is_ok() {
        available.push(Provider::Google);
    }
    if env::var("TAVILY_API_KEY").is_ok() {
        available.push(Provider::Tavily);
    }
    if env::var("EXA_API_KEY").is_ok() {
        available.push(Provider::Exa);
    }
    if env::var("SERPAPI_API_KEY").is_ok() {
        available.push(Provider::Serpapi);
    }
    available.push(Provider::Duckduckgo); // Always available
    if env::var("BRAVE_API_KEY").is_ok() {
        available.push(Provider::Brave);
    }
    if env::var("SEARXNG_URL").is_ok() {
        available.push(Provider::Searxng);
    }
    available.push(Provider::Arxiv); // Always available

    available
}

async fn check_provider_availability(provider_name: &str) -> bool {
    match provider_name {
        "Google" => env::var("GOOGLE_API_KEY").is_ok() && env::var("GOOGLE_CX").is_ok(),
        "Tavily" => env::var("TAVILY_API_KEY").is_ok(),
        "Exa" => env::var("EXA_API_KEY").is_ok(),
        "SerpAPI" => env::var("SERPAPI_API_KEY").is_ok(),
        "DuckDuckGo" => true,
        "Brave" => env::var("BRAVE_API_KEY").is_ok(),
        "SearXNG" => env::var("SEARXNG_URL").is_ok(),
        "ArXiv" => true,
        _ => false,
    }
}

fn display_results(
    results: &[websearch::types::SearchResult],
    format: &OutputFormat,
    show_raw: bool,
    provider: Option<&str>,
) {
    match format {
        OutputFormat::Json => {
            println!("{}", serde_json::to_string_pretty(results).unwrap());
        }
        OutputFormat::Simple => {
            for (i, result) in results.iter().enumerate() {
                println!("{}. {}", i + 1, result.title);
                println!("   {}", result.url);
                if let Some(snippet) = &result.snippet {
                    println!("   {}", snippet);
                }
                println!();
            }
        }
        OutputFormat::Table => {
            if let Some(provider) = provider {
                println!("{} {}", "Search Results from".bold(), provider.bold().blue());
            } else {
                println!("{}", "Search Results".bold().blue());
            }
            println!("{}", "".repeat(80).dimmed());

            for (i, result) in results.iter().enumerate() {
                println!("{}. {}", (i + 1).to_string().bold(), result.title.bold());
                println!("   🔗 {}", result.url.blue().underline());

                if let Some(domain) = &result.domain {
                    println!("   🌐 {}", domain.green());
                }

                if let Some(snippet) = &result.snippet {
                    let truncated = if snippet.len() > 200 {
                        format!("{}...", &snippet[..200])
                    } else {
                        snippet.clone()
                    };
                    println!("   📄 {}", truncated.italic());
                }

                if let Some(published_date) = &result.published_date {
                    println!("   📅 {}", published_date.yellow());
                }

                if let Some(provider) = &result.provider {
                    println!("   🔍 Provider: {}", provider.cyan());
                }

                if show_raw {
                    if let Some(raw) = &result.raw {
                        println!("   📊 Raw: {}", serde_json::to_string_pretty(raw).unwrap());
                    }
                }

                println!();
            }

            println!("{} {}", "Total results:".bold(), results.len().to_string().bold());
        }
    }
}

fn display_provider_stats(multi_search: &MultiProviderSearch) {
    let stats = multi_search.get_stats();

    println!();
    println!("{}", "Provider Statistics:".bold().blue());
    println!("{}", "".repeat(80).dimmed());

    for (provider, stat) in stats {
        println!("{}:", provider.bold());
        println!("  Total requests: {}", stat.total_requests);
        println!("  Successful: {}", stat.successful_requests.to_string().green());
        println!("  Failed: {}", stat.failed_requests.to_string().red());
        println!("  Avg response time: {:.2}ms", stat.avg_response_time_ms);
        if stat.total_requests > 0 {
            let success_rate = (stat.successful_requests as f64 / stat.total_requests as f64) * 100.0;
            println!("  Success rate: {:.1}%", success_rate);
        }
        println!();
    }
}