grok-imagine-image-2.0
Grok Imagine Image 2.0 可依描述生成圖片,並選擇比例、解析度與品質。模型本身也支援圖片編輯及視覺風格轉換。
關於模型
此說明介紹模型的能力。Ailoot 可用的輸入、輸出與選項,依所選方法列於下方。
生成與調整圖片
Grok Imagine Image 2.0 接收場景描述後生成圖片。xAI 的此模型也能處理原始視覺素材,依文字指令修改,並將先前成果當作新輸入,繼續編輯。Ailoot 已公開的是文字生成方法。
視覺風格
對 Image 2.0,xAI 描述了寫實攝影、動漫、油畫及鉛筆素描等風格。風格透過文字指定;使用原始圖片時,指令決定所需的美感。連續修改可逐步加入細節,並調整成果。
比例、尺寸與數量
n指定同一描述生成 1 至 10 張圖片,預設為一張。aspect_ratio選擇畫面形狀,auto則交由模型選擇。resolution指定 1K 或 2K,預設為 1K。
提供正方形、橫式及直式比例:1:1、16:9、9:16、4:3、3:4、3:2、2:3、2:1、1:2。也有細長螢幕比例 19.5:9、9:19.5、20:9、9:20,以及寬幅比例 21:9 與 5:2。
品質選擇
Image 2.0 支援 low、medium 及 auto。此參數僅適用於這個版本;未指定品質時使用 auto。在查核當時,自動模式於生成時選擇 low,編輯時選擇 medium。
依 xAI 說明,medium 為圖片的細節處理分配更多運算。明確選擇 low 或 medium 可固定所需模式,auto 的行為則由製造商目前的設定決定。
輸入與成果
模型具有文字與視覺輸入,成果為圖片。在 xAI 自身的編輯模式中,Image 2.0 最多接收五張原始圖片;目前的 Ailoot 生成方法使用文字輸入。成果可透過連結中的檔案,或 base64 資料傳送。
Ailoot · 圖片 POST /v1/images/generations grok-imagine-image-2.0
grok-imagine-image-2.0入門
Grok Imagine Image 2.0 可依描述生成圖片,並選擇比例、解析度與品質。模型本身也支援圖片編輯及視覺風格轉換。
- 接受的輸入
- 文字
- 結果
- 圖片
Ailoot 可用 · 輸入與方法
Ailoot · 圖片 POST /v1/images/generations
- 輸入
text- 輸出
image- 輸出格式
- 圖片檔案
| 欄位 | 類型 | 要求 | 值與限制 | 預設值 |
|---|---|---|---|---|
欄位model | 類型string | 要求必填 | 值與限制 grok-imagine-image-2.0 | 預設值— |
欄位prompt | 類型string | 要求必填 | 值與限制 | 預設值— |
欄位n | 類型integer | 要求選填 | 值與限制 最小值: 1 最大值: 10 | 預設值1 |
欄位response_format | 類型string | 要求選填 | 值與限制 url, b64_json | 預設值url |
欄位resolution | 類型string | 要求選填 | 值與限制 1k, 2k | 預設值1k |
欄位aspect_ratio | 類型string | 要求選填 | 值與限制 auto, 1:1, 16:9, 9:16, 4:3, 3:4, 3:2, 2:3, 2:1, 1:2, 19.5:9, 9:19.5, 20:9, 9:20, 21:9, 5:2 | 預設值auto |
欄位quality | 類型string | 要求選填 | 值與限制 low, medium, auto | 預設值— |
輸入素材組合
文字生成圖片 · 必填: prompt
方法參數與生命週期
| 參數 | 規格 |
|---|---|
參數material_types | 規格text |
參數required | 規格model, prompt |
參數optional_controls | 規格null |
參數content_type | 規格application/json |
生命週期: synchronous_result_then_owned_library
GET /v1/media/tasks/{task_id} · 實際回傳的 task_id 或媒體庫紀錄
GET /v1/media/assets/{asset_id}/content
GET /v1/media/assets
GET /v1/media/assets/{asset_id}
方法結構與 ID 均為精確值;供應商能力與准入狀態分開。
方案
Ailoot 方法費率
POST /v1/images/generations- 輸入
- US$0.01 每張輸入圖片
- 輸出
- US$0.05 每張 1.5K 低品質圖片
- 輸出
- US$0.07 每張 1.5K 中等品質圖片
- 輸出
- US$0.04 每張 1K 低品質圖片
- 輸出
- US$0.06 每張 1K 中等品質圖片
- 輸出
- US$0.06 每張 2K 低品質圖片
- 輸出
- US$0.08 每張 2K 中等品質圖片
Ailoot 會在請求前預留估算金額。取得結果後,依實測用量結算最終費用。串流結算採用最終用量紀錄。預留金額與結算的運作方式 →
請求範例
Ailoot · 圖片
set -eu
: "${AILOOT_API_KEY:?Set your Ailoot API key}"
export AILOOT_API_KEY
export AILOOT_API_KEY
: "${AILOOT_PROMPT_FILE:?Set your actual UTF-8 image brief}"
export AILOOT_PROMPT_FILE
python3 - <<'PY_REQUEST'
import json,os
from pathlib import Path
p=json.loads('{"model": "grok-imagine-image-2.0", "prompt": ""}')
f=Path(os.environ["AILOOT_PROMPT_FILE"])
if not f.is_file():raise SystemExit("Choose your actual UTF-8 brief")
p['prompt']=f.read_text(encoding="utf-8")
if not p['prompt'].strip():raise SystemExit("Brief must contain text")
Path("request.json").write_text(json.dumps(p,ensure_ascii=False))
PY_REQUEST
curl --fail-with-body --silent --show-error https://api.ailoot.ai/v1/images/generations \
-H "Authorization: Bearer $AILOOT_API_KEY" -H 'Content-Type: application/json' \
--data-binary @request.json -D response-headers.txt -o result.json
python3 - <<'PY_RESULT'
import base64, json, os, subprocess
from pathlib import Path
from urllib.parse import urlsplit, urljoin
def save_images(items):
if not items: raise SystemExit("No completed images; retain the full response")
for index, item in enumerate(items):
encoded=item.get("b64_json")
uri=item.get("url", "")
if not encoded and uri.startswith("data:image/"):
header, separator, encoded=uri.partition(",")
if not separator or ";base64" not in header: raise SystemExit("Unsupported image data URI")
if encoded:
raw=base64.b64decode(encoded,validate=True)
elif uri:
uri=urljoin("https://api.ailoot.ai",uri)
parsed=urlsplit(uri)
if parsed.scheme!="https" or not parsed.netloc or parsed.username or parsed.password:
raise SystemExit("Invalid returned image URL")
owned=parsed.netloc=="api.ailoot.ai" and parsed.path.startswith("/v1/media/assets/") and parsed.path.endswith("/content")
args=["curl","--fail-with-body","--silent","--show-error",uri]
if owned: args += ["-H","Authorization: Bearer "+os.environ["AILOOT_API_KEY"]]
temporary=Path(f"image-{index}.bin")
subprocess.run(args+["-o",str(temporary)],check=True)
raw=temporary.read_bytes()
temporary.unlink()
else: raise SystemExit("Image has neither bytes nor URL")
if not raw: raise SystemExit("Empty image result")
ext="png" if raw.startswith(b"\x89PNG") else "jpg" if raw.startswith(b"\xff\xd8") else "webp" if raw[:4]==b"RIFF" and raw[8:12]==b"WEBP" else "svg" if raw.lstrip().startswith((b"<svg",b"<?xml")) else "bin"
Path(f"image-{index}.{ext}").write_bytes(raw)
print("Every returned image saved; complete response metadata retained")
save_images(json.loads(Path("result.json").read_text())["data"])
PY_RESULT
from openai import OpenAI
import base64, json, os, subprocess
from pathlib import Path
from urllib.parse import urlsplit, urljoin
def save_images(items):
if not items: raise SystemExit("No completed images; retain the full response")
for index, item in enumerate(items):
encoded=item.get("b64_json")
uri=item.get("url", "")
if not encoded and uri.startswith("data:image/"):
header, separator, encoded=uri.partition(",")
if not separator or ";base64" not in header: raise SystemExit("Unsupported image data URI")
if encoded:
raw=base64.b64decode(encoded,validate=True)
elif uri:
uri=urljoin("https://api.ailoot.ai",uri)
parsed=urlsplit(uri)
if parsed.scheme!="https" or not parsed.netloc or parsed.username or parsed.password:
raise SystemExit("Invalid returned image URL")
owned=parsed.netloc=="api.ailoot.ai" and parsed.path.startswith("/v1/media/assets/") and parsed.path.endswith("/content")
args=["curl","--fail-with-body","--silent","--show-error",uri]
if owned: args += ["-H","Authorization: Bearer "+os.environ["AILOOT_API_KEY"]]
temporary=Path(f"image-{index}.bin")
subprocess.run(args+["-o",str(temporary)],check=True)
raw=temporary.read_bytes()
temporary.unlink()
else: raise SystemExit("Image has neither bytes nor URL")
if not raw: raise SystemExit("Empty image result")
ext="png" if raw.startswith(b"\x89PNG") else "jpg" if raw.startswith(b"\xff\xd8") else "webp" if raw[:4]==b"RIFF" and raw[8:12]==b"WEBP" else "svg" if raw.lstrip().startswith((b"<svg",b"<?xml")) else "bin"
Path(f"image-{index}.{ext}").write_bytes(raw)
print("Every returned image saved; complete response metadata retained")
f=Path(os.environ["AILOOT_PROMPT_FILE"])
if not f.is_file():raise SystemExit("Set your actual UTF-8 image brief file")
request={'model': 'grok-imagine-image-2.0', 'prompt': ''}
request["prompt"]=f.read_text(encoding="utf-8")
client=OpenAI(base_url="https://api.ailoot.ai/v1",api_key=os.environ["AILOOT_API_KEY"],max_retries=0)
result=client.images.generate(**request)
Path("sdk-result.txt").write_text(str(result),encoding="utf-8")
save_images([{"b64_json":getattr(item,"b64_json",None),"url":getattr(item,"url",None)} for item in result.data])
import OpenAI from "openai";
import { readFileSync, writeFileSync } from "node:fs";
const key=process.env.AILOOT_API_KEY;
if(!key) throw new Error("Set your actual Ailoot API key");
const client=new OpenAI({baseURL:"https://api.ailoot.ai/v1",apiKey:key,maxRetries:0});
const request={"model": "grok-imagine-image-2.0", "prompt": ""};
if(!process.env.AILOOT_PROMPT_FILE)throw new Error("Set your actual UTF-8 image brief file");
request.prompt=readFileSync(process.env.AILOOT_PROMPT_FILE,"utf8");
const result=await client.images.generate(request);
writeFileSync("sdk-result.json",JSON.stringify(result,null,2));
if(!result.data?.length) throw new Error("No completed images");
for(let index=0;index<result.data.length;index++) {
const item=result.data[index];let encoded=item.b64_json,uri=item.url||"",raw;
if(!encoded && uri.startsWith("data:image/")) {
const comma=uri.indexOf(",");if(comma<0 || !uri.slice(0,comma).includes(";base64")) throw new Error("Unsupported image data URI");
encoded=uri.slice(comma+1);
}
if(encoded) {
if(encoded.length%4!==0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(encoded)) throw new Error("Invalid Base64");
raw=Buffer.from(encoded,"base64");
} else if(uri) {
const u=new URL(uri,"https://api.ailoot.ai");
if(u.protocol!=="https:" || u.username || u.password) throw new Error("Invalid returned URL");
const owned=u.origin==="https://api.ailoot.ai" && u.pathname.startsWith("/v1/media/assets/") && u.pathname.endsWith("/content");
const response=await fetch(u,{headers:owned?{Authorization:"Bearer "+key}:{},redirect:"manual"});
if(!response.ok) throw new Error("Image content download failed: "+response.status);
raw=Buffer.from(await response.arrayBuffer());
} else throw new Error("Image has neither bytes nor URL");
if(!raw.length) throw new Error("Empty image result");
const ext=raw.subarray(0,4).equals(Buffer.from([137,80,78,71]))?"png":raw[0]===255&&raw[1]===216?"jpg":raw.toString("ascii",0,4)==="RIFF"&&raw.toString("ascii",8,12)==="WEBP"?"webp":raw.toString("utf8").trimStart().startsWith("<svg")||raw.toString("utf8").trimStart().startsWith("<?xml")?"svg":"bin";
writeFileSync(`image-${index}.${ext}`,raw);
}
console.log("Every returned image saved; sdk-result.json retains complete metadata");
接收並儲存結果
Ailoot · 圖片
下載每張傳回的圖片,或儲存其 Base64 內容
GET /v1/media/tasks/{task_id}GET /v1/media/assets/{asset_id}/contentGET /v1/media/assetsGET /v1/media/assets/{asset_id}
保留所有已完成的結果
請儲存每張已完成的圖片;從每個傳回的 URL 取得圖片,或解碼其 Base64 內容。
儲存所有資料項目。解碼每個 b64_json,或透過每個回傳的已簽署 URL 取得內容。依實際 MIME 類型/位元組內容選擇副檔名。
需要檢查原始回應時
若圖片生成或編輯結果需要檢查,請保留原始 operation_id/X-Client-Request-ID 與回傳的結果資訊。使用實際的 task_id 或 asset_id 值,透過媒體庫取回自己擁有的既有結果。請勿重新提交生成/編輯請求,也請勿以 operation_id 組成輪詢 URL。
回應欄位
| 欄位 | 類型 |
|---|---|
欄位created | 類型integer |
欄位data[].url | 類型string |
欄位data[].b64_json | 類型base64 string |
欄位usage | 類型object |
錯誤與後續步驟
| 回應 | 條件 | 下一步 |
|---|---|---|
回應400 · invalid_request_error | 條件必要欄位、素材表示方式或參數值無效 | 下一步提出新的建立請求前,先修正指定欄位。 |
回應server_error | 條件回傳的回應表示該作業或結果需要檢查 | 下一步保留原始回傳的作業/任務 ID、請求標頭與回應;繼續以支援的方式讀取該原始作業。請勿重新提交建立請求。 |
別名
模型別名
Ailoot grok-imagine-image-2.0
方法路徑別名
請使用上方列出的 API 方法路徑。
相關呼叫用 ID
FAQ · grok-imagine-image-2.0
- 可以使用哪些輸入與結果?
POST /v1/images/generations·grok-imagine-image-2.0:text→image- 請求使用哪些欄位?
POST /v1/images/generations·grok-imagine-image-2.0:model,prompt,n,response_format,resolution,aspect_ratio,quality- 適用哪些限制?
POST /v1/images/generations·grok-imagine-image-2.0:n.minimum:1;n.maximum:10