模型能力

图像生成

查看 Markdown

使用 Grok Imagine 模型根据文本 prompt 生成图像。API 支持批量生成多张图像,并可控制宽高比、分辨率和质量。


快速开始

通过一次 API 调用生成图像:

import xai_sdk

client = xai_sdk.Client()

response = client.image.sample(
    prompt="A collage of London landmarks in a stenciled street‑art style",
    model="grok-imagine-image-2.0",
)

print(response.url)

图像默认以 URL 形式返回。URL 是临时的,因此请及时下载或处理。你也可以请求 base64 输出,以便直接嵌入图像。


配置

多张图像

通过 n 参数(110)在单次请求中生成多张图像。在 REST API 和兼容 OpenAI 的 SDK 中,n 为可选参数,默认值为 1。xAI Python SDK 使用 sample() 生成单张图像,使用 sample_batch(n=...) 生成多张图像——n 必须提供给 sample_batch()

import xai_sdk

client = xai_sdk.Client()

responses = client.image.sample_batch(
    prompt="A futuristic city skyline at night",
    model="grok-imagine-image-2.0",
    n=4,
)

for i, image in enumerate(responses):
    print(f"Variation {i + 1}: {image.url}")

宽高比

使用 aspect_ratio 参数。省略时默认为 auto,由模型根据 prompt 选择最佳宽高比。

比例用例
1:1社交媒体、缩略图
16:9 / 9:16宽屏、移动端、故事
4:3 / 3:4演示文稿、人像
3:2 / 2:3摄影
2:1 / 1:2横幅、页眉
19.5:9 / 9:19.5现代智能手机屏幕(iPhone)
20:9 / 9:20现代智能手机屏幕(Android)
21:9电影宽银幕
5:2宽幅横幅
auto模型自动为提示词选择最佳比例
import xai_sdk

client = xai_sdk.Client()

response = client.image.sample(
    prompt="Mountain landscape at sunrise",
    model="grok-imagine-image-2.0",
    aspect_ratio="16:9",
)

print(response.url)

分辨率

你可以通过 resolution 参数指定输出图像的分辨率。目前支持的图像分辨率包括:

  • 1k(省略时的默认值)

  • 2k

import xai_sdk

client = xai_sdk.Client()

response = client.image.sample(
    prompt="An astronaut performing EVA in LEO.",
    model="grok-imagine-image-2.0",
    resolution="2k"
)

print(response.url)

质量

使用可选的 quality 参数控制生成质量。允许的值为 lowmediumauto。省略时默认值为 auto,由服务为每次请求选择质量。目前 Auto 使用 low 生成图像,并使用 medium 进行图像编辑。图像按实际提供的质量计费(参阅价格)。传入 lowmedium 可固定使用特定质量。该参数仅支持 grok-imagine-image-2.0

import xai_sdk

client = xai_sdk.Client()

response = client.image.sample(
    prompt="A watercolor painting of a lighthouse at dawn",
    model="grok-imagine-image-2.0",
    quality="low",
)

print(response.url)

base64 输出

使用以下参数控制输出格式:response_format 参数。省略时默认为 url,返回临时托管 URL。如需直接嵌入图像而无需下载,请请求 base64:

import xai_sdk

client = xai_sdk.Client()

response = client.image.sample(
    prompt="A serene Japanese garden",
    model="grok-imagine-image-2.0",
    image_format="base64",
)

# Save to file
with open("garden.jpg", "wb") as f:
    f.write(response.image)

响应详情

除图像 URL 或 Base64 数据外,xAI SDK 还会在响应对象上提供额外元数据。

内容审核:检查生成的图像是否通过内容审核:

Python

if response.respect_moderation:
    print(response.url)
else:
    print("Image filtered by moderation")

模型:获取实际使用的模型(解析所有别名):

Python

print(f"Model: {response.model}")

并发请求

当你需要使用不同的提示词,例如并行生成互不相关的图像时,请使用 AsyncClient 搭配 asyncio.gather 并发发起请求。这比逐一发起请求快得多。

Python

import asyncio
import xai_sdk

async def generate_concurrently():
    client = xai_sdk.AsyncClient()

    # Each request uses a different prompt
    prompts = [
        "A futuristic city skyline at sunset",
        "A serene Japanese garden in winter",
        "An astronaut floating above Earth",
        "A medieval castle on a misty mountain",
    ]

    # Fire all requests concurrently
    tasks = [
        client.image.sample(
            prompt=prompt,
            model="grok-imagine-image-2.0",
        )
        for prompt in prompts
    ]

    results = await asyncio.gather(*tasks)

    for prompt, result in zip(prompts, results):
        print(f"{prompt}: {result.url}")

asyncio.run(generate_concurrently())


最后更新:2026 年 8 月 29 日