Overview

Updated at:

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

Python

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

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

Java

// 建议 OpenAI Java SDK版本 >= 3.5.0
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionCreateParams;

public class Main {
    public static void main(String[] args) {
        try {
            OpenAIClient client = OpenAIOkHttpClient.builder()
                    // 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
                    // 若没有配置环境变量,请用阿里云百炼API Key将下行替换为.apiKey("sk-xxx")
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    // 以下为华北2(北京)地域的URL,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的URL不同。
                    .baseUrl("https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1")
                    .build();

            // 创建 ChatCompletion 参数
            ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
                    .model("qwen4-max")
                    .addSystemMessage("You are a helpful assistant.")
                    .addUserMessage("你是谁?")
                    .build();

            // 发送请求并获取响应
            ChatCompletion chatCompletion = client.chat().completions().create(params);
            String content = chatCompletion.choices().get(0).message().content().orElse("未返回有效内容");
            System.out.println(content);
            // 如需查看完整响应,请取消下列注释
            // System.out.println(chatCompletion);

        } catch (Exception e) {
            System.err.println("错误信息:" + e.getMessage());
            System.out.println("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
        }
    }
}

Response

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

Node.js

// 需要 Node.js v18+,需在 ES Module 环境下运行
import OpenAI from "openai";

const openai = new OpenAI(
    {
        // 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
        // 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:apiKey: "sk-xxx",
        apiKey: process.env.DASHSCOPE_API_KEY,
        // 以下为华北2(北京)地域的URL,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的URL不同。
        baseURL: "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
    }
);
const completion = await openai.chat.completions.create({
    model: "qwen4-max",
    messages: [
        { role: "system", content: "You are a helpful assistant." },
        { role: "user", content: "你是谁?" }
    ],
});
console.log(completion.choices[0].message.content);
// 如需查看完整响应,请取消下列注释
// console.log(JSON.stringify(completion, null, 4));

Response

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

Go

// OpenAI Go SDK版本不低于 v2.4.0
package main

import (
	"context"
	// 如需查看完整响应,请取消下方及代码末尾的注释
	// "encoding/json"
	"fmt"
	"os"

	"github.com/openai/openai-go/v2"
	"github.com/openai/openai-go/v2/option"
)

func main() {
	// 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
	// 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:apiKey := "sk-xxx"
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	client := openai.NewClient(
		option.WithAPIKey(apiKey),
		// 以下为华北2(北京)地域的URL,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的URL不同。
		option.WithBaseURL("https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"),
	)
	chatCompletion, err := client.Chat.Completions.New(
		context.TODO(), openai.ChatCompletionNewParams{
			Messages: []openai.ChatCompletionMessageParamUnion{
				openai.SystemMessage("You are a helpful assistant."),
				openai.UserMessage("你是谁?"),
			},
			Model: "qwen4-max",
		},
	)

	if err != nil {
		fmt.Fprintf(os.Stderr, "请求失败: %v\n", err)
		// 更多错误信息,请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code
		os.Exit(1)
	}

	if len(chatCompletion.Choices) > 0 {
		fmt.Println(chatCompletion.Choices[0].Message.Content)
	}
	// 如需查看完整响应,请取消下列注释
	// jsonData, _ := json.MarshalIndent(chatCompletion, "", "  ")
	// fmt.Println(string(jsonData))

}

Response

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

C#(HTTP)

using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;

class Program
{
    private static readonly HttpClient httpClient = new HttpClient();

    static async Task Main(string[] args)
    {
        // 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
        // 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:string? apiKey = "sk-xxx";
        string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
        // 以下为华北2(北京)地域的URL,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的URL不同。
        string url = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions";
        string jsonContent = @"{
            ""model"": ""qwen4-max"",
            ""messages"": [
                {
                    ""role"": ""system"",
                    ""content"": ""You are a helpful assistant.""
                },
                {
                    ""role"": ""user"",
                    ""content"": ""你是谁?""
                }
            ]
        }";

        string result = await SendPostRequestAsync(url, jsonContent, apiKey);

        // 如需查看完整响应,请取消下列注释
        // Console.WriteLine(result);

        // 解析JSON并只输出content部分
        using JsonDocument doc = JsonDocument.Parse(result);
        JsonElement root = doc.RootElement;

        if (root.TryGetProperty("choices", out JsonElement choices) &&
            choices.GetArrayLength() > 0)
        {
            JsonElement firstChoice = choices[0];
            if (firstChoice.TryGetProperty("message", out JsonElement message) &&
                message.TryGetProperty("content", out JsonElement content))
            {
                Console.WriteLine(content.GetString());
            }
        }
    }

    private static async Task<string> SendPostRequestAsync(string url, string jsonContent, string apiKey)
    {
        using (var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
        {
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = await httpClient.PostAsync(url, content);
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStringAsync();
            }
            else
            {
                // 更多错误信息,请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code
                return $"请求失败: {response.StatusCode}";
            }
        }
    }
}

Response

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

PHP(HTTP)

<?php
// 设置请求的URL
// 各地域配置不同,请根据实际地域修改
$url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions';
// 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
// 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:$apiKey = "sk-xxx";
$apiKey = getenv('DASHSCOPE_API_KEY');
// 设置请求头
$headers = [
    'Authorization: Bearer '.$apiKey,
    'Content-Type: application/json'
];
// 设置请求体
$data = [
    "model" => "qwen4-max",
    "messages" => [
        [
            "role" => "system",
            "content" => "You are a helpful assistant."
        ],
        [
            "role" => "user",
            "content" => "你是谁?"
        ]
    ]
];
// 初始化cURL会话
$ch = curl_init();
// 设置cURL选项
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// 执行cURL会话
$response = curl_exec($ch);
// 检查是否有错误发生
// 更多错误信息,请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code
if (curl_errno($ch)) {
    echo 'Curl error: ' . curl_error($ch);
}
// 关闭cURL资源
curl_close($ch);
// 输出响应结果
$dataObject = json_decode($response);
$content = $dataObject->choices[0]->message->content;
echo $content;
// 如需查看完整响应,请取消下列注释
//echo $response;
?>

Response

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

curl

The 'base_url' and API key are region-specific. See OpenAI compatible - Chat for endpoint URLs and Obtain an API key to get your key.

# 各地域配置不同,请根据实际地域修改
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen4-max",
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user",
            "content": "你是谁?"
        }
    ]
}'

Response

The following response example uses qwen3.8-max to illustrate the response fields.

{
    "choices": [
        {
            "message": {
                "role": "assistant",
                "content": "我是千问,阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我可以帮助你回答问题、创作文字,比如写故事、写公文、写邮件、写剧本、逻辑推理、编程等等,还能表达观点,玩游戏等。如果你有任何问题或需要帮助,欢迎随时告诉我!"
            },
            "finish_reason": "stop",
            "index": 0,
            "logprobs": null
        }
    ],
    "object": "chat.completion",
    "usage": {
        "prompt_tokens": 26,
        "completion_tokens": 66,
        "total_tokens": 92
    },
    "created": 1726127645,
    "system_fingerprint": null,
    "model": "qwen3.8-max",
    "id": "chatcmpl-81951b98-28b8-9659-ab07-xxxxxx"
}

OpenAI-Compatible Responses API

The Responses API succeeds the Chat Completions API. For usage instructions, code examples, and migration guides, see OpenAI-Compatible Responses.

Python

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"),
        # 各地域配置不同,请根据实际地域修改
        base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
    )

    response = client.responses.create(
        model="qwen4-max",
        input="简要介绍下你能做什么?"
    )

    print(response)
except Exception as e:
    print(f"错误信息:{e}")
    print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")

Response

Key response fields:

  • id: The response ID.

  • output: List containing reasoning and message objects.

    reasoning only appears when thinking is enabled (enabled by default for Qwen3.6 series).

  • usage: Token usage.

Sample message content. For the full response, see the curl section.

你好!我是人工智能助手,基于截至 2026 年的知识库训练。以下是我能为你做的主要事情:

1.  **文字创作**:撰写文章、邮件、报告、故事、诗歌等。
2.  **代码辅助**:编写、调试、解释代码,支持多种主流编程语言。
3.  **知识问答**:回答科学、历史、文化、技术等领域的问题。
4.  **逻辑分析**:协助数学解题、数据分析、方案规划与决策支持。
5.  **语言翻译**:支持多种语言之间的准确互译。
6.  **日常对话**:聊天解闷、提供生活建议、角色扮演或学习辅导。

有什么具体任务需要我帮忙吗?随时告诉我!

Node.js

// 需要 Node.js v18+,需在 ES Module 环境下运行
import OpenAI from "openai";

const openai = new OpenAI({
    // 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
    // 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:apiKey: "sk-xxx",
    apiKey: process.env.DASHSCOPE_API_KEY,
    // 各地域配置不同,请根据实际地域修改
    baseURL: "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
});

async function main() {
    try {
        const response = await openai.responses.create({
            model: "qwen4-max",
            input: "简要介绍下你能做什么?"
        });

        // 获取模型回复
        console.log(response);
    } catch (error) {
        console.error("错误信息:", error);
    }
}

main();

Response

Key response fields:

  • id: The response ID.

  • output: List containing reasoning and message objects.

    reasoning only appears when thinking is enabled (enabled by default for Qwen3.6 series).

  • usage: Token usage.

Sample message content. For the full response, see the curl section.

你好!我是人工智能助手,基于截至 2026 年的知识库训练。以下是我能为你做的主要事情:

1.  **文字创作**:撰写文章、邮件、报告、故事、诗歌等。
2.  **代码辅助**:编写、调试、解释代码,支持多种主流编程语言。
3.  **知识问答**:回答科学、历史、文化、技术等领域的问题。
4.  **逻辑分析**:协助数学解题、数据分析、方案规划与决策支持。
5.  **语言翻译**:支持多种语言之间的准确互译。
6.  **日常对话**:聊天解闷、提供生活建议、角色扮演或学习辅导。

有什么具体任务需要我帮忙吗?随时告诉我!

curl

# 各地域配置不同,请根据实际地域修改
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen4-max",
    "input": "简要介绍下你能做什么?"
}'

Response

The following response example uses qwen3.8-max to illustrate the response fields.

{
    "created_at": 1772249644,
    "id": "56ec1cc7-f246-448e-bdf9-b13838bc6xxx",
    "model": "qwen3.8-max",
    "object": "response",
    "output": [
        {
            "id": "msg_082d9e97-2317-4a74-9c07-fc46e4845xxx",
            "summary": [
                {
                    "text": "Thinking Process:\n\n1.  **Analyze the Request:**\n    *   User asks: \"简要介绍下你能做什么?\" (Briefly introduce what you can do?)\n\n...(篇幅原因,此处省略完整思考过程)",
                    "type": "summary_text"
                }
            ],
            "type": "reasoning"
        },
        {
            "content": [
                {
                    "annotations": [],
                    "text": "你好!我是人工智能助手。基于截至 2026 年的知识库,我可以为你提供以下帮助:\n\n1.  **内容创作**:撰写文章、邮件、故事、诗歌及各类文案。\n2.  **代码辅助**:编写、调试、解释代码,支持多种主流编程语言。\n3.  **知识问答**:回答科学、历史、文化等各类知识性问题。\n4.  **文本处理**:翻译、总结长文、提取关键信息、润色修改。\n5.  **逻辑与分析**:协助分析问题、提供建议、进行逻辑推理。\n\n请注意,我无法执行物理操作,且若无特定工具支持,无法访问实时互联网信息。有什么具体任务需要我协助吗?",
                    "type": "output_text"
                }
            ],
            "id": "msg_28643acb-1153-4d4f-84f8-19df29f11xxx",
            "role": "assistant",
            "status": "completed",
            "type": "message"
        }
    ],
    "parallel_tool_calls": false,
    "status": "completed",
    "tool_choice": "auto",
    "tools": [],
    "usage": {
        "input_tokens": 52,
        "input_tokens_details": {
            "cached_tokens": 0
        },
        "output_tokens": 1280,
        "output_tokens_details": {
            "reasoning_tokens": 1122
        },
        "total_tokens": 1332,
        "x_details": [
            {
                "input_tokens": 52,
                "output_tokens": 1280,
                "output_tokens_details": {
                    "reasoning_tokens": 1122
                },
                "total_tokens": 1332,
                "x_billing_type": "response_api"
            }
        ]
    }
}

DashScope API

ImportantIn the DashScope API, the model's input modalities determine which API to use: models that accept only text use the text API, while models that accept images or videos use the multimodal API, even when you pass only text. Check the input modalities on each model page in the text generation model list. Using the wrong API returns a url error. To pass images or videos, see Image and Video Understanding.

Text API

Python

import os
import dashscope
from dashscope import DashScopeError

# 以下为华北2(北京)地域的配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的region取值不同。
client = dashscope.Client(
    # 各地域的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"),
    workspace="{WorkspaceId}",
    region="cn-beijing",
)
messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "你是谁?"},
]
try:
    response = client.chat.completions.create(
        # qwen3.7-max、qwen3.7-max-2026-05-20仅支持文本接口,qwen4-max、qwen3.7-max-2026-06-08、Qwen3.6、Qwen3.5系列需要使用多模态接口,直接替换模型会导致报错
        model="qwen-plus",
        messages=messages,
    )
    print(response.choices[0].message.content)
    # 如需查看完整响应,请取消下列注释
    # print(response.model_dump_json(indent=2))
except DashScopeError as e:
    print(f"HTTP返回码:{e.status_code}")
    print(f"错误码:{e.code}")
    print(f"错误信息:{e.message}")
    print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")

Response

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

Java

import java.util.Arrays;
import java.lang.System;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.protocol.Protocol;
import com.alibaba.dashscope.utils.JsonUtils;

public class Main {
    public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
        // 以下为华北2(北京)地域的URL,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的URL不同。
        Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1");
        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content("You are a helpful assistant.")
                .build();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content("你是谁?")
                .build();
        GenerationParam param = GenerationParam.builder()
                // 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:.apiKey("sk-xxx")
                // 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // qwen3.7-max、qwen3.7-max-2026-05-20仅支持文本接口,qwen4-max、qwen3.7-max-2026-06-08支持多模态接口,Qwen3.6、Qwen3.5系列需要使用多模态接口,直接替换模型会导致报错
                .model("qwen-plus")
                .messages(Arrays.asList(systemMsg, userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();
        return gen.call(param);
    }
    public static void main(String[] args) {
        try {
            GenerationResult result = callWithMessage();
            System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
            // 如需查看完整响应,请取消下列注释
            // System.out.println(JsonUtils.toJson(result));
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.err.println("错误信息:"+e.getMessage());
            System.out.println("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
        }
    }
}

Response

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

Node.js(HTTP)

// 需要 Node.js v18+
// 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
// 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:const apiKey = "sk-xxx";
const apiKey = process.env.DASHSCOPE_API_KEY;

const data = {
    // qwen3.7-max、qwen3.7-max-2026-05-20仅支持文本接口,qwen4-max、qwen3.7-max-2026-06-08支持多模态接口,Qwen3.6、Qwen3.5系列需要使用多模态接口,直接替换模型会导致报错
    model: "qwen-plus",
    input: {
        messages: [
            {
                role: "system",
                content: "You are a helpful assistant."
            },
            {
                role: "user",
                content: "你是谁?"
            }
        ]
    },
    parameters: {
        result_format: "message"
    }
};

async function callApi() {
    try {
        // 各地域配置不同,请根据实际地域修改
        const response = await fetch('https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });

        const result = await response.json();
        console.log(result.output.choices[0].message.content);
        // 如需查看完整响应,请取消下列注释
        // console.log(JSON.stringify(result));
    } catch (error) {
        // 更多错误信息,请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code
        console.error('调用失败:', error.message);
    }
}

callApi();

Response

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

Go(HTTP)

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
)

func main() {
	requestBody := map[string]interface{}{
		// qwen3.7-max、qwen3.7-max-2026-05-20仅支持文本接口,qwen4-max、qwen3.7-max-2026-06-08支持多模态接口,Qwen3.6、Qwen3.5系列需要使用多模态接口,直接替换模型会导致报错
		"model": "qwen-plus",
		"input": map[string]interface{}{
			"messages": []map[string]string{
				{
					"role":    "system",
					"content": "You are a helpful assistant.",
				},
				{
					"role":    "user",
					"content": "你是谁?",
				},
			},
		},
		"parameters": map[string]string{
			"result_format": "message",
		},
	}

	// 序列化为 JSON
	jsonData, _ := json.Marshal(requestBody)

	// 创建 HTTP 客户端和请求
	client := &http.Client{}
	// 各地域配置不同,请根据实际地域修改
	req, _ := http.NewRequest("POST", "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation", bytes.NewBuffer(jsonData))

	// 设置请求头
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	// 读取响应体
	bodyText, _ := io.ReadAll(resp.Body)

	// 解析JSON并输出content内容
	var result map[string]interface{}
	json.Unmarshal(bodyText, &result)
	content := result["output"].(map[string]interface{})["choices"].([]interface{})[0].(map[string]interface{})["message"].(map[string]interface{})["content"].(string)
	fmt.Println(content)

	// 如需查看完整响应,请取消下列注释
	// fmt.Printf("%s\n", bodyText)
}

Response

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

C#(HTTP)

using System.Net.Http.Headers;
using System.Text;

class Program
{
    private static readonly HttpClient httpClient = new HttpClient();

    static async Task Main(string[] args)
    {
        // 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
        // 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:string? apiKey = "sk-xxx";
        string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
        // 设置请求 URL 和内容
        // 各地域配置不同,请根据实际地域修改
        string url = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
        // qwen3.7-max、qwen3.7-max-2026-05-20仅支持文本接口,qwen4-max、qwen3.7-max-2026-06-08支持多模态接口,Qwen3.6、Qwen3.5系列需要使用多模态接口,直接替换模型会导致报错
        string jsonContent = @"{
            ""model"": ""qwen-plus"",
            ""input"": {
                ""messages"": [
                    {
                        ""role"": ""system"",
                        ""content"": ""You are a helpful assistant.""
                    },
                    {
                        ""role"": ""user"",
                        ""content"": ""你是谁?""
                    }
                ]
            },
            ""parameters"": {
                ""result_format"": ""message""
            }
        }";

        // 发送请求并获取响应
        string result = await SendPostRequestAsync(url, jsonContent, apiKey);
        var jsonResult = System.Text.Json.JsonDocument.Parse(result);
        var content = jsonResult.RootElement.GetProperty("output").GetProperty("choices")[0].GetProperty("message").GetProperty("content").GetString();
        Console.WriteLine(content);
        // 如需查看完整响应,请取消下列注释
        // Console.WriteLine(result);
    }

    private static async Task<string> SendPostRequestAsync(string url, string jsonContent, string apiKey)
    {
        using (var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
        {
            // 设置请求头
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // 发送请求并获取响应
            HttpResponseMessage response = await httpClient.PostAsync(url, content);

            // 处理响应
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStringAsync();
            }
            else
            {
                return $"请求失败: {response.StatusCode}";
            }
        }
    }
}

Response

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": "我是千问,阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我可以帮助你回答问题、创作文字,比如写故事、写公文、写邮件、写剧本、逻辑推理、编程等等,还能表达观点,玩游戏等。如果你有任何问题或需要帮助,欢迎随时告诉我!"
                }
            }
        ]
    },
    "usage": {
        "total_tokens": 92,
        "output_tokens": 66,
        "input_tokens": 26
    },
    "request_id": "09dceb20-ae2e-999b-85f9-xxxxxx"
}

PHP(HTTP)

<?php
// 各地域配置不同,请根据实际地域修改
$url = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
// 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
// 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:$apiKey = "sk-xxx";
$apiKey = getenv('DASHSCOPE_API_KEY');

$data = [
    // qwen3.7-max、qwen3.7-max-2026-05-20仅支持文本接口,qwen4-max、qwen3.7-max-2026-06-08支持多模态接口,Qwen3.6、Qwen3.5系列需要使用多模态接口,直接替换模型会导致报错
    "model" => "qwen-plus",
    "input" => [
        "messages" => [
            [
                "role" => "system",
                "content" => "You are a helpful assistant."
            ],
            [
                "role" => "user",
                "content" => "你是谁?"
            ]
        ]
    ],
    "parameters" => [
        "result_format" => "message"
    ]
];

$jsonData = json_encode($data);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer $apiKey",
    "Content-Type: application/json"
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($httpCode == 200) {
    $jsonResult = json_decode($response, true);
    $content = $jsonResult['output']['choices'][0]['message']['content'];
    echo $content;
    // 如需查看完整响应,请取消下列注释
    // echo "模型响应: " . $response;
} else {
    echo "请求错误: " . $httpCode . " - " . $response;
}

curl_close($ch);
?>

Response

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

curl

The base URL and API key vary by region. For details, see DashScope and Obtain an API key.

# 各地域配置不同,请根据实际地域修改
curl --location "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
    "model": "qwen-plus",
    "input":{
        "messages":[
            {
                "role": "system",
                "content": "You are a helpful assistant."
            },
            {
                "role": "user",
                "content": "你是谁?"
            }
        ]
    },
    "parameters": {
        "result_format": "message"
    }
}'

Response

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": "我是千问,阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我可以帮助你回答问题、创作文字,比如写故事、写公文、写邮件、写剧本、逻辑推理、编程等等,还能表达观点,玩游戏等。如果你有任何问题或需要帮助,欢迎随时告诉我!"
                }
            }
        ]
    },
    "usage": {
        "total_tokens": 92,
        "output_tokens": 66,
        "input_tokens": 26
    },
    "request_id": "09dceb20-ae2e-999b-85f9-xxxxxx"
}

dashscope CLI

Call via the dashscope command line.

export DASHSCOPE_API_KEY="your-api-key"
# 将 {WorkspaceId} 替换为业务空间ID,cn-beijing 替换为对应地域(新加坡: ap-southeast-1, 美东: us-east-1)
export DASHSCOPE_HTTP_BASE_URL="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"
dashscope generation create -m qwen-plus -p "你好"

ImportantThe SDK Expert interactive assistant can accomplish the same development and troubleshooting in natural language. See

DashScope SDK Expert.

For the complete region table, see Base URL overview.

Multimodal API

Python

import os
import dashscope
from dashscope import DashScopeError

# 以下为华北2(北京)地域的配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的region取值不同。
client = dashscope.Client(
    # 各地域的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"),
    workspace="{WorkspaceId}",
    region="cn-beijing",
)
messages = [
    {"role": "system", "content": [{"text": "You are a helpful assistant."}]},
    {"role": "user", "content": [{"text": "你是谁?"}]},
]
try:
    response = client.multimodal.chat.create(
        model="qwen4-max",  # 可按需更换为其他多模态模型
        messages=messages,
    )
    print(response.output_text)
    # 如需查看完整响应,请取消下列注释
    # print(response.model_dump_json(indent=2))
except DashScopeError as e:
    print(f"HTTP返回码:{e.status_code}")
    print(f"错误码:{e.code}")
    print(f"错误信息:{e.message}")
    print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")

Response

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

Java

import java.util.Arrays;
import java.util.Collections;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;

public class Main {
    // 以下为华北2(北京)地域的URL,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的URL不同。
    static {Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";}

    public static void main(String[] args) {
        MultiModalConversation conv = new MultiModalConversation();
        MultiModalMessage systemMsg = MultiModalMessage.builder()
                .role(Role.SYSTEM.getValue())
                .content(Arrays.asList(Collections.singletonMap("text", "You are a helpful assistant.")))
                .build();
        MultiModalMessage userMsg = MultiModalMessage.builder()
                .role(Role.USER.getValue())
                .content(Arrays.asList(Collections.singletonMap("text", "你是谁?")))
                .build();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                // 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
                // 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("qwen4-max")  // 可按需更换为其他多模态模型
                .messages(Arrays.asList(systemMsg, userMsg))
                .build();
        try {
            MultiModalConversationResult result = conv.call(param);
            System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}

Response

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

curl

# 以下为华北2(北京)地域的URL,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的URL不同。
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen4-max",
    "input": {
        "messages": [
            {
                "role": "system",
                "content": [{"text": "You are a helpful assistant."}]
            },
            {
                "role": "user",
                "content": [{"text": "你是谁?"}]
            }
        ]
    }
}'

Response

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [{"text": "我是千问,阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我可以帮助你回答问题、创作文字,比如写故事、写公文、写邮件、写剧本、逻辑推理、编程等等,还能表达观点,玩游戏等。如果你有任何问题或需要帮助,欢迎随时告诉我!"}]
                }
            }
        ]
    },
    "usage": {
        "total_tokens": 92,
        "output_tokens": 66,
        "input_tokens": 26
    },
    "request_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
}

Asynchronous calls

Asynchronous calls improve throughput for high-concurrency workloads.

OpenAI-compatible Chat Completions API

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)
import com.openai.client.OpenAIClientAsync;
import com.openai.client.okhttp.OpenAIOkHttpClientAsync;
import com.openai.models.chat.completions.ChatCompletionCreateParams;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;

public class Main {
    public static void main(String[] args) {
        // 创建 OpenAI 客户端,连接 DashScope 的兼容接口
        OpenAIClientAsync client = OpenAIOkHttpClientAsync.builder()
                // 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
                // 若没有配置环境变量,请用阿里云百炼API Key将下行替换为.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // 以下为华北2(北京)地域的URL,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的URL不同。
                .baseUrl("https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1")
                .build();

        // 定义问题列表
        List<String> questions = Arrays.asList("你是谁?", "你会什么?", "天气怎么样?");

        // 创建异步任务列表
        CompletableFuture<?>[] futures = questions.stream()
                .map(question -> CompletableFuture.supplyAsync(() -> {
                    System.out.println("发送问题: " + question);
                    // 创建 ChatCompletion 参数
                    ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
                            .model("qwen-plus")  // 指定模型
                            .addSystemMessage("You are a helpful assistant.")
                            .addUserMessage(question)
                            .build();

                    // 发送异步请求并处理响应
                    return client.chat().completions().create(params)
                        .thenAccept(chatCompletion -> {
                            String content = chatCompletion.choices().get(0).message().content().orElse("无响应内容");
                            System.out.println("模型回复: " + content);
                        })
                        .exceptionally(e -> {
                            System.err.println("错误信息:" + e.getMessage());
                            System.out.println("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
                            return null;
                        });
                }).thenCompose(future -> future))
                .toArray(CompletableFuture[]::new);

        // 等待所有异步操作完成
        CompletableFuture.allOf(futures).join();
    }
}

DashScope

Asynchronous text generation with the DashScope SDK is only supported in Python.

# 需要 dashscope 2.0.1 及以上版本
import asyncio
import platform
import os
import dashscope

# 以下为华北2(北京)地域的配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的region取值不同。
aclient = dashscope.AsyncClient(
    # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="cn-beijing",
)

# 定义异步任务列表
async def task(question):
    print(f"发送问题: {question}")
    response = await aclient.chat.completions.create(
        model="qwen-plus",  # 模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
        messages=[{"role": "system", "content": "You are a helpful assistant."},
                  {"role": "user", "content": question}],
    )
    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.
午后,一只老猫蜷在窗台,数着光斑打盹。
阳光轻轻跃过它斑驳的脊背,像在翻阅一本旧相册。
尘埃浮起又落下,仿佛时光低语:你曾年轻,我也炽热。

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.

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).