教程
如何通过 hiapi API 使用 flux-2-klein-4b/image-to-image
- 模型
- flux-2-klein-4b
FLUX.2 [klein] 4B 是 Black Forest Labs 推出的紧凑、快速的图像编辑模型:给它一张参考图和一段自然语言指令,它就能返回一张最高 4 MP 的编辑后图像。在 hiapi 上,它和其他所有模型一样通过同一个 Unified Async API 运行——用 POST /v1/tasks 创建任务,然后轮询或接收回调获取结果。本指南涵盖确切的请求结构、可用的 curl/Python 示例,以及如何将其接入生产环境。
你需要准备什么
- 一个 hiapi API 密钥。可从 dashboard 获取——密钥形如
sk-...,放在Authorization: Bearer请求头中。 - 一个可公开访问的参考图 URL(jpeg、png 或 webp——不支持 svg)。超过 4 MP 的图像会自动缩小到 4 MP。
flux-2-klein-4b/image-to-image的当前定价按分辨率分档(0.25 MP 到 4 MP)——请查看 hiapi pricing 获取实时价格,不要在这里硬编码。
最小可用示例
模型 ID 是 flux-2-klein-4b/image-to-image——请严格按此写法使用(包含斜杠),作为 model 的值(不要放在 URL 路径中)。所有 hiapi 模型共享同一个端点;只有 input 对象的字段因模型而异。
curl -X POST "https://api.hiapi.ai/v1/tasks" \
-H "Authorization: Bearer sk-YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "flux-2-klein-4b/image-to-image",
"input": {
"prompt": "Keep the subject and camera angle. Replace the background with a deep-blue studio gradient and add soft rim lighting.",
"image_urls": ["https://your-cdn.example.com/product-shot.jpg"],
"resolution": "2 MP",
"aspect_ratio": "16:9"
}
}'
该请求会立即返回一个 taskId——生成是异步进行的:
{"code": 0, "message": "success", "data": {"taskId": "task_..."}}
轮询获取结果:
curl "https://api.hiapi.ai/v1/tasks/task_..." \
-H "Authorization: Bearer sk-YOUR_API_KEY"
当 status 变为 "success" 时,编辑后的图像位于 data.output[0].url。该 URL 是临时的(带有 expireAt),因此请立即下载或重新托管该文件——不要直接存储这个热链接。
用 Python 实现同样的流程:
import time
import requests
API = "https://api.hiapi.ai/v1/tasks"
HEADERS = {
"Authorization": "Bearer sk-YOUR_API_KEY",
"Content-Type": "application/json",
}
def create_task(prompt: str, image_url: str) -> str:
payload = {
"model": "flux-2-klein-4b/image-to-image",
"input": {
"prompt": prompt,
"image_urls": [image_url],
"resolution": "2 MP",
"aspect_ratio": "16:9",
},
}
resp = requests.post(API, headers=HEADERS, json=payload, timeout=30)
resp.raise_for_status()
return resp.json()["data"]["taskId"]
def wait_task(task_id: str, timeout_s: int = 300, poll_s: int = 5) -> dict:
deadline = time.time() + timeout_s
while time.time() < deadline:
r = requests.get(f"{API}/{task_id}", headers=HEADERS, timeout=30)
task = r.json()["data"]
if task["status"] == "success":
return task
if task["status"] == "fail":
raise RuntimeError(f"task {task_id} failed: {task.get('error')}")
time.sleep(poll_s)
raise TimeoutError(f"task {task_id} did not finish in {timeout_s}s")
task_id = create_task(
"Keep the subject and camera angle. Replace the background with a deep-blue "
"studio gradient and add soft rim lighting.",
"https://your-cdn.example.com/product-shot.jpg",
)
result = wait_task(task_id)
print(result["output"][0]["url"])
请求参数
flux-2-klein-4b/image-to-image 接受严格的输入 schema——此处未列出的额外字段会被拒绝并返回 400:
| 字段 | 是否必填 | 说明 |
|---|---|---|
prompt |
是 | 对要应用的编辑的自然语言描述。 |
image_urls |
是 | 包含恰好一个参考图 URL 的数组。传入多个会返回 maxItems: got N, want 1。 |
resolution |
否 | 可选值之一:0.25 MP、0.5 MP、1 MP(默认)、2 MP、4 MP。用 0.25/0.5 MP 低成本草稿,用 2/4 MP 完成最终输出。 |
aspect_ratio |
否 | 可选值之一:match_input_image(默认)、1:1、16:9、9:16、3:2、2:3、4:3、3:4、5:4、4:5、21:9、9:21。 |
seed |
否 | 整数,用于在其余完全相同的请求之间实现可复现的输出。 |
output_format |
否 | jpg(默认)、png 或 webp。 |
output_quality |
否 | 整数,jpg/webp 的压缩质量(默认 95)。 |
此模型没有 size 或 n 字段——这些是其他提供商的约定,此 schema 不识别。每个 hiapi 模型都有自己的字段集,因此在移植为其他模型构建的请求之前,请查看模型参考页面。
生产环境注意事项
优先使用回调而非轮询。 添加一个顶层 callback 对象,hiapi 会通知你的服务,而不是让你在循环中轮询:
{
"model": "flux-2-klein-4b/image-to-image",
"input": { "prompt": "...", "image_urls": ["..."] },
"callback": { "url": "https://your-domain.com/hiapi/callback", "when": "final" }
}
when 只接受 "final"——任务到达终态(success 或 fail)时发送一次通知,而不是进度流。将回调视为唤醒信号:收到后,仍应 GET /v1/tasks/<taskId> 读取权威状态,并让处理程序对 taskId 保持幂等,以防重复投递。
幂等性。 在 create_task 返回后立即持久化 taskId,然后再开始轮询或等待回调。如果进程在等待期间崩溃,重启后应使用 GET /v1/tasks/<taskId> 恢复,而不是重新创建任务——任务创建是计费事件,GET 可以免费重复。
错误处理。 无效或未授权的密钥会返回 HTTP 401 和结构化响应体:
{
"error": {
"code": "permission_denied",
"message": "This API key cannot use the selected model. Please check permissions or use another key. If the issue persists, contact support with request ID: ...",
"request_id": "...",
"type": "hiapi_error"
}
}
记录 request_id——支持团队可以据此查找确切的调用。格式错误的 input(缺少 prompt/image_urls、不支持的 aspect_ratio 值,或无法识别的额外字段)会返回 400,带有 error_code: "INVALID_REQUEST",并在消息中指明有问题的字段;请修正请求体,而不是原样重试。
相关阅读
- FLUX.2 [klein] 4B 图生图模型参考——完整参数文档和示例请求体。
- FLUX.2 [klein] 4B 文生图模型参考——对应的文生图变体,无需参考图。
- hiapi pricing——当前按分辨率分档的每张图像成本。
- Unified Async API 概览——平台上每个模型共享的
POST /v1/tasks/GET /v1/tasks/:id契约。
常见问题
image_urls 接受哪些图像格式?
jpeg、png 或 webp。不支持 svg。大于 4 MP 的图像会在编辑前自动缩小到 4 MP。
我可以传入多张参考图吗?
不可以——此模型上的 image_urls 上限恰好为一个元素。传入更多会返回 400(maxItems: got N, want 1)。
为什么我的请求被拒绝,提示 "additional properties ... not allowed"?
该 schema 是严格的:任何不在上述参数表中的字段(例如其他提供商的 size、n 或 strength 等约定)都会触发 400。查看模型参考了解确切接受的字段集。
如何保持原始图像的宽高比?
将 aspect_ratio 设为 match_input_image——如果你完全省略该字段,这也是默认值。
flux-2-klein-4b/image-to-image 和 9B 变体有什么区别?
两者共享相同的请求 schema(prompt、image_urls、resolution、aspect_ratio、seed、output_format、output_quality)。9B 路线牺牲一些速度和成本,换取更强的真实感、文本渲染和细节——当你快速、低成本地迭代时用 4B,当编辑需要在精细细节上经得起考验时用 9B。
我需要回调 URL 吗,还是轮询就可以?
使用 GET /v1/tasks/:id 轮询对于本地开发、低量任务,或作为回调投递遗漏时的兜底方案是没问题的。对于生产流量,回调可以避免每个请求都进行轮询循环的开销。