Valyu Rust SDK
Official Rust SDK for the Valyu AI API.
Search for AIs - Valyu's Deepsearch API gives AI the context it needs. Integrate trusted, high-quality public and proprietary sources, with full-text multimodal retrieval.
Get $10 free credits for the Valyu API when you sign up at platform.valyu.ai! No credit card required.
⚠️ Alpha Release: This SDK is currently in alpha. The API is stable, but some features and interfaces may change based on user feedback. We welcome your input!
How Does It Work?
We do all the heavy lifting for you - one unified API for all data:
- Academic & Research Content - Access millions of scholarly papers, journals, and textbooks
- Real-time Web Search - Get the latest information from across the internet
- Medical Literature - Peer-reviewed studies, clinical trials, and regulatory documents
- Structured Financial Data - Stock prices, market data, and financial metrics
- Intelligent Reranking - Results across all sources are automatically sorted by relevance
- Transparent Pricing - Pay only for what you use with clear CPM (cost per thousand) pricing
Features
- Type-safe API: Full type coverage with serde support for all API endpoints
- Async/await: Built on tokio and reqwest for efficient async operations
- Builder pattern: Fluent interface for constructing complex search requests
- Comprehensive error handling: Detailed error types for all failure scenarios
- Four powerful endpoints: DeepSearch, Contents, Answer, and DeepResearch APIs
- Well documented: Extensive documentation with examples for all features
- Production ready: Designed for reliability and ease of use in production environments
Installation
Add this to your Cargo.toml:
[]
= "0.1"
= { = "1", = ["full"] }
Get your API key from platform.valyu.ai.
Quick Start
Basic Usage
use ValyuClient;
async
Advanced Usage with Builder Pattern
use ;
async
Authentication
Set your API key in one of these ways:
Environment Variable (Recommended)
Then in your code:
use env;
use ValyuClient;
let api_key = var.expect;
let client = new;
Direct Initialization
use ValyuClient;
let client = new;
Using .env File
For local development, use the dotenvy crate:
[]
= "0.15"
use env;
use ValyuClient;
async
Error Handling
The SDK uses a custom ValyuError type for detailed error handling:
use ;
async
Custom HTTP Client Configuration
use ValyuClient;
use Duration;
let http_client = builder
.timeout
.build
.unwrap;
let client = with_client;
API Reference
ValyuClient
The main client for interacting with the Valyu API.
Methods
new(api_key: impl Into<String>) -> Self- Create a new client with an API keywith_base_url(api_key, base_url) -> Self- Create client with custom base URLwith_client(api_key, reqwest::Client) -> Self- Create client with custom HTTP clientsearch(query: impl Into<String>) -> Result<DeepSearchResponse>- Simple search with default settingsdeep_search(request: &DeepSearchRequest) -> Result<DeepSearchResponse>- Advanced search with custom parameterscontents(request: &ContentsRequest) -> Result<ContentsResponse>- Extract content from URLsanswer(request: &AnswerRequest) -> Result<AnswerResponse>- Get AI-powered answersask(query: impl Into<String>) -> Result<AnswerResponse>- Simple answer with defaultsdeepresearch_create(request: &DeepResearchCreateRequest) -> Result<DeepResearchCreateResponse>- Create async research taskdeepresearch_status(task_id) -> Result<DeepResearchStatusResponse>- Get task statusdeepresearch_wait(task_id, poll_interval_secs, max_wait_secs) -> Result<DeepResearchStatusResponse>- Wait for task completiondeepresearch_list(api_key_id, limit) -> Result<DeepResearchListResponse>- List tasksdeepresearch_cancel(task_id) -> Result<DeepResearchOperationResponse>- Cancel running taskdeepresearch_delete(task_id) -> Result<DeepResearchOperationResponse>- Delete taskresearch(query: impl Into<String>) -> Result<DeepResearchCreateResponse>- Simple research with defaults
DeepSearchRequest
Builder for constructing search requests with optional parameters.
Constructor
new(query: impl Into<String>) -> Self- Create a new request with just a query
Builder Methods
with_max_results(max: u8) -> Self- Set max results (1-20)with_search_type(type: impl Into<String>) -> Self- Set search type: "all", "web", or "proprietary"with_fast_mode(enabled: bool) -> Self- Enable fast mode for reduced latencywith_response_length(length: impl Into<String>) -> Self- Set response length: "short", "medium", "large", or "max"with_relevance_threshold(threshold: f64) -> Self- Set relevance threshold (0.0-1.0)with_included_sources(sources: Vec<String>) -> Self- Specify sources to includewith_excluded_sources(sources: Vec<String>) -> Self- Specify sources to excludewith_date_range(start: impl Into<String>, end: impl Into<String>) -> Self- Set date range (YYYY-MM-DD format)with_max_price(price: f64) -> Self- Set maximum CPM pricewith_category(category: impl Into<String>) -> Self- Set category filterwith_country_code(code: impl Into<String>) -> Self- Set country code (2-letter ISO)with_is_tool_call(is_tool_call: bool) -> Self- Set whether this is a tool call
ContentsRequest
Builder for URL content extraction requests.
Constructor
new(urls: Vec<String>) -> Self- Create request with URLs (1-10)
Builder Methods
with_response_length(length: impl Into<String>) -> Self- Set response length presetwith_custom_response_length(chars: i32) -> Self- Set custom character limit (1K-1M)with_extract_effort(effort: impl Into<String>) -> Self- Set extraction effort: "normal", "high", or "auto"with_summary(enabled: bool) -> Self- Enable/disable default summarizationwith_summary_instructions(instructions: impl Into<String>) -> Self- Set custom summary instructionswith_summary_schema(schema: serde_json::Value) -> Self- Set JSON schema for structured extractionwith_max_price_dollars(max_price: f64) -> Self- Set maximum price in dollars
AnswerRequest
Builder for AI-powered answer requests.
Constructor
new(query: impl Into<String>) -> Self- Create request with query
Builder Methods
with_system_instructions(instructions: impl Into<String>) -> Self- Set custom AI instructions (max 2000 chars)with_structured_output(schema: serde_json::Value) -> Self- Set JSON schema for structured responsewith_search_type(type: impl Into<String>) -> Self- Set search type: "all", "web", or "proprietary"with_fast_mode(enabled: bool) -> Self- Enable fast modewith_data_max_price(price: f64) -> Self- Set maximum data CPM pricewith_included_sources(sources: Vec<String>) -> Self- Set included sourceswith_excluded_sources(sources: Vec<String>) -> Self- Set excluded sourceswith_date_range(start, end) -> Self- Set date range filterwith_country_code(code: impl Into<String>) -> Self- Set country code
Response Types
DeepSearchResponse
Fields:
success: bool- Whether the request succeedederror: Option<String>- Error message if failedtx_id: Option<String>- Transaction IDquery: Option<String>- The search queryresults: Option<Vec<SearchResult>>- Array of search resultsresults_by_source: Option<ResultsBySource>- Breakdown of results by sourcetotal_deduction_dollars: Option<f64>- Cost in dollarstotal_characters: Option<i32>- Total characters in results
SearchResult
Individual search result with fields including:
title: Option<String>- Result titleurl: Option<String>- Result URLcontent: Option<String>- Result content/snippetsource: Option<String>- Source typepublication_date: Option<String>- Publication dateauthors: Option<Vec<String>>- List of authorscitation: Option<String>- Citation information- And more...
ContentsResponse
Fields:
success: bool- Whether request succeededresults: Option<Vec<ContentResult>>- Extracted content resultsurls_requested: Option<i32>- Number of URLs requestedurls_processed: Option<i32>- Number successfully processedurls_failed: Option<i32>- Number that failedtotal_cost_dollars: Option<f64>- Total cost
AnswerResponse
Fields:
success: bool- Whether request succeededcontents: Option<serde_json::Value>- AI-generated answer (string or structured)data_type: Option<String>- "unstructured" or "structured"search_results: Option<Vec<AnswerSearchResult>>- Sources usedsearch_metadata: Option<AnswerSearchMetadata>- Search metadataai_usage: Option<AiUsage>- Token usage statisticscost: Option<AnswerCost>- Cost breakdown (search + AI)
DeepResearchCreateRequest
Builder for creating comprehensive async research tasks.
Constructor
new(input: impl Into<String>) -> Self- Create a new research request
Builder Methods
with_mode(mode: DeepResearchMode) -> Self- Set research mode:Fast,Lite, orHeavywith_output_formats(formats: Vec<String>) -> Self- Set output formats: ["markdown"], ["markdown", "pdf"]with_structured_output(schema: serde_json::Value) -> Self- Use JSON schema for structured outputwith_strategy(strategy: impl Into<String>) -> Self- Set natural language research strategywith_search(config: DeepResearchSearchConfig) -> Self- Set search configurationwith_urls(urls: Vec<String>) -> Self- Add URLs to extract content from (max 10)with_files(files: Vec<DeepResearchFileAttachment>) -> Self- Add file attachments (max 10)with_mcp_servers(servers: Vec<DeepResearchMCPServerConfig>) -> Self- Add MCP servers (max 5)with_code_execution(enabled: bool) -> Self- Enable/disable code executionwith_previous_reports(ids: Vec<String>) -> Self- Use previous reports as context (max 3)with_webhook_url(url: impl Into<String>) -> Self- Set webhook for completion notificationwith_metadata(metadata: serde_json::Value) -> Self- Set custom metadata
DeepResearchMode
Research mode options:
Fast- Quick lookups, simple questions (1-2 min, $0.15)Lite- Moderate research depth (5-10 min, $0.50)Heavy- Comprehensive analysis (15-90 min, $1.50)
DeepResearchStatusResponse
Fields:
success: bool- Whether request succeededdeepresearch_id: Option<String>- Task identifierstatus: Option<DeepResearchStatus>- Current status: Queued, Running, Completed, Failed, Cancelledquery: Option<String>- Original querymode: Option<DeepResearchMode>- Research mode usedprogress: Option<DeepResearchProgress>- Current/total steps (when running)output: Option<serde_json::Value>- Research output (when completed)pdf_url: Option<String>- PDF download URL (if requested)images: Option<Vec<DeepResearchImage>>- Generated imagessources: Option<Vec<DeepResearchSource>>- Sources usedusage: Option<DeepResearchUsage>- Cost breakdown
Examples
The repository includes several examples demonstrating different use cases:
Basic Search
use ValyuClient;
let client = new;
let response = client.search.await?;
println!;
Academic Research
Search academic papers on specific topics:
use DeepSearchRequest;
let request = new
.with_search_type
.with_included_sources
.with_relevance_threshold
.with_max_results;
let response = client.deep_search.await?;
Web Search with Date Filtering
let request = new
.with_search_type
.with_date_range
.with_max_results;
let response = client.deep_search.await?;
Hybrid Search
Search both web and proprietary sources:
let request = new
.with_search_type
.with_category
.with_relevance_threshold
.with_max_price;
let response = client.deep_search.await?;
Processing Results
let response = client.search.await?;
if response.success
Content Extraction
Basic content extraction from URLs:
use ContentsRequest;
let request = new;
let response = client.contents.await?;
if let Some = &response.results
Content with AI Summary
let request = new
.with_summary
.with_response_length;
let response = client.contents.await?;
Structured Data Extraction
use json;
let company_schema = json!;
let request = new
.with_summary_schema
.with_response_length;
let response = client.contents.await?;
AI-Powered Answers
Get AI-generated answers with sources:
use AnswerRequest;
let request = new
.with_search_type
.with_system_instructions;
let response = client.answer.await?;
if let Some = &response.contents
if let Some = &response.search_results
Structured Answer Output
use json;
let schema = json!;
let request = new
.with_structured_output;
let response = client.answer.await?;
Multiple URLs Processing
let request = new
.with_summary_instructions
.with_max_price_dollars;
let response = client.contents.await?;
println!;
println!;
DeepResearch (Async Research Tasks)
Perform comprehensive async research:
use ;
// Create a research task
let request = new
.with_mode
.with_output_formats;
let task = client.deepresearch_create.await?;
println!;
// Wait for completion
let result = client.deepresearch_wait.await?;
// Access results
if let Some = &result.output
if let Some = &result.sources
if let Some = &result.usage
All Examples
# Basic search example
# Advanced search with custom parameters
# Content extraction from URLs
# AI-powered answers
# Structured answer output
# DeepResearch async research tasks
# Custom HTTP client configuration
Note: You'll need to create a .env file with your API key:
# Edit .env and add your VALYU_API_KEY
Known Limitations
As an alpha release, there are some known limitations:
Current Limitations
-
No built-in retry logic: The SDK does not automatically retry requests that fail due to transient errors (503 Service Unavailable, 429 Rate Limit). Implement your own retry logic with exponential backoff if needed.
-
No automatic rate limiting: Rate limit management is left to the user. If you receive 429 errors, implement delays between requests or use a rate limiting library.
-
No streaming support: All responses are returned as complete objects. If the API adds streaming in the future, SDK updates will be required.
-
Limited client-side validation: The SDK performs minimal validation on request parameters (e.g., checking ranges for
max_num_results). Invalid parameters will result in API errors. -
No pagination support: If the API adds pagination for large result sets in the future, SDK updates will be needed.
-
Alpha status: As an alpha release, some APIs and type signatures may change based on user feedback. We will follow semantic versioning for breaking changes.
Workarounds
Implementing Retry Logic
use ;
use Duration;
use sleep;
async
Rate Limiting
use ;
// Simple rate limiter: max 10 requests per second
let mut last_request = now;
let min_interval = from_millis;
for query in queries
We welcome feedback on these limitations and suggestions for improvement!
Getting Started
- Sign up for a free account at platform.valyu.ai and get $10 free credits
- Get your API key from the dashboard
- Install the SDK: Add
valyu = "0.1"to yourCargo.toml - Start building with the examples above
Documentation
Minimum Supported Rust Version (MSRV)
This crate requires Rust 1.70 or later.
Support
- Documentation: docs.valyu.ai
- API Reference: Full parameter documentation above
- Examples: Check the examples/ directory in this repository
- Issues: Report bugs on GitHub
- Platform: platform.valyu.ai
License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Before submitting a PR, please make sure to:
- Run
cargo testto ensure all tests pass - Run
cargo fmtto format your code - Run
cargo clippyto check for common mistakes - Add tests for any new functionality
Feedback
This SDK is in alpha and we value your feedback! Please open an issue on GitHub to:
- Report bugs or issues
- Suggest new features
- Share your use cases
- Ask questions
Your input helps us improve the SDK for everyone.