skill-image-qwen Skill
Generate or edit images using the Qwen-Image-3.0 model. This model supports both text-to-image (T2I) and image-to-image/image editing (I2I). It can generate images directly from text prompts or precisely edit images based on 1-3 reference images combined with editing instructions. The core goal has shifted from 'looking good' to 'being useful'—generated images should be directly deliverable final products. Core principle: maximize the model's capabilities through prompts; prioritize 'requirement clarification', 'prompt review and optimization', and 'pre-generation confirmation'.
V3 Core Upgrade: Three-Stage Token Chain (Code-Level Guarantee, 100% Effective)
V2 had two stages (prepare/generate), theoretically allowing the model to skip optimization and go directly to prepare. V3 introduces a 'prompt optimization and review stage' as a code-level gate, forming a three-stage token chain:
- Stage 1
optimize: The model completes review and optimization according to the official template (6-step paradigm). It then logs a record—mandatory with an 'optimization before/after comparison + change explanation' (to prevent perfunctory work). The code generates Token A (bound to thesha256fingerprint of the optimized prompt) and persists the record. Never calls the real API. - Stage 2
prepare: The code checks Token A (no Token A -> reject with a message 'Must complete the optimization and review stage first'). If valid, it presents the 'original request -> optimized prompt -> change explanation' to the user for confirmation. It generates Token B, destroys Token A (use once, then discard). Never calls the real API. - Stage 3
generate: The code checks Token B (no Token B / mismatch / tampered content -> reject). If valid, it executes the API call, then destroys Token B after success (use once, then discard).
Token Relay: optimize ->(Token A)-> prepare ->(Token B)-> generate. No ticket, no entry; the model trying to jump from raw request to generation will be blocked at prepare or generate.
Tokens are workflow byproducts, not hardcoded passwords: Dynamically generated content fingerprints (
sha256(prompt)) by the code. The model cannot forge them even by reading the source code; it must faithfully complete each stage to earn the key.Tokens are bound to content: Different requests yield different tokens. Submitting content inconsistent with the logged/confirmed version is rejected, preventing 'showing one thing, generating another'.
Token Scope: The fingerprint only covers the prompt content. Technical parameters like size/format are retrieved from the log, not included in the fingerprint—the gate locks primarily on 'the user confirmed the content'. Technical parameters are handled flexibly, avoiding a full re-run for a size change.
Use Once, Then Discard: prepare consumes and destroys Token A. generate destroys Token B upon success, preventing reuse of old tokens to skip steps or repeat execution.
Rejection Messages as Teaching: Error messages guide the workflow. When blocked, the model can self-correct and return to the correct path.
Anti-Perfunctory Mechanism: The optimize log mandates an 'optimization before/after comparison + change explanation'. prepare presents this unchanged to the user for confirmation. Cutting corners requires fabricating a change reason, raising the cost of perfunctory work. The user can verify the rationale during confirmation, spotting deviations (e.g., 'realistic style' changed to 'cartoon style'). One output serves dual roles: 'anti-perfunctory work' and 'user confirmation basis', adding no extra steps.
Models and Versions
| Version | Model ID | Positioning | Generation Unit Price |
|---|---|---|---|
| Standard (Default) | qwen-image-3.0 | Quality-speed balance, convenient for daily creative work | 1K/2K: 0.18 RMB/image |
| Pro (Optional) | qwen-image-3.0-pro | Dense layout, extreme detail, rich knowledge | 1K: 0.25 RMB/image, 2K: 0.50 RMB/image |
Model Core Capabilities (Official 'Three Realities'):
| Capability | Description | Key Metrics |
|---|---|---|
| Abundant Content | Fits an entire page: generate exams, newspapers, visual guides, infographics in one go | Instruction length up to 4.5K tokens |
| Realistic Detail | Withstands magnification: texture quality approaches real materials | 10px small text remains clear; pores and hair strands are vividly rendered |
| Rich Knowledge | Knows a lot: cross-lingual, cross-domain | Covers 12 languages, 100+ art styles, and various UI interfaces |
- Standard version is used by default. Switch to Pro only when the user explicitly needs Pro capabilities (dense layout within an image, realistic details like micro-expressions/pores/hair strands) or explicitly requests Pro.
- Input pricing is the same for both versions (0.02 RMB/image). See
references/pricing_and_models.md. - Model capability boundaries and selection recommendations are in
references/pricing_and_models.md.
Workflow (Must Follow)
① Intent Recognition and Clarification -> ② Version Selection -> ③ Build Prompt and optimize for Review and Optimization -> ④ Display Confirmation -> ⑤ prepare Confirmation -> ⑥ generate and Iterate -> ⑦ Feedback Consumption.
Step 1: Intent Recognition and Requirement Clarification (Critical, Do Not Skip)
As an AI image generation expert, determine if the user's request is sufficiently clear and detailed. User initial requests are often vague; this step is key to output quality. Must repeatedly confirm with the user.
- Parse Intent: Based on the user's text question + input attachments (reference images/sketches/screenshots), make an initial judgment:
- Task type: Create from scratch (T2I)? Edit based on existing images (I2I)?
- Does it involve specific real people/brands/objects that require fidelity?
- Number of reference images and role of each (editing target / style reference / subject source).
- Multi-Dimensional Refinement (when ambiguous, confirm item by item, can use
request_user_inputfor batch questions or natural follow-ups; when already detailed, light confirmation is sufficient):- Main subject 2. Style 3. Composition and angle 4. Atmosphere and lighting 5. Size and aspect ratio 6. Quantity 7. Purpose 8. Reference images 9. Fidelity requirements
- Involving Real People: Ask and record identifying features for each person (hairstyle/hair color/glasses/skin tone/face shape/clothing/body type/age) to use as prompt anchors.
- Summarize as an 'Image Specification' and echo back to the user for confirmation.
Efficiency Principle: When the request is clear, only do a light confirmation (restate + ask 'Is that correct? Need any adjustments?'), don't mechanically go through the full list; only dig deep on ambiguous or high-risk dimensions (fidelity, reference image roles).
Step 2: Select Version
Based on the clarified requirements from Step 1, select the version according to the selection recommendations (see references/pricing_and_models.md):
| Scenario | Recommended Version |
|---|---|
| Everyday posters, illustrations, social media graphics, UI prototypes, batch generation | Standard (Default) |
| High-resolution 2K output without extreme detail | Standard (2K same price, more economical) |
| E-commerce product image compositing into home scenes (I2I multi-image) | Standard; Pro optional for extreme material quality |
| Newspaper layouts, exam papers, storyboards, menus, infographics (dense layout) | Pro |
| Portrait photography, product close-ups (micro-expressions/pores/hair strand real details) | Pro |
| Knowledge visual guides, history teaching infographics (multi-module + cross-lingual) | Pro |
- Default to Standard; when Pro is needed, explicitly inform the user of the cost difference (2K Pro is 178% more expensive).
- If the user does not specify a version, default to Standard and mention it in the generation plan.
Step 3: Build Prompt and Call optimize (Review and Optimization Logging, Never Call API)
Based on the intent and specifications from Step 1, review and optimize the prompt using best practices and the case library, then select the mode. Then, call optimize (instead of direct generation). optimize is the core stage to maximize model capability: raw requests are usually brief and vague, must be expanded into a visually descriptive prompt using the official 6-step paradigm, and log the 'optimization before/after comparison + change explanation'.
3.1 Consult Best Practices and Case Library
First, review references/best_practices.md and references/case_library.md for official examples of similar scenarios. Learn their prompt structure patterns and key techniques, identify common pitfalls, and avoid them proactively.
Scenario to Case Quick Reference:
| User Scenario | Reference Case | Prompt Focus |
|---|---|---|
| Exam paper/document/report layout | Case 1 (Chinese Exam Paper) | Area-by-area scan description + word-by-word text rendering |
| Macro photography/product close-ups | Case 2 (Embroidery Macro) | Material fibers + action moment + shallow depth of field |
| Handwritten notes/math formulas | Case 3 (Math Notes) | Three-color annotations + formula word-by-word + geometric diagrams |
| E-commerce product image compositing | Case 4 (Product Composite I2I) | Editing rules (extract/ignore/keep/generate) |
| Character design/multi-view consistency | Case 5 (Character Design Sheet) | Extremely detailed single person description + multi-view zoning |
| Hand-drawn map/infographic | Case 6 (Food Map) | Area-by-area description + numbered points + legend system |
| Menu/price list | Case 7 (Chaoshan Menu) | Column zoning + dish list + embedded photos |
| Knowledge visual guide/science poster | Case 8 (Ruqun Visual Guide) | Modular description + main visual character + auxiliary modules |
| Vector motion/guide infographic | Case 9 (Hiking Guide Map) | English vector style + color system + route waypoints |
| History teaching/cross-lingual infographic | Case 10 (An Lushan Rebellion) | Bilingual mode + ultra-wide horizontal layout + negative constraints |
| Commercial portrait photography | Case 11 (Italian Street Portrait) | Multi-layer background narrative + extremely detailed person + film look |
| Lighting portrait photography | Case 12 (Straw Hat Lighting Portrait) | Light source origin and placement + photography parameters + negative constraints |
For detailed prompt structure analysis and key techniques of all 12 official cases, see
references/case_library.md; for complete original prompts, seeQwen-Image-3.0Official Best Practice Cases and Complete Prompt Handbook.md.
3.2 Choose Method (Based on Goal)
| Goal | Method | Call |
|---|---|---|
| Create from scratch, no reference images | Text-to-Image T2I | Prompt only, no --image |
| Preserve/extend existing image subject or content | Image-to-Image I2I | Prompt + 1~3 --image |
3.3 Write Prompt (Official 6-Step Paradigm)
Organize content according to the official prompt structure skeleton summarized from 12 cases (see references/best_practices.md Chapter 3):
- Opening Tone: One sentence describing the image type, orientation, overall style and atmosphere. E.g., 'This is a vertical... poster, overall background is...'
- Spatial Flow: Describe strictly in spatial order (top to bottom, left to right, subject to background) for each area. Clearly state the relative positional relationships of elements.
- Word-by-Word Text Rendering: Write all text that needs to be rendered (titles/body text/labels/prices/footers) verbatim in quotes in the prompt. Specify font/font size/color/position.
- Five Details: Give specific color names, texture words for materials, direction and hardness for lighting, style for fonts, and layers for composition.
- Closing Constraints: List negative constraints (garbled text/misalignment/distortion/overexposure/watermarks, etc.) starting with 'Avoid...'. Can also use
--negative-promptparameter. - Aspect Ratio and Photography Parameters: For realistic/portrait types, optionally include aspect ratio, lens focal length, aperture, etc. (e.g., 'Vertical 3:4, 85mm, f/2').
Official 3 Usage Tips:
- Instructions can be 'long': 4.5K tokens allows for complex layouts; describe every area, every piece of text, every relative position clearly.
- Small text must be 'explicitly called out': Write exact text directly into the instruction, use quotes and specify font/font size/color/position.
- Style must be 'fully described': For photography style, describe light, line, and atmosphere (focal length/aperture/exposure/film grain). For illustration style, describe material, color palette, brushstrokes.
Editing/Reference (I2I) Specific Points: Clearly state 'Keep X, only change Y'. Reiterate invariants during iteration to prevent drift. For multi-image compositing, focus on editing rules (what to extract/ignore/keep/generate). Use strong constraint words like 'must' and 'must not' to ensure complete use of reference images.
3.4 Call optimize (Log Comparison + Change Explanation, Return Token A, Never Call API)
After prompt review and optimization, call the optimize stage (instead of direct generation). optimize will validate against perfunctory work (original/optimized/change explanation must be complete with substantial change explanation), validate parameters, calculate the optimized prompt fingerprint, persist the review record, and return Token A. Never calls the real API, no cost incurred:
optimize T2I: python scripts/generate_image.py optimize --original-prompt "raw request" --optimized-prompt "optimized prompt" --change-explanation "change explanation" --size 1024*1024
optimize I2I: python scripts/generate_image.py optimize --original-prompt "raw request" --optimized-prompt "optimized prompt" --change-explanation "change explanation" --image ref.png --model qwen-image-3.0-pro
optimize multi-image: python scripts/generate_image.py optimize --original-prompt "..." --optimized-prompt "..." --change-explanation "..." --n 4
Required optimize parameters: --original-prompt (raw request), --optimized-prompt (optimized prompt), --change-explanation (change explanation: what was optimized and why—anti-perfunctory work and user confirmation basis). Common parameters: --model (default qwen-image-3.0), --image (1-3 reference images), --size Width*Height, --n (1-6), --negative-prompt, --seed, --watermark, --no-prompt-extend, --prompt-extend-mode direct|agent, -o output path. All parameters are locked into the record during optimize and cannot be modified in subsequent stages (only generate's -o can override the output path).
Prompt-type parameters support
@filesyntax: When a value starts with@, read its content from the following file path (for very long prompts, to avoid command-line length limits), e.g.,--optimized-prompt @optimized.txt.
optimize output: raw request, optimized prompt, change explanation, generation plan (mode/model/size/quantity/rewrite style/estimated cost), review token (Token A). Carry these completely into Step 4.
Step 4: Display Confirmation (Mandatory Wait for User Confirmation)
Display the optimize output 'raw request -> optimized prompt -> change explanation' + generation plan + Token A completely to the user and wait for explicit user confirmation:
- User confirms -> Proceed to Step 5, call
prepareusing Token A. - User requests changes -> Go back to Step 3 for re-optimization, then re-run
optimize(generates new Token A, old token naturally expires/is cleaned up), then re-display for confirmation. - ⚠️ Do not call
prepare/generatebefore user confirmation. Although the code does not verify 'user actually saw it',preparemust rely on a validoptimizeToken A. Standard display confirmation is a key gate for quality and cost. The user can check the change explanation during confirmation to see if the optimization direction deviated (e.g., 'realistic style' changed to 'cartoon style').
Step 5: prepare Confirmation (Consume Token A, Return Token B, No API Call)
After user confirmation, call prepare using Token A + the optimized prompt identical to the one logged in optimize:
prepare: python scripts/generate_image.py prepare --token <Token A> --optimized-prompt "<optimized prompt logged by optimize>"
- The script passes three checks (review record exists / Token A matches / optimized prompt matches logged version). Upon success, it presents the unchanged 'raw request -> optimized prompt (confirmed version) -> change explanation' + generation plan, returns a confirmation token (Token B), and destroys Token A (use once, then discard).
- Technical parameters (images/size/quantity, etc.) are retrieved and locked from the optimize record, cannot be modified in the prepare stage.
- No Token A or content mismatch -> Reject (error message serves as workflow guide).
Step 6: generate and Single-Point Iteration
Call generate using Token B + the prompt identical to the version confirmed in prepare:
generate: python scripts/generate_image.py generate --token <Token B> --prompt "<confirmed prompt>" [-o output path]
- The script passes three checks (confirmation record exists / Token B matches / prompt matches confirmed version) before calling the API. Other parameters are retrieved and locked from the record, cannot be modified in the generate stage.
- Upon success, it automatically outputs actual size, usage, cost, and destroys Token B (single-use, non-reusable).
- Displays image with absolute path.
- Iteration: Change only one thing each time -> re-run
optimize(new Token A) -> display confirmation ->prepare(new Token B) ->generate. If results are unsatisfactory, prioritize adjusting 'style/atmosphere/composition', or go back to Step 3 for a different strategy.
Step 7: Feedback Consumption
After generation, the script automatically outputs the usage and cost for this run (version, input/output tier, number of images, unit price, total). Summarize for the user in the reply:
- Version and method used (T2I/I2I), model ID.
- Output size, number generated, billing tier (1K/2K).
- Input cost, output cost, total cost (RMB).
- Request ID (for traceability).
Cost calculation rules and examples are in references/pricing_and_models.md.
Token and Record Mechanism (Three-Stage Chain, Code-Level Details)
- Token Format:
sha256(prompt)-nonce8(fingerprint bound to prompt content, nonce prevents multiple logs of the same prompt from overwriting each other). Token A and Token B have the same content and fingerprint but different nonces, making them two different tokens. - Token Relay: optimize produces Token A -> prepare consumes Token A and produces Token B (destroys A) -> generate consumes Token B (destroys B after success). Missing a link leads to rejection.
- Record Storage: Two directories in the system temporary directory:
skill_image_qwen_optimize/<tokenA>.json(Token A, containing original_prompt/optimized_prompt/change_explanation/params),skill_image_qwen_pending/<tokenB>.json(Token B, containing confirmed version and retrieved parameters).optimizeonly stores image paths/URLs, does not read image content, keeping records lightweight. - Token Scope: Fingerprint only covers prompt content (
sha256(prompt)). Technical parameters like size/format are retrieved from the record, not included in the fingerprint—changing size does not require a full re-run (unless size/watermark themselves are compliance elements the user must confirm). - Anti-Perfunctory: optimize log mandates an 'optimization before/after comparison + change explanation'; change explanation must meet a minimum character count. prepare presents this unchanged for user confirmation.
- Lifecycle: Token A is destroyed immediately upon successful prepare. Token B is destroyed immediately upon successful generate (single-use, prevents reuse). If the API call fails, Token B is retained to allow retry with the same token (no need for re-confirmation). Records older than 2 hours are automatically invalidated and cleaned up.
- Parameter Locking: Images/size/quantity/rewrite style, etc., are locked into the record during
optimizeand retrieved from the record in subsequent stages, cannot be tampered with;generatecan only use-oto override the output path. - Image files must still exist at generate time:
optimizeonly checks existence and logs the path.generatereads the file from disk to convert to data URI.
Prompt Construction Rules
- 6-Step Paradigm: Opening tone -> Spatial flow -> Word-by-word text rendering -> Five details -> Closing constraints -> Aspect ratio and photography parameters (see
references/best_practices.md). - Qwen Characteristics: Prefers detailed, visually descriptive long descriptions (up to 4.5K tokens);
prompt_extendis enabled by default to enhance short prompts. - Text in Images: Enclose content in quotes, specify font/font size/color/position, require verbatim rendering.
- Editing/Reference: Clearly state 'Keep X, only change Y'. Reiterate invariants during iteration to prevent drift.
- Size: Use
Width*Height(asterisk-separated, e.g.,1920*1080); if not specified, the model recommends automatically. - See
references/best_practices.mdfor complete best practices and FAQ;references/case_library.mdfor structural analysis of 12 official cases;references/api_reference.mdfor API parameters.
Reference File Index
| File | Content |
|---|---|
references/best_practices.md | Overview of the Three Realities, 3 official tips, 6-step prompt paradigm, FAQ, size tiers, iteration recommendations |
references/case_library.md | Category index of 12 official cases, prompt structure analysis, key techniques, scenario-to-mode quick reference |
references/api_reference.md | API endpoint, request body structure, parameter descriptions, response body, usage field, error codes |
references/pricing_and_models.md | Model comparison, price table, cost calculation, selection recommendations |
Qwen-Image-3.0Official Best Practice Cases and Complete Prompt Handbook.md | Official original: 12 cases' complete prompts, usage tips, API pricing |
scripts/generate_image.py | Three-stage generation script (optimize/prepare/generate, T2I/I2I, pure standard library, three-stage token chain enforcing optimization review + confirmation, anti-perfunctory, automatic billing) |
Important Constraints
- Key Security: Read only from the environment variable
DASHSCOPE_API_KEY. Never write it into skill files, never ask users for plain-text keys in chat. If not set, provide setup instructions and wait. - Three Stages Cannot Be Bypassed: No
optimizeToken A ->preparerejected; noprepareToken B ->generaterejected;optimize/preparedo not call API and incur no cost. The model cannot jump from raw request directly to generation. - Anti-Perfunctory Mandatory:
optimizemust log an 'optimization before/after comparison + change explanation'; change explanation must have substantial content.preparepresents this unchanged for user confirmation. - Display Confirmation Mandatory: After
optimize, the 'raw request -> optimized prompt -> change explanation' + plan must be displayed to the user for confirmation beforeprepare/generate. - Clarify Before Generate: Do not call the script before completing Step 1 (intent recognition and clarification).
- Output Location: Default save to
output/under the current working directory. If the image is for the current project, move it to an appropriate location within the project after generation. - No Overwrite: Unless the user explicitly asks to replace, use versioned filenames.
- Image Timeliness: The image URL returned by the API is valid for 24 hours; the script automatically downloads it locally.
Environment Setup
- Must set the environment variable
DASHSCOPE_API_KEY(Alibaba Cloud Bailian API Key). - PowerShell temporary setup (type the key, it will not be stored in command history):
$env:DASHSCOPE_API_KEY = Read-Host -Prompt 'DASHSCOPE_API_KEY' - Permanent setup: Write
DASHSCOPE_API_KEYvia the system environment variable interface, or usesetxthen reopen the terminal. Do not write the actual value into repository files. - Optional
DASHSCOPE_BASE_URL: Override the default endpointhttps://dashscope.aliyuncs.com(e.g., for a workspace-specific domain). - API Key acquisition: https://help.aliyun.com/zh/model-studio/get-api-key