deepseek-sdk 0.7.1

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

use crate::{ApiErrorEnvelope, DeepSeekClient, api_request, check_response, error::DeepSeekError};

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

    /// The file to recognize: PDF, Word (DOC, DOCX), PowerPoint (PPT, PPTX),
    /// or an image such as PNG, JPEG, WebP, GIF, BMP, or TIFF. The format is
    /// detected from the actual file content. At most 100 MiB and 1,000 pages.
    pub file: Vec<u8>,

    /// The file name sent with the multipart part.
    pub filename: String,

    /// **Possible values:** `text_recognition`, `rich_layout_recognition`
    ///
    /// `text_recognition` extracts text directly from Word and PowerPoint files
    /// without images and recognizes other files page by page.
    /// `rich_layout_recognition` recognizes every file page by page. See the
    /// [OCR guide](https://api-docs.deepseek.com/guides/ocr#response) for the output.
    pub purpose: Purpose,
}

impl OCRRequestBuilder {
    fn validate(&self) -> Result<(), String> {
        if let Some(file) = self.file.as_ref()
            && file.is_empty()
        {
            return Err("file must not be empty".to_string());
        }

        if let Some(filename) = self.filename.as_ref()
            && filename.trim().is_empty()
        {
            return Err("filename must not be empty".to_string());
        }

        Ok(())
    }
}

#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Purpose {
    TextRecognition,
    RichLayoutRecognition,
}

impl Purpose {
    pub fn text_recognition() -> Self {
        Purpose::TextRecognition
    }

    pub fn rich_layout_recognition() -> Self {
        Purpose::RichLayoutRecognition
    }

    pub fn as_str(&self) -> &'static str {
        match self {
            Purpose::TextRecognition => "text_recognition",
            Purpose::RichLayoutRecognition => "rich_layout_recognition",
        }
    }
}

impl OCRRequest {
    /// Send the OCR request.
    pub async fn send(self) -> Result<OCRResponse, DeepSeekError> {
        let part = multipart::Part::bytes(self.file).file_name(self.filename);

        let form = multipart::Form::new()
            .text("purpose", self.purpose.as_str())
            .part("file", part);

        let response = api_request(
            Method::POST,
            "/v1/tools/ocr",
            |request| request.multipart(form),
            self.client.clone(),
        )
        .await?;
        let response = check_response(response).await?;
        let text = response.text().await?;

        // Once recognition has started the status is already `200`, so a
        // failure arrives as an error envelope inside a successful response.
        if let Ok(envelope) = serde_json::from_str::<ApiErrorEnvelope>(&text) {
            return Err(DeepSeekError::api(envelope.error, Some(200), Some(text)));
        }

        serde_json::from_str::<OCRResponse>(&text)
            .map_err(|err| DeepSeekError::decode(err.to_string(), text))
    }
}

/// Response from `POST /v1/tools/ocr`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OCRResponse {
    /// The recognition ID, of the form `ocr-....`
    pub id: String,
    /// The object type, which is always `ocr.result`.
    pub object: String,
    /// The Unix timestamp (in seconds) of when the recognition was created.
    pub created: i64,
    /// **Possible values:** `text_recognition`, `rich_layout_recognition`
    ///
    /// The `purpose` of the request.
    pub purpose: Purpose,
    /// The number of pages, equal to the length of `pages`.
    pub page_count: u32,
    /// The recognition result of every page, in page order.
    pub pages: Vec<OCRPage>,
    /// The token usage of all pages. For reference only; not used for billing.
    pub usage: OCRUsage,
}

/// The recognition result of a single page.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OCRPage {
    /// The page number, starting from 0.
    pub index: u32,
    /// The raw model output for the page, without any cleanup.
    pub text: String,
    /// **Possible values:** `stop`, `length`
    ///
    /// `stop` when the page was recognized completely;
    /// `length` when the output reached the limit and the page text is incomplete.
    pub finish_reason: FinishReason,
}

#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FinishReason {
    Stop,
    Length,
}

/// Token usage, for reference only; not used for billing.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OCRUsage {
    /// The OCR input tokens of all pages. For reference only; not used for billing.
    pub input_tokens: u64,
    /// The OCR output tokens of all pages. For reference only; not used for billing.
    pub output_tokens: u64,
    /// The sum of `input_tokens` and `output_tokens`.
    pub total_tokens: u64,
}

#[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() -> OCRRequestBuilder {
        OCRRequestBuilder::default()
            .client(client())
            .file(vec![0u8; 4])
            .filename("document.pdf")
            .purpose(Purpose::TextRecognition)
    }

    #[test]
    fn purpose_serializes_api_values() {
        assert_eq!(
            serde_json::to_value(Purpose::TextRecognition).unwrap(),
            json!("text_recognition")
        );
        assert_eq!(
            serde_json::to_value(Purpose::RichLayoutRecognition).unwrap(),
            json!("rich_layout_recognition")
        );
        assert_eq!(Purpose::text_recognition().as_str(), "text_recognition");
        assert_eq!(
            Purpose::rich_layout_recognition().as_str(),
            "rich_layout_recognition"
        );
    }

    #[test]
    fn validation_rejects_empty_inputs() {
        assert!(builder().file(Vec::new()).build().is_err());
        assert!(builder().filename("  ").build().is_err());
        assert!(
            OCRRequestBuilder::default()
                .file(vec![0u8])
                .filename("document.pdf")
                .purpose(Purpose::TextRecognition)
                .build()
                .is_err()
        );
        assert!(builder().build().is_ok());
    }

    #[test]
    fn response_deserializes_api_example() {
        let value = json!({
            "id": "ocr-9b2f4c1e-3c0e-4d0f-9d3a-5f2a6f7e8b90",
            "object": "ocr.result",
            "created": 1762790000,
            "purpose": "text_recognition",
            "page_count": 2,
            "pages": [
                {"index": 0, "text": "first page", "finish_reason": "stop"},
                {"index": 1, "text": "second page", "finish_reason": "length"}
            ],
            "usage": {"input_tokens": 1536, "output_tokens": 412, "total_tokens": 1948}
        });
        let resp: OCRResponse = serde_json::from_value(value).unwrap();
        assert_eq!(resp.purpose, Purpose::TextRecognition);
        assert_eq!(resp.page_count, 2);
        assert_eq!(resp.pages.len(), 2);
        assert_eq!(resp.pages[1].finish_reason, FinishReason::Length);
        assert_eq!(resp.usage.total_tokens, 1948);
    }
}