Tradução de apoio para consulta. Código e identificadores técnicos preservados. Consultar referência original ↗
Qwen — Geração de imagem compatível com OpenAI
Ligue para o Qwen modelos de geração e edição de imagens para edição/edição de texto para imagem e imagem para imagem por meio do protocolo compatível com OpenAI Images
Obtenha uma chave de API e defini-lo como uma variável de ambiente. Se estiver usando o SDK, instale-o.
A geração da imagem pode demorar um pouco. Defina um tempo limite generoso do lado do cliente. Para saída de múltiplas imagens (maior n) ou chamadas simultâneas, comece em 600 segundos para evitar que o cliente se desconecte antecipadamente.
OpenAPI
openapi: 3.1.0
info:
title: Qwen Image Generation & Editing — OpenAI-compatible API
description: Call the Qwen image generation and editing models through the OpenAI Images-compatible protocol for text-to-image (T2I) and image-to-image/editing (I2I).
version: 1.0.0
servers:
- url: https://maas.qwencloudapi.com
description: DashScope API server
security:
- bearer: []
paths:
/compatible-mode/v1/images/generations:
post:
operationId: createQwenImageOpenAICompatible
summary: OpenAI-compatible image generation & editing
description: |-
If your application is already built on the OpenAI Images protocol or the OpenAI SDK, you can call the Qwen image generation and editing models through the OpenAI-compatible mode without changing your request structure. Text-to-image (T2I) and image-to-image/editing (I2I) share the same endpoint: **omit** `image` for T2I, **provide** `image` for I2I.
This mode is a **synchronous, non-streaming** endpoint. Image editing uses the `image` extension field and does **not** use the multipart upload of the official OpenAI `/images/edits`. Not yet supported: asynchronous calls, streaming, partial images, `/images/edits`, multipart, and mask. Passing `response_format=b64_json` does not raise an error, but it is ignored and the response still contains image URLs. For asynchronous calls, use DashScope asynchronous.
`image`, `negative_prompt`, `seed`, `prompt_extend`, `prompt_extend_mode`, `enable_thinking`, and `watermark` are QwenCloud extension fields (not official OpenAI parameters): place them at the top level for raw HTTP requests, or pass them via `extra_body` with the OpenAI SDK.
security:
- bearer: []
requestBody:
required: true
content:
application/json:
schema:
type: object
required:
- model
- prompt
properties:
model:
type: string
enum:
- qwen-image-3.0-pro
- qwen-image-3.0
- qwen-image-2.1-pro
description: Model name.
example: qwen-image-3.0-pro
prompt:
type: string
description: Positive prompt describing the desired image content, style, and composition. Chinese and English supported, up to ~4500 tokens. Cannot be empty.
example: A vertical outdoor portrait photograph with a warm afternoon street atmosphere. Deep green vines and small orange flowers cascade from building eaves across the upper area. A dark blue sign reads 'Il Messaggero' in white Gothic lettering, partially obscured by foliage. Below, a newsstand displays newspapers behind black metal-framed glass, blurred by shallow depth of field. Strong backlight streams from the street's end. Center-right, a young woman in a black spaghetti-strap backless dress looks back at the camera with a warm smile. Her long, thick wavy black hair is outlined by golden rim light. She has fair skin, bright eyes, soft coral-red lips, and holds a large bouquet of orange, apricot, pink and peach roses contrasting with her black dress. The sunlit city street stretches into the blurred background. Warm film-like tones with fine grain, soft contrast and pronounced backlit edge glow create a romantic, bright, urban strolling atmosphere.
image:
anyOf:
- type: string
- type: array
items:
type: string
description: |-
URL or Base64 encoded data of the input image. Omit for T2I; provide for I2I (1-3 images for the qwen-image-3.0 series, 1-10 images for qwen-image-2.1-pro). Pass a string for one image, or an array of strings for multiple (array order defines image order). Do not pass `null` or an empty array, or a 400 is returned. Formats: JPG/JPEG/PNG/BMP/TIFF/WEBP/GIF; width and height 384-2048 px recommended; size up to 10MB.
Supported input formats:
1. Public URL: HTTP and HTTPS protocols are supported.
2. Base64 encoding: Format is `data:{MIME_type};base64,{base64_data}`.
n:
type: integer
minimum: 1
maximum: 6
default: 1
description: Number of output images. A string (e.g. `"1"`) returns 400; must be an integer.
size:
type: string
default: auto
description: Output resolution as `widthxheight` (**letter x separator**). `auto` lets the model recommend. Pixel area 512x512 to 2048x2048, aspect ratio 1:8 to 8:1. Note this differs from the DashScope `*` separator; adjust when migrating.
example: 1024x1024
negative_prompt:
type: string
description: Negative prompt describing content you do not want in the image. Only qwen-image-3.0 series models support this parameter; qwen-image-2.1-pro does not.
seed:
type: integer
minimum: 0
maximum: 2147483647
description: Random seed. Random when omitted; a fixed seed makes results relatively stable.
prompt_extend:
type: boolean
default: true
description: Whether to enable intelligent prompt rewriting (recommended). Rewrites the positive prompt per `prompt_extend_mode`.
prompt_extend_mode:
type: string
enum:
- direct
- agent
default: direct
description: "Prompt rewriting mode. `direct`: direct prompt enhancement (DPE), supports both T2I and I2I; `agent`: agentic prompt enhancement (APE), T2I only; passing it for I2I returns 400."
enable_thinking:
type: boolean
default: true
description: Whether to enable thinking mode. Improves image quality with stronger reasoning but increases latency. Effective only when `prompt_extend=true`; I2I Agent is not yet supported.
watermark:
type: boolean
default: false
description: Whether to add a watermark.
examples:
Text-to-image (T2I):
summary: Text-to-image (T2I)
value:
model: qwen-image-3.0-pro
prompt: A vertical outdoor portrait photograph with a warm afternoon street atmosphere. Deep green vines and small orange flowers cascade from building eaves across the upper area. A dark blue sign reads 'Il Messaggero' in white Gothic lettering, partially obscured by foliage. Below, a newsstand displays newspapers behind black metal-framed glass, blurred by shallow depth of field. Strong backlight streams from the street's end. Center-right, a young woman in a black spaghetti-strap backless dress looks back at the camera with a warm smile. Her long, thick wavy black hair is outlined by golden rim light. She has fair skin, bright eyes, soft coral-red lips, and holds a large bouquet of orange, apricot, pink and peach roses contrasting with her black dress. The sunlit city street stretches into the blurred background. Warm film-like tones with fine grain, soft contrast and pronounced backlit edge glow create a romantic, bright, urban strolling atmosphere.
size: 1024x1024
n: 1
prompt_extend: true
Image-to-image / editing (I2I):
summary: Image-to-image / editing (I2I)
value:
model: qwen-image-3.0-pro
prompt: "Generate a sophisticated urban-style female portrait. Perfectly preserve the facial features and smooth black long hair of the young woman in the input image. She changes from her beige knit top into an elegant urban professional outfit: a champagne silk blouse with a well-tailored dark grey casual blazer and matching high-waisted wide-leg trousers. The scene is in a modern minimalist upscale coffee shop with floor-to-ceiling windows showing a bustling city view. Dark wood tables and leather chairs furnish the interior, with a silver laptop, documents, and a steaming Americano on the table. She sits relaxed, leaning slightly back with one arm on the armrest and the other holding a coffee cup, gazing at the camera with calm, slightly languid eyes and an elegant smile. Polished formal makeup with clean base, defined brows, and mauve lipstick. Soft afternoon light enters from the side through the windows, creating delicate light transitions on her face and clothing. Natural bokeh background in earth tones, greys and warm whites, creating a serene, sophisticated urban office atmosphere."
image: https://alidocs.oss-cn-zhangjiakou.aliyuncs.com/res/yBRq1ZPYEaXdyOdv/img/33a80a19-7ac7-4c64-b0fa-7d685b7046a0.png
size: 1024x1024
n: 1
prompt_extend: true
responses:
"200":
description: Successful response
content:
application/json:
schema:
type: object
properties:
created:
type: integer
description: Unix timestamp (seconds) when the response was created.
data:
type: array
description: List of generated results. Contains multiple elements when `n` > 1.
items:
type: object
properties:
url:
type: string
description: URL of the generated image (PNG). **Valid for 24 hours** — download and save promptly.
usage:
type: object
description: "Resource usage for this call, returned only on success. This is **image input/output metering, not token usage**. Fields vary by model series: the qwen-image-3.0 series returns the `output_*` / `input_*` fields; qwen-image-2.1-pro returns `image_count` / `width` / `height`."
properties:
output_width:
type: integer
description: Width of the output image (px). Returned by the qwen-image-3.0 series only.
output_height:
type: integer
description: Height of the output image (px). Returned by the qwen-image-3.0 series only.
input_image_count:
type: integer
description: Number of input images. 0 for T2I; the actual count for I2I. Returned by the qwen-image-3.0 series only.
input_image_type:
type: string
description: Input image metering tier. Area ≤2,250,000 is `qima_input_1k`, otherwise `qima_input_2k`. Returned by the qwen-image-3.0 series only.
output_image_count:
type: integer
description: Number of output images returned. Returned by the qwen-image-3.0 series only.
output_image_type:
type: string
description: Output image metering tier. Area ≤2,250,000 is `qima_output_1k`, otherwise `qima_output_2k`. Returned by the qwen-image-3.0 series only.
image_count:
type: integer
description: Number of images generated. Not returned by the qwen-image-3.0 series, which uses `output_image_count` instead.
width:
type: integer
description: Width of the generated image (px). Not returned by the qwen-image-3.0 series, which uses `output_width` instead.
height:
type: integer
description: Height of the generated image (px). Not returned by the qwen-image-3.0 series, which uses `output_height` instead.
error:
type: object
description: Error info, returned only on failure. OpenAI-compatible mode does not return `request_id` in the body; the request id is returned via the `x-request-id` HTTP header. With the OpenAI Python SDK, read `response._request_id` on success or `APIStatusError.request_id` on failure.
properties:
message:
type: string
description: Detailed failure message.
type:
type: string
description: Error type, e.g. `invalid_request_error`.
param:
type:
- string
- "null"
description: Name of the offending parameter, or `null` when it cannot be identified.
code:
type: string
description: Failure error code. See [Error codes](/api-reference/preparation/error-messages).
examples:
Success:
summary: Success
value:
created: 1788339600
data:
- url: https://dashscope-result-sg.oss-ap-southeast-1.aliyuncs.com/xxx.png?Expires=xxx
usage:
output_height: 1024
output_width: 1024
input_image_count: 0
input_image_type: qima_input_1k
output_image_count: 1
output_image_type: qima_output_1k
Failure:
summary: Failure
value:
error:
message: Field 'prompt' is required
type: invalid_request_error
param: null
code: InvalidParameter
x-codeSamples:
- lang: bash
label: Text-to-image (T2I)
source: |-
curl --location 'https://maas.qwencloudapi.com/compatible-mode/v1/images/generations' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--data '{
"model": "qwen-image-3.0-pro",
"prompt": "A vertical outdoor portrait photograph with a warm afternoon street atmosphere. Deep green vines and small orange flowers cascade from building eaves across the upper area. A dark blue sign reads '\''Il Messaggero'\'' in white Gothic lettering, partially obscured by foliage. Below, a newsstand displays newspapers behind black metal-framed glass, blurred by shallow depth of field. Strong backlight streams from the street'\''s end. Center-right, a young woman in a black spaghetti-strap backless dress looks back at the camera with a warm smile. Her long, thick wavy black hair is outlined by golden rim light. She has fair skin, bright eyes, soft coral-red lips, and holds a large bouquet of orange, apricot, pink and peach roses contrasting with her black dress. The sunlit city street stretches into the blurred background. Warm film-like tones with fine grain, soft contrast and pronounced backlit edge glow create a romantic, bright, urban strolling atmosphere.",
"size": "1024x1024",
"n": 1,
"prompt_extend": true
}'
- lang: bash
label: Image-to-image / editing (I2I)
source: |-
curl --location 'https://maas.qwencloudapi.com/compatible-mode/v1/images/generations' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--data '{
"model": "qwen-image-3.0-pro",
"prompt": "Generate a sophisticated urban-style female portrait. Perfectly preserve the facial features and smooth black long hair of the young woman in the input image. She changes from her beige knit top into an elegant urban professional outfit: a champagne silk blouse with a well-tailored dark grey casual blazer and matching high-waisted wide-leg trousers. The scene is in a modern minimalist upscale coffee shop with floor-to-ceiling windows showing a bustling city view. Dark wood tables and leather chairs furnish the interior, with a silver laptop, documents, and a steaming Americano on the table. She sits relaxed, leaning slightly back with one arm on the armrest and the other holding a coffee cup, gazing at the camera with calm, slightly languid eyes and an elegant smile. Polished formal makeup with clean base, defined brows, and mauve lipstick. Soft afternoon light enters from the side through the windows, creating delicate light transitions on her face and clothing. Natural bokeh background in earth tones, greys and warm whites, creating a serene, sophisticated urban office atmosphere.",
"image": "https://alidocs.oss-cn-zhangjiakou.aliyuncs.com/res/yBRq1ZPYEaXdyOdv/img/33a80a19-7ac7-4c64-b0fa-7d685b7046a0.png",
"size": "1024x1024",
"n": 1,
"prompt_extend": true
}'
- lang: python
label: Text-to-image (T2I)
source: |-
import os
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://maas.qwencloudapi.com/compatible-mode/v1",
timeout=600.0,
)
response = client.images.generate(
model="qwen-image-3.0-pro",
prompt="A vertical outdoor portrait photograph with a warm afternoon street atmosphere. Deep green vines and small orange flowers cascade from building eaves across the upper area. A dark blue sign reads 'Il Messaggero' in white Gothic lettering, partially obscured by foliage. Below, a newsstand displays newspapers behind black metal-framed glass, blurred by shallow depth of field. Strong backlight streams from the street's end. Center-right, a young woman in a black spaghetti-strap backless dress looks back at the camera with a warm smile. Her long, thick wavy black hair is outlined by golden rim light. She has fair skin, bright eyes, soft coral-red lips, and holds a large bouquet of orange, apricot, pink and peach roses contrasting with her black dress. The sunlit city street stretches into the blurred background. Warm film-like tones with fine grain, soft contrast and pronounced backlit edge glow create a romantic, bright, urban strolling atmosphere.",
size="1024x1024",
n=1,
# All parameters above are official OpenAI parameters. Extension fields such as
# image and prompt_extend go through extra_body. See the I2I example.
)
for item in response.data:
print(item.url)
print(f"request_id: {response._request_id}")
- lang: python
label: Image-to-image / editing (I2I)
source: |-
import os
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://maas.qwencloudapi.com/compatible-mode/v1",
timeout=600.0,
)
response = client.images.generate(
model="qwen-image-3.0-pro",
prompt="Generate a sophisticated urban-style female portrait. Perfectly preserve the facial features and smooth black long hair of the young woman in the input image. Change her outfit to an elegant urban professional look. Set the scene in a modern minimalist upscale coffee shop.",
size="1024x1024",
n=1,
extra_body={
# A single image can also be passed as a plain string. Base64 is also accepted:
# data:{MIME_type};base64,{base64_data}
"image": [
"https://alidocs.oss-cn-zhangjiakou.aliyuncs.com/res/yBRq1ZPYEaXdyOdv/img/33a80a19-7ac7-4c64-b0fa-7d685b7046a0.png",
],
"prompt_extend": True,
},
)
for item in response.data:
print(item.url)
print(f"request_id: {response._request_id}")
- lang: python
label: Read request_id for a failed request
source: |-
import os
from openai import OpenAI, APIStatusError
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://maas.qwencloudapi.com/compatible-mode/v1",
timeout=600.0,
)
try:
response = client.images.generate(
model="qwen-image-3.0-pro",
prompt="A vertical outdoor portrait photograph with a warm afternoon street atmosphere.",
)
print(response.data[0].url)
except APIStatusError as exc:
print(f"status_code: {exc.status_code}")
print(f"request_id: {exc.request_id}")
print(exc)
components:
securitySchemes:
bearer:
type: http
scheme: bearer
description: DashScope API key. Get your API key from [QwenCloud console](https://home.qwencloud.com/api-keys).