deepseek-sdk 0.7.1

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

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

/// Request body for `POST /v1/tools/asr`.
///
/// The whole audio file is sent in one request as `multipart/form-data`; the
/// language is detected from the audio automatically.
#[derive(Clone, PartialEq, Serialize, Builder)]
#[builder(
    pattern = "owned",
    setter(into, strip_option),
    build_fn(validate = "Self::validate"),
    name = "ASRRequestBuilder"
)]
pub struct ASRRequest {
    #[serde(skip_serializing)]
    pub client: DeepSeekClient,

    /// The raw audio bytes: 16-bit PCM WAV or Ogg Opus, detected from the file
    /// content. At most 8 MiB and 120 seconds.
    pub file: Vec<u8>,

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

impl ASRRequestBuilder {
    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(())
    }
}

impl ASRRequest {
    /// Send the speech-to-text request.
    pub async fn send(self) -> Result<ASRResponse, DeepSeekError> {
        let part = multipart::Part::bytes(self.file).file_name(self.filename);

        let form = multipart::Form::new().part("file", part);

        api_post_multipart("/v1/tools/asr", form, self.client.clone()).await
    }
}

/// Response from `POST /v1/tools/asr`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ASRResponse {
    /// The request ID.
    pub request_id: String,
    /// The transcript.
    pub text: String,
    /// The duration of the audio, in milliseconds.
    pub duration_ms: 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() -> ASRRequestBuilder {
        ASRRequestBuilder::default()
            .client(client())
            .file(vec![0u8; 4])
            .filename("speech.wav")
    }

    #[test]
    fn validation_rejects_empty_inputs() {
        assert!(builder().file(Vec::new()).build().is_err());
        assert!(builder().filename("   ").build().is_err());
        assert!(
            ASRRequestBuilder::default()
                .file(vec![0u8])
                .filename("speech.wav")
                .build()
                .is_err()
        );
        assert!(builder().build().is_ok());
    }

    #[test]
    fn response_deserializes_api_example() {
        let value = json!({
            "request_id": "0b8c1c7e-3c0e-4d0f-9d3a-5f2a6f7e8b90",
            "text": "What is the weather like in Shanghai today?",
            "duration_ms": 3200
        });
        let resp: ASRResponse = serde_json::from_value(value).unwrap();
        assert_eq!(resp.text, "What is the weather like in Shanghai today?");
        assert_eq!(resp.duration_ms, 3200);
    }
}