Skip to main content

Overview

A text generation model generates text from natural language prompts for applications such as chatbots, content creation, document summarization, and code generation.

Input can range from a single keyword to complex, multi-step prompts with context. Common use cases include:
  • Content creation: Generate news articles, product descriptions, and short-form video scripts.
  • Customer service: Build 24/7 automated chatbots to answer frequently asked questions.
  • Text translation: Translate text between multiple languages.
  • Summarization: Summarize long articles, reports, and emails.
  • Legal document drafting: Draft contract templates and legal opinions.
For more examples, see Text Generation Examples.

Key concepts

The input to a text generation model is a prompt, which consists of one or more message objects each containing a role and content:
  • System message: Sets the model's persona, behavior guidelines, or task-specific instructions. Defaults to "You are a helpful assistant."
  • User message: The user's question, instruction, or input to the model.
  • Assistant message: The model's response. In a multi-turn conversation, pass historical assistant messages to maintain context.
To call the model, construct an array of these message objects named messages. A typical request consists of a system message that defines behavior guidelines and a user message with the user's input.
The system message is optional but recommended. Defining the model's role and behavioral constraints produces more consistent and predictable output.
[
    {"role": "system", "content": "你是一个有帮助的助手,需要提供精准、高效且富有洞察力的回应,随时准备协助用户处理各种任务与问题。"},
    {"role": "user", "content": "你是谁?"}
]
The response contains the model's reply in an assistant message.
{
    "role": "assistant",
    "content": "你好!我是Qwen,是阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我可以帮助你回答问题、创作文字、进行逻辑推理、编程等。我能够理解并生成多种语言,支持多轮对话和复杂任务处理。如果你有任何需要帮助的地方,尽管告诉我!"
}

Quick start

Prerequisites: Get an API key and Configure API key as an environment variable. If using an SDK, also install the OpenAI or DashScope SDK. The {WorkspaceId} in the example base URLs is your workspace ID. For how to obtain it, see Regions and access domains.
  • OpenAI-compatible Chat Completions API
  • OpenAI-Compatible Responses API
  • DashScope API
  • Python
  • Java
  • Node.js
  • Go
  • C#(HTTP)
  • PHP(HTTP)
  • curl
import os
from openai import OpenAI

try:
    client = OpenAI(
        # 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
        # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx",
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        # 以下为华北2(北京)地域的URL,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的URL不同。
        base_url="https://{WorkspaceId}.cn-beijing.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)
    # 如需查看完整响应,请取消下列注释
    # print(completion.model_dump_json())
except Exception as e:
    print(f"错误信息:{e}")
    print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")

Response

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

Asynchronous calls

Asynchronous calls improve throughput for high-concurrency workloads.
  • OpenAI-compatible Chat Completions API
  • DashScope
Python
import os
import asyncio
from openai import AsyncOpenAI
import platform

# 创建异步客户端实例
client = AsyncOpenAI(
    # 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
    # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下为华北2(北京)地域的URL,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的URL不同。
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
)

# 定义异步任务列表
async def task(question):
    print(f"发送问题: {question}")
    response = await client.chat.completions.create(
        messages=[
            {"role": "system", "content": "You are a helpful assistant." },
            {"role": "user", "content": question}
        ],
        model="qwen-plus",  # 模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
    )
    print(f"模型回复: {response.choices[0].message.content}")

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

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

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

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

Production use

Building high-quality context

Feeding large amounts of raw data to a model increases costs and can degrade performance due to context window limitations. Context engineering -- dynamically loading precise knowledge -- improves generation quality and efficiency. Key techniques include:
  • prompt engineering: Design and optimize text prompts to guide the model toward the desired output. For more information, see the Prompt guide for text generation and the Alibaba Cloud Model Studio Prompt Templates page.
  • Retrieval-Augmented Generation (RAG): Lets the model answer questions from an external knowledge base such as product documentation or technical manuals.
  • tool calling: Retrieves real-time information (weather, traffic) or performs actions (API calls, sending emails) on behalf of the model.
  • memory: Provides long-term and short-term memory so the model can recall context across multi-turn conversations.
For a systematic understanding, see the Alibaba Cloud Certified Professional (ACP) course for large model senior engineers.

Controlling response diversity

The temperature and top_p parameters control the diversity of the generated text. Higher values increase diversity; lower values increase determinism. To isolate the effect of each parameter, adjust only one at a time.
  • temperature: Range: [0, 2). Primarily adjusts randomness.
  • top_p: Range: (0, 1]. Filters responses based on a probability threshold.
The following examples show how parameter settings affect output. Input prompt: "Write a three-sentence short story where the main characters are a cat and a sunbeam."
  • High diversity (Example: temperature=0.9): Best for scenarios that require creativity, imagination, and novel expression, such as creative writing, brainstorming, or marketing copy.
阳光斜斜地切进窗台,橘猫蹑手蹑脚走近那块发光的方砖,绒毛瞬间被染成熔化的蜜糖。
它伸出前爪轻拍光斑,却像踩进温热的池水般陷了进去,整片阳光顺着肉垫汩汩漫上脊背。
午后忽然变得很重——猫儿蜷在流动的金砂里,听见时光在呼噜声中轻轻融化。
  • High determinism (Example: temperature=0.1): Best for scenarios that demand accuracy, rigor, and predictability, such as factual Q&A, code generation, or legal texts.
午后,一只老猫蜷在窗台,数着光斑打盹。
阳光轻轻跃过它斑驳的脊背,像在翻阅一本旧相册。
尘埃浮起又落下,仿佛时光低语:你曾年轻,我也炽热。
temperature:
  • A higher temperature flattens the token probability distribution, making less likely tokens more probable and increasing output randomness.
  • A lower temperature sharpens the distribution, making high-probability tokens even more likely and reducing output randomness.
top_p:top_p sampling refers to sampling from the set of tokens with the highest probability (the most core ones). It sorts all possible next tokens by probability from highest to lowest, then accumulates the probabilities starting from the token with the highest probability 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.
  • A higher top_p widens the token selection pool, producing more diverse text.
  • A lower top_p narrows the pool, producing more focused and deterministic text.

More features

For more complex scenarios, the following features are available:
  • multi-turn conversation: For continuous interaction such as follow-up questions or information gathering.
  • streaming output: Returns tokens incrementally as they are generated, preventing timeouts for chatbots and real-time code generation.
  • deep thinking: Produces higher-quality, more structured answers for complex reasoning or strategic analysis.
  • structured output: Constrains responses to a consistent JSON format for programmatic use and data parsing.
  • prefix completion: Continues generation from existing text, useful for code completion or long-form writing.

API reference

For all parameters, 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-generated markers are also counted as tokens. For example, when the message {"role": "user", "content": "Hello"} is sent to qwen3.8-max, "Hello" corresponds to only 1 token after tokenization (Tokenize), but when the system processes it, the actual full input text is <|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n `Md`, and after tokenization the total token count increases to 11. A: The Qianwen API cannot access web page content directly. Instead, use function calling and MCP, or a web scraping tool like Python's Beautiful Soup to extract the content and pass it to the model.

Q: Why do the responses from Qianwen (Web) and the Qianwen API differ?

A: Qianwen (Web) adds features on top of the Qianwen API, including webpage parsing, web search, image creation, and PPT generation. These are not included in the base API, but you can build similar functionality using web search, function calling, and MCP.

Q: How to handle model timeouts

A: Use streaming output to avoid timeouts. Streaming returns tokens incrementally, eliminating the wait for a complete response. For non-streaming calls, the maximum timeout is at least 300 seconds and varies by region and model. If not completed in time, the service interrupts it and returns the content generated so far without reporting a timeout error. The response header includes x-dashscope-partialresponse: true to indicate a partial result.
If the response header is not accessible (for example, when using an SDK), check the finish_reason field. A value of null indicates incomplete content, though not necessarily a timeout.
To resume generation from incomplete output, see Continue Writing from Incomplete Output.
Prefix-based continuation is not yet supported in the Java SDK.

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

A: No. Text generation models only output plain text. Convert the output to the desired format using your own code or third-party libraries, or generate the files using applications like the Model Studio (Bailian) PPT auto-generation application or Qianwen (Web).