All Products
Search
Document Center

Alibaba Cloud Model Studio:Code capabilities (Qwen-Coder)

Last Updated:Sep 28, 2026

Qwen-Coder is a language model designed for code tasks. You can use the API to generate code, complete code, and call tools to interact with external systems.

NoteIt is recommended to use the latest general-purpose model instead of the Qwen-Coder model. See Text Generation to select a model that fits your scenario.

Quick Start

API prerequisites: You have obtained and configured an API Key and configured the API Key as an environment variable. If calling via SDK, you need to install the OpenAI or DashScope SDK.

The following examples will demonstrate how to callqwen3-coder-nextthe Model to write a Python function that finds prime numbers.

OpenAI-compatible Chat Completions API

Python

Request Example
import os
from openai import OpenAI

client = OpenAI(
    # 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
    # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 请将{WorkspaceId}替换为业务空间ID
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
    model="qwen3-coder-next",
    messages=[
        {'role': 'system', 'content': 'You are a helpful assistant.'},
        {'role': 'user', 'content': '请编写一个Python函数 find_prime_numbers,该函数接受一个整数 n 作为参数,并返回一个包含所有小于 n 的质数(素数)的列表。不要输出非代码的内容和Markdown的代码块。'}],
)
print(completion.choices[0].message.content)
Response
def find_prime_numbers(n):
    if n <= 2:
        return []

    primes = []
    for num in range(2, n):
        is_prime = True
        for i in range(2, int(num ** 0.5) + 1):
            if num % i == 0:
                is_prime = False
                break
        if is_prime:
            primes.append(num)

    return primes

Node.js

Request Example
import OpenAI from "openai";

const client = new OpenAI(
    {
        // 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
        // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey: "sk-xxx",
        apiKey: process.env.DASHSCOPE_API_KEY,
        // 以下为新加坡地域URL,调用时请将WorkspaceId替换为真实的业务空间ID,各地域的URL不同。
        baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
    }
);

async function main() {
    const completion = await client.chat.completions.create({
        model: "qwen3-coder-next",
        messages: [
            { role: "system", content: "You are a helpful assistant." },
            { role: "user", content: "请编写一个Python函数 find_prime_numbers,该函数接受一个整数 n 作为参数,并返回一个包含所有小于 n 的质数(素数)的列表。不要输出非代码的内容和Markdown的代码块。" }
        ],
    });
    console.log(completion.choices[0].message.content);
}

main();
Response
def find_prime_numbers(n):
    if n <= 2:
        return []

    primes = []
    for num in range(2, n):
        is_prime = True
        for i in range(2, int(num ** 0.5) + 1):
            if num % i == 0:
                is_prime = False
                break
        if is_prime:
            primes.append(num)

    return primes

curl

Request Example

The URL differs by region.

curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen3-coder-next",
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user",
            "content": "请编写一个Python函数 find_prime_numbers,该函数接受一个整数 n 作为参数,并返回一个包含所有小于 n 的质数(素数)的列表。不要输出非代码的内容和Markdown的代码块。"
        }
    ]
}'
Response
{
    "model": "qwen3-coder-next",
    "id": "chatcmpl-3123d5cb-01b8-9a90-98cc-5bffbb369xxx",
    "choices": [
        {
            "message": {
                "content": "def find_prime_numbers(n):\n    if n <= 2:\n        return []\n    \n    primes = []\n    for num in range(2, n):\n        is_prime = True\n        for i in range(2, int(num ** 0.5) + 1):\n            if num % i == 0:\n                is_prime = False\n                break\n        if is_prime:\n            primes.append(num)\n    \n    return primes",
                "role": "assistant"
            },
            "index": 0,
            "finish_reason": "stop"
        }
    ],
    "created": 1770108104,
    "object": "chat.completion",
    "usage": {
        "total_tokens": 155,
        "completion_tokens": 89,
        "prompt_tokens": 66
    }
}

DashScope

Python

Request Example
import dashscope
import os

# 请将{WorkspaceId}替换为业务空间ID
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'

messages = [
    {
        "role": "system",
        "content": "You are a helpful assistant."
    },
    {
        "role": "user",
        "content": "请编写一个Python函数 find_prime_numbers,该函数接受一个整数 n 作为参数,并返回一个包含所有小于 n 的质数(素数)的列表。不要输出非代码的内容和Markdown的代码块。"
    }
]

response = dashscope.Generation.call(
    # 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
    # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key = "sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="qwen3-coder-next",
    messages=messages,
    result_format="message"
)

if response.status_code == 200:
    print(response.output.choices[0].message.content)
else:
    print(f"HTTP返回码:{response.status_code}")
    print(f"错误码:{response.code}")
    print(f"错误信息:{response.message}")
Response
def find_prime_numbers(n):
    if n <= 2:
        return []

    primes = []
    for num in range(2, n):
        is_prime = True
        for i in range(2, int(num ** 0.5) + 1):
            if num % i == 0:
                is_prime = False
                break
        if is_prime:
            primes.append(num)

    return primes

Java

Request Examples
import java.util.Arrays;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
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;

public class Main {
    public static GenerationResult callWithMessage()
            throws NoApiKeyException, ApiException, InputRequiredException {
        String apiKey = System.getenv("DASHSCOPE_API_KEY");
        // 请将{WorkspaceId}替换为业务空间ID
        Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
        Message sysMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content("You are a helpful assistant.").build();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content("请编写一个Python函数 find_prime_numbers,该函数接受一个整数 n 作为参数,并返回一个包含所有小于 n 的质数(素数)的列表。不要输出非代码的内容和Markdown的代码块。").build();
        GenerationParam param = GenerationParam.builder()
                .apiKey(apiKey)
                .model("qwen3-coder-next")
                .messages(Arrays.asList(sysMsg, 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());
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.err.println("请求异常: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
Response
def find_prime_numbers(n):
    if n <= 2:
        return []

    primes = []
    for num in range(2, n):
        is_prime = True
        for i in range(2, int(num ** 0.5) + 1):
            if num % i == 0:
                is_prime = False
                break
        if is_prime:
            primes.append(num)

    return primes

curl

Request Examples

The URL varies by region.

curl -X POST "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen3-coder-next",
    "input":{
        "messages":[
            {
                "role": "system",
                "content": "You are a helpful assistant."
            },
            {
                "role": "user",
                "content": "请编写一个Python函数 find_prime_numbers,该函数接受一个整数 n 作为参数,并返回一个包含所有小于 n 的质数(素数)的列表。不要输出非代码的内容和Markdown的代码块。"
            }
        ]
    },
    "parameters": {
        "result_format": "message"
    }
}'
Response
{
    "output": {
        "choices": [
            {
                "message": {
                    "content": "def find_prime_numbers(n):\n    if n <= 2:\n        return []\n    \n    primes = []\n    for num in range(2, n):\n        is_prime = True\n        for i in range(2, int(num ** 0.5) + 1):\n            if num % i == 0:\n                is_prime = False\n                break\n        if is_prime:\n            primes.append(num)\n    \n    return primes",
                    "role": "assistant"
                },
                "finish_reason": "stop"
            }
        ]
    },
    "usage": {
        "total_tokens": 155,
        "input_tokens": 66,
        "output_tokens": 89
    },
    "request_id": "dd78b1cf-8029-46bb-9bea-b794ded7bxxx"
}

Core Capabilities

Built-in Tools

To enable the model to interact with the external environment (for example, reading and writing files, calling APIs, and operating databases), you can provide it with a series of tools. The model will decide whether and how to call these tools based on your instructions. For details, seeFunction Calling。

The complete tool calling process includes:

  1. Define tools and send a request:Define the tool list in the request, and present to the model the task that needs to be completed using tools.
  2. Execute tool:Parse the model's returned tool_calls, and call the corresponding tool function you have implemented locally to execute the task.
  3. Return execution result:Wrap the tool's execution result into a specific format and send it back to the model, letting it complete the final task based on the result.

The following example demonstrates how to guide the model to generate code, and use write_file tool to save it to a local file.

OpenAI-compatible Chat Completions API

Python

import os
import json
from openai import OpenAI

client = OpenAI(
    # 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
    # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 请将{WorkspaceId}替换为业务空间ID
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

tools = [
    {
        "type": "function",
        "function": {
            "name": "write_file",
            "description": "将内容写入指定文件,若文件不存在则创建。",
            "parameters": {
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "目标文件的相对或绝对路径"
                    },
                    "content": {
                        "type": "string",
                        "description": "写入文件的字符串内容"
                    }
                },
                "required": ["path", "content"]
            }
        }
    }
]

# 工具函数实现
def write_file(path: str, content: str) -> str:
    """写入文件内容"""
    try:
        # 确保目录存在
        os.makedirs(os.path.dirname(path),
                    exist_ok=True) if os.path.dirname(path) else None
        with open(path, 'w', encoding='utf-8') as f:
            f.write(content)
        return f"成功: 文件 '{path}' 已写入"
    except Exception as e:
        return f"错误: 写入文件时发生异常 - {str(e)}"

messages = [{"role": "user", "content": "写一个python代码,快速排序,命名为quick_sort.py"}]

completion = client.chat.completions.create(
    model="qwen3-coder-next",
    messages=messages,
    tools=tools
)

assistant_output = completion.choices[0].message
if assistant_output.content is None:
    assistant_output.content = ""
messages.append(assistant_output)

# 如果不需要调用工具,直接输出内容
if assistant_output.tool_calls is None:
    print(f"无需调用工具,直接回复:{assistant_output.content}")
else:
    # 进入工具调用循环(限制最大迭代次数,避免无限循环导致成本或超时问题)
    max_rounds = 10
    current_round = 0
    while assistant_output.tool_calls is not None and current_round < max_rounds:
        current_round += 1
        for tool_call in assistant_output.tool_calls:
            tool_call_id = tool_call.id
            func_name = tool_call.function.name
            arguments = json.loads(tool_call.function.arguments)
            print(f"正在调用工具 [{func_name}],参数:{arguments}")
            # 执行工具
            tool_result = write_file(**arguments)
            # 构造工具返回信息
            tool_message = {
                "role": "tool",
                "tool_call_id": tool_call_id,
                "content": tool_result,
            }
            print(f"工具返回:{tool_message['content']}")
            messages.append(tool_message)
        # 再次调用模型,获取总结后的自然语言回复
        response = client.chat.completions.create(
            model="qwen3-coder-next",
            messages=messages,
            tools=tools
        )
        assistant_output = response.choices[0].message
        if assistant_output.content is None:
            assistant_output.content = ""
        messages.append(assistant_output)
    print(f"模型最终回复:{assistant_output.content}")
Response
正在调用工具 [write_file],参数:{'content': 'def quick_sort(arr):\\n    if len(arr) <= 1:\\n        return arr\\n    pivot = arr[len(arr) // 2]\\n    left = [x for x in arr if x < pivot]\\n    middle = [x for x in arr if x == pivot]\\n    right = [x for x in arr if x > pivot]\\n    return quick_sort(left) + middle + quick_sort(right)\\n\\nif __name__ == \\"__main__\\":\\n    example_list = [3, 6, 8, 10, 1, 2, 1]\\n    print(\\"Original list:\\", example_list)\\n    sorted_list = quick_sort(example_list)\\n    print(\\"Sorted list:\\", sorted_list)', 'path': 'quick_sort.py'}
工具返回:成功: 文件 'quick_sort.py' 已写入
模型最终回复:好的,已经为你创建了名为 `quick_sort.py` 的文件,其中包含了快速排序的 Python 实现。你可以运行这个文件查看示例输出。如果需要进一步修改或解释,请告诉我!

Node.js

import OpenAI from "openai";
import fs from "fs/promises";
import path from "path";

const client = new OpenAI({
    // 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
    // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey: "sk-xxx",
    apiKey: process.env.DASHSCOPE_API_KEY,
    // 请将{WorkspaceId}替换为业务空间ID
    baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
});

const tools = [
    {
        "type": "function",
        "function": {
            "name": "write_file",
            "description": "将内容写入指定文件,若文件不存在则创建。",
            "parameters": {
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "目标文件的相对或绝对路径"
                    },
                    "content": {
                        "type": "string",
                        "description": "写入文件的字符串内容"
                    }
                },
                "required": ["path", "content"]
            }
        }
    }
];

// 工具函数实现
async function write_file(filePath, content) {
    try {
        // 为安全起见,文件写入功能已默认禁用,如需使用请取消注释并确保路径安全
        // const dir = path.dirname(filePath);
        // if (dir) {
        //     await fs.mkdir(dir, { recursive: true });
        // }
        // await fs.writeFile(filePath, content, "utf-8");
        return `成功: 文件 '${filePath}' 已写入`;
    } catch (error) {
        return `错误: 写入文件时发生异常 - ${error.message}`;
    }
}

const messages = [{"role": "user", "content": "写一个python代码,快速排序,命名为quick_sort.py"}];

async function main() {
    const completion = await client.chat.completions.create({
        model: "qwen3-coder-next",
        messages: messages,
        tools: tools
    });

    let assistant_output = completion.choices[0].message;
    // 确保 content 不是 null
    if (!assistant_output.content) assistant_output.content = "";
    messages.push(assistant_output);

    // 如果不需要调用工具,直接输出内容
    if (!assistant_output.tool_calls) {
        console.log(`无需调用工具,直接回复:${assistant_output.content}`);
    } else {
        // 进入工具调用循环(限制最大迭代次数,避免无限循环导致成本或超时问题)
        const maxRounds = 10;
        let currentRound = 0;
        while (assistant_output.tool_calls && currentRound < maxRounds) {
            currentRound++;
            for (const tool_call of assistant_output.tool_calls) {
                const tool_call_id = tool_call.id;
                const func_name = tool_call.function.name;
                const args = JSON.parse(tool_call.function.arguments);
                console.log(`正在调用工具 [${func_name}],参数:`, args);
                // 执行工具
                const tool_result = await write_file(args.path, args.content);
                // 构造工具返回信息
                const tool_message = {
                    "role": "tool",
                    "tool_call_id": tool_call_id,
                    "content": tool_result
                };
                console.log(`工具返回:${tool_message.content}`);
                messages.push(tool_message);
            }
            // 再次调用模型,获取总结后的自然语言回复
            const response = await client.chat.completions.create({
                model: "qwen3-coder-next",
                messages: messages,
                tools: tools
            });
            assistant_output = response.choices[0].message;
            if (!assistant_output.content) assistant_output.content = "";
            messages.push(assistant_output);
        }
        console.log(`模型最终回复:${assistant_output.content}`);
    }
}

main();
Response
正在调用工具 [write_file],参数: {
  content: 'def quick_sort(arr):\\n    if len(arr) <= 1:\\n        return arr\\n    pivot = arr[len(arr) // 2]\\n    left = [x for x in arr if x < pivot]\\n    middle = [x for x in arr if x == pivot]\\n    right = [x for x in arr if x > pivot]\\n    return quick_sort(left) + middle + quick_sort(right)\\n\\nif __name__ == \\"__main__\\":\\n    example_list = [3, 6, 8, 10, 1, 2, 1]\\n    print(\\"Original list:\\", example_list)\\n    sorted_list = quick_sort(example_list)\\n    print(\\"Sorted list:\\", sorted_list)',
  path: 'quick_sort.py'
}
工具返回:成功: 文件 'quick_sort.py' 已写入
模型最终回复:已成功创建 `quick_sort.py` 文件,其中包含快速排序的 Python 实现。你可以运行该文件以查看示例列表的排序结果。如果需要进一步修改或解释,请告诉我!

curl

This example demonstrates the first step of the tool calling process: sending a request and obtaining the model's tool calling intent.

The URLs vary by region.

curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen3-coder-next",
    "messages": [
        {
            "role": "user",
            "content": "写一个python代码,快速排序,命名为quick_sort.py"
        }
    ],
    "tools": [
        {
            "type": "function",
            "function": {
                "name": "write_file",
                "description": "将内容写入指定文件,若文件不存在则创建。",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "path": {
                            "type": "string",
                            "description": "目标文件的相对或绝对路径"
                        },
                        "content": {
                            "type": "string",
                            "description": "写入文件的字符串内容"
                        }
                    },
                    "required": ["path", "content"]
                }
            }
        }
    ]
}'
Response
{
    "choices": [
        {
            "message": {
                "content": "",
                "role": "assistant",
                "tool_calls": [
                    {
                        "index": 0,
                        "id": "call_0ca7505bb6e44471a40511e5",
                        "type": "function",
                        "function": {
                            "name": "write_file",
                            "arguments": "{\"content\": \"def quick_sort(arr):\\\\n    if len(arr) <= 1:\\\\n        return arr\\\\n    pivot = arr[len(arr) // 2]\\\\n    left = [x for x in arr if x < pivot]\\\\n    middle = [x for x in arr if x == pivot]\\\\n    right = [x for x in arr if x > pivot]\\\\n    return quick_sort(left) + middle + quick_sort(right)\\\\n\\\\nif __name__ == \\\\\\\"__main__\\\\\\\":\\\\n    example_list = [3, 6, 8, 10, 1, 2, 1]\\\\n    print(\\\\\\\"Original list:\\\\\\\", example_list)\\\\n    sorted_list = quick_sort(example_list)\\\\n    print(\\\\\\\"Sorted list:\\\\\\\", sorted_list)\", \"path\": \"quick_sort.py\"}"
                        }
                    }
                ]
            },
            "finish_reason": "tool_calls",
            "index": 0,
            "logprobs": null
        }
    ],
    "object": "chat.completion",
    "usage": {
        "prompt_tokens": 494,
        "completion_tokens": 193,
        "total_tokens": 687,
        "prompt_tokens_details": {
            "cached_tokens": 0
        }
    },
    "created": 1761620025,
    "system_fingerprint": null,
    "model": "qwen3-coder-next",
    "id": "chatcmpl-20e96159-beea-451f-b3a4-d13b218112b5"
}

DashScope

Python

import os
import json
import dashscope

# 请将{WorkspaceId}替换为业务空间ID
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'

tools = [
    {
        "type": "function",
        "function": {
            "name": "write_file",
            "description": "将内容写入指定文件,若文件不存在则创建。",
            "parameters": {
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "目标文件的相对或绝对路径"
                    },
                    "content": {
                        "type": "string",
                        "description": "写入文件的字符串内容"
                    }
                },
                "required": ["path", "content"]
            }
        }
    }
]

# 工具函数实现
def write_file(path: str, content: str) -> str:
    """写入文件内容"""
    try:
        # 为安全起见,文件写入功能已默认禁用,如需使用请取消注释并确保路径安全
        # os.makedirs(os.path.dirname(path),exist_ok=True) if os.path.dirname(path) else None
        # with open(path, 'w', encoding='utf-8') as f:
        #     f.write(content)
        return f"成功: 文件 '{path}' 已写入"
    except Exception as e:
        return f"错误: 写入文件时发生异常 - {str(e)}"

messages = [{"role": "user", "content": "写一个python代码,快速排序,命名为quick_sort.py"}]

response = dashscope.Generation.call(
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model='qwen3-coder-next',
    messages=messages,
    tools=tools,
    result_format='message'
)

if response.status_code == 200:
    assistant_output = response.output.choices[0].message
    messages.append(assistant_output)

    # 如果不需要调用工具,直接输出内容
    if "tool_calls" not in assistant_output or not assistant_output["tool_calls"]:
        print(f"无需调用工具,直接回复:{assistant_output['content']}")
    else:
        # 进入工具调用循环(限制最大迭代次数,避免无限循环导致成本或超时问题)
        max_rounds = 10
        current_round = 0
        while "tool_calls" in assistant_output and assistant_output["tool_calls"] and current_round < max_rounds:
            current_round += 1
            for tool_call in assistant_output["tool_calls"]:
                func_name = tool_call["function"]["name"]
                arguments = json.loads(tool_call["function"]["arguments"])
                tool_call_id = tool_call.get("id")
                print(f"正在调用工具 [{func_name}],参数:{arguments}")
                # 执行工具
                tool_result = write_file(**arguments)
                # 构造工具返回信息
                tool_message = {
                    "role": "tool",
                    "content": tool_result,
                    "tool_call_id": tool_call_id
                }
                print(f"工具返回:{tool_message['content']}")
                messages.append(tool_message)
            # 再次调用模型,获取总结后的自然语言回复
            response = dashscope.Generation.call(
                api_key=os.getenv('DASHSCOPE_API_KEY'),
                model='qwen3-coder-next',
                messages=messages,
                tools=tools,
                result_format='message'
            )
            if response.status_code == 200:
                print(f"模型最终回复:{response.output.choices[0].message.content}")
                assistant_output = response.output.choices[0].message
                messages.append(assistant_output)
            else:
                print(f"总结回复时执行错误:{response}")
                break
else:
    print(f"执行错误:{response}")
Response
正在调用工具 [write_file],参数:{'content': 'def quick_sort(arr):\\n    if len(arr) <= 1:\\n        return arr\\n    pivot = arr[len(arr) // 2]\\n    left = [x for x in arr if x < pivot]\\n    middle = [x for x in arr if x == pivot]\\n    right = [x for x in arr if x > pivot]\\n    return quick_sort(left) + middle + quick_sort(right)\\n\\nif __name__ == \\"__main__\\":\\n    example_list = [3, 6, 8, 10, 1, 2, 1]\\n    print(\\"Original list:\\", example_list)\\n    sorted_list = quick_sort(example_list)\\n    print(\\"Sorted list:\\", sorted_list)', 'path': 'quick_sort.py'}
工具返回:成功: 文件 'quick_sort.py' 已写入
模型最终回复:已成功创建 `quick_sort.py` 文件,其中包含快速排序的 Python 实现。你可以运行该文件以查看示例列表的排序结果。如果需要进一步修改或解释,请告诉我!

Java

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.protocol.Protocol;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.tools.FunctionDefinition;
import com.alibaba.dashscope.tools.ToolCallBase;
import com.alibaba.dashscope.tools.ToolCallFunction;
import com.alibaba.dashscope.tools.ToolFunction;
import com.alibaba.dashscope.utils.JsonUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {

    /**
     * 写入文件内容
     * @param arguments 模型传入的、包含工具所需参数的JSON字符串。
     * @return 工具执行后的结果字符串。
     */
    public static String writeFile(String arguments) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode argsNode = objectMapper.readTree(arguments);
            String path = argsNode.get("path").asText();
            String content = argsNode.get("content").asText();

            // 为安全起见,文件写入功能已默认禁用,如需使用请取消注释并确保路径安全
            // File file = new File(path);
            // File parentDir = file.getParentFile();
            // if (parentDir != null && !parentDir.exists()) {
            //     parentDir.mkdirs();
            // }
            // Files.write(Paths.get(path), content.getBytes(StandardCharsets.UTF_8));
            return "成功: 文件 '" + path + "' 已写入";
        } catch (Exception e) {
            return "错误: 写入文件时发生异常 - " + e.getMessage();
        }
    }

    public static void main(String[] args) {
        try {
            // 定义工具参数模式
            String writePropertyParams =
                    "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"目标文件的相对或绝对路径\"},\"content\":{\"type\":\"string\",\"description\":\"写入文件的字符串内容\"}},\"required\":[\"path\",\"content\"]}";

            FunctionDefinition writeFileFunction = FunctionDefinition.builder()
                    .name("write_file")
                    .description("将内容写入指定文件,若文件不存在则创建。")
                    .parameters(JsonUtils.parseString(writePropertyParams).getAsJsonObject())
                    .build();

            // 请将{WorkspaceId}替换为业务空间ID
            Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");

            String userInput = "写一个python代码,快速排序,命名为quick_sort.py";
            List<Message> messages = new ArrayList<>();
            messages.add(Message.builder().role(Role.USER.getValue()).content(userInput).build());

            // 首次调用模型
            GenerationParam param = GenerationParam.builder()
                    .model("qwen3-coder-next")
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .messages(messages)
                    .tools(Arrays.asList(ToolFunction.builder().function(writeFileFunction).build()))
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                    .build();

            GenerationResult result = gen.call(param);
            Message assistantOutput = result.getOutput().getChoices().get(0).getMessage();
            messages.add(assistantOutput);

            // 如果不需要调用工具,直接输出内容
            if (assistantOutput.getToolCalls() == null || assistantOutput.getToolCalls().isEmpty()) {
                System.out.println("无需调用工具,直接回复:" + assistantOutput.getContent());
            } else {
                // 进入工具调用循环
                while (assistantOutput.getToolCalls() != null && !assistantOutput.getToolCalls().isEmpty()) {
                    for (ToolCallBase toolCall : assistantOutput.getToolCalls()) {
                        ToolCallFunction functionCall = (ToolCallFunction) toolCall;
                        String funcName = functionCall.getFunction().getName();
                        String arguments = functionCall.getFunction().getArguments();
                        System.out.println("正在调用工具 [" + funcName + "],参数:" + arguments);

                        // 执行工具
                        String toolResult = writeFile(arguments);

                        // 构造工具返回信息
                        Message toolMessage = Message.builder()
                                .role("tool")
                                .toolCallId(toolCall.getId())
                                .content(toolResult)
                                .build();
                        System.out.println("工具返回:" + toolMessage.getContent());
                        messages.add(toolMessage);
                    }

                    // 再次调用模型,获取总结后的自然语言回复
                    param.setMessages(messages);
                    result = gen.call(param);
                    assistantOutput = result.getOutput().getChoices().get(0).getMessage();
                    messages.add(assistantOutput);
                }
                System.out.println("模型最终回复:" + assistantOutput.getContent());
            }

        } catch (NoApiKeyException | InputRequiredException e) {
            System.err.println("错误: " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Response
正在调用工具 [write_file],参数:{"content": "def quick_sort(arr):\\n    if len(arr) <= 1:\\n        return arr\\n    pivot = arr[len(arr) // 2]\\n    left = [x for x in arr if x < pivot]\\n    middle = [x for x in arr if x == pivot]\\n    right = [x for x in arr if x > pivot]\\n    return quick_sort(left) + middle + quick_sort(right)\\n\\nif __name__ == \\\"__main__\\\":\\n    example_array = [3, 6, 8, 10, 1, 2, 1]\\n    print(\\\"Original array:\\\", example_array)\\n    sorted_array = quick_sort(example_array)\\n    print(\\\"Sorted array:\\\", sorted_array)", "path": "quick_sort.py"}
工具返回:成功: 文件 'quick_sort.py' 已写入
模型最终回复:已成功为您创建了快速排序的Python代码文件 `quick_sort.py`。该文件包含一个 `quick_sort` 函数和一个示例用法,您可以在终端或编辑器中运行它来测试快速排序功能。

curl

This example demonstrates the first step of the tool calling process: sending a request and obtaining the model's tool calling intent.

The URLs vary by region.

curl --location "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
    "model": "qwen3-coder-next",
    "input": {
        "messages": [{
            "role": "user",
            "content": "写一个python代码,快速排序,命名为quick_sort.py"
        }]
    },
    "parameters": {
        "result_format": "message",
        "tools": [
        {
            "type": "function",
            "function": {
                "name": "write_file",
                "description": "将内容写入指定文件,若文件不存在则创建。",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "path": {
                            "type": "string",
                            "description": "目标文件的相对或绝对路径"
                        },
                        "content": {
                            "type": "string",
                            "description": "写入文件的字符串内容"
                        }
                    },
                    "required": ["path", "content"]
                }
            }
        }
    ]
    }
}'
Response
{
    "output": {
        "choices": [
            {
                "finish_reason": "tool_calls",
                "message": {
                    "role": "assistant",
                    "tool_calls": [
                        {
                            "function": {
                                "name": "write_file",
                                "arguments": "{\"content\": \"def quick_sort(arr):\\\\n    if len(arr) <= 1:\\\\n        return arr\\\\n    pivot = arr[len(arr) // 2]\\\\n    left = [x for x in arr if x < pivot]\\\\n    middle = [x for x in arr if x == pivot]\\\\n    right = [x for x in arr if x > pivot]\\\\n    return quick_sort(left) + middle + quick_sort(right)\\\\n\\\\nif __name__ == \\\\\\\"__main__\\\\\\\":\\\\n    example_list = [3, 6, 8, 10, 1, 2, 1]\\\\n    print(\\\\\\\"Original list:\\\\\\\", example_list)\\\\n    sorted_list = quick_sort(example_list)\\\\n    print(\\\\\\\"Sorted list:\\\\\\\", sorted_list)\", \"path\": \"quick_sort.py\"}"
                            },
                            "index": 0,
                            "id": "call_645b149bbd274e8bb3789aae",
                            "type": "function"
                        }
                    ],
                    "content": ""
                }
            }
        ]
    },
    "usage": {
        "total_tokens": 684,
        "output_tokens": 193,
        "input_tokens": 491,
        "prompt_tokens_details": {
            "cached_tokens": 0
        }
    },
    "request_id": "d2386acd-fce3-9d0f-8015-c5f3a8bf9f5c"
}

Code generation

Qwen-Coder supports two Code Completion methods. Please choose based on your needs:

  • Prefix Continuation (Partial Mode): Applicable to all Qwen-Coder Models and regions, supports prefix completion, simple to implement, recommended for use.
  • Completions interface: Only supports North China 2 (Beijing) qwen-coder-turbo Model. Supports prefix completion and prefix-suffix completion.

Prefix Continuation (Partial Mode)

This feature is used to let the Model automatically complete the remaining part based on the code (prefix) you have written halfway.

By adding a message with role set to assistant in the messages list and setting partial: true, you can implement this. The assistant message's content is the code prefix you provide. For details, see Prefix Continuation.

OpenAI-compatible

Python

Request Examples
import os
from openai import OpenAI

client = OpenAI(
    # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 请将{WorkspaceId}替换为业务空间ID
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
    model="qwen3-coder-next",
    messages=[{
        "role": "user",
        "content": "请帮我写一个python代码生成100以内的素数。不要输出非代码的内容和Markdown的代码块。"
    },
    {
        "role": "assistant",
        "content": "def generate_prime_number",
        "partial": True
    }]
    )
print(completion.choices[0].message.content)
Response
(n):
    primes = []
    for i in range(2, n+1):
        is_prime = True
        for j in range(2, int(i**0.5)+1):
            if i % j == 0:
                is_prime = False
                break
        if is_prime:
            primes.append(i)
    return primes

prime_numbers = generate_prime_number(100)
print(prime_numbers)

Node.js

Request Examples
import OpenAI from "openai";

const client = new OpenAI(
    {
        // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey: "sk-xxx",
        apiKey: process.env.DASHSCOPE_API_KEY,
        // 请将{WorkspaceId}替换为业务空间ID
        baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
    }
);

async function main() {
    const completion = await client.chat.completions.create({
        model: "qwen3-coder-next",
        messages: [
            { role: "user", content: "请帮我写一个python代码生成100以内的素数。不要输出非代码的内容和Markdown的代码块。" },
            { role: "assistant", content: "def generate_prime_number", partial: true}
        ],
    });
    console.log(completion.choices[0].message.content);
}

main();
Response
(n):
    primes = []
    for i in range(2, n+1):
        is_prime = True
        for j in range(2, int(i**0.5)+1):
            if i % j == 0:
                is_prime = False
                break
        if is_prime:
            primes.append(i)
    return primes

prime_numbers = generate_prime_number(100)
print(prime_numbers)

curl

Request Examples

URLs vary by region.

curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen3-coder-next",
    "messages": [{
        "role": "user",
        "content": "请帮我写一个python代码生成100以内的素数。不要输出非代码的内容和Markdown的代码块。"
    },
    {
        "role": "assistant",
        "content": "def generate_prime_number",
        "partial": true
    }]
}'
Response
{
    "choices": [
        {
            "message": {
                "content": "(n):\n    primes = []\n    for num in range(2, n + 1):\n        is_prime = True\n        for i in range(2, int(num ** 0.5) + 1):\n            if num % i == 0:\n                is_prime = False\n                break\n        if is_prime:\n            primes.append(num)\n    return primes\n\nprime_numbers = generate_prime_number(100)\nprint(prime_numbers)",
                "role": "assistant"
            },
            "finish_reason": "stop",
            "index": 0,
            "logprobs": null
        }
    ],
    "object": "chat.completion",
    "usage": {
        "prompt_tokens": 38,
        "completion_tokens": 93,
        "total_tokens": 131,
        "prompt_tokens_details": {
            "cached_tokens": 0
        }
    },
    "created": 1761634556,
    "system_fingerprint": null,
    "model": "qwen3-coder-next",
    "id": "chatcmpl-c108050a-bb6d-4423-9d36-f64aa6a32976"
}

DashScope

Python

Request Examples
from http import HTTPStatus
import dashscope
import os

# 请将{WorkspaceId}替换为业务空间ID
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'

messages = [{
    "role": "user",
    "content": "请帮我写一个python代码生成100以内的素数,不要输出非代码的内容和Markdown的代码块。"
},
{
    "role": "assistant",
    "content": "def generate_prime_number",
    "partial": True
}]
response = dashscope.Generation.call(
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model='qwen3-coder-next',
    messages=messages,
    result_format='message',
)
if response.status_code == HTTPStatus.OK:
    print(response.output.choices[0].message.content)
else:
    print(f"HTTP返回码:{response.status_code}")
    print(f"错误码:{response.code}")
    print(f"错误信息:{response.message}")
Response
(n):
    primes = []
    for i in range(2, n+1):
        is_prime = True
        for j in range(2, int(i**0.5)+1):
            if i % j == 0:
                is_prime = False
                break
        if is_prime:
            primes.append(i)
    return primes

prime_numbers = generate_prime_number(100)
print(prime_numbers)

curl

Request Examples

URLs vary by region.

curl -X POST "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen3-coder-next",
    "input":{
        "messages":[{
            "role": "user",
            "content": "请帮我写一个python代码生成100以内的素数,不要输出非代码的内容和Markdown的代码块。"
        },
        {
            "role": "assistant",
            "content": "def generate_prime_number",
            "partial": true
        }]
    },
    "parameters": {
        "result_format": "message"
    }
}'
Response
{
    "output": {
        "choices": [
            {
                "message": {
                    "content": "(n):\n    prime_list = []\n    for i in range(2, n+1):\n        is_prime = True\n        for j in range(2, int(i**0.5)+1):\n            if i % j == 0:\n                is_prime = False\n                break\n        if is_prime:\n            prime_list.append(i)\n    return prime_list\n\nprime_numbers = generate_prime_number(100)\nprint(prime_numbers)",
                    "role": "assistant"
                },
                "finish_reason": "stop"
            }
        ]
    },
    "usage": {
        "total_tokens": 131,
        "output_tokens": 92,
        "input_tokens": 39,
        "prompt_tokens_details": {
            "cached_tokens": 0
        }
    },
    "request_id": "9917f629-e819-4519-af44-b0e677e94b2c"
}

Completions Interface

ImportantThe Completions interface is only applicable to models in the China North 2 (Beijing) region and requires using the China North 2 (Beijing) region API Key.

Supported Models:

qwen-coder-turbo

Completions APIBy prompt using special fim (Fill-in-the-Middle) tags to guide the model to complete.

Prefix-based completion

Prompt Template:
<|fim_prefix|>{prefix_content}<|fim_suffix|>
  • <|fim_prefix|> and <|fim_suffix|> are special Tokens, used to guide the model in text completion, no modification needed.
  • {prefix_content}Need to be replaced with the passed-in prefix information, such as function name, Input Parameters, usage instructions, etc.
import os
from openai import OpenAI

client = OpenAI(
    # 请将{WorkspaceId}替换为业务空间ID
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
    api_key=os.getenv("DASHSCOPE_API_KEY")
)

completion = client.completions.create(
  model="qwen-coder-turbo",
  prompt="<|fim_prefix|>def quick_sort(arr):<|fim_suffix|>",
)

print(completion.choices[0].text)
import OpenAI from "openai";

const client = new OpenAI(
    {
        // 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:apiKey: "sk-xxx",
        apiKey: process.env.DASHSCOPE_API_KEY,
        // 请将{WorkspaceId}替换为业务空间ID
        baseURL: "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
    }
);

async function main() {
    const completion = await client.completions.create({
        model: "qwen-coder-turbo",
        prompt: "<|fim_prefix|>def quick_sort(arr):<|fim_suffix|>",
    });
    console.log(completion.choices[0].text)
}

main();
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen-coder-turbo",
    "prompt": "<|fim_prefix|>def quick_sort(arr):<|fim_suffix|>"
}'

Prefix and suffix-based completion

Prompt Template:

<|fim_prefix|>{prefix_content}<|fim_suffix|>{suffix_content}<|fim_middle|>
  • <|fim_prefix|>, <|fim_suffix|>, and <|fim_middle|> are special tokens used to guide the model in text completion, no modification needed.
  • {prefix_content} needs to be replaced with the prefix information passed in, such as the function name, input parameters, usage instructions, etc.
  • {suffix_content} needs to be replaced with the suffix information passed in, such as the function's return parameters, etc.
import os
from openai import OpenAI

client = OpenAI(
    # 请将{WorkspaceId}替换为业务空间ID
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
    api_key=os.getenv("DASHSCOPE_API_KEY")
)

prefix_content = """def reverse_words_with_special_chars(s):
'''
反转字符串中的每个单词(保留非字母字符的位置),并保持单词顺序。
    示例:
    reverse_words_with_special_chars("Hello, world!") -> "olleH, dlrow!"
    参数:
        s (str): 输入字符串(可能包含标点符号)
    返回:
        str: 处理后的字符串,单词反转但非字母字符位置不变
'''
"""

suffix_content = "return result"

completion = client.completions.create(
  model="qwen-coder-turbo",
  prompt=f"<|fim_prefix|>{prefix_content}<|fim_suffix|>{suffix_content}<|fim_middle|>",
)

print(completion.choices[0].text)
import OpenAI from 'openai';

const client = new OpenAI({
  // 请将{WorkspaceId}替换为业务空间ID
  baseURL: "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
  apiKey: process.env.DASHSCOPE_API_KEY
});

const prefixContent = `def reverse_words_with_special_chars(s):
'''
反转字符串中的每个单词(保留非字母字符的位置),并保持单词顺序。
    示例:
    reverse_words_with_special_chars("Hello, world!") -> "olleH, dlrow!"
    参数:
        s (str): 输入字符串(可能包含标点符号)
    返回:
        str: 处理后的字符串,单词反转但非字母字符位置不变
'''
`;

const suffixContent = "return result";

async function main() {
  const completion = await client.completions.create({
    model: "qwen-coder-turbo",
    prompt: `<|fim_prefix|>${prefixContent}<|fim_suffix|>${suffixContent}<|fim_middle|>`
  });

  console.log(completion.choices[0].text);
}

main();
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen-coder-turbo",
    "prompt": "<|fim_prefix|>def reverse_words_with_special_chars(s):\n\"\"\"\n反转字符串中的每个单词(保留非字母字符的位置),并保持单词顺序。\n    示例:\n    reverse_words_with_special_chars(\"Hello, world!\") -> \"olleH, dlrow!\"\n    参数:\n        s (str): 输入字符串(可能包含标点符号)\n    返回:\n        str: 处理后的字符串,单词反转但非字母字符位置不变\n\"\"\"\n<|fim_suffix|>return result<|fim_middle|>"
}'

Production Usage

To optimize the efficiency and reduce the cost of using the Qwen-Coder model, refer to the following recommendations:

  • Enable Stream: Setting stream=True can return intermediate results in real time, reducing timeout risks and improving user experience.
  • Lower the temperature parameter: Code generation tasks usually require determinacy and accuracy in results. It is recommended to lower the temperature parameter to reduce the randomness of generated results.
  • Use a model that supports context caching: In scenarios containing a large number of repeated prefixes (such as code completion and code review), it is recommended to use a model that supportsContext Cache to effectively reduce costs.
  • Control Tool Count: To ensure the efficiency and cost-effectiveness of model calls, it is recommended that the number of tools passed in a single calltools does not exceed 20. Passing a large number of tool descriptions will consume too many input Tokens, which not only increases costs and reduces response speed, but also makes it harder for the model to select the correct tool. For details, see Function Calling.

Billing and Rate Limiting

  • Basic Billing: Based on each request's input Token count and output Token count for billing. Unit prices differ across models; for specific prices, refer to Models。

  • Special Billing Items:

    • Tiered Pricing: The qwen3-coder series models adopt tiered pricing. When SingleAfter the number of input Tokens in a request reaches a specific tier, all input and output Tokens of that request are billed at the unit price of this tier.
    • Context Cache: For models that support context caching, when multiple requests contain large amounts of repeated input (such as code review), the caching mechanism can significantly reduce costs. HitImplicit Cache's input text is billed at 20% of the unit price, hitExplicit Cache's input text is billed at 10% of the unit price. For details, please refer to Context Cache.
    • Built-in Tools (Function Calling): When using the built-in tools feature, you are in tools The tool descriptions defined in the parameters are counted as input content Token total volume and incur costs.
  • Rate Limiting: API calls are subject to dual limits of requests per minute (RPM) and tokens per minute (TPM). For details, see Rate Limiting.

  • Free Quota (Singapore only): The Validity is calculated from the date of activating Bailian or model application Pass, within the 90-day Validity, Qwen-Coder models each provide 1 million Token new user Free Quota.

API Reference

For the Input Parameters and output parameters of the Qwen Code model, see Text Generation.

FAQ

When using development tools like Qwen Code, Claude Code, etc., why are a large number of Tokens consumed?

When calling the Qwen-Coder Model through external development tools to handle problems, the tool may call the API multiple times, thereby consuming a large number of Tokens. For specific methods of monitoring and reducing Token consumption, please refer to Qwen Code and Claude CodeDocs. You can enable the Free Quota Only feature to avoid extra costs after the Free Quota is exhausted.

You can also purchase an AI coding plan, adopting a fixed monthly fee and providing monthly request quotas supported for Use in AI tools. For details, please see Coding Plan Overview.

How to view Model Usage?

After Model Calling occursper-minutecan be viewed in Monitoring charts. Log in to the Monitoring page (SingaporeOrBeijing), select in the left navigation barO&M Management > MonitoringEnter the monitoring overview page, set query conditions (for example, select time range, business space, etc.), then in the Models area find the target model and click View Details to view the calling statistics of that model. For details, see Monitoring Docs.

Monitoring data is updated per minute and is for Reference only, not as a billing basis.

How to make the model only output Code without any explanatory text?

You can Refer to the following methods:

  1. Prompt Constraints: Explicitly instruct in the prompt, for example: "Only return code, do not include any explanations, comments, or markdown tags."
  2. SettingsstopSequence: Use stop=["\n# Explanation:", "Note:", "Explanation:", "Note:"] and similar phrases to terminate early when the Model begins generating explanatory text. For details, see Qwen API Reference.