Skip to main content

agentai_audio/
lib.rs

1//! # AgentAI Audio
2//!
3//! Text-to-speech, dialogues, voice cloning and voice design for
4//! [AgentAI](https://crates.io/crates/agentai): from your code with [`SpeechGenerator`], or by an
5//! agent with [`SpeechToolBox`] (feature `toolbox`).
6//!
7//! ## Speaking texts
8//!
9//! [`speech_provider`] builds a provider by name (`openai`, `elevenlabs`, `fishaudio`, `omlx`) or
10//! [`SpeechProviderKind`] and its speech model; the API key and URL come from the provider's
11//! environment variables unless you set them on the builder. Every call of the generator is a
12//! builder: set its options with `with_*` and `.await` it.
13//!
14//! ```rust,no_run
15//! use agentai_audio::{SpeechGenerator, speech_provider};
16//!
17//! # async fn run() -> Result<(), agentai_audio::AudioError> {
18//! // The API key from `OPENAI_API_KEY`
19//! let generator = SpeechGenerator::new(speech_provider("openai", "gpt-4o-mini-tts").build()?);
20//! let response = generator
21//!     .generate("Good morning")
22//!     .with_voice("alloy")
23//!     .with_instructions("Cheerful and fast")
24//!     .await?;
25//! // response.audio is an agentai `Media`, base64 data or a URL
26//! # Ok(())
27//! # }
28//! ```
29//!
30//! A voice is a [`VoiceId`]: a preset, a voice of your account or a voice you cloned or designed.
31//! OpenAI and ElevenLabs need one, or the request fails with [`AudioError::MissingVoice`]; Fish
32//! Audio and oMLX use their own voice when none is set.
33//!
34//! With [`with_storage`](SpeechGenerator::with_storage) every audio is saved in a
35//! [`MediaSave`](storage::MediaSave) and gets an ID. The [`storage`] module (from
36//! `agentai-core`) has the storage traits and [`MemoryStorage`](storage::MemoryStorage).
37//!
38//! [`SpeechRequest::with_timestamps`] asks for the time of every word, returned in
39//! [`SpeechResponse::timestamps`] as [`WordTimestamp`]s (Fish Audio; other providers return
40//! [`AudioError::Unsupported`]).
41//!
42//! ## Engines and models
43//!
44//! A provider has up to three engines, each with its own model: speech (always), dialogue
45//! ([`with_dialogue_model`](SpeechProviderBuilder::with_dialogue_model)) and voice design
46//! ([`with_design_model`](SpeechProviderBuilder::with_design_model)). An engine without a model is
47//! off: calling it returns [`AudioError::MissingModel`] without sending anything, and
48//! [`supports_dialogue`](SpeechGenerator::supports_dialogue) and
49//! [`supports_voice_design`](SpeechGenerator::supports_voice_design) tell whether it is on.
50//! `with_model` on a call overrides the engine's model for that call only. The builder fails with
51//! [`AudioError::Unsupported`] when the provider has no such engine.
52//!
53//! | Provider | Dialogue | Voice design | Voice store |
54//! |---|---|---|---|
55//! | Fish Audio | yes | yes | yes |
56//! | ElevenLabs | yes | yes | no |
57//! | oMLX | no | yes | yes |
58//! | OpenAI | no | no | no |
59//!
60//! [`SpeechProviderKind::known_models`] lists the models this crate knows and what each can do
61//! ([`AudioModel`]: `speech`, `dialogue`, `voice_design`), for example to fill a model picker;
62//! [`SpeechGenerator::list_models`] asks the API, where it can.
63//!
64//! ```rust,no_run
65//! use agentai_audio::SpeechProviderKind;
66//!
67//! # fn run() -> Result<(), agentai_audio::AudioError> {
68//! for model in SpeechProviderKind::FishAudio.known_models() {
69//!     if model.dialogue {
70//!         println!("{} ({})", model.id, model.name);
71//!     }
72//! }
73//! let provider = SpeechProviderKind::FishAudio
74//!     .builder("s2-pro")
75//!     .with_dialogue_model("drama-3")
76//!     .with_design_model("voice-design-1")
77//!     .build()?;
78//! # Ok(())
79//! # }
80//! ```
81//!
82//! ## Dialogues
83//!
84//! [`SpeechGenerator::generate_dialogue`] speaks a list of [`DialogueTurn`]s, each a voice and
85//! its plain text, as one audio, with the dialogue model. Fish Audio (`drama-3`, `s2-pro`, ...)
86//! and ElevenLabs (`eleven_v3`, `eleven_v4`) speak dialogues; the provider marks the speakers
87//! itself.
88//!
89//! ```rust,no_run
90//! use agentai_audio::{DialogueTurn, SpeechGenerator, speech_provider};
91//!
92//! # async fn run() -> Result<(), agentai_audio::AudioError> {
93//! // The API key from `ELEVENLABS_API_KEY`
94//! let provider = speech_provider("elevenlabs", "eleven_multilingual_v2")
95//!     .with_dialogue_model("eleven_v3")
96//!     .build()?;
97//! let generator = SpeechGenerator::new(provider);
98//! let response = generator
99//!     .generate_dialogue([
100//!         DialogueTurn::new("voice-a", "Ready?"),
101//!         DialogueTurn::new("voice-b", "Always."),
102//!     ])
103//!     .await?;
104//! # Ok(())
105//! # }
106//! ```
107//!
108//! Fish Audio takes a voice either as a voice model of the account or as a sample. With a
109//! [`VoiceStore`] set, the IDs found in it are sent as their samples: a request whose voices
110//! are all in the store sends samples, one whose voices are none in it sends IDs, and a mix
111//! fails with [`AudioError::InvalidRequest`] before anything is sent.
112//!
113//! ## Cloning voices
114//!
115//! [`SpeechGenerator::create_voice`] clones a voice from samples and returns its [`VoiceId`].
116//! It works with providers that can clone
117//! ([`supports_voice_cloning`](SpeechGenerator::supports_voice_cloning)): ElevenLabs, Fish Audio
118//! (a voice model in the account) and oMLX. oMLX has no voice library: it clones from a sample
119//! sent with every request, so it needs a [`VoiceStore`] that keeps the samples:
120//!
121//! ```rust,no_run
122//! use agentai::Media;
123//! use agentai_audio::{MemoryVoiceStore, SpeechGenerator, VoiceSource, speech_provider};
124//!
125//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
126//! // Settings from `OMLX_ENDPOINT` and `OMLX_API_KEY`
127//! let provider = speech_provider("omlx", "mlx-community/VoxCPM2-8bit")
128//!     .with_voice_store(MemoryVoiceStore::new())
129//!     .build()?;
130//! let generator = SpeechGenerator::new(provider);
131//! let sample = Media::from_bytes("audio/wav", std::fs::read("sample.wav")?);
132//! let voice = generator
133//!     .create_voice(
134//!         "me",
135//!         VoiceSource::samples(vec![sample], Some("What is said in the sample.")),
136//!         None,
137//!     )
138//!     .await?;
139//! let response = generator.generate("Hello").with_voice(voice).await?;
140//! # Ok(())
141//! # }
142//! ```
143//!
144//! ## Designing voices
145//!
146//! [`SpeechGenerator::design_voice`] makes voices from a description with the design model:
147//! Fish Audio (`voice-design-1`), ElevenLabs (`eleven_ttv_v3`) and oMLX (a model that turns
148//! `instructions` into a voice). It returns [`VoicePreview`]s to listen to;
149//! [`create_voice`](SpeechGenerator::create_voice) keeps one as a voice. Fish Audio returns
150//! `with_count` previews and ElevenLabs its own number; oMLX needs the text and a [`VoiceStore`]
151//! to keep a preview. ElevenLabs needs the description again to save a preview.
152//!
153//! ```rust,no_run
154//! use agentai_audio::{SpeechGenerator, speech_provider};
155//!
156//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
157//! let provider = speech_provider("fishaudio", "s2-pro")
158//!     .with_design_model("voice-design-1")
159//!     .build()?;
160//! let generator = SpeechGenerator::new(provider);
161//! let description = "A warm, calm woman with a low voice";
162//! let previews = generator
163//!     .design_voice(description)
164//!     .with_text("Welcome back.")
165//!     .with_count(2)
166//!     .await?;
167//! // Listen to `previews[n].audio`, then keep the one you like
168//! let voice = generator
169//!     .create_voice("narrator", &previews[0], Some(description))
170//!     .await?;
171//! let response = generator.generate("Good evening").with_voice(voice).await?;
172//! # Ok(())
173//! # }
174//! ```
175//!
176//! ## Tools for agents
177//!
178//! [`SpeechToolBox`] gives the agent two tools:
179//!
180//! - `generate_speech`: speaks a text (with a required file `name`, an optional `voice` and
181//!   `instructions`) and saves it in the storage.
182//! - `list_voices`: lists the voices the model can choose from.
183//!
184//! By default the model gets only the metadata of the audio as JSON ([`SpeechToolOutput::Metadata`]),
185//! because most models cannot listen; [`SpeechToolOutput::Media`] returns the audio itself.
186//! [`with_voices`](SpeechToolBox::with_voices) limits the voices to an allowlist. No tool speaks
187//! dialogues, clones or designs voices: those stay in your code.
188//!
189//! ```rust,no_run
190//! # #[cfg(feature = "toolbox")]
191//! # async fn run() -> anyhow::Result<()> {
192//! use agentai::Agent;
193//! use agentai::tool::ToolBoxSet;
194//! use agentai_audio::storage::MemoryStorage;
195//! use agentai_audio::{SpeechGenerator, SpeechToolBox, speech_provider};
196//!
197//! let generator = SpeechGenerator::new(speech_provider("openai", "gpt-4o-mini-tts").build()?);
198//! let mut tools = ToolBoxSet::new();
199//! tools.add_tool(SpeechToolBox::new(generator, MemoryStorage::new()));
200//! let agent = Agent::new("claude-haiku-5-5", "You are a voice assistant.")?.with_toolbox(tools);
201//! let result = agent
202//!     .run::<String>("Say good morning with the voice alloy and name the file greeting")
203//!     .await?;
204//! # Ok(())
205//! # }
206//! ```
207//!
208//! ## Providers
209//!
210//! The speech APIs live in [`provider`]: [`openai`](provider::openai) (OpenAI and compatible
211//! servers; OpenAI shuts its speech models down on 2027-01-06),
212//! [`elevenlabs`](provider::elevenlabs), [`fishaudio`](provider::fishaudio) and
213//! [`omlx`](provider::omlx). Each is public, with `new`, `from_env` and its own `with_*`
214//! settings, for when you build it yourself and pass it to
215//! [`SpeechGenerator::from_provider`]. Implement [`provider::SpeechProvider`] to use another API.
216//!
217//! ## Features
218#![doc = document_features::document_features!()]
219
220mod generator;
221pub mod provider;
222mod request;
223#[cfg(feature = "toolbox")]
224mod toolbox;
225mod voice_store;
226
227#[doc(inline)]
228pub use agentai_core::{base64, mime, storage};
229pub use generator::SpeechGenerator;
230pub use provider::{
231    AudioError, AudioFormat, AudioModel, IntoSpeechProviderKind, SpeechProviderBuilder,
232    SpeechProviderKind, SpeechResponse, VoiceId, VoiceInfo, VoiceOrigin, VoicePreview, VoiceSource,
233    WordTimestamp, speech_provider,
234};
235pub use request::{DesignVoiceRequest, DialogueRequest, DialogueTurn, SpeechRequest};
236#[cfg(feature = "toolbox")]
237pub use toolbox::{SpeechToolBox, SpeechToolOutput};
238pub use voice_store::{MemoryVoiceStore, StoredVoice, VoiceStore};