
OpenMontage 中 BFL FLUX API 集成实战指南区域端点、异步轮询、限流与 Webhook 全解析【免费下载链接】OpenMontageWorlds first open-source, agentic video production system. 12 production pipelines, 100 tools, 700 agent skill and production-knowledge files. Turn your AI coding assistant into a full video production studio.项目地址: https://gitcode.com/GitHub_Trending/op/OpenMontageBlack Forest Labs 的 FLUX 系列模型是当前文本生成图像T2I与图像编辑I2I领域的重要力量。本文基于 OpenMontage 仓库中的 .claude/skills/bfl-api/SKILL.md 技能文档系统讲解 BFL FLUX API 的完整集成路径从 API Key 配置、区域端点与模型选型到异步轮询、速率限制、错误处理与生产级 Webhook 落地。读完本文你将能够在自己的应用脚本、CLI 工具或服务端中直接调用 BFL 官方 API构建稳定、可扩展的图像生成与编辑流水线并理解 OpenMontage 仓库中 FLUX 图像生成能力与官方 API 的衔接方式。使用该技能的场景在 OpenMontage 的 Agent 工作流中当需要把 BFL FLUX API 接入应用时应优先加载本技能。它覆盖了从零到生产环境的完整链路典型触发场景包括初始化 BFL API 客户端实现异步轮询polling模式获取生成结果处理限流rate limit与各类错误为生产环境配置 Webhook 通知选择合适的地域端点Global / EU / US构建生产级集成。仓库的图像生成工具链同样引用了这一技能在 tools/graphics/flux_image.py 中FluxImage工具将flux-best-practices与bfl-api同时声明为agent_skills这意味着在仓库的能力体系里BFL 官方 API 是与 fal.ai 途径 并列的 FLUX 能力接入方式之一。第一步检查并配置 API Key在任何图像生成请求之前必须先确认 API Key 已正确配置。未设置或无效的 Key 会直接导致401 Not authenticated类错误。echo $BFL_API_KEY如果输出为空则需要完成以下配置流程登录 BFL 官方控制台的 Get Started 页面dashboard.bfl.ai/get-started点击Create Key创建密钥选择组织若存在多个组织选项复制密钥以bfl_前缀开头。推荐将 Key 持久化到项目根目录的.env文件并确保不要提交到版本库echo BFL_API_KEYbfl_your_key_here .env echo .env .gitignore # 不要提交密钥详细的配置流程见 references/api-key-setup.md其中还包含面向 Agent 的自动化方案当会话中未设置BFL_API_KEY时可先检查已有.env并导出或主动向用户索要密钥后写入.env并export保证后续 curl / API 调用可用。快速校验命令如下[ -z $BFL_API_KEY ] echo Error: BFL_API_KEY not set || echo OK: Key configured区域端点与认证方式BFL API 提供三个区域入口满足不同数据驻留与合规需求RegionEndpoint适用场景Globalhttps://api.bfl.ai默认自动故障转移EUhttps://api.eu.bfl.aiGDPR 合规、欧盟数据驻留UShttps://api.us.bfl.ai美国数据驻留建议除非有明确的区域合规要求否则一律使用 Global 端点api.bfl.ai。所有请求都需要在请求头中携带 API Keyx-key: YOUR_API_KEY模型端点与定价BFL API 使用信用点credits计费1 credit $0.01 USD。FLUX.2 系列采用基于百万像素megapixel, MP的动态定价成本随分辨率升高而增长。FLUX.2 系列T2I / I2I 通用模型路径首 MP后续每 MP1MP T2I1MP I2I最佳场景FLUX.2 [klein] 4B/v1/flux-2-klein-4b1.4c0.1c$0.014$0.015实时、高吞吐FLUX.2 [klein] 9B/v1/flux-2-klein-9b1.5c0.2c$0.015$0.017质量/速度均衡FLUX.2 [pro]/v1/flux-2-pro3c1.5c$0.03$0.045生产环境、快速周转FLUX.2 [max]/v1/flux-2-max7c3c$0.07$0.10最高质量FLUX.2 [flex]/v1/flux-2-flex5c5c$0.05$0.10排版文字、可调参数FLUX.2 [dev]---免费免费本地开发非商用定价公式单位为分(firstMP (outputMP - 1) * mpPrice) (inputMP * mpPrice)FLUX.1 系列模型路径每张价格最佳场景FLUX.1 Kontext [pro]/v1/flux-kontext$0.04带上下文信息的图像编辑FLUX.1 Kontext [max]/v1/flux-kontext-max$0.08最高质量编辑FLUX1.1 [pro]/v1/flux-pro-1.1$0.04标准 T2I快速可靠FLUX1.1 [pro] Ultra/v1/flux-pro-1.1-ultra$0.06超高分辨率FLUX1.1 [pro] Raw/v1/flux-pro-1.1-raw$0.06自然抓拍感摄影FLUX.1 Fill [pro]/v1/flux-pro-1.0-fill$0.05局部重绘inpainting关键提示所有 FLUX.2 模型都通过input_image参数原生支持图像编辑无需单独的编辑端点。在做图像编辑时官方推荐优先选择 FLUX.2 而非 FLUX.1 Kontext性能表现更好。请求参数详解文生图T2I通用参数参数类型必填说明promptstring是文本描述最长 32K tokenswidthinteger否图像宽度16 的倍数总像素上限 4MPheightinteger否图像高度16 的倍数总像素上限 4MPseedinteger否随机种子用于结果复现safety_toleranceinteger否0严格到 5宽松默认 2output_formatstring否jpeg或png默认jpegwebhook_urlstring否异步通知回调地址webhook_secretstring否Webhook 签名密钥图生图I2I参数优先使用图片 URL 而非 base64——API 会自动抓取 URL更简单方便。URL 与 base64 都可用但推荐在有 URL 的情况下直接用 URL。参数类型必填说明promptstring是编辑指令input_imagestring是URL推荐或 base64API 自动抓取input_image_2~input_image_8string否额外参考图 URL 或 base64widthinteger否输出宽度heightinteger否输出高度FLUX.2 [flex] 专属参数参数类型默认值说明stepsinteger50推理步数1–50guidancefloat4.5引导系数1.5–10分辨率约束最小64×64 像素最大总计 4MP宽 × 高倍数宽高均须为 16 的倍数。常用分辨率参考宽高比分辨率百万像素1:1方形1024x10241.05 MP16:9宽屏1920x10802.07 MP9:16竖屏1080x19202.07 MP4:3经典1536x11521.77 MP2:1全景2048x10242.10 MP图生图与多参考编辑单图编辑FLUX.2 系列只需在请求中加入input_image即可完成编辑无需切换端点curl -X POST https://api.bfl.ai/v1/flux-2-pro \ -H x-key: $BFL_API_KEY \ -H Content-Type: application/json \ -d { prompt: Change the background to a sunset, input_image: https://example.com/photo.jpg }多参考编辑FLUX.2 支持同时传入多张参考图用于元素组合、风格迁移与角色一致性保持。各模型最大参考图数量如下模型最大参考图数FLUX.2 [klein]4 张FLUX.2 [pro/max/flex]8 张参数依次为input_image、input_image_2、input_image_3…input_image_8。在 prompt 中按编号引用对应图片curl -X POST https://api.bfl.ai/v1/flux-2-pro \ -H x-key: $BFL_API_KEY \ -H Content-Type: application/json \ -d { prompt: The person from image 1 in the environment from image 2, input_image: https://example.com/person.jpg, input_image_2: https://example.com/background.jpg }Prompt 引用示例The subject from image 1 in the environment from image 2Apply the style of image 2 to the scene in image 1The person from image 1 wearing the outfit from image 2, in the pose from image 3多参考场景的详细模式角色一致性、风格迁移、姿态引导可参考 flux-best-practices/rules/multi-reference-editing.md更完整的提示词技巧T2I、I2I、排版、色彩见 flux-best-practices 技能其中包含 t2i-prompting.md、i2i-prompting.md、typography-text.md 等专门规则。核心请求流程提交 → 轮询 → 下载BFL API 采用异步生成模型所有生成请求立即返回一个polling_url真正的图像结果需要轮询获取。这是整条集成链路中最关键的行为特征。1. POST 请求模型端点 └─ 立即返回: { polling_url: ... } 2. GET polling_url重复直到完成 └─ 返回: { status: Pending | Ready | Error, ... } 3. 当状态为 Ready 时下载结果 URL └─ URL 10 分钟后过期——必须立即下载快速开始4 步跑通第 1 步提交生成请求curl -s -X POST https://api.bfl.ai/v1/flux-2-pro \ -H x-key: $BFL_API_KEY \ -H Content-Type: application/json \ -d {prompt: A serene mountain landscape at sunset, width: 1024, height: 1024}响应{ id: abc123, polling_url: https://api.bfl.ai/v1/get_result?idabc123 }第 2 步轮询结果curl -s POLLING_URL -H x-key: $BFL_API_KEY就绪时响应{ status: Ready, result: { sample: https://..., seed: 1234 } }第 3 步立即下载图片curl -s -o output.png IMAGE_URL重要提醒结果 URL 仅 10 分钟有效。状态变为Ready后必须立即下载不要缓存或存储 URL 本身。第 4 步多参考示例见上文多参考编辑。轮询端点的完整响应状态定义见 references/endpoints.md// Pending { status: Pending } // Ready { status: Ready, result: { sample: https://bfldeliveryprod.blob.core.windows.net/results/..., prompt: ..., seed: 1234567890 } } // Error { status: Error, error: Error description }异步轮询模式深度实践轮询是集成 BFL API 的基础模式适用于脚本、CLI 工具、本地开发与简单集成。参考 references/polling-patterns.md共有三种轮询策略固定间隔轮询import time import requests def poll_fixed_interval(polling_url, headers, interval2, timeout120): Simple polling with fixed interval. start_time time.time() while time.time() - start_time timeout: response requests.get(polling_url, headersheaders) data response.json() if data[status] Ready: return data[result] elif data[status] Error: raise Exception(data.get(error, Generation Error)) time.sleep(interval) raise TimeoutError(Polling timeout exceeded)指数退避轮询推荐import time import random import requests def poll_with_backoff(polling_url, headers, max_attempts30): Polling with exponential backoff and jitter. base_delay 0.5 # 从 500ms 起步 max_delay 10 # 上限 10 秒 for attempt in range(max_attempts): response requests.get(polling_url, headersheaders) data response.json() if data[status] Ready: return data[result] elif data[status] Error: raise Exception(data.get(error, Generation Error)) # 指数退避 抖动 delay min(base_delay * (2 ** attempt), max_delay) jitter random.uniform(0, delay * 0.1) # 10% jitter time.sleep(delay jitter) raise TimeoutError(Max polling attempts exceeded)自适应轮询根据返回状态动态调整间隔Pending时 2 秒、未知状态 1.5 秒实现更灵活的轮询节奏import time import requests def poll_adaptive(polling_url, headers, timeout120): Adaptive polling that adjusts based on status. start_time time.time() delays { Pending: 2.0, # 排队/处理中 None: 1.5 # 未知/默认 } while time.time() - start_time timeout: response requests.get(polling_url, headersheaders) data response.json() status data.get(status) if status Ready: return data[result] elif status Error: raise Exception(data.get(error, Generation Error)) delay delays.get(status, delays[None]) time.sleep(delay) raise TimeoutError(Polling timeout exceeded)完整客户端提交 轮询封装参考 references/polling-patterns.md 中的完整示例可封装一个带渐进退避1 秒起步、每次 ×1.5、封顶 5 秒的BFLClient对外只暴露一个generate(model, prompt)方法。更完整的生产级实现可直接使用仓库中的 python-client.py它内置了异常体系AuthenticationError、RateLimitError、GenerationError等、Semaphore并发控制、generate_i2i、generate_batch、download等方法支持 global/eu/us 三区域端点并对flux-kontext-max并发上限 6与默认端点24区分了不同的限流值。批量并发生成高吞吐场景可用asyncio aiohttp并行提交与轮询import asyncio import aiohttp async def generate_batch(client, prompts, modelflux-2-pro): Generate multiple images concurrently. async with aiohttp.ClientSession() as session: # 提交所有请求 tasks [] for prompt in prompts: task submit_and_poll(session, client, model, prompt) tasks.append(task) # 等待全部完成 results await asyncio.gather(*tasks, return_exceptionsTrue) return results轮询最佳实践永远设置超时——绝不无限轮询使用指数退避——降低服务器负载应对拥塞加入抖动jitter——避免多请求并发轮询时形成惊群效应处理所有状态值——包括未预料到的状态立即下载——URL 10 分钟过期记录轮询日志——便于调试与监控尊重限流——对 429 响应实现合理的退避。速率限制与并发控制BFL API 通过限流保障公平使用与系统稳定。当前主要限制为并发请求数已提交但未完成的在途请求端点类别并发请求数Standard大多数模型24Kontext Max特殊6响应头中会携带限流状态X-RateLimit-Limit: 24 X-RateLimit-Remaining: 23 X-RateLimit-Reset: 1640000000被限流时返回 HTTP 429{ error: rate_limit_exceeded, message: Too many concurrent requests, retry_after: 5 }四种限流应对策略1. 客户端主动计数信号量用threading.Semaphore(max_concurrent)包装请求达到上限时阻塞等待详见 references/rate-limiting.md。2. 429 指数退避重试import time def request_with_retry(endpoint, payload, headers, max_retries5): Make request with automatic retry on rate limit. for attempt in range(max_retries): response requests.post(endpoint, jsonpayload, headersheaders) if response.status_code 429: retry_after int(response.headers.get(Retry-After, 5)) wait_time retry_after * (2 ** attempt) # 指数退避 print(fRate limited. Waiting {wait_time}s...) time.sleep(wait_time) continue response.raise_for_status() return response raise Exception(Max retries exceeded due to rate limiting)3. 队列化架构高流量应用可启动 N 个 worker 线程消费任务队列天然把并发压在上限内。4. 异步信号量asyncio.Semaphore(max_concurrent)配合aiohttp即可在并发 50 个任务的场景下稳定运行完整代码。限流监控与区域分发可维护一个RateLimitMonitor统计总请求数、429 命中次数与命中率超大规模场景可考虑在三个区域端点间做轮询round-robin分发但使用前务必确认各区域限流是否相互独立。限流处理的最佳实践主动跟踪在途请求、客户端侧提前设限、用信号量优雅控制并发、高峰用队列缓冲、监控响应头剩余额度、接近上限时优雅降级、并注意 Kontext Max 的并发上限是 6 而非 24。错误处理与恢复策略参考 references/error-handling.mdBFL API 的错误分为两类HTTP 层错误与生成层错误。HTTP 状态码速查| 码 | 含义 | 原因 | 应对 | | -- | ---- | ---- | ---- | | 200 | OK | 请求成功 | 处理响应 | | 400 | Bad Request | 参数无效 | 检查请求格式 | | 401 | Unauthorized | Key 无效/缺失 | 校验凭据 | | 402 | Payment Required | 信用点不足 | 账户充值 | | 403 | Forbidden | 访问被拒 | 检查权限 | | 404 | Not Found | 端点无效 | 核对 URL | | 429 | Too Many Requests | 被限流 | 实现退避 | | 500 | Internal Server Error | 服务器问题 | 退避重试 | | 502 | Bad Gateway | 网络问题 | 退避重试 | | 503 | Service Unavailable | 临时不可用 | 退避重试 |错误响应格式{ error: error_code, message: Human-readable description, details: { field: specific field info } }常见错误与解法401 invalid_api_keyKey 无效或过期。可在客户端做前置校验Key 非空且以bfl_开头。402 insufficient_credits账户余额不足需充值后继续。429 rate_limit_exceeded并发超限按Retry-After退避。400 validation_error常见于width非 16 的倍数、prompt为空、总像素超过 4MP。客户端可在提交前用validate_request前置拦截避免浪费请求。生成层错误轮询阶段返回status: Error常见原因包括content_policy_violation提示词/图片触发安全策略、generation_timeout生成超时、internal_error服务端问题、invalid_image输入图无法处理。可重试 / 不可重试分类可重试429、500、502、503以及generation_timeout、internal_error不可重试400、401、402、403以及content_policy_violation、invalid_image。参考文档给出了完整的classify_error 指数退避重试框架以及一个覆盖全部场景的BFLError异常体系含AuthenticationError、InsufficientCreditsError、RateLimitError、ValidationError、GenerationError。生产系统还可叠加**熔断器Circuit Breaker**模式连续失败达到阈值如 5 次后进入 open 状态暂停请求并在冷却期如 60 秒后进入 half-open 试探恢复。Webhook 集成生产环境的通知机制对于生产级工作负载官方推荐用 Webhook 替代轮询详见 references/webhook-integration.md。Webhook 相比轮询的优势减少 API 调用——无需反复轮询即时通知——生成完成的瞬间即收到回调资源效率更高——不浪费计算在轮询上架构可扩展——事件驱动设计。请求中携带 Webhookcurl -X POST https://api.bfl.ai/v1/flux-2-pro \ -H x-key: YOUR_API_KEY \ -H Content-Type: application/json \ -d { prompt: A beautiful sunset over mountains, webhook_url: https://your-server.com/api/bfl-webhook, webhook_secret: your-secret-key-here }Webhook Payload成功{ id: gen_abc123xyz, status: Ready, result: { sample: https://bfldeliveryprod.blob.core.windows.net/results/..., prompt: ..., seed: 1234567890 }, timestamp: 2025-01-15T10:30:00Z }失败{ id: gen_abc123xyz, status: Error, error: content_policy_violation, message: The prompt violated content policy, timestamp: 2025-01-15T10:30:00Z }签名校验安全关键配置了webhook_secret后BFL 会用HMAC-SHA256对请求体签名签名放在X-BFL-Signature请求头中X-BFL-Signature: sha256hex-encoded-signaturePython 校验实现完整 Flask 示例import hmac import hashlib def verify_webhook_signature(payload, signature, secret): Verify the webhook came from BFL. if not signature or not signature.startswith(sha256): return False expected_signature hmac.new( secret.encode(utf-8), payload, hashlib.sha256 ).hexdigest() provided_signature signature[7:] # 去掉 sha256 前缀 return hmac.compare_digest(expected_signature, provided_signature)同样地typescript-client.ts 中提供了 Node.js/Express 版本的crypto.timingSafeEqual签名校验实现。Webhook 服务端要求必须 HTTPSBFL 不会向 HTTP 端点发送 Webhook收到回调后需返回2xx确认30 秒内响应处理器要保持轻量重活如下载、入库异步化。投递重试策略BFL 对失败的 Webhook 投递会重试次数延迟第 1 次重试1 秒第 2 次重试5 秒第 3 次重试30 秒3 次失败后该 Webhook 被放弃。关键任务应回退到轮询兜底。幂等处理由于存在重试Webhook 可能重复投递。推荐用 Redis 的SET NX如webhook:processed:{generation_id}TTL 1 小时做去重重复回调直接返回 200。混合模式Webhook 优先 轮询兜底生产最佳实践是同时配置 Webhook 与轮询优先等待 Webhook 到达设置超时超时未到则回退到polling_url轮询。配合WebhookMetrics监控类可统计接收数、处理数、失败数与平均延迟持续观测 Webhook 健康状况。参考文档导航本技能附带完整的参考文档体系均位于仓库.claude/skills/bfl-api/目录下references/api-key-setup.md — API Key 创建与配置含 Agent 自动化方案references/endpoints.md — 全部端点文档与请求示例references/polling-patterns.md — 异步轮询实现与批量并发references/rate-limiting.md — 限流处理策略与监控references/error-handling.md — 错误码与恢复方案references/webhook-integration.md — Webhook 配置、签名与安全。代码示例默认优先使用 cURL因为它无需 Python 或 Node.js 环境即可运行构建生产应用时再选用语言客户端references/code-examples/curl-examples.sh — 完整的 cURL 脚本含 Key 校验、提交、轮询、下载、I2I 示例references/code-examples/python-client.py — 生产级 Python 客户端references/code-examples/typescript-client.ts — TypeScript 客户端。集成决策速查最后把本文的关键决策点汇总为一张速查清单选模型实时高吞吐选 [klein] 4B质量速度均衡选 [klein] 9B生产默认选 [pro]最高质量选 [max]排版文字选 [flex]本地免费开发用 [dev]选端点无合规要求用 Global欧盟合规用 EU美国驻留用 US传图方式优先 URL多参考按input_image_N编号并最多 8 张取结果简单场景用轮询加超时、退避、抖动生产高并发场景用 Webhook 轮询兜底 签名校验 幂等去重控并发默认以 24 并发为上限Kontext Max 为 6用信号量或队列控制防错误提交前校验分辨率16 倍数、≤4MP、≥64px对 429/5xx 退避重试对 4xx 立即修复参数记时间结果 URL 10 分钟过期Ready后立即下载不要缓存 URL。【免费下载链接】OpenMontageWorlds first open-source, agentic video production system. 12 production pipelines, 100 tools, 700 agent skill and production-knowledge files. Turn your AI coding assistant into a full video production studio.项目地址: https://gitcode.com/GitHub_Trending/op/OpenMontage创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考