> ## 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.

# Rust SDK: DeepResearch

> Create DeepResearch tasks from Rust, pick a mode from instant to max, wait for completion or use webhooks, and get cited reports and structured output.

> [!NOTE]
>
> The Rust SDK is in **alpha**. Interfaces may change between releases; check the crate version before upgrading.

Run a multi-step investigation and retrieve a cited report or structured output. Create a task, retain its ID, then wait for completion or receive a webhook.

Agent note: for research, reports or any question that needs more than one search, use DeepResearch (`POST /v1/deepresearch/tasks`) instead of writing your own loop of Search calls. Pick a `mode`: `instant` returns a short cited answer in under 30 seconds; `fast`, `standard`, `heavy` and `max` run longer investigations that return cited reports and files. Use Search when your own model needs raw results to reason over. Docs index: [/llms.txt](https://docs.valyu.ai/llms.txt). Append `.md` to any page URL for Markdown. Docs MCP server: `https://docs.valyu.ai/mcp`. Integration guide for coding agents: [/AGENTS.md](https://docs.valyu.ai/AGENTS.md).

> [!NOTE]
>
> For the conceptual overview, search configuration, and best practices, see the [DeepResearch Guide](https://docs.valyu.ai/guides/deepresearch.md). This page is the Rust SDK method reference.

## Basic usage

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

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

    // Create a task (defaults to standard mode)
    let task = client.research("What are the key differences between RAG and fine-tuning?").await?;

    let task_id = task.deepresearch_id.as_deref().ok_or("Research task was not created")?;

    // Wait for completion - (task_id, poll_interval_secs, timeout_secs)
    let result = client.deepresearch_wait(
        task_id,
        5,
        900,
    ).await?;

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

    Ok(())
}
```

> [!NOTE]
>
> The Rust SDK does not model the `cost` and `cost_breakdown` fields of the status response yet, and the API no longer returns the legacy `usage` field, so `result.usage` is always `None`. To read a task's charge, call [`GET /v1/deepresearch/tasks/{id}/status`](https://docs.valyu.ai/api-reference/endpoint/deepresearch-status) directly.

## Research modes

Use `DeepResearchMode::Fast` (25 credits per task), `::Standard` (100 credits, the default) or `::Heavy` (500). The Rust SDK has no `max` or `instant` variant; to run `max` (2,500 credits), call the [REST API](https://docs.valyu.ai/api-reference/endpoint/deepresearch-create.md) directly. Tool and deliverable charges can apply; see [pricing](https://docs.valyu.ai/pricing.md) and the [DeepResearch guide](https://docs.valyu.ai/guides/deepresearch.md) for mode selection.

Creating a task holds its mode price against your balance. If the available balance is too low, the API returns `402` with the required and available amounts; if billing cannot be checked, it returns `503` and you should retry with backoff. See [billing and credit holds](https://docs.valyu.ai/guides/deepresearch.md#billing-and-credit-holds).

## Builder pattern

Use `DeepResearchCreateRequest` for full control, then call `client.deepresearch_create(&request)`:

```rust theme={null}
use valyu::{DeepResearchCreateRequest, DeepResearchMode};

let request = DeepResearchCreateRequest::new(
    "What are the latest advances in quantum error correction?"
)
.with_mode(DeepResearchMode::Heavy)
.with_output_formats(vec!["markdown".to_string(), "pdf".to_string()])
.with_strategy("Focus on peer-reviewed papers from 2023-2024. Include citations.");

let task = client.deepresearch_create(&request).await?;
let result = client.deepresearch_wait(
    task.deepresearch_id.as_ref().unwrap(),
    10,   // poll every 10s (heavy mode takes longer)
    7200, // 120-minute timeout
).await?;

if let Some(pdf_url) = &result.pdf_url {
    println!("PDF report: {}", pdf_url);
}
```

In production, prefer webhooks over polling. The `webhook_secret` is returned **only once** on create - store it securely:

```rust theme={null}
let request = DeepResearchCreateRequest::new("Comprehensive AI safety research")
    .with_mode(DeepResearchMode::Heavy)
    .with_webhook_url("https://your-app.com/webhooks/deepresearch");

let task = client.deepresearch_create(&request).await?;
if let Some(secret) = &task.webhook_secret {
    // store securely - not retrievable later
}
```

## Reference

> [accordion] Builder methods
>
> **`input`** (`impl Into<String>`, required) - research query or task description.
>
> | Method | Type | Description | Default |
> | - | - | - | - |
> | `with_mode()` | `DeepResearchMode` | Research mode | `Standard` |
> | `with_output_formats()` | `Vec<String>` | `["markdown"]`, `["markdown", "pdf"]` | `["markdown"]` |
> | `with_structured_output()` | `serde_json::Value` | JSON schema for structured output | None |
> | `with_strategy()` | `impl Into<String>` | Natural-language research strategy | None |
> | `with_search()` | `DeepResearchSearchConfig` | Search config (see below) | None |
> | `with_urls()` | `Vec<String>` | URLs to analyze (max 10) | None |
> | `with_files()` | `Vec<DeepResearchFileAttachment>` | File attachments (max 10) | None |
> | `with_deliverables()` | `Vec<serde_json::Value>` | Additional file outputs (max 10) | None |
> | `with_mcp_servers()` | `Vec<DeepResearchMCPServerConfig>` | MCP server configs (max 5) | None |
> | `with_code_execution()` | `bool` | Set the legacy code-execution option | Unset |
> | `with_previous_reports()` | `Vec<String>` | Previous report IDs for context (max 3) | None |
> | `with_webhook_url()` | `impl Into<String>` | Webhook URL for completion notification | None |
> | `with_metadata()` | `serde_json::Value` | Custom metadata | None |

> [accordion] Search configuration
>
> `DeepResearchSearchConfig` (passed via `with_search()`) controls which sources are queried. Request-level parameters are enforced and cannot be overridden by the agent.
>
> ```rust theme={null}
> use valyu::{DeepResearchCreateRequest, DeepResearchSearchConfig};
>
> let request = DeepResearchCreateRequest::new("Latest AI research in healthcare diagnostics")
>     .with_search(DeepResearchSearchConfig {
>         included_sources: Some(vec!["academic".to_string(), "web".to_string()]),
>         search_type: Some("all".to_string()),
>     });
> ```
>
> Source presets: `web`, `academic`, `finance`, `health`, `medical`, `chemistry`, `genomics`, `physics`, `patent`, `transportation`, `politics`, `legal`, `cybersecurity`, `environment`, `automotive`, `compliance`, `pulse`. You can also pass dataset ids, domains, or `collection:<name>`. The 0.3 SDK search configuration exposes `search_type` and `included_sources`. Use the REST API for parameters not exposed by this SDK version. See the [DeepResearch Guide](https://docs.valyu.ai/guides/deepresearch.md#search-configuration) for full detail.

> [accordion] Deliverables and file attachments
>
> This example also requires `base64 = "0.22"` and `serde_json = "1"` in Cargo.toml.
>
> ```rust theme={null}
> use valyu::{DeepResearchCreateRequest, DeepResearchFileAttachment, DeliverableStatus};
> use base64::{engine::general_purpose::STANDARD, Engine as _};
> use serde_json::json;
>
> let pdf_base64 = STANDARD.encode(std::fs::read("paper.pdf")?);
>
> let request = DeepResearchCreateRequest::new("Summarize this paper and compare with recent literature")
>     .with_files(vec![DeepResearchFileAttachment {
>         data: format!("data:application/pdf;base64,{}", pdf_base64),
>         filename: "paper.pdf".to_string(),
>         media_type: "application/pdf".to_string(),
>         context: Some("Primary research paper".to_string()),
>     }])
>     .with_deliverables(vec![
>         json!("CSV file with company names, founding year, and funding"),
>         json!("PowerPoint presentation with 5 slides"),
>     ]);
>
> let task = client.deepresearch_create(&request).await?;
> let result = client.deepresearch_wait(
>     task.deepresearch_id.as_ref().unwrap(), 10, 5400,
> ).await?;
>
> for d in result.deliverables.as_deref().unwrap_or(&[]) {
>     if d.status == DeliverableStatus::Completed {
>         println!("{}: {}", d.title, d.url);
>     }
> }
> ```
>
> Up to 10 deliverables per task (csv, xlsx, pptx, docx, pdf), generated after research completes. Supported file types: PDFs, images (PNG, JPEG, WebP), and documents.

> [accordion] Client methods
>
> ```rust theme={null}
> client.deepresearch_create(&request).await?;
> client.deepresearch_status("task-id").await?;             // status + progress
> client.deepresearch_wait("task-id", 5, 900).await?;       // (id, poll_secs, timeout_secs)
> client.deepresearch_list("api-key-id", Some(50)).await?;
> client.deepresearch_cancel("task-id").await?;
> client.deepresearch_delete("task-id").await?;
> ```

> [accordion] Response types
>
> ```rust theme={null}
> pub struct DeepResearchCreateResponse {
>     pub success: bool,
>     pub deepresearch_id: Option<String>,
>     pub status: Option<DeepResearchStatus>,
>     pub created_at: Option<String>,
>     pub webhook_secret: Option<String>,  // Only returned once - store securely
>     pub error: Option<String>,
>     // ... other optional fields
> }
>
> pub struct DeepResearchStatusResponse {
>     pub success: bool,
>     pub deepresearch_id: Option<String>,
>     pub status: Option<DeepResearchStatus>,  // Queued, Running, Completed, Failed, Cancelled
>     pub query: Option<String>,
>     pub mode: Option<DeepResearchMode>,
>     pub progress: Option<DeepResearchProgress>,  // current_step / total_steps
>     pub output: Option<serde_json::Value>,
>     pub output_type: Option<String>,             // "markdown" | "json"
>     pub pdf_url: Option<String>,
>     pub images: Option<Vec<DeepResearchImage>>,
>     pub deliverables: Option<Vec<DeliverableResult>>,
>     pub sources: Option<Vec<DeepResearchSource>>,
>     pub usage: Option<DeepResearchUsage>,    // legacy, not returned by the API
>     pub error: Option<String>,
>     // ... other optional fields
> }
> ```

> [accordion] Error handling
>
> ```rust theme={null}
> use valyu::{DeepResearchCreateRequest, ValyuError};
>
> match client.deepresearch_create(&DeepResearchCreateRequest::new("test query")).await {
>     Ok(task) if task.success => println!("Created: {:?}", task.deepresearch_id),
>     Ok(task) => eprintln!("Failed: {:?}", task.error),
>     Err(ValyuError::InvalidApiKey) => eprintln!("Invalid API key"),
>     Err(ValyuError::ApiError(msg)) if msg.contains("Insufficient credits") => {
>         eprintln!("Not enough credits - please top up");
>     }
>     Err(ValyuError::RateLimitExceeded) => eprintln!("Rate limit exceeded"),
>     Err(e) => eprintln!("Error: {}", e),
> }
> ```
>
> `deepresearch_wait` errors when the task is cancelled or the timeout is exceeded - use a longer timeout for heavy mode (about 60 minutes) and max mode (about 120 minutes).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.