Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

7.9 KB
Raw Blame
import type { FalClient } from '@fal-ai/client';
import debug from 'debug';
import type { RuntimeVideoGenParams } from 'model-bank';

import { getVideoReferenceImages } from '../../core/usageConverters/utils/computeVideoCost';
import type { CreateVideoResult, PollVideoStatusResult } from '../../types/video';
import type { FalJsonSchema } from './schema';
import { coerceFalInput } from './schema';

const log = debug('lobe-video:fal');

interface FalVideoModelSpec {
  /** Model-specific input fields sent with every task */
  buildBaseInput: (params: RuntimeVideoGenParams) => Record<string, unknown>;
  /** fal takes `duration` as a string enum (e.g. `"4"`–`"30"`) instead of a number */
  durationAsString?: boolean;
  /** Input field of the reference-to-video endpoint that holds the reference images */
  referenceImagesField: string;
}

/**
 * Video model cards that map to one fal app with a separate endpoint per task. The runtime picks
 * the endpoint from the request params, so the user sees a single model.
 */
const FAL_VIDEO_MODELS: Record<string, FalVideoModelSpec> = {
  'bytedance/seedance-2.5': {
    buildBaseInput: ({ generateAudio }) =>
      typeof generateAudio === 'boolean' ? { generate_audio: generateAudio } : {},
    durationAsString: true,
    referenceImagesField: 'image_urls',
  },
  'minimax/h3-max': {
    buildBaseInput: ({ promptExtend }) => ({
      enable_safety_checker: false,
      // Required by fal; the model card exposes the three modes through `promptExtend`.
      prompt_expansion_mode: typeof promptExtend === 'string' ? promptExtend : 'balanced',
    }),
    referenceImagesField: 'reference_image_urls',
  },
};

/**
 * fal queue requests live at `<owner>/<app>/requests/<id>`. Using that path as the inference id
 * keeps polling self-contained: the router polls with the inference id only, and the status and
 * result endpoints need the app id, not the task endpoint.
 */
const REQUEST_PATH_SEPARATOR = '/requests/';

/** Video model cards whose task endpoint the runtime picks from the request params */
export const isFalTaskRoutedVideoModel = (model: string) => Object.hasOwn(FAL_VIDEO_MODELS, model);

const FAL_VIDEO_TASKS = ['text-to-video', 'image-to-video', 'reference-to-video'] as const;

/** fal endpoints a task-routed video card sends requests to; empty for any other model */
export const getFalTaskRoutedVideoEndpoints = (model: string) =>
  isFalTaskRoutedVideoModel(model) ? FAL_VIDEO_TASKS.map((task) => `${model}/${task}`) : [];

export const toFalVideoInferenceId = (appId: string, requestId: string) =>
  `${appId}${REQUEST_PATH_SEPARATOR}${requestId}`;

export const parseFalVideoInferenceId = (inferenceId: string) => {
  const index = inferenceId.lastIndexOf(REQUEST_PATH_SEPARATOR);
  if (index <= 0) throw new Error(`Invalid fal video inference id: ${inferenceId}`);

  return {
    appId: inferenceId.slice(0, index),
    requestId: inferenceId.slice(index + REQUEST_PATH_SEPARATOR.length),
  };
};

/**
 * Build the fal endpoint and input for a task-routed video model:
 * - reference images β†’ `/reference-to-video`; first/last frames join the reference pool (the
 *   endpoint has no frame slots), matching how MiniMax H3 is served by its official API
 * - first or last frame β†’ `/image-to-video`, whose output follows the first frame's aspect ratio
 * - otherwise β†’ `/text-to-video`
 */
export const buildFalVideoRequest = (model: string, params: RuntimeVideoGenParams) => {
  const spec = isFalTaskRoutedVideoModel(model) ? FAL_VIDEO_MODELS[model] : undefined;
  if (!spec) throw new Error(`Unsupported fal video model: ${model}`);

  const { aspectRatio, duration, endImageUrl, imageUrl, imageUrls, prompt, resolution, seed } =
    params;

  const input: Record<string, unknown> = { ...spec.buildBaseInput(params), prompt };
  if (duration) input.duration = spec.durationAsString ? String(duration) : duration;
  if (resolution) input.resolution = resolution;
  if (typeof seed === 'number' && seed >= 0) input.seed = seed;

  let task: (typeof FAL_VIDEO_TASKS)[number];
  if (imageUrls?.length) {
    task = 'reference-to-video';
    // Shared with pricing so the billed reference tokens cover every image sent
    input[spec.referenceImagesField] = getVideoReferenceImages({
      endImageUrl,
      imageUrl,
      imageUrls,
    });
    if (aspectRatio) input.aspect_ratio = aspectRatio;
  } else if (imageUrl || endImageUrl) {
    task = 'image-to-video';
    if (imageUrl) input.image_url = imageUrl;
    if (endImageUrl) input.end_image_url = endImageUrl;
  } else {
    task = 'text-to-video';
    if (aspectRatio) input.aspect_ratio = aspectRatio;
  }

  return { endpoint: `${model}/${task}`, input };
};

/**
 * Build the input of any other fal video endpoint, whose id already names its task (e.g.
 * `fal-ai/kling-video/v2.1/master/image-to-video`). Fields use fal's common names; the caller
 * fits them to the endpoint's schema with `coerceFalInput`.
 */
export const buildGenericFalVideoInput = (params: RuntimeVideoGenParams) => {
  const {
    aspectRatio,
    duration,
    endImageUrl,
    generateAudio,
    imageUrl,
    imageUrls,
    prompt,
    resolution,
    seed,
  } = params;

  const input: Record<string, unknown> = { prompt };
  if (aspectRatio) input.aspect_ratio = aspectRatio;
  if (duration) input.duration = duration;
  if (resolution) input.resolution = resolution;
  if (typeof seed === 'number' && seed >= 0) input.seed = seed;
  if (imageUrl) input.image_url = imageUrl;
  if (endImageUrl) input.end_image_url = endImageUrl;
  if (imageUrls?.length) input.image_urls = imageUrls;
  if (typeof generateAudio === 'boolean') input.generate_audio = generateAudio;

  return input;
};

const getFalErrorMessage = (error: unknown): string => {
  const detail = (error as { body?: { detail?: unknown } } | undefined)?.body?.detail;
  if (typeof detail === 'string') return detail;
  if (Array.isArray(detail)) {
    const messages = detail
      .map((item) => (item as { msg?: unknown } | undefined)?.msg)
      .filter((msg): msg is string => typeof msg === 'string');
    if (messages.length > 0) return messages.join('; ');
  }

  return error instanceof Error ? error.message : String(error);
};

export const createFalVideo = async (
  client: FalClient,
  model: string,
  params: RuntimeVideoGenParams,
  loadInputSchema?: (endpoint: string) => Promise<FalJsonSchema | undefined>,
): Promise<CreateVideoResult> => {
  let endpoint: string;
  let input: Record<string, unknown>;

  if (isFalTaskRoutedVideoModel(model)) {
    ({ endpoint, input } = buildFalVideoRequest(model, params));
  } else {
    endpoint = model;
    input = coerceFalInput(buildGenericFalVideoInput(params), await loadInputSchema?.(endpoint));
  }
  log('Submitting fal video request to %s with input: %O', endpoint, input);

  const { request_id } = await client.queue.submit(endpoint, { input });

  // Status and result URLs only use `<owner>/<app>`, so a full endpoint id also works as app id
  return { inferenceId: toFalVideoInferenceId(model, request_id) };
};

export const pollFalVideoStatus = async (
  client: FalClient,
  inferenceId: string,
): Promise<PollVideoStatusResult> => {
  const { appId, requestId } = parseFalVideoInferenceId(inferenceId);

  const status = await client.queue.status(appId, { logs: false, requestId });
  if (status.status !== 'COMPLETED') return { status: 'pending' };

  // A failed request also reaches COMPLETED; fetching its result throws the provider error.
  let data: unknown;
  try {
    ({ data } = await client.queue.result(appId, { requestId }));
  } catch (error) {
    log('fal video request %s failed: %O', inferenceId, error);
    return { error: getFalErrorMessage(error), status: 'failed' };
  }

  const output = data as { video?: { url?: string }; videos?: { url?: string }[] } | undefined;
  const videoUrl = output?.video?.url ?? output?.videos?.[0]?.url;
  if (!videoUrl) return { error: 'fal returned no video', status: 'failed' };

  return { status: 'success', videoUrl };
};