Skip to main content
The Rust SDK is currently in alpha. The API is stable, but some features and interfaces may change based on user feedback.
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

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 DeepSearchRequest to configure advanced search parameters:
use valyu::{ValyuClient, DeepSearchRequest};

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

    let request = DeepSearchRequest::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)

ParameterTypeDescription
queryimpl Into<String>The search query string (see Prompting Guide)

Builder Methods (Optional)

MethodTypeDescriptionDefault
with_search_type()"web" | "proprietary" | "all"Search type: web only, Valyu datasets, or both"all"
with_max_results()u8Maximum results to return (1-20)10
with_max_price()f64Maximum cost per thousand retrievals (CPM)None
with_is_tool_call()boolSet to true for AI agents/toolstrue
with_relevance_threshold()f64Minimum relevance score (0.0-1.0)0.5
with_included_sources()Vec<String>Sources to search withinNone
with_excluded_sources()Vec<String>Sources to exclude from resultsNone
with_category()impl Into<String>Natural language category to guide searchNone
with_date_range()(start, end)Date filter in YYYY-MM-DD formatNone
with_country_code()impl Into<String>2-letter ISO country code to bias resultsNone
with_response_length()impl Into<String>Content length: "short", "medium", "large", or "max""short"
with_fast_mode()boolEnable fast mode for reduced latencyfalse
Check out our other guides for more information on how to best use the Search API: Quick Start.

Response Format

pub struct DeepSearchResponse {
    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:
let request = DeepSearchRequest::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:
// Web search only
let web_request = DeepSearchRequest::new("AI news")
    .with_search_type("web")
    .with_max_results(10);

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

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

Source Filtering

Control which specific sources to include or exclude:
// Include specific sources
let request = DeepSearchRequest::new("quantum computing applications")
    .with_search_type("all")
    .with_max_results(10)
    .with_included_sources(vec![
        "nature.com".to_string(),
        "science.org".to_string(),
        "valyu/valyu-arxiv".to_string(),
    ])
    .with_response_length("medium");

let response = client.deep_search(&request).await?;
// Exclude specific sources
let request = DeepSearchRequest::new("quantum computing applications")
    .with_search_type("all")
    .with_max_results(10)
    .with_excluded_sources(vec![
        "reddit.com".to_string(),
        "quora.com".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:
let request = DeepSearchRequest::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:
// Predefined lengths
let short_request = DeepSearchRequest::new("AI").with_response_length("short");   // 25k chars
let medium_request = DeepSearchRequest::new("AI").with_response_length("medium"); // 50k chars
let large_request = DeepSearchRequest::new("AI").with_response_length("large");   // 100k chars
let max_request = DeepSearchRequest::new("AI").with_response_length("max");       // Full content

Use Case Examples

Academic Research Assistant

Build a comprehensive research tool that searches across academic databases:
use valyu::{ValyuClient, DeepSearchRequest};

async fn academic_research(
    client: &ValyuClient,
    query: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let request = DeepSearchRequest::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(())
}
Search both web and proprietary sources:
let request = DeepSearchRequest::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

use valyu::{ValyuClient, DeepSearchRequest, ValyuError};

let request = DeepSearchRequest::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 for more information.