从写代码,到创作下一幕

探索 字节跳动 - 火山方舟 的 AI 编程与视频创作活动。

火山方舟 Agent Plan 与 Coding Plan 活动,价格 ¥9.9 起

Agent Plan & Coding Plan

一站体验多款热门模型,为 AI 编程与智能体开发提供更多选择。新用户可联系(微信: goo_lvyouyou)免费体验 9.9 agent plan。

查看套餐优惠
Seedance 2.5 视频创作活动:30 秒视频、多模态参考、局部编辑

Seedance 2.5

让创意,跃然成片。探索 30 秒视频、多模态参考与局部编辑,把脑海中的画面变成下一支作品。

探索视频创作

工具

图像生成工具

查看 Markdown

图像生成工具让 Grok 可以在对话中使用 Grok Imagine 创建和编辑图像。该工具使用最新的 Imagine 图像模型(grok-imagine-image-2.0)。你向模型提供该工具;模型会决定何时调用它、编写图像 prompt、选择宽高比,并将最终图像与文本响应一并返回。由于该工具在服务端运行,模型还可以在单个请求中串联调用,例如先生成图像,再编辑图像。

如果已有精确的 prompt,并希望直接控制宽高比和分辨率,请改用 图像生成 和 图像编辑 endpoint。当图像创建只是更大的对话或智能体工作流中的一个步骤时,再使用该工具。


SDK 支持

SDK/API工具名称
xAI SDKimage_generation
OpenAI Responses APIimage_generation

所有与 Responses API 兼容的 SDK 也支持该工具。Vercel AI SDK 尚未提供图像生成工具。


基础用法

将 image_generation 添加到 tools 并请求生成图像。在 xAI SDK 中,每张生成的图像通过 response.image_outputs 以解码后的字节形式提供,可直接写入文件。在 Responses API 中,每张图像以 image_generation_call 输出项的形式返回,其 result 字段包含不带 data-URL 前缀的 base64 编码图像,因此可以直接解码。

import base64
import os

from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("XAI_API_KEY"),
    base_url="https://api.x.ai/v1",
)

response = client.responses.create(
    model="grok-4.7",
    input="Generate an image of a corgi surfing a big wave, in the style of a Japanese woodblock print",
    tools=[{"type": "image_generation"}],
)

image_data = [
    output.result
    for output in response.output
    if output.type == "image_generation_call"
]

if image_data:
    with open("corgi_surfing.jpg", "wb") as f:
        f.write(base64.b64decode(image_data[0]))

一个完整的 image_generation_call 输出项如下所示:

JSON

{
  "type": "image_generation_call",
  "id": "ig_d817cfd0-4f39-9cb3-bda2-44e538841ef2_call-a1b4dd05",
  "status": "completed",
  "prompt": "A corgi surfing a big wave, Japanese woodblock print style",
  "result": "/9j/4AAQSkZJRgABAQAAAQABAAD..."
}

其中 prompt 字段显示模型为图像模型编写的 prompt,有助于理解和调试生成内容。生成项 ID 以 ig_ 为前缀,编辑项 ID 以 ie_ 为前缀。

该工具不接受大小或格式参数;模型会为每次调用选择宽高比。如需控制,请在请求中明确说明(例如“使用 9:16 竖向宽高比”),生成图像会与之匹配。


action 参数

默认情况下,模型既可以生成新图像,也可以编辑现有图像。可选的 action 参数可以限制该行为:

操作行为
auto默认。模型可以生成和编辑图像
generate仅文本生成图像
edit仅图像编辑

例如,允许模型创建图像,但绝不修改对话中已有的图像:

response = client.responses.create(
    model="grok-4.7",
    input="Generate an image of a hot air balloon over the desert",
    tools=[{"type": "image_generation", "action": "generate"}],
)

编辑输入图像

当 action 设置为 edit(或使用默认的 auto)时,模型可以编辑对话中任意已有图像,包括作为输入附加的图像和之前生成的图像。编辑会生成 image_generation_call 项,其 ID 使用 ie_ 前缀。

import base64
import os

from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("XAI_API_KEY"),
    base_url="https://api.x.ai/v1",
)

response = client.responses.create(
    model="grok-4.7",
    input=[
        {
            "role": "user",
            "content": [
                {
                    "type": "input_text",
                    "text": "Edit this image so it looks like a watercolor painting.",
                },
                {
                    "type": "input_image",
                    "image_url": "https://docs.x.ai/assets/api-examples/images/style-realistic.png",
                },
            ],
        }
    ],
    tools=[{"type": "image_generation", "action": "edit"}],
)

image_data = [
    output.result
    for output in response.output
    if output.type == "image_generation_call"
]

if image_data:
    with open("watercolor.jpg", "wb") as f:
        f.write(base64.b64decode(image_data[0]))

多轮编辑

之前轮次生成的图像在后续轮次中仍可编辑。继续对话时,在 xAI SDK 中将上一条响应追加到聊天,或在 Responses API 中传入 previous_response_id,模型便可参考此前的图像进一步修改:

import base64
import os

from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("XAI_API_KEY"),
    base_url="https://api.x.ai/v1",
)

response = client.responses.create(
    model="grok-4.7",
    input="Generate an image of a lighthouse on a rocky coast",
    tools=[{"type": "image_generation"}],
)

image_data = [
    output.result
    for output in response.output
    if output.type == "image_generation_call"
]

if image_data:
    with open("lighthouse.jpg", "wb") as f:
        f.write(base64.b64decode(image_data[0]))

# Follow up: edit the image from the previous turn
followup = client.responses.create(
    model="grok-4.7",
    previous_response_id=response.id,
    input="Make it night time with a full moon",
    tools=[{"type": "image_generation"}],
)

image_data_followup = [
    output.result
    for output in followup.output
    if output.type == "image_generation_call"
]

if image_data_followup:
    with open("lighthouse_night.jpg", "wb") as f:
        f.write(base64.b64decode(image_data_followup[0]))

如果不使用 previous_response_id,而是自行管理对话状态,请将上一轮的输出项(包括 image_generation_call 项)通过 input 原样传回;这些项携带的图像在下一个请求中仍可编辑。


与其他工具结合

图像生成工具可以与其他服务端工具组合。在同一请求中包含多个工具,模型会在单个智能体循环中协调它们,将一个工具的发现传给下一个。以下示例先通过 Web Search 查找事实,再根据获取的信息编写图像 prompt:

import base64
import os

from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("XAI_API_KEY"),
    base_url="https://api.x.ai/v1",
)

response = client.responses.create(
    model="grok-4.7",
    input=(
        "Find out which team won the most recent FIFA World Cup, then generate an "
        "image of a celebratory poster for that team, in a vintage travel-poster style."
    ),
    tools=[
        {"type": "web_search"},
        {"type": "image_generation"},
    ],
)

for output in response.output:
    if output.type == "web_search_call":
        print(f"Web search: {output.action}")
    elif output.type == "image_generation_call":
        print(f"Image prompt: {output.prompt}")
        with open("champions_poster.jpg", "wb") as f:
            f.write(base64.b64decode(output.result))
    elif output.type == "message":
        print(output.content[0].text)

响应输出按执行顺序交错包含工具调用:一个 web_search_call 项、一条带引用、回答事实问题的消息,以及一个携带海报的 image_generation_call 项。

相同模式也适用于 X Search、Code Execution 和自己的客户端函数。更多工具组合模式请参阅 高级用法。


流式传输

流式传输时,每次图像生成调用都会发出进度事件:in_progress,然后是 generating,然后是 completed;之后发出 response.output_item.done 事件,其项携带 base64 结果。不会发出部分图像预览。

在 xAI SDK 中,传入 include=["verbose_streaming"] 可实时查看工具调用;流结束后,解码后的图像可通过累积响应中的 response.image_outputs 获取。

import base64
import os

from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("XAI_API_KEY"),
    base_url="https://api.x.ai/v1",
)

stream = client.responses.create(
    model="grok-4.7",
    input="Generate an image of an origami fox in a paper forest",
    tools=[{"type": "image_generation"}],
    stream=True,
)

for event in stream:
    if event.type.startswith("response.image_generation_call."):
        # in_progress -> generating -> completed
        print(f"Image generation status: {event.type.rsplit('.', 1)[-1]}")
    elif event.type == "response.output_item.done" and event.item.type == "image_generation_call":
        # The base64 image rides on the final output item
        with open("origami_fox.jpg", "wb") as f:
            f.write(base64.b64decode(event.item.result))
    elif event.type == "response.output_text.delta":
        print(event.delta, end="", flush=True)


最后更新:2026 年 8 月 18 日