人気のモデル
概要
Flux、Nano Banana Pro などの最先端 AI モデルを使って、テキストの説明から画像を生成します。この例では、生成リクエストの送信から最終的な画像の取得までの完全なワークフローを解説します。画像生成は非同期です。すぐにジョブ ID が返されるので、画像が完成するまでポーリングして結果を取得します。
インタラクティブなプレイグラウンド
さまざまな言語での完全な例を以下に示します:// 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 トークンを置き換えてください上記のサンプルにある YOUR_API_TOKEN プレースホルダーを置き換えるには、krea.ai/settings/api-tokens で API トークンを生成する必要があります。ヘルプが必要な場合は、API Keys & Billing ページの手順に従ってください。
詳細
以下では、生成リクエストの送信から最終的な画像の取得までの完全なワークフローを解説します。ステップ 1: 画像生成ジョブを作成する
/generate/image/bfl/flux-1-dev にプロンプトとパラメータを指定して POST リクエストを送信します。API は即座にジョブ 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: 結果をポーリングする
ジョブが完了するまで、/jobs/{job_id} を 2 秒ごとにポーリングします。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 ページをご覧ください。