模型能力

图像生成

使用 Grok Imagine 模型根据文本 prompt 生成图像。API 支持批量生成多张图像,并可控制 aspect ratio 和 resolution。

快速开始

通过一次 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-quality",
)

print(response.url)

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

配置

多张图像

使用 sample_batch() 方法和 n 参数在一次请求中生成多张图像。该方法会返回由 ImageResponse 对象组成的列表。

import xai_sdk

client = xai_sdk.Client()

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

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

Aspect Ratio

使用 aspect_ratio 参数控制图像尺寸。该参数适用于图像生成和使用多张图像进行的图像编辑。 使用单张图像进行图像编辑时,输出 aspect ratio 会遵循输入图像的 aspect ratio。

Ratio用例
1:1社交媒体、缩略图
16:9 / 9:16宽屏、移动端、Stories
4:3 / 3:4演示文稿、人像
3:2 / 2:3摄影
2:1 / 1:2Banner、Header
19.5:9 / 9:19.5现代智能手机显示屏
20:9 / 9:20超宽显示屏
auto模型自动为 prompt 选择最佳 ratio
import xai_sdk

client = xai_sdk.Client()

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

print(response.url)

Resolution

你可以为输出图像指定不同的 resolution。目前支持的图像 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-quality",
    resolution="2k"
)

print(response.url)

Base64 输出

要直接嵌入图像而不下载,请请求 base64:

import xai_sdk

client = xai_sdk.Client()

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

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

Response 详情

除图像 URL 或 base64 数据外,xAI SDK 还会在 response 对象上提供额外 metadata。

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

Python

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

Model — 获取实际使用的 model(解析所有 alias):

Python

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

并发请求

当你需要使用不同的 prompt生成多张图像(例如并行生成互不相关的图像)时,请使用 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-quality",
        )
        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())