热门模型
概述
使用 Flux、Nano Banana Pro 以及其他前沿 AI 模型,从文本描述生成图像。本示例将带你完成从提交生成请求到获取最终图像的完整流程。图像生成是异步的。你会立即收到一个 job ID,然后需要轮询结果,直到图像生成完成。
交互式 Playground
以下是不同语言的完整示例:// npm install @krea-ai/sdk
import { Krea } from "@krea-ai/sdk";
const krea = new Krea({ apiKey: process.env.KREA_API_KEY });
const result = await krea.subscribe("image/bfl/flux-1-dev", {
input: {
prompt: "a serene mountain landscape at sunset",
width: 1024,
height: 576,
steps: 28
}
});
console.log(`Image ready: ${result.data?.urls[0]}`);
import requests
import time
API_BASE = "https://api.krea.ai"
API_TOKEN = "your-token-secret"
# Step 1: Create generation job
response = requests.post(
f"{API_BASE}/generate/image/bfl/flux-1-dev",
headers={
"Authorization": f"Bearer {API_TOKEN}",
"Content-Type": "application/json"
},
json={
"prompt": "a serene mountain landscape at sunset",
"width": 1024,
"height": 576,
"steps": 28
}
)
job = response.json()
job_id = job["job_id"]
# Step 2: Poll for completion
while True:
response = requests.get(
f"{API_BASE}/jobs/{job_id}",
headers={"Authorization": f"Bearer {API_TOKEN}"}
)
job = response.json()
if job["status"] == "completed":
image_url = job["result"]["urls"][0]
print(f"Image ready: {image_url}")
break
if job["status"] in ("failed", "cancelled"):
raise Exception(f"Job failed: {job['status']}")
print(f"Status: {job['status']}")
time.sleep(2)
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"time"
)
func main() {
apiBase := "https://api.krea.ai"
apiToken := "your-token-secret"
client := &http.Client{}
// Step 1: Create generation job
payload := map[string]interface{}{
"prompt": "a serene mountain landscape at sunset",
"width": 1024,
"height": 576,
"steps": 28,
}
jsonData, _ := json.Marshal(payload)
req, _ := http.NewRequest("POST", apiBase+"/generate/image/bfl/flux-1-dev", bytes.NewBuffer(jsonData))
req.Header.Set("Authorization", "Bearer "+apiToken)
req.Header.Set("Content-Type", "application/json")
resp, _ := client.Do(req)
var job map[string]interface{}
json.NewDecoder(resp.Body).Decode(&job)
resp.Body.Close()
jobID := job["job_id"].(string)
// Step 2: Poll for completion
for {
req, _ := http.NewRequest("GET", apiBase+"/jobs/"+jobID, nil)
req.Header.Set("Authorization", "Bearer "+apiToken)
resp, _ := client.Do(req)
var jobStatus map[string]interface{}
json.NewDecoder(resp.Body).Decode(&jobStatus)
resp.Body.Close()
switch jobStatus["status"] {
case "completed":
result := jobStatus["result"].(map[string]interface{})
imageURL := result["urls"].([]interface{})[0].(string)
fmt.Printf("Image ready: %s\n", imageURL)
return
case "failed", "cancelled":
fmt.Printf("Job failed: %s\n", jobStatus["status"])
return
}
fmt.Printf("Status: %s\n", jobStatus["status"])
time.Sleep(2 * time.Second)
}
}
# Step 1: Create generation job
curl -X POST https://api.krea.ai/generate/image/bfl/flux-1-dev \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"prompt": "a serene mountain landscape at sunset",
"width": 1024,
"height": 576,
"steps": 28
}'
# Response: {"job_id": "550e8400-e29b-41d4-a716-446655440000", ...}
# Step 2: Poll for completion (repeat until completed)
curl -X GET https://api.krea.ai/jobs/550e8400-e29b-41d4-a716-446655440000 \
-H "Authorization: Bearer YOUR_API_TOKEN"
替换为你的 API Token要替换上述示例中的 YOUR_API_TOKEN 占位符,你需要在 krea.ai/settings/api-tokens 生成一个 API token。如果需要帮助,请参考 API Keys & Billing 页面上的说明。
分步说明
下面我们将带你完成从提交生成请求到获取最终图像的完整流程。步骤 1:创建图像生成任务
向/generate/image/bfl/flux-1-dev 发送 POST 请求,附带你的提示词和参数。API 会立即返回一个 job ID——生成过程是异步的。
// npm install @krea-ai/sdk
import { Krea } from "@krea-ai/sdk";
const krea = new Krea({ apiKey: process.env.KREA_API_KEY });
const job = await krea.image("bfl/flux-1-dev", {
prompt: "a serene mountain landscape at sunset",
width: 1024,
height: 576,
steps: 28
});
console.log(`Job ID: ${job.job_id}`);
curl -X POST https://api.krea.ai/generate/image/bfl/flux-1-dev \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"prompt": "a serene mountain landscape at sunset",
"width": 1024,
"height": 576,
"steps": 28
}'
import requests
API_BASE = "https://api.krea.ai"
API_TOKEN = "your-token-secret"
response = requests.post(
f"{API_BASE}/generate/image/bfl/flux-1-dev",
headers={
"Authorization": f"Bearer {API_TOKEN}",
"Content-Type": "application/json"
},
json={
"prompt": "a serene mountain landscape at sunset",
"width": 1024,
"height": 576,
"steps": 28
}
)
job = response.json()
print(f"Job ID: {job['job_id']}")
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
func main() {
apiBase := "https://api.krea.ai"
apiToken := "your-token-secret"
payload := map[string]interface{}{
"prompt": "a serene mountain landscape at sunset",
"width": 1024,
"height": 576,
"steps": 28,
}
jsonData, _ := json.Marshal(payload)
req, _ := http.NewRequest("POST", apiBase+"/generate/image/bfl/flux-1-dev", bytes.NewBuffer(jsonData))
req.Header.Set("Authorization", "Bearer "+apiToken)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, _ := client.Do(req)
defer resp.Body.Close()
var job map[string]interface{}
json.NewDecoder(resp.Body).Decode(&job)
fmt.Printf("Job ID: %s\n", job["job_id"])
}
{
"job_id": "550e8400-e29b-41d4-a716-446655440000",
"status": "queued",
"created_at": "2025-01-15T10:30:00.000Z"
}
步骤 2:轮询结果
每 2 秒轮询一次/jobs/{job_id},直到任务完成。Krea API 会为部分模型提供中间生成结果。
// npm install @krea-ai/sdk
import { Krea } from "@krea-ai/sdk";
const krea = new Krea({ apiKey: process.env.KREA_API_KEY });
async function waitForJob(jobId) {
const completed = await krea.jobs.wait(jobId, { intervalMs: 2000 });
return completed.result.urls[0];
}
const imageUrl = await waitForJob(job.job_id);
console.log(`Image ready: ${imageUrl}`);
# Check job status
curl -X GET https://api.krea.ai/jobs/YOUR_JOB_ID \
-H "Authorization: Bearer YOUR_API_TOKEN"
import time
def wait_for_job(job_id):
while True:
response = requests.get(
f"{API_BASE}/jobs/{job_id}",
headers={"Authorization": f"Bearer {API_TOKEN}"}
)
job = response.json()
if job["status"] == "completed":
return job["result"]["urls"][0]
if job["status"] in ("failed", "cancelled"):
raise Exception(f"Job failed: {job['status']}")
print(f"Status: {job['status']}")
time.sleep(2)
image_url = wait_for_job(job["job_id"])
print(f"Image ready: {image_url}")
func waitForJob(jobID string) (string, error) {
for {
req, _ := http.NewRequest("GET", apiBase+"/jobs/"+jobID, nil)
req.Header.Set("Authorization", "Bearer "+apiToken)
resp, _ := client.Do(req)
var job map[string]interface{}
json.NewDecoder(resp.Body).Decode(&job)
resp.Body.Close()
switch job["status"] {
case "completed":
result := job["result"].(map[string]interface{})
urls := result["urls"].([]interface{})
return urls[0].(string), nil
case "failed", "cancelled":
return "", fmt.Errorf("job failed: %s", job["status"])
}
fmt.Printf("Status: %s\n", job["status"])
time.Sleep(2 * time.Second)
}
}
Webhook 可用!设置 webhook,可在任务完成时收到通知。参见 Webhooks 指南 开始使用。
要查看所有模型的详细参数列表,请访问 Model APIs 页面。
{
"job_id": "550e8400-e29b-41d4-a716-446655440000",
"status": "completed",
"created_at": "2025-01-15T10:30:00.000Z",
"completed_at": "2025-01-15T10:30:25.000Z",
"result": {
"urls": [
"https://krea.ai/generations/your-image.png"
]
}
}
要了解所有可能的任务状态以及完整的任务生命周期,请查看 Job Lifecycle 页面。