minimax_client/lib.rs
1//! An async Rust client for the [MiniMax](https://platform.minimaxi.com) APIs.
2//!
3//! Everything goes through [`MinimaxClient`], which owns a [`reqwest::Client`]
4//! internally. Keep one instance alive for the lifetime of your program so
5//! connections are reused; cloning it is cheap and shares the same pool.
6//!
7//! # Capabilities
8//!
9//! | Area | Methods |
10//! |------|---------|
11//! | Speech | [`tts_stream`], [`tts_synthesize`] |
12//! | Music | [`generate_lyrics`], [`generate_music`], [`stream_music`], [`stream_music_with_lyrics`] |
13//! | Covers | [`cover_preprocess`], [`generate_cover`], [`cover_generate_with_lyrics`] |
14//! | Images | [`image_generation`] |
15//! | Voices | [`get_voices`], [`voice_design`], [`delete_voice`] |
16//! | Cloning | [`upload_file`], [`voice_clone`] |
17//!
18//! [`tts_stream`]: MinimaxClient::tts_stream
19//! [`tts_synthesize`]: MinimaxClient::tts_synthesize
20//! [`generate_lyrics`]: MinimaxClient::generate_lyrics
21//! [`generate_music`]: MinimaxClient::generate_music
22//! [`stream_music`]: MinimaxClient::stream_music
23//! [`stream_music_with_lyrics`]: MinimaxClient::stream_music_with_lyrics
24//! [`cover_preprocess`]: MinimaxClient::cover_preprocess
25//! [`generate_cover`]: MinimaxClient::generate_cover
26//! [`cover_generate_with_lyrics`]: MinimaxClient::cover_generate_with_lyrics
27//! [`image_generation`]: MinimaxClient::image_generation
28//! [`get_voices`]: MinimaxClient::get_voices
29//! [`voice_design`]: MinimaxClient::voice_design
30//! [`delete_voice`]: MinimaxClient::delete_voice
31//! [`upload_file`]: MinimaxClient::upload_file
32//! [`voice_clone`]: MinimaxClient::voice_clone
33//!
34//! # Quick start
35//!
36//! ```no_run
37//! use futures_util::StreamExt;
38//! use minimax_client::{types::TtsRequest, MinimaxClient};
39//!
40//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
41//! let client = MinimaxClient::from_env()?;
42//!
43//! let request = TtsRequest {
44//! text: "Hello, world!".into(),
45//! ..Default::default()
46//! };
47//!
48//! let mut stream = client.tts_stream(&request);
49//! while let Some(chunk) = stream.next().await {
50//! let pcm = chunk?; // raw PCM i16 little-endian at 32 kHz
51//! println!("received {} bytes", pcm.len());
52//! }
53//! # Ok(())
54//! # }
55//! ```
56//!
57//! # Streaming behavior
58//!
59//! The streaming methods spawn a background Tokio task, so they must be called
60//! from within a runtime and the request begins before the stream is first
61//! polled. Chunks are buffered in an unbounded queue, which keeps the HTTP
62//! connection draining even when the consumer falls behind; if you cannot keep
63//! up with real time, write chunks to disk rather than holding them in memory.
64//! Dropping the stream stops the background task at the next chunk boundary.
65//!
66//! # Error handling
67//!
68//! Every method returns [`Result<T, Error>`](Error). [`Error`] distinguishes
69//! transport failures from MiniMax's own `base_resp` codes, and offers
70//! [`is_auth_error`](Error::is_auth_error),
71//! [`is_rate_limited`](Error::is_rate_limited), and
72//! [`is_retryable`](Error::is_retryable) so you can branch without matching on
73//! numeric codes:
74//!
75//! ```no_run
76//! # use minimax_client::{MinimaxClient, types::TtsRequest};
77//! # async fn run(client: MinimaxClient, request: TtsRequest) {
78//! match client.tts_synthesize(&request).await {
79//! Ok(result) => println!("{} bytes", result.audio_bytes.len()),
80//! Err(e) if e.is_rate_limited() => println!("slow down: {e}"),
81//! Err(e) if e.is_auth_error() => println!("check your API key: {e}"),
82//! Err(e) => println!("failed: {e}"),
83//! }
84//! # }
85//! ```
86//!
87//! # TLS
88//!
89//! The `rustls-tls` feature is enabled by default. To link against the
90//! platform's TLS stack instead, disable default features and enable
91//! `native-tls`.
92
93#![forbid(unsafe_code)]
94#![cfg_attr(docsrs, feature(doc_cfg))]
95
96pub mod error;
97pub mod types;
98
99mod http;
100mod image;
101mod music;
102mod sse;
103mod tts;
104mod voice;
105
106pub use error::{Error, Result};
107
108use std::pin::Pin;
109use std::time::Duration;
110
111use futures_util::Stream;
112use reqwest::Client;
113
114use crate::http::Http;
115
116/// The default MiniMax base URL, matching the official OpenAPI specification.
117pub const DEFAULT_BASE_URL: &str = "https://api.minimaxi.com";
118
119/// The global endpoint.
120pub const BASE_URL_GLOBAL: &str = "https://api.minimax.io";
121
122/// The western United States endpoint.
123pub const BASE_URL_US_WEST: &str = "https://api-uw.minimax.io";
124
125/// The mainland China endpoint.
126pub const BASE_URL_CHINA: &str = "https://api.minimaxi.chat";
127
128/// The environment variable read by [`MinimaxClient::from_env`].
129pub const API_KEY_ENV: &str = "MINIMAX_API_KEY";
130
131/// An async client for the MiniMax APIs.
132///
133/// Build one with [`new`](Self::new) or [`from_env`](Self::from_env), then
134/// chain the `with_*` methods to override defaults:
135///
136/// ```
137/// use std::time::Duration;
138/// use minimax_client::{MinimaxClient, BASE_URL_CHINA};
139///
140/// let client = MinimaxClient::new("your-api-key")
141/// .with_base_url(BASE_URL_CHINA)
142/// .with_timeout(Duration::from_secs(60));
143/// ```
144///
145/// Cloning is cheap and shares the underlying connection pool, so a clone per
146/// task is fine.
147#[derive(Clone, Debug)]
148pub struct MinimaxClient {
149 http: Http,
150}
151
152impl MinimaxClient {
153 /// Create a client using the given API key and the default base URL.
154 pub fn new(api_key: impl Into<String>) -> Self {
155 Self {
156 http: Http::new(api_key.into(), DEFAULT_BASE_URL.to_string()),
157 }
158 }
159
160 /// Create a client from the `MINIMAX_API_KEY` environment variable.
161 ///
162 /// # Errors
163 ///
164 /// Returns [`Error::Other`] when the variable is unset or empty.
165 pub fn from_env() -> Result<Self> {
166 let key = std::env::var(API_KEY_ENV)
167 .ok()
168 .filter(|k| !k.trim().is_empty())
169 .ok_or_else(|| Error::Other(format!("{API_KEY_ENV} is not set")))?;
170 Ok(Self::new(key))
171 }
172
173 /// Point the client at a different endpoint.
174 ///
175 /// See [`BASE_URL_GLOBAL`], [`BASE_URL_US_WEST`], and [`BASE_URL_CHINA`].
176 /// A trailing slash is fine.
177 pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
178 self.http.set_base_url(base_url.into());
179 self
180 }
181
182 /// Supply your own [`reqwest::Client`], for example to share a connection
183 /// pool or configure a proxy.
184 ///
185 /// Note that the per-request timeout set by
186 /// [`with_timeout`](Self::with_timeout) still applies on top of any
187 /// timeout configured on the supplied client.
188 pub fn with_http_client(mut self, client: Client) -> Self {
189 self.http.set_client(client);
190 self
191 }
192
193 /// Override the per-request timeout, which defaults to 5 minutes.
194 ///
195 /// The timeout covers a streaming request in full, not the gap between
196 /// chunks, so leave ample room for long generations.
197 pub fn with_timeout(mut self, timeout: Duration) -> Self {
198 self.http.set_timeout(timeout);
199 self
200 }
201
202 /// The base URL this client sends requests to.
203 pub fn base_url(&self) -> &str {
204 self.http.base_url()
205 }
206
207 // ── Text to speech ────────────────────────────────────────────────
208
209 /// Stream synthesized speech as it is produced.
210 ///
211 /// Yields raw audio chunks in the format chosen by
212 /// [`TtsAudioSettings::format`](types::TtsAudioSettings::format), which
213 /// defaults to PCM i16 little-endian at 32 kHz.
214 ///
215 /// # Panics
216 ///
217 /// Panics if called outside a Tokio runtime.
218 pub fn tts_stream(
219 &self,
220 request: &types::TtsRequest,
221 ) -> impl Stream<Item = Result<Vec<u8>>> + Send + 'static {
222 tts::stream(&self.http, request)
223 }
224
225 /// Synthesize an entire utterance in one request.
226 ///
227 /// Set [`TtsRequest::output_format`](types::TtsRequest::output_format) to
228 /// [`OutputFormat::Url`](types::OutputFormat::Url) to receive a download
229 /// link in [`TtsResult::audio_url`](types::TtsResult::audio_url) instead of
230 /// inline bytes.
231 pub async fn tts_synthesize(&self, request: &types::TtsRequest) -> Result<types::TtsResult> {
232 tts::synthesize(&self.http, request).await
233 }
234
235 // ── Lyrics ────────────────────────────────────────────────────────
236
237 /// Generate lyrics from a theme description.
238 pub async fn generate_lyrics(
239 &self,
240 request: &types::LyricsRequest,
241 ) -> Result<types::LyricsResult> {
242 music::generate_lyrics(&self.http, request).await
243 }
244
245 /// Generate lyrics, then immediately stream music that sings them.
246 ///
247 /// A convenience wrapper over [`generate_lyrics`](Self::generate_lyrics)
248 /// and [`stream_music`](Self::stream_music) that fills in
249 /// [`MusicRequest::lyrics`](types::MusicRequest::lyrics) for you and
250 /// returns both halves of the result.
251 ///
252 /// ```no_run
253 /// # use futures_util::StreamExt;
254 /// # use minimax_client::{MinimaxClient, types::{LyricsRequest, MusicRequest}};
255 /// # async fn run(client: MinimaxClient) -> Result<(), Box<dyn std::error::Error>> {
256 /// let output = client
257 /// .stream_music_with_lyrics(
258 /// LyricsRequest {
259 /// prompt: "a breezy summer pop song".into(),
260 /// ..Default::default()
261 /// },
262 /// MusicRequest {
263 /// prompt: "Pop, upbeat, female vocal".into(),
264 /// ..Default::default()
265 /// },
266 /// )
267 /// .await?;
268 ///
269 /// println!("title: {:?}", output.lyrics.title);
270 ///
271 /// let mut stream = output.stream;
272 /// while let Some(chunk) = stream.next().await {
273 /// let mp3 = chunk?;
274 /// println!("received {} bytes", mp3.len());
275 /// }
276 /// # Ok(())
277 /// # }
278 /// ```
279 pub async fn stream_music_with_lyrics(
280 &self,
281 lyrics_request: types::LyricsRequest,
282 mut music_request: types::MusicRequest,
283 ) -> Result<LyricsWithMusicStream> {
284 let lyrics = self.generate_lyrics(&lyrics_request).await?;
285 music_request.lyrics = Some(lyrics.lyrics.clone());
286
287 Ok(LyricsWithMusicStream {
288 lyrics,
289 stream: Box::pin(music::stream_music(&self.http, &music_request)),
290 })
291 }
292
293 // ── Music ─────────────────────────────────────────────────────────
294
295 /// Generate a complete track in one request.
296 pub async fn generate_music(
297 &self,
298 request: &types::MusicRequest,
299 ) -> Result<types::MusicResult> {
300 music::generate_music(&self.http, request).await
301 }
302
303 /// Stream a track over SSE as it is generated.
304 ///
305 /// Yields audio chunks in the format chosen by
306 /// [`MusicAudioSettings::format`](types::MusicAudioSettings::format), which
307 /// defaults to MP3.
308 ///
309 /// # Panics
310 ///
311 /// Panics if called outside a Tokio runtime.
312 pub fn stream_music(
313 &self,
314 request: &types::MusicRequest,
315 ) -> impl Stream<Item = Result<Vec<u8>>> + Send + 'static {
316 music::stream_music(&self.http, request)
317 }
318
319 // ── Covers ────────────────────────────────────────────────────────
320
321 /// Analyze a reference track before generating a cover. This step is free.
322 ///
323 /// Returns a `cover_feature_id` plus the transcribed lyrics, which you can
324 /// edit and pass to
325 /// [`cover_generate_with_lyrics`](Self::cover_generate_with_lyrics).
326 pub async fn cover_preprocess(
327 &self,
328 request: &types::CoverPreprocessRequest,
329 ) -> Result<types::CoverPreprocessResult> {
330 music::cover_preprocess(&self.http, request).await
331 }
332
333 /// Generate a cover directly from a reference track.
334 pub async fn generate_cover(
335 &self,
336 request: &types::CoverRequest,
337 ) -> Result<types::MusicResult> {
338 music::generate_cover(&self.http, request).await
339 }
340
341 /// Generate a cover from preprocessed features plus rewritten lyrics.
342 pub async fn cover_generate_with_lyrics(
343 &self,
344 request: &types::CoverWithLyricsRequest,
345 ) -> Result<types::MusicResult> {
346 music::cover_generate_with_lyrics(&self.http, request).await
347 }
348
349 // ── Voices ────────────────────────────────────────────────────────
350
351 /// List the voices available to your account.
352 ///
353 /// ```no_run
354 /// # use minimax_client::{MinimaxClient, types::{GetVoiceRequest, VoiceType}};
355 /// # async fn run(client: MinimaxClient) -> Result<(), Box<dyn std::error::Error>> {
356 /// let result = client
357 /// .get_voices(&GetVoiceRequest {
358 /// voice_type: VoiceType::System,
359 /// })
360 /// .await?;
361 ///
362 /// for voice in result.system_voice.unwrap_or_default() {
363 /// println!("{} — {}", voice.voice_name, voice.voice_id);
364 /// }
365 /// # Ok(())
366 /// # }
367 /// ```
368 pub async fn get_voices(
369 &self,
370 request: &types::GetVoiceRequest,
371 ) -> Result<types::GetVoiceResult> {
372 voice::get_voices(&self.http, request).await
373 }
374
375 /// Delete a cloned or designed voice. System voices cannot be deleted.
376 pub async fn delete_voice(
377 &self,
378 request: &types::DeleteVoiceRequest,
379 ) -> Result<types::DeleteVoiceResult> {
380 voice::delete_voice(&self.http, request).await
381 }
382
383 /// Create a voice from a written description of the timbre you want.
384 ///
385 /// Returns the new voice ID along with decoded preview audio.
386 ///
387 /// ```no_run
388 /// # use minimax_client::{MinimaxClient, types::VoiceDesignRequest};
389 /// # async fn run(client: MinimaxClient) -> Result<(), Box<dyn std::error::Error>> {
390 /// let result = client
391 /// .voice_design(&VoiceDesignRequest {
392 /// prompt: "a low, resonant male narrator".into(),
393 /// preview_text: "It was late, and the old house was quiet.".into(),
394 /// ..Default::default()
395 /// })
396 /// .await?;
397 ///
398 /// println!("designed {}", result.voice_id);
399 /// # Ok(())
400 /// # }
401 /// ```
402 pub async fn voice_design(
403 &self,
404 request: &types::VoiceDesignRequest,
405 ) -> Result<types::VoiceDesignResult> {
406 voice::voice_design(&self.http, request).await
407 }
408
409 // ── Images ────────────────────────────────────────────────────────
410
411 /// Generate images from a text prompt.
412 ///
413 /// ```no_run
414 /// # use minimax_client::{MinimaxClient, types::{AspectRatio, ImageRequest}};
415 /// # async fn run(client: MinimaxClient) -> Result<(), Box<dyn std::error::Error>> {
416 /// let result = client
417 /// .image_generation(&ImageRequest {
418 /// prompt: "A serene mountain landscape at sunset".into(),
419 /// aspect_ratio: Some(AspectRatio::R16x9),
420 /// ..Default::default()
421 /// })
422 /// .await?;
423 ///
424 /// for url in result.data.image_urls.unwrap_or_default() {
425 /// println!("{url}");
426 /// }
427 /// # Ok(())
428 /// # }
429 /// ```
430 pub async fn image_generation(
431 &self,
432 request: &types::ImageRequest,
433 ) -> Result<types::ImageResult> {
434 image::image_generation(&self.http, request).await
435 }
436
437 // ── Voice cloning ─────────────────────────────────────────────────
438
439 /// Upload a recording to clone from.
440 ///
441 /// Accepts MP3, M4A, and WAV between 10 seconds and 5 minutes, up to 20 MB.
442 /// The returned `file_id` feeds into [`voice_clone`](Self::voice_clone).
443 pub async fn upload_file(
444 &self,
445 request: &types::UploadFileRequest,
446 ) -> Result<types::UploadFileResult> {
447 voice::upload_file(&self.http, request).await
448 }
449
450 /// Clone a voice from a previously uploaded recording.
451 ///
452 /// ```no_run
453 /// # use minimax_client::{MinimaxClient, types::{UploadFileRequest, VoiceCloneRequest}};
454 /// # async fn run(client: MinimaxClient) -> Result<(), Box<dyn std::error::Error>> {
455 /// let upload = client
456 /// .upload_file(&UploadFileRequest {
457 /// file_data: std::fs::read("voice_sample.mp3")?,
458 /// file_name: "voice_sample.mp3".into(),
459 /// })
460 /// .await?;
461 ///
462 /// let cloned = client
463 /// .voice_clone(&VoiceCloneRequest {
464 /// file_id: upload.file_id,
465 /// voice_id: "MyClonedVoice001".into(),
466 /// text: Some("This is my cloned voice.".into()),
467 /// model: Some("speech-2.8-hd".into()),
468 /// ..Default::default()
469 /// })
470 /// .await?;
471 ///
472 /// println!("preview: {}", cloned.demo_audio);
473 /// # Ok(())
474 /// # }
475 /// ```
476 pub async fn voice_clone(
477 &self,
478 request: &types::VoiceCloneRequest,
479 ) -> Result<types::VoiceCloneResult> {
480 voice::voice_clone(&self.http, request).await
481 }
482}
483
484/// Lyrics paired with the audio stream that sings them.
485///
486/// Returned by [`MinimaxClient::stream_music_with_lyrics`].
487pub struct LyricsWithMusicStream {
488 /// The generated lyrics, including title and style tags.
489 pub lyrics: types::LyricsResult,
490 /// Audio chunks, MP3 by default.
491 pub stream: Pin<Box<dyn Stream<Item = Result<Vec<u8>>> + Send>>,
492}
493
494impl std::fmt::Debug for LyricsWithMusicStream {
495 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
496 f.debug_struct("LyricsWithMusicStream")
497 .field("lyrics", &self.lyrics)
498 .field("stream", &"<stream>")
499 .finish()
500 }
501}
502
503// Compile the README's examples as doctests so they cannot drift.
504#[cfg(doctest)]
505#[doc = include_str!("../README.md")]
506struct ReadmeDoctests;
507
508#[cfg(test)]
509mod tests {
510 use super::*;
511
512 #[test]
513 fn defaults_to_the_official_base_url() {
514 assert_eq!(MinimaxClient::new("k").base_url(), DEFAULT_BASE_URL);
515 }
516
517 #[test]
518 fn base_url_can_be_overridden() {
519 let client = MinimaxClient::new("k").with_base_url(BASE_URL_CHINA);
520 assert_eq!(client.base_url(), BASE_URL_CHINA);
521 }
522
523 #[test]
524 fn debug_output_hides_the_api_key() {
525 let rendered = format!("{:?}", MinimaxClient::new("super-secret"));
526 assert!(!rendered.contains("super-secret"));
527 }
528
529 #[test]
530 fn builders_are_chainable_and_clone_is_cheap() {
531 let client = MinimaxClient::new("k")
532 .with_base_url(BASE_URL_GLOBAL)
533 .with_timeout(Duration::from_secs(30))
534 .with_http_client(Client::new());
535 assert_eq!(client.clone().base_url(), BASE_URL_GLOBAL);
536 }
537}