Skip to main content

agentai_video/provider/
mod.rs

1//! # Video providers
2//!
3//! [`VideoProvider`] is the interface to a video generation API. Each submodule implements it
4//! for one API. Implement it yourself to use another API.
5
6pub mod comfy_serve;
7pub mod openrouter;
8
9use agentai_core::HttpError;
10use agentai_core::message::Media;
11use async_trait::async_trait;
12use serde::{Deserialize, Serialize};
13use serde_json::Value;
14use thiserror::Error;
15
16/// A request to generate a video.
17///
18/// Unset options are not sent, the server uses its defaults. Values are not checked here: the
19/// API reports the ones it does not accept.
20#[derive(Debug, Clone, PartialEq)]
21#[non_exhaustive]
22pub struct VideoRequest {
23    /// What the video shows.
24    pub prompt: String,
25    /// Length in whole seconds.
26    pub duration: Option<u32>,
27    /// Resolution, in the format of the provider (for example `720p`).
28    pub resolution: Option<String>,
29    /// Aspect ratio, in the format of the provider (for example `16:9`).
30    pub aspect_ratio: Option<String>,
31    /// Seed of the random generator.
32    pub seed: Option<u32>,
33    /// Images, videos and audio the video is made from.
34    pub inputs: VideoInputs,
35}
36
37impl VideoRequest {
38    /// Creates a text-to-video request.
39    pub fn new(prompt: impl Into<String>) -> Self {
40        Self {
41            prompt: prompt.into(),
42            duration: None,
43            resolution: None,
44            aspect_ratio: None,
45            seed: None,
46            inputs: VideoInputs::None,
47        }
48    }
49
50    /// Sets the length in seconds.
51    pub fn with_duration(mut self, seconds: u32) -> Self {
52        self.duration = Some(seconds);
53        self
54    }
55
56    /// Sets the resolution.
57    pub fn with_resolution(mut self, resolution: impl Into<String>) -> Self {
58        self.resolution = Some(resolution.into());
59        self
60    }
61
62    /// Sets the aspect ratio.
63    pub fn with_aspect_ratio(mut self, aspect_ratio: impl Into<String>) -> Self {
64        self.aspect_ratio = Some(aspect_ratio.into());
65        self
66    }
67
68    /// Sets the seed.
69    pub fn with_seed(mut self, seed: u32) -> Self {
70        self.seed = Some(seed);
71        self
72    }
73
74    /// Sets the inputs.
75    pub fn with_inputs(mut self, inputs: VideoInputs) -> Self {
76        self.inputs = inputs;
77        self
78    }
79}
80
81/// What a video is made from. Frames and references exclude each other.
82#[derive(Debug, Clone, PartialEq)]
83#[non_exhaustive]
84pub enum VideoInputs {
85    /// Text-to-video.
86    None,
87    /// Image-to-video: at least one of the two frames.
88    Frames {
89        /// The image the video starts with.
90        first: Option<Media>,
91        /// The image the video ends with.
92        last: Option<Media>,
93    },
94    /// Reference-to-video.
95    References(VideoReferences),
96}
97
98/// The files of a reference-to-video request.
99///
100/// A provider that cannot send some of them returns [`VideoError::Unsupported`].
101#[derive(Debug, Clone, PartialEq, Default)]
102#[non_exhaustive]
103pub struct VideoReferences {
104    /// Reference images.
105    pub images: Vec<Media>,
106    /// Reference videos.
107    pub videos: Vec<Media>,
108    /// Reference audio.
109    pub audio: Vec<Media>,
110    /// Indices into `videos` whose sound is also an audio input.
111    pub video_sound: Vec<u32>,
112}
113
114impl VideoReferences {
115    /// Creates an empty set of references.
116    pub fn new() -> Self {
117        Self::default()
118    }
119
120    /// Adds a reference image.
121    pub fn with_image(mut self, image: Media) -> Self {
122        self.images.push(image);
123        self
124    }
125
126    /// Adds a reference video.
127    pub fn with_video(mut self, video: Media) -> Self {
128        self.videos.push(video);
129        self
130    }
131
132    /// Adds a reference audio.
133    pub fn with_audio(mut self, audio: Media) -> Self {
134        self.audio.push(audio);
135        self
136    }
137
138    /// Marks the sound of the reference video with this index as an audio input.
139    pub fn with_video_sound(mut self, index: u32) -> Self {
140        self.video_sound.push(index);
141        self
142    }
143}
144
145/// A video job at a provider. Store it and give it back to follow the job, also after a
146/// restart and with a new provider instance. A job does not record which provider made it, so
147/// the application stores the provider and model name next to it.
148#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
149#[non_exhaustive]
150pub struct VideoJob {
151    /// ID of the job at the provider.
152    pub id: String,
153    /// Whatever the provider needs to find the job again besides the ID; `null` for providers
154    /// that need nothing more.
155    pub data: Value,
156}
157
158impl VideoJob {
159    /// Creates a job with an ID and no data.
160    pub fn new(id: impl Into<String>) -> Self {
161        Self {
162            id: id.into(),
163            data: Value::Null,
164        }
165    }
166
167    /// Sets the data the provider needs to find the job.
168    pub fn with_data(mut self, data: Value) -> Self {
169        self.data = data;
170        self
171    }
172}
173
174/// Where a job is.
175#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
176#[serde(rename_all = "snake_case")]
177#[non_exhaustive]
178pub enum JobStatus {
179    /// Waiting to start.
180    Queued,
181    /// Being generated.
182    Running,
183    /// Done: [`VideoProvider::download`] returns the video.
184    Completed,
185    /// The job failed, with the provider's message.
186    Failed(String),
187    /// The provider no longer knows the job: it was cancelled or expired.
188    Gone,
189}
190
191/// A kind of input a model accepts.
192#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
193#[serde(rename_all = "snake_case")]
194#[non_exhaustive]
195pub enum VideoInputKind {
196    /// An image the video starts with.
197    FirstFrame,
198    /// An image the video ends with.
199    LastFrame,
200    /// A reference image.
201    Image,
202    /// A reference video.
203    Video,
204    /// A reference audio.
205    Audio,
206}
207
208/// A video model and what it accepts, as the provider reports it.
209///
210/// `None` in a list means the provider does not say, never "not supported": offer the option and
211/// let the server answer. An empty list means the provider says there is nothing to choose.
212#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
213#[non_exhaustive]
214pub struct VideoModel {
215    /// The name to use with `from_model`, with the provider prefix.
216    pub model: String,
217    /// The ID of the model at the provider.
218    pub id: String,
219    /// A display name.
220    pub name: Option<String>,
221    /// Lengths in seconds, ascending.
222    pub durations: Option<Vec<u32>>,
223    /// Resolutions, in the format of the provider.
224    pub resolutions: Option<Vec<String>>,
225    /// Aspect ratios, in the format of the provider.
226    pub aspect_ratios: Option<Vec<String>>,
227    /// The kinds of input the model accepts.
228    pub inputs: Option<Vec<VideoInputKind>>,
229}
230
231impl VideoModel {
232    /// Creates a model that says nothing about its capabilities.
233    pub fn new(model: impl Into<String>, id: impl Into<String>) -> Self {
234        Self {
235            model: model.into(),
236            id: id.into(),
237            name: None,
238            durations: None,
239            resolutions: None,
240            aspect_ratios: None,
241            inputs: None,
242        }
243    }
244}
245
246/// Errors of video providers.
247#[derive(Debug, Error)]
248#[non_exhaustive]
249pub enum VideoError {
250    /// The request could not be sent or the response could not be read.
251    #[error(transparent)]
252    Http(HttpError),
253    /// The API answered with an error status.
254    #[error("video API error (status {status}): {message}")]
255    Api {
256        /// HTTP status code.
257        status: u16,
258        /// Message of the API.
259        message: String,
260    },
261    /// The API answered with something the provider cannot read.
262    #[error("invalid video API response: {0}")]
263    InvalidResponse(String),
264    /// The provider cannot do this, for example cancel a job.
265    #[error("not supported by the video provider: {0}")]
266    Unsupported(&'static str),
267    /// No provider matches the model name.
268    #[error("no video provider for model '{0}'")]
269    UnknownProvider(String),
270    /// The environment variable with the API key is not set.
271    #[error("the API key is missing, set {0}")]
272    MissingApiKey(&'static str),
273    /// The environment variable with the base URL is not set.
274    #[error("the base URL is missing, set {0}")]
275    MissingBaseUrl(&'static str),
276}
277
278impl From<HttpError> for VideoError {
279    fn from(err: HttpError) -> Self {
280        match err {
281            HttpError::Status { status, message } => Self::Api { status, message },
282            err => Self::Http(err),
283        }
284    }
285}
286
287impl VideoError {
288    /// Returns `true` when the API rejected the credentials (status 401 or 403).
289    pub fn is_auth(&self) -> bool {
290        matches!(
291            self,
292            Self::Api {
293                status: 401 | 403,
294                ..
295            }
296        )
297    }
298}
299
300/// A video generation API.
301///
302/// `status`, `download` and `cancel` need no model, so a provider built with an empty model
303/// name can follow a stored [`VideoJob`].
304#[async_trait]
305pub trait VideoProvider: Send + Sync + 'static {
306    /// Name of the model, if the provider has one.
307    fn model(&self) -> Option<&str> {
308        None
309    }
310
311    /// Sends the request; the job is queued or running (or already complete).
312    async fn submit(&self, request: VideoRequest) -> Result<VideoJob, VideoError>;
313
314    /// Asks where the job is.
315    async fn status(&self, job: &VideoJob) -> Result<JobStatus, VideoError>;
316
317    /// Downloads the finished video.
318    async fn download(&self, job: &VideoJob) -> Result<Media, VideoError>;
319
320    /// Returns `true` when [`cancel`](VideoProvider::cancel) works.
321    fn supports_cancel(&self) -> bool {
322        false
323    }
324
325    /// Cancels the job. A running job stops a moment later: [`status`](VideoProvider::status) may
326    /// still say [`JobStatus::Running`] right after, and then [`JobStatus::Gone`]. Default:
327    /// [`VideoError::Unsupported`].
328    async fn cancel(&self, _job: &VideoJob) -> Result<(), VideoError> {
329        Err(VideoError::Unsupported("cancelling a job"))
330    }
331
332    /// Lists the models. Default: [`VideoError::Unsupported`].
333    async fn list_models(&self) -> Result<Vec<VideoModel>, VideoError> {
334        Err(VideoError::Unsupported("listing models"))
335    }
336}
337
338/// The APIs [`from_model`] knows.
339#[derive(Debug, Clone, Copy, PartialEq, Eq)]
340enum ProviderKind {
341    ComfyServe,
342    OpenRouter,
343}
344
345impl ProviderKind {
346    fn from_name(name: &str) -> Option<Self> {
347        match name {
348            "comfy-serve" => Some(Self::ComfyServe),
349            "openrouter" => Some(Self::OpenRouter),
350            _ => None,
351        }
352    }
353
354    fn build(self, model: &str) -> Result<Box<dyn VideoProvider>, VideoError> {
355        Ok(match self {
356            Self::ComfyServe => Box::new(comfy_serve::ComfyServeVideoProvider::from_env(model)?),
357            Self::OpenRouter => Box::new(openrouter::OpenRouterVideoProvider::from_env(model)?),
358        })
359    }
360}
361
362/// Splits `provider::model` and finds the provider. The prefix is required.
363fn resolve(model: &str) -> Result<(ProviderKind, &str), VideoError> {
364    model
365        .split_once("::")
366        .and_then(|(provider, name)| Some((ProviderKind::from_name(provider)?, name)))
367        .ok_or_else(|| VideoError::UnknownProvider(model.to_string()))
368}
369
370/// Creates the provider for a `provider::model` name, with its settings from environment
371/// variables, for example `comfy-serve::wan` (see
372/// [`ComfyServeVideoProvider::from_env`](comfy_serve::ComfyServeVideoProvider::from_env)).
373pub fn from_model(model: &str) -> Result<Box<dyn VideoProvider>, VideoError> {
374    let (kind, name) = resolve(model)?;
375    kind.build(name)
376}
377
378/// Lists the video models of a provider (`comfy-serve`, `openrouter`), with its settings from
379/// environment variables as in [`from_model`].
380///
381/// ```rust,no_run
382/// # async fn run() -> Result<(), agentai_video::VideoError> {
383/// for model in agentai_video::provider::list_models("comfy-serve").await? {
384///     println!("{} {:?}", model.model, model.durations);
385/// }
386/// # Ok(())
387/// # }
388/// ```
389pub async fn list_models(provider: &str) -> Result<Vec<VideoModel>, VideoError> {
390    let kind = ProviderKind::from_name(provider)
391        .ok_or_else(|| VideoError::UnknownProvider(provider.to_string()))?;
392    kind.build("")?.list_models().await
393}
394
395#[cfg(test)]
396mod tests {
397    use serde_json::json;
398
399    use super::*;
400
401    #[test]
402    fn a_prefix_selects_the_provider_and_is_required() {
403        assert_eq!(
404            resolve("comfy-serve::wan/2.2").unwrap(),
405            (ProviderKind::ComfyServe, "wan/2.2")
406        );
407        assert_eq!(
408            resolve("openrouter::google/veo-3.1").unwrap(),
409            (ProviderKind::OpenRouter, "google/veo-3.1")
410        );
411        for model in ["wan", "comfy::wan", "other::wan"] {
412            assert!(matches!(resolve(model), Err(VideoError::UnknownProvider(m)) if m == model));
413        }
414    }
415
416    #[test]
417    fn jobs_and_statuses_keep_dreamers_stored_format() {
418        assert_eq!(
419            serde_json::to_value(JobStatus::Failed("x".into())).unwrap(),
420            json!({"failed": "x"})
421        );
422        assert_eq!(
423            serde_json::to_value(JobStatus::Queued).unwrap(),
424            json!("queued")
425        );
426        assert_eq!(
427            serde_json::to_value(VideoJob::new("j").with_data(json!({"polling_url": null})))
428                .unwrap(),
429            json!({"id": "j", "data": {"polling_url": null}})
430        );
431    }
432}