pub mod comfy_serve;
pub mod openrouter;
use agentai_core::HttpError;
use agentai_core::message::Media;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct VideoRequest {
pub prompt: String,
pub duration: Option<u32>,
pub resolution: Option<String>,
pub aspect_ratio: Option<String>,
pub seed: Option<u32>,
pub inputs: VideoInputs,
}
impl VideoRequest {
pub fn new(prompt: impl Into<String>) -> Self {
Self {
prompt: prompt.into(),
duration: None,
resolution: None,
aspect_ratio: None,
seed: None,
inputs: VideoInputs::None,
}
}
pub fn with_duration(mut self, seconds: u32) -> Self {
self.duration = Some(seconds);
self
}
pub fn with_resolution(mut self, resolution: impl Into<String>) -> Self {
self.resolution = Some(resolution.into());
self
}
pub fn with_aspect_ratio(mut self, aspect_ratio: impl Into<String>) -> Self {
self.aspect_ratio = Some(aspect_ratio.into());
self
}
pub fn with_seed(mut self, seed: u32) -> Self {
self.seed = Some(seed);
self
}
pub fn with_inputs(mut self, inputs: VideoInputs) -> Self {
self.inputs = inputs;
self
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum VideoInputs {
None,
Frames {
first: Option<Media>,
last: Option<Media>,
},
References(VideoReferences),
}
#[derive(Debug, Clone, PartialEq, Default)]
#[non_exhaustive]
pub struct VideoReferences {
pub images: Vec<Media>,
pub videos: Vec<Media>,
pub audio: Vec<Media>,
pub video_sound: Vec<u32>,
}
impl VideoReferences {
pub fn new() -> Self {
Self::default()
}
pub fn with_image(mut self, image: Media) -> Self {
self.images.push(image);
self
}
pub fn with_video(mut self, video: Media) -> Self {
self.videos.push(video);
self
}
pub fn with_audio(mut self, audio: Media) -> Self {
self.audio.push(audio);
self
}
pub fn with_video_sound(mut self, index: u32) -> Self {
self.video_sound.push(index);
self
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct VideoJob {
pub id: String,
pub data: Value,
}
impl VideoJob {
pub fn new(id: impl Into<String>) -> Self {
Self {
id: id.into(),
data: Value::Null,
}
}
pub fn with_data(mut self, data: Value) -> Self {
self.data = data;
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum JobStatus {
Queued,
Running,
Completed,
Failed(String),
Gone,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum VideoInputKind {
FirstFrame,
LastFrame,
Image,
Video,
Audio,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct VideoModel {
pub model: String,
pub id: String,
pub name: Option<String>,
pub durations: Option<Vec<u32>>,
pub resolutions: Option<Vec<String>>,
pub aspect_ratios: Option<Vec<String>>,
pub inputs: Option<Vec<VideoInputKind>>,
}
impl VideoModel {
pub fn new(model: impl Into<String>, id: impl Into<String>) -> Self {
Self {
model: model.into(),
id: id.into(),
name: None,
durations: None,
resolutions: None,
aspect_ratios: None,
inputs: None,
}
}
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum VideoError {
#[error(transparent)]
Http(HttpError),
#[error("video API error (status {status}): {message}")]
Api {
status: u16,
message: String,
},
#[error("invalid video API response: {0}")]
InvalidResponse(String),
#[error("not supported by the video provider: {0}")]
Unsupported(&'static str),
#[error("no video provider for model '{0}'")]
UnknownProvider(String),
#[error("the API key is missing, set {0}")]
MissingApiKey(&'static str),
#[error("the base URL is missing, set {0}")]
MissingBaseUrl(&'static str),
}
impl From<HttpError> for VideoError {
fn from(err: HttpError) -> Self {
match err {
HttpError::Status { status, message } => Self::Api { status, message },
err => Self::Http(err),
}
}
}
impl VideoError {
pub fn is_auth(&self) -> bool {
matches!(
self,
Self::Api {
status: 401 | 403,
..
}
)
}
}
#[async_trait]
pub trait VideoProvider: Send + Sync + 'static {
fn model(&self) -> Option<&str> {
None
}
async fn submit(&self, request: VideoRequest) -> Result<VideoJob, VideoError>;
async fn status(&self, job: &VideoJob) -> Result<JobStatus, VideoError>;
async fn download(&self, job: &VideoJob) -> Result<Media, VideoError>;
fn supports_cancel(&self) -> bool {
false
}
async fn cancel(&self, _job: &VideoJob) -> Result<(), VideoError> {
Err(VideoError::Unsupported("cancelling a job"))
}
async fn list_models(&self) -> Result<Vec<VideoModel>, VideoError> {
Err(VideoError::Unsupported("listing models"))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ProviderKind {
ComfyServe,
OpenRouter,
}
impl ProviderKind {
fn from_name(name: &str) -> Option<Self> {
match name {
"comfy-serve" => Some(Self::ComfyServe),
"openrouter" => Some(Self::OpenRouter),
_ => None,
}
}
fn build(self, model: &str) -> Result<Box<dyn VideoProvider>, VideoError> {
Ok(match self {
Self::ComfyServe => Box::new(comfy_serve::ComfyServeVideoProvider::from_env(model)?),
Self::OpenRouter => Box::new(openrouter::OpenRouterVideoProvider::from_env(model)?),
})
}
}
fn resolve(model: &str) -> Result<(ProviderKind, &str), VideoError> {
model
.split_once("::")
.and_then(|(provider, name)| Some((ProviderKind::from_name(provider)?, name)))
.ok_or_else(|| VideoError::UnknownProvider(model.to_string()))
}
pub fn from_model(model: &str) -> Result<Box<dyn VideoProvider>, VideoError> {
let (kind, name) = resolve(model)?;
kind.build(name)
}
pub async fn list_models(provider: &str) -> Result<Vec<VideoModel>, VideoError> {
let kind = ProviderKind::from_name(provider)
.ok_or_else(|| VideoError::UnknownProvider(provider.to_string()))?;
kind.build("")?.list_models().await
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn a_prefix_selects_the_provider_and_is_required() {
assert_eq!(
resolve("comfy-serve::wan/2.2").unwrap(),
(ProviderKind::ComfyServe, "wan/2.2")
);
assert_eq!(
resolve("openrouter::google/veo-3.1").unwrap(),
(ProviderKind::OpenRouter, "google/veo-3.1")
);
for model in ["wan", "comfy::wan", "other::wan"] {
assert!(matches!(resolve(model), Err(VideoError::UnknownProvider(m)) if m == model));
}
}
#[test]
fn jobs_and_statuses_keep_dreamers_stored_format() {
assert_eq!(
serde_json::to_value(JobStatus::Failed("x".into())).unwrap(),
json!({"failed": "x"})
);
assert_eq!(
serde_json::to_value(JobStatus::Queued).unwrap(),
json!("queued")
);
assert_eq!(
serde_json::to_value(VideoJob::new("j").with_data(json!({"polling_url": null})))
.unwrap(),
json!({"id": "j", "data": {"polling_url": null}})
);
}
}