All insights

Model APIs

Qwen Prompting Guide: Write Better Prompts and Call Qwen Through an API

A practical guide to prompting Qwen-Plus for text tasks through Alibaba Cloud Model Studio: build a clear prompt, make an OpenAI-compatible API request, and check the output.

Illustration for Qwen prompting guide

Quick answer

For a Qwen text task, name the job, provide the facts or context the model may use, spell out constraints, and say what the answer should look like. This guide uses Qwen-Plus (qwen-plus) through Alibaba Cloud Model Studio’s OpenAI-compatible Chat Completions API as a concrete example—not as a claim that it is the best model for every job. Model Studio’s model information lists Qwen-Plus for US (Virginia), with text input and text output. (alibabacloud.com)

The prompt advice below concerns text/chat, not image generation. Model Studio describes prompts as role-and-content messages, with a system message available for behavior and task constraints. (help.aliyun.com)

1. Choose the model that matches the task

Start by identifying what you want the model to do and what kind of input it needs:

  • Text in, text out: use a text-generation/chat model such as the qwen-plus example below for drafting, summarization, or structured responses. Check the model’s regional availability and capabilities before using it.
  • Image generation or image editing: use an image model and its separate image workflow. The image prompt examples discussed below are not instructions for submitting images through this text-only chat request.

A third-party Qwen-Image prompt collection discusses visual composition and image edits; it is not evidence for how to prompt a Qwen text model.

2. Build a text prompt from four parts

A useful starting template is:

  1. Task: Say exactly what to produce or do.
  2. Context: Supply relevant source material, audience, or facts.
  3. Constraints: State what to include, avoid, or do when information is missing.
  4. Output format: Specify the structure, length, tone, or fields you need.

For example, rather than asking “Write a product answer,” tell the model who the answer is for, which supplied facts it may rely on, what it must not invent, and which fields to return. Alibaba Cloud’s prompt guide recommends making the task clear and specific. Clearer instructions communicate the request; they do not guarantee correctness. (help.aliyun.com)

Worked example: answer a product FAQ from supplied facts

System message

You write concise customer-support answers. Use only the facts provided by the user. If a fact needed to answer is missing, say so instead of guessing. Return one JSON object with the keys "answer" and "unknowns". Do not include Markdown fences.

User message

Task: Answer a customer asking whether the Northstar Bottle is dishwasher-safe.

Facts provided:
- The bottle is made from stainless steel.
- The care instructions say to hand-wash the bottle.
- The cap is dishwasher-safe on the top rack.

Constraints:
- Distinguish the bottle from the cap.
- Do not imply the bottle itself is dishwasher-safe.

Return "answer" as a short customer-facing response and "unknowns" as a JSON array.

This example illustrates prompt construction; it is not a reported model test. Its key technique is to provide the evidence and decision rule rather than ask the model to fill gaps from memory.

3. Send the prompt through Model Studio’s API

This example uses the US (Virginia) Model Studio endpoint and the OpenAI-compatible Chat Completions interface. Model Studio documents the Virginia endpoint pattern and the required model name in the request body. Its guidance recommends setting the API key as an environment variable. Use an API key created for the same region as the endpoint; Model Studio says keys are region-bound. (help.aliyun.com)

Install the SDK and set your credentials and workspace-specific base URL in your shell. Replace the placeholders with values from your Model Studio account; do not commit the key to source control.

python -m pip install openai
export DASHSCOPE_API_KEY="YOUR_MODEL_STUDIO_API_KEY"
export QWEN_BASE_URL="https://YOUR_WORKSPACE_ID.us-east-1.maas.aliyuncs.com/compatible-mode/v1"

The Model Studio Chat Completions reference documents the Virginia base URL with a workspace ID. Check the current endpoint instructions for your account if your console or region-specific documentation gives you a different base URL. (help.aliyun.com)

Then save and run this Python example:

import json
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ['DASHSCOPE_API_KEY'],
    base_url=os.environ['QWEN_BASE_URL'],
)

system_prompt = '''You write concise customer-support answers. Use only the facts provided by the user. If a needed fact is missing, say so instead of guessing. Return one JSON object with the keys "answer" and "unknowns". Do not include Markdown fences.'''
user_prompt = '''Task: Answer a customer asking whether the Northstar Bottle is dishwasher-safe.

Facts provided:
- The bottle is made from stainless steel.
- The care instructions say to hand-wash the bottle.
- The cap is dishwasher-safe on the top rack.

Constraints:
- Distinguish the bottle from the cap.
- Do not imply the bottle itself is dishwasher-safe.

Return "answer" as a short customer-facing response and "unknowns" as a JSON array.'''

response = client.chat.completions.create(
    model='qwen-plus',
    messages=[
        {'role': 'system', 'content': system_prompt},
        {'role': 'user', 'content': user_prompt},
    ],
)

# For a non-streaming Chat Completions response, read the answer here.
content = response.choices[0].message.content
if content is None:
    raise RuntimeError('The response did not contain text content.')

result = json.loads(content)
assert set(result) == {'answer', 'unknowns'}
assert isinstance(result['answer'], str)
assert isinstance(result['unknowns'], list)
print(json.dumps(result, indent=2))

The OpenAI-compatible setup uses the SDK client’s api_key and base_url, and the request names the model and supplies role/content messages. Model Studio’s Chat Completions documentation describes the interface as OpenAI-compatible and provides input/output parameters and call examples; in the SDK’s standard non-streaming Chat Completions response, the first choice’s message content contains the generated text. (help.aliyun.com)

Expected outcome: the program prints a parsed JSON object with an answer string and an unknowns list. The code checks that the returned content parses as JSON with the requested keys and types; it does not prove the answer is factually correct. This example makes a standard non-streaming call without adding model-specific settings. It has not been run against an account here.

4. Check the answer, then revise one thing at a time

For the FAQ example, check the output against these acceptance criteria:

  • Does it say the bottle should be hand-washed?
  • Does it separately say the cap can go on the top rack?
  • Does it avoid adding care instructions that were not supplied?
  • Does it parse as JSON with both required fields and the right value types?

If it fails, identify the specific failure and tighten the relevant instruction. For example, if it conflates the cap and bottle, add: “Never transfer a care instruction from one component to another.” If it invents a detail, reinforce the instruction to use only the supplied facts. Then run the same check again. For production use, test a representative set of real questions and edge cases; one response is not evidence that a prompt will always work.

The JSON parsing check is useful when your application needs structured text, but asking for JSON in a prompt alone does not guarantee valid JSON. Keep validation in your application and handle parse failures explicitly, as the example does by allowing json.loads to raise an error. For business-critical answers, also verify the content against an authoritative source or approved knowledge base.

5. If the API call fails

Check these setup items before rewriting the prompt:

  • Confirm the API key is set in the shell where Python is running.
  • Confirm the base URL uses the endpoint and workspace ID specified for your region.
  • Use an API key created in the same region as the endpoint; Model Studio says a key from another region is rejected.
  • Confirm the key has permission to call the selected model and that the model is available in that region.
  • Check the provider’s current API reference for request and error details. (alibabacloud.com)

Text prompting is not image prompting

For image creation or editing, switch to the relevant image model and API documentation rather than reusing this text-only request. A third-party Qwen-Image prompt collection recommends quoting short exact text strings and describing placement for text inside images; those are image-prompt recommendations, not guidance for Qwen chat messages or proof of perfect text rendering.

Sources

OpenAI compatible - Chat — Alibaba Cloud Model Studio

qwen-plus Model Info — Alibaba Cloud Model Studio

Make your first API call to Qwen — Alibaba Cloud Model Studio

Call Qwen models via OpenAI API — Alibaba Cloud Model Studio

OpenAI Python SDK: ChatCompletion response type

OpenAI Python SDK: ChatCompletionMessage type

Qwen-Image prompt collection — Techpresso

Contact us