deepseek-sdk 0.7.0

DeepSeek API client for Rust.
Documentation
//! Text to Speech (`/v1/tools/tts`).
use derive_builder::Builder;
use futures_util::StreamExt;
use serde::{Deserialize, Serialize};

use crate::{
    DeepSeekClient, DeepSeekError, DeepSeekRequest, api_post_byte_stream, api_post_bytes,
    spawn_blocking_stream,
};
use tokio::sync::mpsc;

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

    /// The text to read. Must not be empty.
    pub text: String,

    /// The voice. `stella` is a female voice and `tide` is a male voice.
    /// Defaults to `stella` on the server.
    #[builder(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub voice_id: Option<VoiceId>,

    /// The audio format of the response. `wav` returns `audio/wav`; `pcm` returns
    /// raw 16-bit signed mono PCM at 24 kHz. Defaults to `wav` on the server.
    #[builder(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub format: Option<AudioFormat>,

    /// Whether to remove Markdown formatting from the text before reading it.
    /// Defaults to `true` on the server.
    #[builder(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filter_markdown: Option<bool>,
}

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

/// Voice used for speech synthesis.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum VoiceId {
    /// Female voice.
    Stella,
    /// Male voice.
    Tide,
}

/// Audio format of the TTS response.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum AudioFormat {
    /// WAV file (`audio/wav`).
    Wav,
    /// Raw 16-bit signed mono PCM at 24 kHz (`audio/pcm`).
    Pcm,
}

/// Stream item produced by TTS streaming: a chunk of audio bytes.
pub type TTSStreamItem = Result<Vec<u8>, DeepSeekError>;

/// Blocking iterator over streamed audio chunks.
pub struct TTSStreamBlocking {
    pub rx: std::sync::mpsc::Receiver<TTSStreamItem>,
}

impl Iterator for TTSStreamBlocking {
    type Item = TTSStreamItem;

    fn next(&mut self) -> Option<Self::Item> {
        self.rx.recv().ok()
    }
}

impl DeepSeekRequest for TTSRequest {
    /// The full audio payload (WAV by default, or raw PCM when `format` is `pcm`).
    type Response = Vec<u8>;
    type StreamItem = TTSStreamItem;
    type BlockingStream = TTSStreamBlocking;

    async fn send(self) -> Result<Self::Response, DeepSeekError> {
        let client = self.client.clone();
        api_post_bytes("/v1/tools/tts", &self, client).await
    }

    async fn stream(self) -> Result<mpsc::Receiver<Self::StreamItem>, DeepSeekError> {
        let client = self.client.clone();
        let response = api_post_byte_stream("/v1/tools/tts", &self, client).await?;

        let (tx, rx) = mpsc::channel(32);
        tokio::spawn(async move {
            let mut body = response.bytes_stream();
            while let Some(chunk) = body.next().await {
                let item = chunk
                    .map(|bytes| bytes.to_vec())
                    .map_err(DeepSeekError::from);
                let failed = item.is_err();
                if tx.send(item).await.is_err() || failed {
                    break;
                }
            }
        });

        Ok(rx)
    }

    fn stream_blocking(self) -> Result<Self::BlockingStream, DeepSeekError> {
        let rx = spawn_blocking_stream(self.stream())?;
        Ok(TTSStreamBlocking { rx })
    }
}

#[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() -> TTSRequestBuilder {
        TTSRequestBuilder::default()
            .client(client())
            .text("Hello from DeepSeek.")
    }

    #[test]
    fn request_serializes_text_and_skips_optional_fields() {
        let req = builder().build().unwrap();
        assert_eq!(
            serde_json::to_value(&req).unwrap(),
            json!({"text": "Hello from DeepSeek."})
        );
    }

    #[test]
    fn request_serializes_all_fields_when_set() {
        let req = builder()
            .voice_id(VoiceId::Tide)
            .format(AudioFormat::Pcm)
            .filter_markdown(false)
            .build()
            .unwrap();
        assert_eq!(
            serde_json::to_value(&req).unwrap(),
            json!({
                "text": "Hello from DeepSeek.",
                "voice_id": "tide",
                "format": "pcm",
                "filter_markdown": false
            })
        );
    }

    #[test]
    fn enums_serialize_api_values() {
        assert_eq!(
            serde_json::to_value(VoiceId::Stella).unwrap(),
            json!("stella")
        );
        assert_eq!(serde_json::to_value(VoiceId::Tide).unwrap(), json!("tide"));
        assert_eq!(
            serde_json::to_value(AudioFormat::Wav).unwrap(),
            json!("wav")
        );
        assert_eq!(
            serde_json::to_value(AudioFormat::Pcm).unwrap(),
            json!("pcm")
        );
    }

    #[test]
    fn validation_rejects_empty_text() {
        assert!(builder().text("").build().is_err());
        assert!(builder().text("   ").build().is_err());
        assert!(TTSRequestBuilder::default().text("Hi").build().is_err());
        assert!(builder().build().is_ok());
    }
}