教程
flux-2-klein-9b API:curl 与 Python 指南
- 模型
- flux-2-klein-9b
在 hiapi 上用 flux-2-klein-9b 生成一张图片,只需一次 POST /v1/tasks 调用加轮询——与平台上每个模型使用的异步任务模式完全一致。本指南记录了一次真实的请求与响应(任务创建、轮询以及最终图片 URL),因此下面的代码可以直接复制运行,而非示意性代码。
你需要准备什么
- 一个 hiapi API 密钥——在控制台中创建。每次请求都会以 Bearer token 的形式发送。
- 完整的模型 ID,包括端点后缀。 flux-2-klein-9b 只能通过
flux-2-klein-9b/text-to-image访问——只写flux-2-klein-9b会返回 400(见下文)。
最小可用请求(curl)
创建任务:
curl -X POST https://api.hiapi.ai/v1/tasks \
-H "Authorization: Bearer sk-<your-key>" \
-H "Content-Type: application/json" \
-d '{
"model": "flux-2-klein-9b/text-to-image",
"input": {
"prompt": "a weathered lighthouse on a rocky coast at sunset, cinematic lighting",
"aspect_ratio": "16:9"
}
}'
响应:
{"code":200,"data":{"taskId":"tk-hiapi-01M0T23CG2GNPENYQV4WEKZJTM"},"message":"success"}
轮询任务直到完成:
curl https://api.hiapi.ai/v1/tasks/tk-hiapi-01M0T23CG2GNPENYQV4WEKZJTM \
-H "Authorization: Bearer sk-<your-key>"
完成时的响应:
{
"code": 200,
"data": {
"taskId": "tk-hiapi-01M0T23CG2GNPENYQV4WEKZJTM",
"status": "success",
"model": "flux-2-klein-9b/text-to-image",
"created": 1787581018,
"completed": 1787581030,
"storage": "temp",
"output": [
{
"type": "image",
"url": "https://temp.hiapi.ai/7c6ttvrbpt/01M0T23CG2GNPENYQV4WEKZJTM-0.png",
"artifactId": "96193",
"expireAt": 1788185830
}
]
},
"message": "success"
}
output[0].url 就是那张 PNG。在测试中,任务从提交到 success 大约用了 12 秒。请注意 expireAt——在构建任何依赖该 URL 持续可用的功能之前,请先阅读下面的存储说明。
Python 中的同一流程
import time
import requests
API_KEY = "sk-<your-key>"
BASE_URL = "https://api.hiapi.ai/v1"
HEADERS = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}
def create_image(prompt: str, aspect_ratio: str = "1:1") -> str:
resp = requests.post(
f"{BASE_URL}/tasks",
headers=HEADERS,
json={
"model": "flux-2-klein-9b/text-to-image",
"input": {"prompt": prompt, "aspect_ratio": aspect_ratio},
},
timeout=30,
)
body = resp.json()
if resp.status_code != 200 or "error" in body:
raise RuntimeError(f"create failed: {body}")
return body["data"]["taskId"]
def wait_for_image(task_id: str, timeout_s: int = 120, interval_s: int = 3) -> str:
deadline = time.time() + timeout_s
while time.time() < deadline:
resp = requests.get(f"{BASE_URL}/tasks/{task_id}", headers=HEADERS, timeout=30)
data = resp.json()["data"]
if data["status"] == "success":
return data["output"][0]["url"]
if data["status"] == "failed":
raise RuntimeError(f"task {task_id} failed: {data}")
time.sleep(interval_s)
raise TimeoutError(f"task {task_id} still running after {timeout_s}s")
if __name__ == "__main__":
task_id = create_image("a weathered lighthouse on a rocky coast at sunset, cinematic lighting", "16:9")
image_url = wait_for_image(task_id)
image_bytes = requests.get(image_url, timeout=60).content
with open("output.png", "wb") as f:
f.write(image_bytes)
print(f"saved output.png from task {task_id}")
flux-2-klein-9b 实际校验的参数
输入 schema 非常严格——只要发送了未列出的字段,API 就会在请求进入队列之前直接拒绝整个请求:
prompt(字符串,必填)——唯一必填的字段。aspect_ratio(字符串,可选)——取值为1:1、4:3、3:4、16:9、9:16之一。其它任何值都会返回 400,并附带value must be one of ...。seed(整数,可选)——在相同的 prompt 下传入相同的 seed,可以得到可复现的结果。output_format(字符串,可选)——取值为jpeg、png、webp之一。
以上就是全部 schema。没有 size、quality、strength 或 n 字段——发送其中任何一个都会失败:
{"code":400,"data":null,"error_code":"INVALID_REQUEST","message":"invalid input: <root>: additional properties 'size' not allowed"}
flux-2-klein-9b 仅支持文生图。也不接受 image_urls——如需图生图,请改用单独的 flux-2-klein-9b/image-to-image 模型 ID,它接受不同的输入结构。
模型 ID 必须带端点后缀
hiapi 上有些模型可以用裸 ID 解析(如 gpt-image-2),但 flux-2-klein-9b 不属于此类。去掉后缀,任务就永远不会被创建:
{"code":400,"data":null,"error_code":"MODEL_UNAVAILABLE","message":"model not available via /v1/tasks"}
请始终把完整的 flux-2-klein-9b/text-to-image 字符串作为 model 发送。
生产环境注意事项
- 两种不同的错误结构。 校验错误(缺少字段、枚举值错误、未知键)会以顶层
{"code":400,"error_code":"INVALID_REQUEST","message":"..."}的形式返回。认证/权限错误则以{"error":{"code":"permission_denied","message":"...","request_id":"..."}}返回——是一个嵌套的error对象,HTTP 401。错误处理中要同时检查这两种结构;只检查resp["code"]的代码会漏掉 401 的情况。 permission_denied指的是密钥,而非请求。 如果prompt存在且类型正确,但仍然收到 401permission_denied,说明该 API 密钥本身没有启用此模型——请在控制台中检查,而不是反复检查你的 JSON。- 输出存储是临时的。
storage: "temp",且每个输出都带有expireAtunix 时间戳——在捕获的示例中约为创建后一周。任务成功后应立即下载文件或推送到你自己的存储;不要把temp.hiapi.ai的 URL 当作永久地址保存。 - 批量任务请使用回调。 轮询一张图片没问题;轮询五十张就是五十次重复往返。在创建请求的顶层设置
callback: {"url": "...", "when": "final"},让 hiapi 在任务真正完成时一次性把结果推送给你。目前when只支持"final"这一个值。 - 在拿到
taskId之前重试,而不是之后。 初始POST /v1/tasks出现网络错误或 5xx 时可以安全重试——此时尚未创建任何东西。一旦拿到了taskId,重新提交相同的 prompt 会创建第二张无关的图片;此时应改为轮询或等待回调。
相关内容
- flux-2-klein-9b 模型页面——当前定价和在线体验区。
- flux-2-klein-9b 文档参考——该模型专属的参考条目。
- hiapi 定价——目录中各模型的费率。
- 异步任务 API 文档——所有 hiapi 模型共享的完整创建/轮询约定。
常见问题
为什么调用 flux-2-klein-9b 时会得到 MODEL_UNAVAILABLE?
模型 ID 需要带端点后缀。请使用 flux-2-klein-9b/text-to-image,而不是裸的 flux-2-klein-9b。
flux-2-klein-9b 支持哪些宽高比?
五种:1:1、4:3、3:4、16:9、9:16。任何其它值都会返回 400,并附带列出这五个值的 value must be one of 消息。
我能控制输出质量或分辨率吗?
不能——schema 只接受 prompt、aspect_ratio、seed 和 output_format。没有 size 或 quality 参数;发送其中之一会返回 additional properties 的 400 错误。
我能用 flux-2-klein-9b 做图生图编辑吗?
不能通过这个模型 ID。请改用 flux-2-klein-9b/image-to-image,它有自己独立的输入 schema。
输出 URL 的有效期是多久?
storage 为 "temp",每个输出都带有 expireAt unix 时间戳,实际约为一周后。任务成功后请立即下载或重新上传该文件——不要把 URL 当作永久地址。
为什么在其他模型上可用的密钥在这个模型上会 401?
模型访问权限是按密钥授予的。返回 401 且 error_code: "permission_denied" 意味着这个特定密钥尚未获得 flux-2-klein-9b 的授权——请在控制台中启用它,这不是你请求体中的 bug。