Skip to main content

Overview

Text generation models generate coherent, contextually relevant text based on natural language prompts, supporting scenarios such as chatbots, content creation, document summarization, and code generation.

The input to a text generation model can be simple keywords, a one-sentence summary, or more complex multi-step instructions and contextual information. Common application scenarios:
  • Content creation: Generate news articles, product descriptions, and short video scripts.
  • Customer service: Build chatbots that automatically respond around the clock and answer frequently asked questions.
  • Text translation: Support fast and accurate translation between multiple languages.
  • Summarization: Extract key information from long documents, reports, and emails.
  • Legal document drafting: Generate basic frameworks for contract templates and legal opinions.

Core concepts

The input to a text generation model is a prompt, which consists of one or more message objects. Each message is composed of a role and content, specifically:
  • System message: Sets the model's role, behavioral guidelines, or specific task instructions. If not specified, the default is "You are a helpful assistant".
  • User message: The questions, instructions, or input content that the user sends to the model.
  • Assistant message: The model's replies. In multi-turn conversations, historical assistant messages are passed in to maintain context.
When calling the model, you need to construct a messages array consisting of the message objects described above. A typical request usually consists of a system message that defines behavioral guidelines and a user message submitted by the user.
The system message is optional but recommended. Clearly defining the model's role and behavioral constraints helps obtain more consistent and predictable output.
[
    {"role": "system", "content": "你是一个有帮助的助手,需要提供精准、高效且富有洞察力的回应,随时准备协助用户处理各种任务与问题。"},
    {"role": "user", "content": "你是谁?"}
]
The response object in the output contains the assistant message replied by the model.
{
    "role": "assistant",
    "content": "你好!我是Qwen,是阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我可以帮助你回答问题、创作文字、进行逻辑推理、编程等。我能够理解并生成多种语言,支持多轮对话和复杂任务处理。如果你有任何需要帮助的地方,尽管告诉我!"
}

QuickStart

Prerequisites for using the API: You have obtained and configured an API Key and completed configuring the API Key in environment variables. If you call the model through an SDK, you need to install the OpenAI or DashScope SDK. In the example endpoint, {WorkspaceId} is the workspace ID. For how to obtain it, see Region, service deployment scope, and endpoint.
  • OpenAI-compatible Chat Completions API
  • OpenAI-compatible Responses API
  • DashScope API
  • Python
  • Java
  • Node.js
  • Go
  • C#(HTTP)
  • PHP(HTTP)
  • curl
  • dashscope CLI
import os
from openai import OpenAI

try:
    client = OpenAI(
        # API keys differ by region. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
        # If the environment variable is unset, replace the next line with your Model Studio API key: api_key="sk-xxx",
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        # The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
        base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
    )

    completion = client.chat.completions.create(
        model="qwen4-max",
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": "你是谁?"},
        ],
    )
    print(completion.choices[0].message.content)
    # To view the full response, uncomment the following line.
    # print(completion.model_dump_json())
except Exception as e:
    print(f"错误信息:{e}")
    print("请参考文档:https://www.alibabacloud.com/help/model-studio/error-code")

Response

我是千问,阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我可以帮助你回答问题、创作文字,比如写故事、写公文、写邮件、写剧本、逻辑推理、编程等等,还能表达观点,玩游戏等。如果你有任何问题或需要帮助,欢迎随时告诉我!

Call models asynchronously

Calling asynchronous interfaces can effectively improve the processing efficiency of high-concurrency requests.
  • OpenAI-compatible Chat Completions API
  • DashScope
Python
import os
import asyncio
from openai import AsyncOpenAI
import platform

# Create an asynchronous client instance.
client = AsyncOpenAI(
    # API keys differ by region. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
    # If the environment variable is unset, replace the next line with your Model Studio API key: api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)

# Define a list of asynchronous tasks
async def task(question):
    print(f"发送问题: {question}")
    response = await client.chat.completions.create(
        messages=[
            {"role": "user", "content": question}
        ],
        model="qwen-plus",  # For a list of models, see https://www.alibabacloud.com/help/model-studio/getting-started/models
    )
    print(f"模型回复: {response.choices[0].message.content}")

# Main asynchronous function.
async def main():
    questions = ["你是谁?", "你会什么?", "天气怎么样?"]
    tasks = [task(q) for q in questions]
    await asyncio.gather(*tasks)

if __name__ == '__main__':
    # Set the event loop policy.
    if platform.system() == 'Windows':
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    # Run the main coroutine.
    asyncio.run(main(), debug=False)
Response
Since the calls are asynchronous, the responses may be returned in a different order than in the examples.
发送问题: 你是谁?
发送问题: 你会什么?
发送问题: 天气怎么样?
模型回复: 你好!我是千问,阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我可以帮助你回答问题、创作文字,比如写故事、写公文、写邮件、写剧本、逻辑推理、编程等等,还能表达观点,玩游戏等。如果你有任何问题或需要帮助,欢迎随时告诉我!
模型回复: 您好!我目前无法实时获取天气信息。您可以告诉我您所在的城市或地区,我会尽力为您提供一些通用的天气建议或信息。或者您也可以使用天气应用查看实时天气情况。
模型回复: 我会很多技能,比如:

1. **回答问题**:无论是学术问题、生活常识还是专业知识,我都可以尝试帮你解答。
2. **创作文字**:我可以写故事、公文、邮件、剧本等各类文本。
3. **逻辑推理**:我可以帮助你解决一些逻辑推理问题,比如数学题、谜语等。
4. **编程**:我可以提供编程帮助,包括代码编写、调试和优化。
5. **多语言支持**:我支持多种语言,包括但不限于中文、英文、法语、西班牙语等。
6. **观点表达**:我可以为你提供一些观点和建议,帮助你做出决策。
7. **玩游戏**:我们可以一起玩文字游戏,比如猜谜语、成语接龙等。

如果你有任何具体的需求或问题,欢迎告诉我,我会尽力帮助你!

Going live

Build high-quality context

Directly feeding a large amount of raw data into an LLM will lead to increased costs and degraded results due to the context capacity limit. Context Engineering dynamically loads precise knowledge to significantly improve generation quality and efficiency. Core techniques include:
  • Prompt engineering: By designing and optimizing text instructions (prompts), you can guide the model more precisely so that its output better matches your expectations. To learn more, see the Prompt Engineering Guide page.
  • Retrieval augmented generation (RAG): Suitable for scenarios where the model needs to answer questions based on an external knowledge base (such as product documentation or technical manuals).
  • Tool calling (Tool): Allows the model to obtain real-time information (such as weather or traffic queries) or perform specific operations (such as calling an API or sending an email).
  • Memory: Establishes long-term and short-term memory for the model, enabling it to understand the history of continuous conversations.

Control response diversity

temperature and top_p are used to control the diversity of generated text. The higher the values, the more diverse the content; the lower the values, the more deterministic the content. To accurately evaluate the effect of a parameter, we recommend adjusting only one at a time.
  • temperature: Range [0, 2). Focuses on adjusting randomness.
  • top_p: Range (0, 1]. Filters responses by a probability threshold.
The following examples show the impact of different parameter settings on the generated content. The input prompt is: "Write a short three-sentence story whose main characters are a cat and a beam of sunlight."
  • High diversity (example temperature=0.9): Suitable for scenarios that require creativity, imagination, and novel expression, such as creative writing, brainstorming, or marketing copy.
阳光斜斜地切进窗台,橘猫蹑手蹑脚走近那块发光的方砖,绒毛瞬间被染成熔化的蜜糖。
它伸出前爪轻拍光斑,却像踩进温热的池水般陷了进去,整片阳光顺着肉垫汩汩漫上脊背。
午后忽然变得很重——猫儿蜷在流动的金砂里,听见时光在呼噜声中轻轻融化。
  • High determinism (example temperature=0.1): Suitable for scenarios that require accurate, rigorous, and predictable content, such as factual Q&A, code generation, or legal texts.
午后,一只老猫蜷在窗台,数着光斑打盹。
阳光轻轻跃过它斑驳的脊背,像在翻阅一本旧相册。
尘埃浮起又落下,仿佛时光低语:你曾年轻,我也炽热。
temperature:
  • The higher the temperature, the flatter the Token probability distribution becomes (that is, the probability of high-probability Tokens decreases while the probability of low-probability Tokens increases), making the model more random when selecting the next Token.
  • The lower the temperature, the steeper the Token probability distribution becomes (that is, high-probability Tokens are more likely to be selected while low-probability Tokens become less likely), making the model tend to choose a small number of high-probability Tokens.
top_p:top_p sampling refers to sampling from the set of Tokens with the highest probabilities (the most essential ones). It sorts all possible next Tokens by probability from highest to lowest, then accumulates probabilities starting from the highest-probability Token until the cumulative probability reaches the threshold (for example, 80%, that is, top_p=0.8), and finally randomly selects one Token from these highest-probability Tokens whose cumulative probability reaches the threshold for output.
  • The higher the top_p, the more Tokens are considered, so the generated text is more diverse.
  • The lower the top_p, the fewer Tokens are considered, so the generated text is more focused and deterministic.

More features

The preceding sections introduced basic interaction methods. For more complex scenarios, see:
  • Multi-turn conversations: Suitable for scenarios that require continuous interaction, such as follow-up questions or information gathering.
  • Streaming output: Suitable for scenarios that require immediate responses, such as chatbots or real-time code generation. It improves user experience and avoids timeouts caused by long response times.
  • Deep thinking: Suitable for scenarios that require high-quality, well-organized in-depth answers, such as complex reasoning or strategy analysis.
  • Structured output: Use this when you need the model to reply in a stable JSON format for program calls or data parsing.
  • Partial mode: Suitable for scenarios where the model continues existing text, such as code completion or long-form writing.

API reference

For the complete list of parameters for model calls, see the OpenAI-compatible API reference and the DashScope API reference.

FAQ

Q: Why is the input Token count higher than the Token count of the text I sent?

A: When processing a conversation, the system uses a Chat Template to wrap the raw input text, adding control markers such as role identifiers and message boundaries. These system-added markers are also counted as Tokens. For example, when you send the message {"role": "user", "content": "Hello"} to qwen3.8-max, "Hello" corresponds to only 1 Token after tokenization, but when the system processes it, the actual full input text is <|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n<think>, and the total Token count increases to 11 after tokenization. A: The Qwen API itself cannot directly access web page links. You can use the Function Calling feature, or combine it with a web scraping tool such as Python's Beautiful Soup to extract web page content and pass it to the model.

Q: Why are the responses from Qwen on the web and the Qwen API inconsistent?

A: Qwen on the web applies additional engineering optimization on top of the Qwen API, which enables features such as parsing web pages, web search, image generation, and creating PPT slides. These capabilities are not inherent to the LLM API, and you can use the Function Calling feature to improve the model's performance.

Q: Can the model directly generate files in Word, Excel, PDF, or PPT format?

A: No. The text generation models of Alibaba Cloud Model Studio output plain text only. You need to use code or a third-party library to convert the text to the desired format.