工具

图像生成工具

查看 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 编码图像,因此可以直接解码。

curl https://api.x.ai/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -d '{
  "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"
    }
  ]
}' | jq -r '.output[] | select(.type == "image_generation_call") | .result' \
  | base64 --decode > corgi_surfing.jpg

一个完整的 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仅图像编辑

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

curl https://api.x.ai/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -d '{
  "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_ 前缀。

curl https://api.x.ai/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -d '{
  "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"
    }
  ]
}'

多轮编辑

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

import os

from xai_sdk import Client
from xai_sdk.chat import user
from xai_sdk.tools import image_generation

client = Client(api_key=os.getenv("XAI_API_KEY"))

chat = client.chat.create(
    model="grok-4.7",
    tools=[image_generation()],
)

# Turn 1: generate an image
chat.append(user("Generate an image of a lighthouse on a rocky coast"))
response = chat.sample()
with open("image.jpeg", "wb") as f:
    f.write(response.image_outputs[0].image)

# Turn 2: edit the image from the previous turn
chat.append(response)
chat.append(user("Make it night time with a full moon"))
followup = chat.sample()
with open("edited_image.jpeg", "wb") as f:
    f.write(followup.image_outputs[0].image)

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


与其他工具结合

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

curl https://api.x.ai/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -d '{
  "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"
    }
  ]
}' | jq -r '.output[] | select(.type == "image_generation_call") | .result' \
  | base64 --decode > champions_poster.jpg

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

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


流式传输

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

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

import os

from xai_sdk import Client
from xai_sdk.chat import user
from xai_sdk.tools import get_tool_call_type, image_generation

client = Client(api_key=os.getenv("XAI_API_KEY"))

chat = client.chat.create(
    model="grok-4.7",
    tools=[image_generation()],
    include=["verbose_streaming"],
)
chat.append(user("Generate an image of an origami fox in a paper forest"))

for response, chunk in chat.stream():
    for tool_call in chunk.tool_calls:
        if get_tool_call_type(tool_call) == "image_generation_tool":
            print(f"\nGenerating image: {tool_call.function.arguments}")
    if chunk.content:
        print(chunk.content, end="", flush=True)

# The accumulated response carries the decoded images once the stream ends
with open("image.jpeg", "wb") as f:
    f.write(response.image_outputs[0].image)


最后更新:2026 年 8 月 18 日