> ## Documentation Index
> Fetch the complete documentation index at: https://docs.valyu.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Search API

> Advanced search across web and proprietary data sources with the Valyu Rust SDK

<Note>
  The Rust SDK is currently in **alpha**. The API is stable, but some features and interfaces may change based on user feedback.
</Note>

The Search API provides powerful search capabilities across web and proprietary data sources, returning relevant content optimized for AI applications and RAG pipelines.

## Basic Usage

```rust theme={null}
use valyu::ValyuClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = ValyuClient::new("your-api-key");

    let response = client.search("What are the latest developments in quantum computing?").await?;

    if let Some(results) = &response.results {
        println!("Found {} results", results.len());
        for result in results {
            println!("Title: {}", result.title.as_deref().unwrap_or("Untitled"));
            println!("URL: {}", result.url.as_deref().unwrap_or("No URL"));
            if let Some(content) = &result.content {
                println!("Content: {}...", &content[..200.min(content.len())]);
            }
        }
    }

    Ok(())
}
```

## Advanced Usage with Builder Pattern

Use `SearchRequest` to configure advanced search parameters:

```rust theme={null}
use valyu::{ValyuClient, SearchRequest};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = ValyuClient::new("your-api-key");

    let request = SearchRequest::new("artificial intelligence")
        .with_max_results(10)
        .with_search_type("web")
        .with_fast_mode(true)
        .with_response_length("medium")
        .with_relevance_threshold(0.7)
        .with_date_range("2024-01-01", "2024-12-31");

    let response = client.deep_search(&request).await?;

    println!("Transaction ID: {}", response.tx_id.as_deref().unwrap_or("N/A"));
    println!("Cost: ${:.4}", response.total_deduction_dollars.unwrap_or(0.0));

    Ok(())
}
```

## Parameters

### Query (Required)

| Parameter | Type                | Description                                                        |
| --------- | ------------------- | ------------------------------------------------------------------ |
| `query`   | `impl Into<String>` | The search query string (see [Prompting Guide](/search/prompting)) |

### Builder Methods (Optional)

| Method                       | Type                                  | Description                                                                                                                                                                                | Default   |
| ---------------------------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------- |
| `with_search_type()`         | `"web"` \| `"proprietary"` \| `"all"` | Search type: web only, Valyu datasets, or both                                                                                                                                             | `"all"`   |
| `with_max_results()`         | `u8`                                  | Maximum results to return (1-20)                                                                                                                                                           | 10        |
| `with_max_price()`           | `f64`                                 | Maximum cost per thousand retrievals (CPM). Not set by default. When omitted, all sources are searched regardless of cost. Setting this too low may exclude relevant higher-priced sources | None      |
| `with_is_tool_call()`        | `bool`                                | Set to `true` for AI agents/tools                                                                                                                                                          | true      |
| `with_relevance_threshold()` | `f64`                                 | Minimum relevance score (0.0-1.0)                                                                                                                                                          | 0.5       |
| `with_included_sources()`    | `Vec<String>`                         | Sources to search within                                                                                                                                                                   | None      |
| `with_excluded_sources()`    | `Vec<String>`                         | Sources to exclude from results                                                                                                                                                            | None      |
| `with_category()`            | `impl Into<String>`                   | Natural language category to guide search                                                                                                                                                  | None      |
| `with_date_range()`          | `(start, end)`                        | Date filter in YYYY-MM-DD format                                                                                                                                                           | None      |
| `with_country_code()`        | `impl Into<String>`                   | 2-letter ISO country code to bias results                                                                                                                                                  | None      |
| `with_response_length()`     | `impl Into<String>`                   | Content length: `"short"`, `"medium"`, `"large"`, or `"max"`                                                                                                                               | `"short"` |
| `with_fast_mode()`           | `bool`                                | Enable fast mode for reduced latency                                                                                                                                                       | false     |

<Tip>
  Check out our other guides for more information on how to best use the Search API: [Quick Start](/search/quickstart#more-guides).
</Tip>

## Response Format

```rust theme={null}
pub struct SearchResponse {
    pub success: bool,
    pub error: Option<String>,
    pub tx_id: Option<String>,
    pub query: Option<String>,
    pub results: Option<Vec<SearchResult>>,
    pub results_by_source: Option<ResultsBySource>,
    pub total_deduction_dollars: Option<f64>,
    pub total_characters: Option<i32>,
}

pub struct SearchResult {
    pub title: Option<String>,
    pub url: Option<String>,
    pub content: Option<String>,
    pub description: Option<String>,
    pub source: Option<String>,
    pub price: Option<f64>,
    pub length: Option<i32>,
    pub relevance_score: Option<f64>,
    pub data_type: Option<String>,
    // Additional fields for academic sources
    pub publication_date: Option<String>,
    pub authors: Option<Vec<String>>,
    pub citation: Option<String>,
    pub doi: Option<String>,
    // ... other optional fields
}
```

## Parameter Examples

### Fast Mode

Enable fast mode for quicker results:

```rust theme={null}
let request = SearchRequest::new("quantum computing")
    .with_fast_mode(true);

let response = client.deep_search(&request).await?;
```

Responses will be quicker but the content will be shorter.

### Search Type Configuration

Control which data sources to search:

```rust theme={null}
// Web search only
let web_request = SearchRequest::new("AI news")
    .with_search_type("web")
    .with_max_results(10);

// Proprietary datasets only
let proprietary_request = SearchRequest::new("transformer architecture")
    .with_search_type("proprietary")
    .with_max_results(8);

// Both web and proprietary (default)
let all_request = SearchRequest::new("machine learning")
    .with_search_type("all")
    .with_max_results(12);
```

### Source Filtering

Control which specific sources to include or exclude:

```rust theme={null}
// Include specific sources
let request = SearchRequest::new("quantum computing applications")
    .with_search_type("all")
    .with_max_results(10)
    .with_included_sources(vec![
        "valyu/valyu-arxiv".to_string(),
        "valyu/valyu-pubmed".to_string(),
        "valyu/valyu-biorxiv".to_string(),
    ])
    .with_response_length("medium");

let response = client.deep_search(&request).await?;
```

```rust theme={null}
// Exclude specific sources
let request = SearchRequest::new("quantum computing applications")
    .with_search_type("all")
    .with_max_results(10)
    .with_excluded_sources(vec![
        "example.com".to_string(),
        "example.org".to_string(),
    ])
    .with_response_length("medium");
```

You can either include or exclude sources, but not both.

### Geographic and Date Filtering

Bias results by location and time range:

```rust theme={null}
let request = SearchRequest::new("renewable energy policies")
    .with_country_code("US")
    .with_date_range("2024-01-01", "2024-12-31")
    .with_max_results(7)
    .with_category("government policy");

let response = client.deep_search(&request).await?;
```

### Response Length Control

Customize content length per result:

```rust theme={null}
// Predefined lengths
let short_request = SearchRequest::new("AI").with_response_length("short");   // 25k chars
let medium_request = SearchRequest::new("AI").with_response_length("medium"); // 50k chars
let large_request = SearchRequest::new("AI").with_response_length("large");   // 100k chars
let max_request = SearchRequest::new("AI").with_response_length("max");       // Full content
```

## Use Case Examples

### Academic Research Assistant

Build a comprehensive research tool that searches across academic databases:

```rust theme={null}
use valyu::{ValyuClient, SearchRequest};

async fn academic_research(
    client: &ValyuClient,
    query: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let request = SearchRequest::new(query)
        .with_search_type("proprietary")
        .with_included_sources(vec![
            "valyu/valyu-pubmed".to_string(),
            "valyu/valyu-arxiv".to_string(),
        ])
        .with_max_results(15)
        .with_response_length("large")
        .with_category("academic research");

    let response = client.deep_search(&request).await?;

    if response.success {
        println!("=== Academic Research Results ===");
        println!("Found papers for: \"{}\"", query);

        if let Some(results) = &response.results {
            // Group by source
            let arxiv_papers: Vec<_> = results.iter()
                .filter(|r| r.source.as_deref().map(|s| s.contains("arxiv")).unwrap_or(false))
                .collect();
            let pubmed_papers: Vec<_> = results.iter()
                .filter(|r| r.source.as_deref().map(|s| s.contains("pubmed")).unwrap_or(false))
                .collect();

            println!("\nArXiv Papers: {}", arxiv_papers.len());
            for (i, paper) in arxiv_papers.iter().enumerate() {
                println!("{}. {}", i + 1, paper.title.as_deref().unwrap_or("Untitled"));
                println!("   Relevance: {:.2}", paper.relevance_score.unwrap_or(0.0));
                println!("   URL: {}", paper.url.as_deref().unwrap_or("N/A"));
                if let Some(date) = &paper.publication_date {
                    println!("   Published: {}", date);
                }
                if let Some(authors) = &paper.authors {
                    println!("   Authors: {}", authors.join(", "));
                }
            }

            println!("\nPubMed Articles: {}", pubmed_papers.len());
            for (i, article) in pubmed_papers.iter().enumerate() {
                println!("{}. {}", i + 1, article.title.as_deref().unwrap_or("Untitled"));
                if let Some(citation) = &article.citation {
                    println!("   Citation: {}", citation);
                }
            }
        }
    }

    Ok(())
}

// Usage
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = ValyuClient::new("your-api-key");

    academic_research(&client, "COVID-19 vaccine efficacy studies").await?;
    academic_research(&client, "machine learning breakthroughs 2024").await?;

    Ok(())
}
```

### Hybrid Search

Search both web and proprietary sources:

```rust theme={null}
let request = SearchRequest::new("quantum computing breakthroughs")
    .with_search_type("all")
    .with_category("technology")
    .with_relevance_threshold(0.6)
    .with_max_price(50.0);

let response = client.deep_search(&request).await?;

if response.success {
    println!("Search cost: ${:.4}", response.total_deduction_dollars.unwrap_or(0.0));

    if let Some(by_source) = &response.results_by_source {
        println!("Sources: Web={:?}, Proprietary={:?}",
            by_source.web, by_source.proprietary);
    }

    if let Some(results) = &response.results {
        for (i, result) in results.iter().enumerate() {
            println!("\n{}. {}", i + 1, result.title.as_deref().unwrap_or("Untitled"));
            println!("   Source: {}", result.source.as_deref().unwrap_or("Unknown"));
            if let Some(content) = &result.content {
                println!("   Content: {}...", &content[..200.min(content.len())]);
            }
        }
    }
}
```

## Error Handling

```rust theme={null}
use valyu::{ValyuClient, SearchRequest, ValyuError};

let request = SearchRequest::new("test query")
    .with_max_results(5);

match client.deep_search(&request).await {
    Ok(response) => {
        if !response.success {
            eprintln!("Search failed: {:?}", response.error);

            // Handle specific error cases
            if let Some(err) = &response.error {
                if err.contains("insufficient credits") {
                    eprintln!("Please add more credits to your account");
                } else if err.contains("invalid") {
                    eprintln!("Check your search parameters");
                }
            }
            return;
        }

        // Process successful results
        println!("Transaction ID: {:?}", response.tx_id);

        if let Some(results) = &response.results {
            for (i, result) in results.iter().enumerate() {
                println!("{}. {}", i + 1, result.title.as_deref().unwrap_or("Untitled"));
                println!("   Relevance: {:.2}", result.relevance_score.unwrap_or(0.0));
                println!("   Source: {}", result.source.as_deref().unwrap_or("Unknown"));
                println!("   URL: {}", result.url.as_deref().unwrap_or("N/A"));
            }
        }
    }
    Err(ValyuError::InvalidApiKey) => eprintln!("Invalid API key"),
    Err(ValyuError::RateLimitExceeded) => eprintln!("Rate limit exceeded"),
    Err(e) => eprintln!("Error: {}", e),
}
```

## Source Types

### Web Sources

* General websites and domains
* News sites and blogs
* Forums and community sites
* Documentation sites

### Proprietary Sources

* `valyu/valyu-arxiv` - Academic papers from arXiv
* `valyu/valyu-pubmed` - Medical and life science literature
* `valyu/valyu-stocks` - Global stock market data
* And many more. Check out the [Valyu Platform Datasets](https://platform.valyu.ai/data-sources) for more information.
