deepseek-sdk 0.6.0

DeepSeek API client for Rust.
Documentation
use derive_builder::Builder;
use serde::{Deserialize, Serialize};

use crate::{DeepSeekClient, api_post, error::DeepSeekError};

/// Request body for `POST /v1/tools/search`.
#[derive(Clone, PartialEq, Serialize, Builder)]
#[builder(
    pattern = "owned",
    setter(into, strip_option),
    build_fn(validate = "Self::validate"),
    name = "SearchRequestBuilder"
)]
pub struct SearchRequest {
    #[serde(skip_serializing)]
    pub client: DeepSeekClient,

    /// **Possible values:** `non-empty` and `<= 128 characters`
    ///
    /// The search query. Supports operators such as `site:`, `-site:`, and quoted phrases.
    /// Must contain 1 to 128 Unicode characters and cannot be all whitespace.
    pub query: String,

    /// **Possible values:** `>= 1` and `<= 50`
    ///
    /// **Default value:** `10` (server-side)
    ///
    /// The number of results to return, between 1 and 50.
    #[builder(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub count: Option<i32>,

    /// **Possible values:** `non-empty` and `<= 128 characters`
    ///
    /// The user's original question that triggered the search, between 1 and 128 characters.
    /// Providing it can improve query understanding. `null` is treated as not provided.
    #[builder(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ori_question: Option<String>,

    /// An optional IP address used to localize search results. Defaults to an empty string.
    #[builder(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub localization: Option<String>,

    /// Whether to return page content in `content`. Defaults to false; when false, `content` is always an empty string.
    #[builder(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub need_content: Option<bool>,
}

impl SearchRequestBuilder {
    fn validate(&self) -> Result<(), String> {
        // `strip_option` wraps `Option<T>` fields in another `Option`;
        // `flatten()` treats "unset" and "explicit None" uniformly.
        if let Some(query) = self.query.as_ref() {
            let chars = query.chars().count();
            if chars == 0 || chars > 128 || query.trim().is_empty() {
                return Err(
                    "query must contain 1 to 128 Unicode characters and cannot be all whitespace"
                        .to_string(),
                );
            }
        }

        if let Some(count) = self.count.flatten()
            && !(1..=50).contains(&count)
        {
            return Err("count must be between 1 and 50".to_string());
        }

        if let Some(ori_question) = self.ori_question.as_ref().and_then(|q| q.as_ref()) {
            let chars = ori_question.chars().count();
            if chars == 0 || chars > 128 || ori_question.trim().is_empty() {
                return Err("ori_question must contain 1 to 128 characters".to_string());
            }
        }

        Ok(())
    }
}

impl SearchRequest {
    /// Send the search request.
    pub async fn send(self) -> Result<SearchResponse, DeepSeekError> {
        let client = self.client.clone();
        api_post("/v1/tools/search", &self, client).await
    }
}

/// Response from `POST /v1/tools/search`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SearchResponse {
    /// The search results. Empty when the query matches no results.
    pub results: Vec<SearchResult>,
}

/// A single web search result.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SearchResult {
    /// **Possible values:** `<= 3`
    ///
    /// A relevance score from 0 to 3 that combines signals such as relevance, authority, and freshness.
    /// Scores of 1.5 or above are considered high-quality results.
    pub rerank_score: f32,

    /// The title of the search result.
    pub title: String,

    /// The URL of the search result.
    pub url: String,

    /// A short summary related to the query, typically 100 to 200 characters, intended for display in a UI.
    pub snippet: String,

    /// A long summary related to the query, typically 600 to 800 characters, intended to be read by a model.
    pub summary: String,

    /// The page content. Empty when `need_content` is `false` or when the content is unavailable.
    pub content: String,

    /// The name of the site, or `null` when unavailable.
    pub site_name: Option<String>,

    /// The URL of the site icon, or `null` when unavailable.
    pub site_icon: Option<String>,

    /// The publication time in UTC, formatted as RFC 3339, or `null` when unknown.
    pub date: Option<String>,

    /// **Possible values:** `>= -1` and `<= 4`
    ///
    /// The authority tier of the page, 0 to 4 (`-1` means unknown).
    /// Values of 3 or above indicate highly authoritative sources.
    pub authority: i32,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::DEFAULT_BASE_URL;
    use serde_json::json;

    fn client() -> DeepSeekClient {
        DeepSeekClient::new("sk-...", DEFAULT_BASE_URL.clone())
    }

    fn builder() -> SearchRequestBuilder {
        SearchRequestBuilder::default()
            .client(client())
            .query("deepseek v4")
    }

    #[test]
    fn request_serializes_query_and_skips_optional_fields() {
        let req = builder().build().unwrap();
        let value = serde_json::to_value(&req).unwrap();
        assert_eq!(value, json!({"query": "deepseek v4"}));
    }

    #[test]
    fn request_serializes_all_fields_when_set() {
        let req = builder()
            .count(5)
            .ori_question("what is deepseek v4?")
            .localization("1.2.3.4")
            .need_content(true)
            .build()
            .unwrap();
        let value = serde_json::to_value(&req).unwrap();
        assert_eq!(
            value,
            json!({
                "query": "deepseek v4",
                "count": 5,
                "ori_question": "what is deepseek v4?",
                "localization": "1.2.3.4",
                "need_content": true
            })
        );
    }

    #[test]
    fn validation_accepts_boundary_values() {
        assert!(builder().count(1).build().is_ok());
        assert!(builder().count(50).build().is_ok());
        let query_128 = "a".repeat(128);
        assert!(builder().query(query_128).build().is_ok());
    }

    #[test]
    fn validation_rejects_out_of_range_values() {
        assert!(builder().count(0).build().is_err());
        assert!(builder().count(51).build().is_err());
        assert!(builder().query("a".repeat(129)).build().is_err());
        assert!(builder().query("   ").build().is_err());
        assert!(builder().ori_question("b".repeat(129)).build().is_err());
        assert!(SearchRequestBuilder::default().query("q").build().is_err());
    }

    #[test]
    fn response_deserializes_api_example() {
        let value = json!({
            "results": [
                {
                    "rerank_score": 2.4,
                    "title": "DeepSeek V4 model released",
                    "url": "https://example.com/deepseek-v4",
                    "snippet": "DeepSeek V4 is now available.",
                    "summary": "DeepSeek has released the V4 model.",
                    "content": "DeepSeek V4 is now generally available...",
                    "site_name": "Example News",
                    "site_icon": "https://example.com/favicon.ico",
                    "date": "2026-06-01T00:00:00+00:00",
                    "authority": 3
                },
                {
                    "rerank_score": 0.5,
                    "title": "No metadata result",
                    "url": "https://example.com/page",
                    "snippet": "snippet",
                    "summary": "summary",
                    "content": "",
                    "site_name": null,
                    "site_icon": null,
                    "date": null,
                    "authority": -1
                }
            ]
        });
        let resp: SearchResponse = serde_json::from_value(value).unwrap();
        assert_eq!(resp.results.len(), 2);
        assert_eq!(
            resp.results[0].date.as_deref(),
            Some("2026-06-01T00:00:00+00:00")
        );
        assert_eq!(resp.results[1].date, None);
        assert_eq!(resp.results[1].site_name, None);
    }
}