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:
The input to a text generation model is a prompt, which consists of one or more message objects each containing a role and content:
The response contains the model's reply in an
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
Asynchronous calls improve throughput for high-concurrency workloads.
Sample response
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:
The
For more complex scenarios, the following features are available:
For all parameters, see the OpenAI-compatible API reference and the DashScope API reference.
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
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.
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.
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
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).
- 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.
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.
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.
assistant message.
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
Response
Asynchronous calls
Asynchronous calls improve throughput for high-concurrency workloads.
- OpenAI-compatible Chat Completions API
- DashScope
Python
Because the calls are asynchronous, the order of the responses may differ from this example.
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.
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.
- 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.
How it works
How it works
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.
- 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.
Q: Why can't the Qianwen API analyze webpage links?
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 theTo resume generation from incomplete output, see Continue Writing from Incomplete Output.finish_reasonfield. A value ofnullindicates incomplete content, though not necessarily a timeout.
Prefix-based continuation is not yet supported in the Java SDK.