Skip to content

openrouter:image_generation 是 OpenRouter 的 Server Tool(Beta),让任何 LLM 模型能够根据文本描述生成图片。模型收到含有图像需求的请求时,会调用该工具生成图片;OpenRouter 在服务端执行图像生成并将图片 URL 返回给模型,模型再将图片融入最终回复。默认使用 openai/gpt-image-1,可通过 parameters 配置 modelqualitysizeaspect_ratiobackgroundoutput_format 等参数。费用 = 标准 LLM token 费用 + 图像生成费用。

openrouter:image_generation Server Tool(目前为 Beta)让任何 LLM 模型都能在一次 API 调用中生成图片,无需客户端单独调用图像生成 API。

Beta 提醒:Server Tools 目前处于 Beta 阶段,API 和行为可能会有变更。

工作原理

  1. tools 数组中包含 { "type": "openrouter:image_generation" }
  2. 根据用户请求,模型决定是否需要生成图片,并撰写图片描述
  3. OpenRouter 调用图像生成模型(默认 openai/gpt-image-1
  4. 生成的图片 URL 返回给模型
  5. 模型将图片融入回复,必要时可在一次请求中生成多张图片

快速开始

javascript
const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
  method: 'POST',
  headers: {
    Authorization: 'Bearer <OPENROUTER_API_KEY>',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'openai/gpt-4o',
    messages: [
      {
        role: 'user',
        content: '画一张夕阳下的未来城市'
      }
    ],
    tools: [
      { type: 'openrouter:image_generation' }
    ]
  }),
});

const data = await response.json();
console.log(data.choices[0].message.content);

参数配置

可通过 parameters 自定义图片生成行为:

json
{
  "type": "openrouter:image_generation",
  "parameters": {
    "model": "openai/gpt-image-1",
    "quality": "high",
    "aspect_ratio": "16:9",
    "size": "1024x1024",
    "background": "transparent",
    "output_format": "png"
  }
}
参数类型默认值说明
modelstringopenai/gpt-image-1图像生成模型
qualitystring图片质量:"low""medium""high"
sizestring图片尺寸:如 "1024x1024""512x512"
aspect_ratiostring宽高比:如 "16:9""1:1""4:3"
backgroundstring背景:"transparent""opaque"
output_formatstring输出格式:"png""jpeg""webp"
output_compressionnumber有损格式的压缩级别(0-100)
moderationstring内容审核级别:"auto""low"

model 外,所有参数直接传递给底层图像生成 API,具体可用值取决于所用模型。

响应格式

工具调用成功时返回:

json
{ "status": "ok", "imageUrl": "https://..." }

生成失败时:

json
{ "status": "error", "error": "Generation failed due to content policy" }

Responses API 支持

也可在 Responses API 中使用:

javascript
const response = await fetch('https://openrouter.ai/api/v1/responses', {
  method: 'POST',
  headers: {
    Authorization: 'Bearer <OPENROUTER_API_KEY>',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'openai/gpt-4o',
    input: '生成一张山地风景图',
    tools: [
      {
        type: 'openrouter:image_generation',
        parameters: { quality: 'high' }
      }
    ]
  }),
});

费用

图像生成费用取决于所用模型:

  • openai/gpt-image-1:参考 OpenAI 定价
  • 其他模型:参考 OpenRouter 对应模型页面的定价

费用 = 标准 LLM token 费用(处理请求和响应)+ 图像生成费用。

常见问题

Q: 模型什么时候会调用图片生成工具?

A: 模型会自主判断用户请求是否需要生成图片。明确包含"画一张"、"生成图片"等表述时大概率触发;对于模糊描述(如"描述这个场景"),模型可能选择用文字描述而非生成图片。如需确保触发,可在系统提示中明确说明期望的行为。

Q: 一次请求可以生成多张图片吗?

A: 可以。如果用户请求需要多张图片(如"给每个步骤画一张说明图"),模型可以在一次请求中多次调用图片生成工具。每次调用独立计费。

Q: 生成的图片 URL 有效期多久?

A: 图片 URL 的有效期由底层图像生成服务(如 OpenAI)决定,通常为数小时到数天。如需长期保存,建议在收到 URL 后立即下载并存储到自己的对象存储服务。