Black Forest Labs 프로바이더

Black Forest Labs 프로바이더

Black Forest Labs의 FLUX 기반 생성형 이미지 플랫폼을 AI SDK에서 쓸 수 있게 해주는 프로바이더예요. 빠르고 고품질이며 정확한 결과를 제공하는 이미지 생성 및 편집을 지원해요.

출처: 문서

본문

Black Forest Labs는 FLUX 기반 모델로 개발자에게 생성형 이미지 플랫폼을 제공해요. 이 플랫폼은 정확하고 일관된 결과로 빠르고 고품질이며 인컨텍스트(in-context) 이미지 생성과 편집을 제공해요.

설정 (Setup)

Black Forest Labs 프로바이더는 @ai-sdk/black-forest-labs 모듈로 제공돼요. 다음과 같이 설치할 수 있어요:

프로바이더 인스턴스 (Provider Instance)

@ai-sdk/black-forest-labs에서 기본 프로바이더 인스턴스 blackForestLabs를 불러올 수 있어요:

import { blackForestLabs } from '@ai-sdk/black-forest-labs';

커스터마이즈가 필요하다면 createBlackForestLabs를 불러와 원하는 설정으로 프로바이더 인스턴스를 만들 수 있어요:

import { createBlackForestLabs } from '@ai-sdk/black-forest-labs';

const blackForestLabs = createBlackForestLabs({
  apiKey: *** // optional, defaults to BFL_API_KEY environment variable
  baseURL: 'custom-url', // optional
  headers: {
    /* custom headers */
  }, // optional
});

Black Forest Labs 프로바이더 인스턴스를 커스터마이즈할 때 사용할 수 있는 선택적 설정은 다음과 같아요:

  • baseURL string

    API 호출에 다른 URL 접두사를 사용해요. 예를 들어 지역 엔드포인트를 쓸 때 유용해요. 기본 접두사는 https://api.bfl.ai/v1이에요.

  • apiKey string

    x-key 헤더로 보내는 API 키예요. 기본값은 BFL_API_KEY 환경 변수예요.

  • headers Record<string,string>

    요청에 포함할 커스텀 헤더예요.

  • fetch (input: RequestInfo, init?: RequestInit) => Promise<Response>

    커스텀 fetch 구현이에요. 요청을 가로채는 미들웨어로 쓸 수도 있고, 예를 들어 테스트용으로 커스텀 fetch 구현을 제공할 수도 있어요.

  • pollIntervalMillis number

    생성 완료를 기다릴 때 폴링 시도 사이의 간격(밀리초)이에요. 이미지 모델은 기본 500ms, 비디오 모델은 2000ms예요.

  • pollTimeoutMillis number

    포기하기 전 폴링의 전체 타임아웃(밀리초)이에요. 이미지 모델은 기본 60000ms(60초), 비디오 모델은 600000ms(10분)예요.

이미지 모델 (Image Models)

.image() 팩토리 메서드로 Black Forest Labs 이미지 모델을 만들 수 있어요. AI SDK에서 이미지 생성에 대해 더 알고 싶다면 generateImage()를 참고하세요.

기본 사용법 (Basic Usage)

import { writeFileSync } from 'node:fs';
import { blackForestLabs } from '@ai-sdk/black-forest-labs';
import { generateImage } from 'ai';

const { image, providerMetadata } = await generateImage({
  model: blackForestLabs.image('flux-pro-1.1'),
  prompt: 'A serene mountain landscape at sunset',
});

const filename = `image-${Date.now()}.png`;
writeFileSync(filename, image.uint8Array);
console.log(`Image saved to ${filename}`);

모델 기능 (Model Capabilities)

Black Forest Labs는 다양한 사용 사례에 최적화된 많은 모델을 제공해요. 다음은 인기 있는 몇 가지 예시예요. 전체 모델 목록은 Black Forest Labs 모델 페이지를 참고하세요.

모델 설명
flux-kontext-pro FLUX.1 Kontext [pro] handles both text and reference images as inputs, enabling targeted edits and complex transformations
flux-kontext-max FLUX.1 Kontext [max] with improved prompt adherence and typography generation
flux-pro-1.1-ultra Ultra-fast, ultra high-resolution image creation
flux-pro-1.1 Fast, high-quality image generation from text.
flux-pro-1.0-fill Inpainting model for filling masked regions of images with new content

Black Forest Labs 모델은 3:7(세로)부터 7:3(가로)까지의 종횡비를 지원해요.

이미지 편집 (Image Editing)

Black Forest Labs Kontext 모델은 참조 이미지를 사용하는 강력한 이미지 편집 기능을 지원해요. prompt.images로 입력 이미지를 전달해 기존 이미지를 변형, 결합 또는 편집할 수 있어요.

단일 이미지 편집 (Single Image Editing)

텍스트 프롬프트로 기존 이미지를 변형해요:

import {
  blackForestLabs,
  BlackForestLabsImageModelOptions,
} from '@ai-sdk/black-forest-labs';
import { generateImage } from 'ai';

const { images } = await generateImage({
  model: blackForestLabs.image('flux-kontext-pro'),
  prompt: {
    text: 'A baby elephant with a shirt that has the logo from the input image.',
    images: [
      'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png',
    ],
  },
  providerOptions: {
    blackForestLabs: {
      width: 1024,
      height: 768,
    } satisfies BlackForestLabsImageModelOptions,
  },
});

다중 참조 편집 (Multi-Reference Editing)

복잡한 변형을 위해 여러 참조 이미지를 결합해요. Black Forest Labs는 최대 10개의 입력 이미지를 지원해요:

import { blackForestLabs } from '@ai-sdk/black-forest-labs';
import { generateImage } from 'ai';

const { images } = await generateImage({
  model: blackForestLabs.image('flux-kontext-pro'),
  prompt: {
    text: 'Combine the style of image 1 with the subject of image 2',
    images: [
      'https://example.com/style-reference.jpg',
      'https://example.com/subject-reference.jpg',
    ],
  },
});
입력 이미지는 URL 또는 base64로 인코딩된 문자열로 제공할 수 있어요. 이미지당 최대 20MB 또는 20메가픽셀을 지원해요.

인페인팅 (Inpainting)

flux-pro-1.0-fill 모델은 이미지의 마스크된 영역을 새 콘텐츠로 채울 수 있는 인페인팅을 지원해요. prompt.images로 소스 이미지를, prompt.mask로 마스크 이미지를 전달하세요:

import { blackForestLabs } from '@ai-sdk/black-forest-labs';
import { generateImage } from 'ai';

const { images } = await generateImage({
  model: blackForestLabs.image('flux-pro-1.0-fill'),
  prompt: {
    text: 'A beautiful garden with flowers',
    images: ['https://example.com/source-image.jpg'],
    mask: 'https://example.com/mask-image.png',
  },
});

마스크 이미지는 흰색 영역이 채울 영역을, 검은색 영역이 보존할 영역을 나타내는 그레이스케일 이미지여야 해요.

프로바이더 옵션 (Provider Options)

Black Forest Labs 이미지 모델은 providerOptions.blackForestLabs 객체를 통해 유연한 프로바이더 옵션을 지원해요. 지원되는 파라미터는 사용된 모델 ID에 따라 달라져요:

  • width number - 출력 너비(픽셀) (256–1920). 설정하면 size에서 파생된 너비를 재정의해요.
  • height number - 출력 높이(픽셀) (256–1920). 설정하면 size에서 파생된 높이를 재정의해요.
  • outputFormat string - 출력 이미지의 원하는 형식 ("jpeg" 또는 "png").
  • steps number - 추론 스텝 수. 값이 높을수록 품질이 좋아질 수 있지만 생성 시간이 늘어나요.
  • guidance number - 생성을 위한 가이던스 스케일. 값이 높을수록 프롬프트를 더 가깝게 따라요.
  • imagePrompt string - 생성의 추가 시각적 컨텍스트로 사용할 base64 인코딩 이미지.
  • imagePromptStrength number - 생성에 대한 이미지 프롬프트 영향의 강도 (0.0~1.0).
  • promptUpsampling boolean - true면 프롬프트에 업샘플링을 수행해요.
  • raw boolean - 더 자연스럽고 정통적인 미학을 위한 raw 모드 활성화.
  • safetyTolerance number - 입력 및 출력의 조정(moderation) 수준 (0 = 가장 엄격, 6 = 더 관대).
  • pollIntervalMillis number - 폴링 시도 사이의 간격(밀리초) (기본 500ms).
  • pollTimeoutMillis number - 타임아웃 전 폴링의 전체 타임아웃(밀리초) (기본 60s).
  • webhookUrl string - 비동기 완료 알림 URL. 유효한 HTTP/HTTPS URL이어야 해요.
  • webhookSecret string - 웹훅 서명 검증용 비밀번호. X-Webhook-Secret 헤더로 전송됨.
편집을 위한 참조 이미지를 전달하려면 프로바이더 옵션 대신 `prompt.images`를 사용하세요. URL 또는 base64 인코딩 문자열로 최대 10개 이미지를 지원해요.

프로바이더 메타데이터 (Provider Metadata)

generateImage 응답은 providerMetadata.blackForestLabs.images[]에 프로바이더별 메타데이터를 포함해요. 각 이미지 객체는 다음 속성을 가질 수 있어요:

  • seed number - 생성에 사용된 시드. 결과를 재현하는 데 유용.
  • start_time number - 생성이 시작된 Unix 타임스탬프.
  • end_time number - 생성이 완료된 Unix 타임스탬프.
  • duration number - 생성 지속 시간(초).
  • cost number - 생성 요청의 비용.
  • inputMegapixels number - 입력 이미지 크기(메가픽셀).
  • outputMegapixels number - 출력 이미지 크기(메가픽셀).
import { blackForestLabs } from '@ai-sdk/black-forest-labs';
import { generateImage } from 'ai';

const { image, providerMetadata } = await generateImage({
  model: blackForestLabs.image('flux-pro-1.1'),
  prompt: 'A serene mountain landscape at sunset',
});

// Access provider metadata
const metadata = providerMetadata?.blackForestLabs?.images?.[0];
console.log('Seed:', metadata?.seed);
console.log('Cost:', metadata?.cost);
console.log('Duration:', metadata?.duration);

지역 엔드포인트 (Regional Endpoints)

기본적으로 요청은 https://api.bfl.ai/v1로 전송돼요. 프로바이더 인스턴스를 만들 때 baseURL을 설정해 지역 엔드포인트를 선택할 수 있어요:

import { createBlackForestLabs } from '@ai-sdk/black-forest-labs';

const blackForestLabs = createBlackForestLabs({
  baseURL: 'https://api.eu.bfl.ai/v1', // or https://api.us.bfl.ai/v1
});

비디오 모델 (Video Models)

FLUX 3 비디오 모델로 experimental_generateVideo 함수를 사용해 비디오를 생성할 수 있어요:

import {
  blackForestLabs,
  type BlackForestLabsVideoModelOptions,
} from '@ai-sdk/black-forest-labs';
import { experimental_generateVideo as generateVideo } from 'ai';

const { video } = await generateVideo({
  model: blackForestLabs.video('flux-3-video'),
  prompt: 'A white kitten chases a butterfly across a sunlit garden.',
  aspectRatio: '16:9',
  duration: 8,
  poll: {
    intervalMs: 2000,
    timeoutMs: 600000, // 10 minutes
  },
  providerOptions: {
    blackForestLabs: {
      resolution: 'fhd',
    } satisfies BlackForestLabsVideoModelOptions,
  },
});

FLUX 3는 호출당 하나의 비디오를 생성해요. 생성은 비동기예요 — 모델이 작업을 제출하고 완료될 때까지 폴링한 다음 서명된 MP4 URL을 AI SDK Core에 전달해요. generateVideo는 해석(resolve) 전에 다운로드하므로 video는 GeneratedFile이에요. 서명된 URL은 providerMetadata.blackForestLabs.videos[0].videoUrl에서 계속 사용할 수 있어요.

최상위 poll 옵션을 사용해 AI SDK Core가 폴링을 조율하고 간격과 타임아웃을 설정하게 하세요. FLUX 3 비디오 API는 현재 웹훅 콜백 입력을 노출하지 않으므로 최상위 webhook은 폴링으로 폴백해요.

duration은 5~20초의 정수 초를 받아요. 분수 값은 반올림되고 범위 밖 값은 잘리며, 각각 경고가 발생해요. 생략하면 FLUX 3가 콘텐츠에 맞게 지속 시간을 조정해요.

오디오는 기본적으로 생성되므로 generateAudio는 꺼야 할 때만 설정하면 돼요. fps와 seed는 API에서 지원되지 않으며 경고로 보고돼요.

프로바이더 메타데이터의 URL은 시간 제한이 있어요. 반환된 `video` 바이트를 자신의 저장소에 영구 보존하세요.

해상도 및 종횡비 (Resolution and aspect ratio)

API는 hd 또는 fhd(기본값은 hd)라는 명명된 해상도 티어를 받으며, fhd는 비디오 업샘플러로 마무리돼요. 정확한 프레임 크기는 종횡비에 따라 달라요.

최상위 resolution 옵션은 {width}x{height} 형식이므로 짧은 변으로 티어에 매핑돼요 — 1280x720은 hd가 되고 1920x1080은 fhd가 돼요. 다른 값은 짧은 변이 720픽셀 이하이면 hd로, 720 초과면 fhd로 매핑되며 매핑을 보고하는 경고가 발생해요. 티어를 직접 설정하려면 providerOptions.blackForestLabs.resolution을 사용하세요.

aspectRatio는 21:9, 2:1, 16:9, 4:3, 1:1, 3:4, 9:16을 받아요. API 기본값은 auto로, 프롬프트와 컨디셔닝 미디어로부터 비율을 추론해요. 최상위 옵션은 {width}:{height}여야 하므로 auto는 providerOptions.blackForestLabs.aspectRatio를 통해서만 요청할 수 있어요.

생성 모드 (Generation modes)

FLUX 3는 mode 판별자가 있는 단일 엔드포인트예요. 모드는 전달하는 입력에서 추론돼요:

  • 텍스트-영상 — prompt만.
  • 이미지-영상 — 시작 이미지를 애니메이션하려면 image(또는 frameType: 'first_frame'의 frameImages 항목)를 전달. last_frame을 추가하면 클립이 그 이미지에서 끝나요. first_frame 없는 last_frame은 표현할 수 없으며 경고와 함께 버려져요.
  • 키프레임 — 이미지가 2개를 초과하거나 특정 초에 고정된 경우 providerOptions.blackForestLabs.keyframes를 전달. image와 frameImages보다 우선해요.
  • 비디오 연속 — 기존 MP4의 마지막 프레임에서 계속하려면 inputReferences에 비디오 유형 항목을 전달. FLUX 3는 단일 비디오를 받아요. 키프레임과 연속은 상호 배타적이에요.
  • 드래프트 향상 — providerOptions.blackForestLabs.draftCache를 전달. 드래프트 모드 참고.

FLUX 3는 참조 이미지 입력이 없으므로 inputReferences에 전달된 이미지는 image, frameImages 또는 keyframes를 가리키는 경고와 함께 무시돼요.

키프레임 (Keyframes)

키프레임은 위치적이에요. 하나의 이미지는 클립을 열고, 두 개는 열고 닫으며, 더 많으면 첫 번째와 마지막이 끝점이고 나머지는 그 사이에 균등하게 배치돼요. 각 이미지는 http(s) URL 또는 base64 문자열이며, 요청은 1~10개를 받아요.

시간 없는 키프레임 3개 이상은 명시적 duration이 필요해요. API가 거부하기 때문에 해당 조합이 전송될 때 프로바이더는 경고를 보고해요.

[seconds, image] 쌍을 시간순으로 전달해 각 이미지를 클립의 특정 초에 고정할 수 있어요:

import {
  blackForestLabs,
  type BlackForestLabsVideoModelOptions,
} from '@ai-sdk/black-forest-labs';
import { experimental_generateVideo as generateVideo } from 'ai';
import { readFileSync } from 'node:fs';

const asBase64 = (file: string) => readFileSync(file).toString('base64');

const { video } = await generateVideo({
  model: blackForestLabs.video('flux-3-video'),
  prompt: 'The cat, then the dog, then the owl each take a turn in the room.',
  duration: 12,
  providerOptions: {
    blackForestLabs: {
      keyframes: [
        [0, asBase64('cat.png')],
        [4.5, asBase64('dog.png')],
        [9, asBase64('owl.png')],
      ],
    } satisfies BlackForestLabsVideoModelOptions,
  },
});

드래프트 모드 (Draft mode)

draft: true를 설정하면 빠르고 낮은 품질의 미리보기를 렌더링하고, providerMetadata.blackForestLabs.videos[0].draftCache로 보고되는 암호화된 번들을 남겨요. 그 번들을 draftCache로 다시 전달하면 같은 생성을 전체 품질로 재현해요.

번들은 원래 모드, 프롬프트, 시드, 컨디셔닝 미디어를 고정하므로 향상 요청은 safetyTolerance 외에는 아무것도 받지 않아요. 호출에 설정된 다른 옵션은 unsupported 경고로 보고돼요. generateVideo는 prompt 인자를 요구하므로 추가할 것이 없다는 뜻으로 빈 문자열을 전달하세요.

import {
  blackForestLabs,
  type BlackForestLabsVideoModelOptions,
} from '@ai-sdk/black-forest-labs';
import { experimental_generateVideo as generateVideo } from 'ai';

const draft = await generateVideo({
  model: blackForestLabs.video('flux-3-video'),
  prompt: 'A white kitten chases a butterfly across a sunlit garden.',
  duration: 6,
  providerOptions: {
    blackForestLabs: { draft: true } satisfies BlackForestLabsVideoModelOptions,
  },
});

const draftCacheUrl = (
  draft.providerMetadata.blackForestLabs?.videos as
    | Array<{ draftCache?: string }>
    | undefined
)?.[0]?.draftCache;

// The download URL expires; sending the base64 `.bin` is the durable path,
// though the URL itself also works while the link is still valid.
const response = await fetch(draftCacheUrl!);
const arrayBuffer = await response.arrayBuffer();

const enhanced = await generateVideo({
  model: blackForestLabs.video('flux-3-video'),
  prompt: '',
  providerOptions: {
    blackForestLabs: {
      draftCache: Buffer.from(arrayBuffer).toString('base64'),
    } satisfies BlackForestLabsVideoModelOptions,
  },
});
드래프트와 그 향상은 두 개의 별도 생성이며, 각각 별도로 과금됩니다.

비디오 프로바이더 옵션 (Video Provider Options)

FLUX 3 비디오에 사용할 수 있는 선택적 프로바이더 옵션은 다음과 같아요:

  • resolution 'hd' | 'fhd'

    출력 해상도 티어예요. 최상위 resolution보다 우선해요.

  • aspectRatio '21:9' | '2:1' | '16:9' | '4:3' | '1:1' | '3:4' | '9:16' | 'auto'

    생성된 비디오의 종횡비예요. 최상위 aspectRatio보다 우선하며, 그것과 달리 auto로 설정할 수 있어요.

  • keyframes Array<string | [number, string]>

    이미지-영상 생성을 위한 키프레임이에요. image와 frameImages가 표현할 수 없는 형태(2개를 초과하는 이미지 또는 특정 초에 고정된 이미지)를 위한 것이며, 둘 다보다 우선해요.

  • safetyTolerance number

    조정(moderation) 엄격성 0(가장 엄격)~4. 기본값은 2. 요청과 관계없이 성적 콘텐츠는 3, 증오 콘텐츠는 2로 제한되고, 컨디셔닝 미디어를 담은 요청은 2로 제한돼요.

  • draft boolean

    완성된 비디오 대신 빠르고 낮은 품질의 미리보기를 렌더링해요. 기본값은 false.

  • draftCache string

    이전 draft 생성의 암호화된 드래프트 캐시 번들이며, 요청을 드래프트 향상 모드로 전환해요.

  • version string

    고정할 모델 버전이에요. 현재는 latest만 사용할 수 있어요.

비디오 프로바이더 메타데이터 (Video Provider Metadata)

FLUX 3 비디오 결과는 providerMetadata.blackForestLabs.videos[]를 포함해요. 각 비디오 객체는 다음 속성을 가질 수 있어요:

  • id string - Black Forest Labs 생성 요청의 ID.
  • videoUrl string - 서명된 MP4 URL (video와 같은 URL). 시간 제한.
  • draftCache string - 드래프트 번들의 다운로드 URL. draft 생성에만 존재.
  • seed number - API가 보고할 때 생성에 사용된 시드.
  • start_time number - 생성이 시작된 Unix 타임스탬프.
  • end_time number - 생성이 완료된 Unix 타임스탬프.
  • duration number - API가 보고한 지속 시간(초).
  • cost number - 크레딧 단위의 생성 요청 비용.
  • inputMegapixels number - 입력 크기(메가픽셀).
  • outputMegapixels number - 출력 크기(메가픽셀).

비디오 모델 기능 (Video Model Capabilities)

모델 설명
flux-3-video Up to full-HD and 20 seconds, with synchronized audio. Text-to-video, keyframes, and video continuation.

더 알아보기 (Learn more)

전체 사이트맵