Skip to main content

Code capabilities (Qwen-Coder)

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.

推荐使用最新的通用模型替代 Qwen-Coder 模型,请参见Text Generation选择适合您场景的模型。

Quick Start

API 使用前提:已获取与配置 API Key并完成配置API Key到环境变量。如果通过SDK调用,需要安装 OpenAI 或 DashScope SDK The following example will demonstrate how to callqwen-coder-plus-latestthe Model to write a Python function that finds prime numbers.
  • OpenAI兼容-Chat Completions API
  • DashScope
  • Python
  • Node.js
  • curl
Request Example
import os
from openai import OpenAI

client = OpenAI(
    # 各地域的API Key不同。获取API Key:https://help.aliyun.com/model-studio/get-api-key
    # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 请将{WorkspaceId}替换为业务空间ID
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
    model="qwen-coder-plus-latest",
    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

Core Capabilities

Calling 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 decides whether and how to call these tools based on your instructions. For details, see Function Calling。 The complete tool calling workflow includes:
  1. Define tools and initiate 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 tools: Parse what the model returns tool_calls, and call the corresponding tool function you have implemented locally to execute the task.
  3. Return execution result: Package the tool's execution result into a specific format and send it back to the model, allowing it to 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兼容-Chat Completions API
  • DashScope
  • Python
  • Node.js
  • curl
import os
import json
from openai import OpenAI

client = OpenAI(
    # 各地域的API Key不同。获取API Key:https://help.aliyun.com/model-studio/get-api-key
    # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 请将{WorkspaceId}替换为业务空间ID
    base_url="https://{WorkspaceId}.cn-beijing.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="qwen-coder-plus-latest",
    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="qwen-coder-plus-latest",
            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 实现。你可以运行这个文件查看示例输出。如果需要进一步修改或解释,请告诉我!

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.
  • Completions API: Only supports North China 2 (Beijing) qwen-coder-turbo-latest models. Supports prefix completion and prefix-suffix completion.

Prefix Continuation (Partial Mode)

This feature lets the model automatically complete the remaining part based on the code (prefix) you have half-written. By messages list, adding one role 为 assistant 的消息,并设置 partial: true 来实现。assistant 消息的 content 即为您提供的代码前缀。详情请参见Prefix Continuation。
  • OpenAI兼容
  • DashScope
  • Python
  • Node.js
  • curl
请求示例
import os
from openai import OpenAI

client = OpenAI(
    # 各地域的API Key不同。获取API Key:https://help.aliyun.com/model-studio/get-api-key
    # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 请将{WorkspaceId}替换为业务空间ID
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
    model="qwen-coder-plus-latest",
    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)

Completions API

The Completions API applies only to models in the North China 2 (Beijing) region, and requires using the North China 2 (Beijing) region'sAPI Key。
Supported Models: qwen-coder-turbo-latest Completions APIPass in prompt Use special fim (Fill-in-the-Middle) tags to guide the Model to perform completion.
  • 基于前缀补全
  • 基于前缀和后缀补全
Prompt template:
<|fim_prefix|>{prefix_content}<|fim_suffix|>
  • <|fim_prefix|> and <|fim_suffix|>are special Tokens, used to guide the Model to perform text completion, no modification needed.
  • {prefix_content}Need to be replaced with the input prefix information, such as function name, Input Parameters, Use Description, and other information.
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-latest",
  prompt="<|fim_prefix|>def quick_sort(arr):<|fim_suffix|>",
)

print(completion.choices[0].text)

Applied to Production Environment

To optimize the usage efficiency of the Qwen code Model and reduce costs, refer to the following suggestions:
  • EnableStream: Settings 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 deterministic and accurate results. It is recommended to lower the temperature parameter to reduce the randomness of the generated results.
  • Use a model that supports context caching: In scenarios with a large amount of repeated prefixes (such as code completion, code review), it is recommended to use a model that supportsContext Cache model to effectively reduce costs.
  • Control tool count: To ensure the efficiency and cost-effectiveness of model calls, it is recommended that the tools passed in a single calltoolsnot exceed 20. Passing a large number of tool descriptions consumes excessive input tokens, which not only increases costs and slows response speed, but also makes it harder for the model to select the correct tool. For details, seeFunction Calling。

Billing and Rate Limiting

  • Basic Billing: Billed based on the input Token count and output Token count of each request. Different models have different unit prices; for specific prices, please refer to Models。
  • Special Billing Items:
    • Tiered Pricing: qwen3-coder series models adopt tiered pricing. When singleAfter the request's input Token count 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 cache mechanism can significantly reduce costs. HitImplicit Cache of input text is billed at 20% of the unit price, hitExplicit Cache of input text is billed at 10% of the unit price. For details, seeContext Cache。
    • Built-in Tools (Function Calling): When using the Built-in Tools feature, you are in tools The tool description defined in the Parameter is counted as input content into Token total and incurs fees.
  • Rate Limit:API Calling is subject to dual limits of requests per minute (RPM) and Tokens per minute (TPM). For details, seeRate Limit。
  • Free Quota (Beijing region only) (Singapore region only):The Validity is calculated from the date of activating Bailian or Model application Pass; within the 90-day Validity, each Qwen-Coder Model provides 1 million Tokens respectivelynew user Free Quota。

API Reference

For the Input Parameters and output parameters of the Qwen Code Model, seeText Generation。

FAQ

Why does using development tools like Qwen Code, Claude Code, etc. consume a large amount of Token?

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 amount of Token. For specific methods on monitoring and reducing Token consumption, please refer toQwen Code and Claude CodeDocs. You can enableFree Quota Onlyfunction to avoid additional costs after the free quota is exhausted. You can also purchase an AI coding plan, adopting a fixed monthly fee, providing monthly request quota, supporting use in AI tools. For details, please refer toCoding Plan Overview。

How to view model call volume?

After a model call occursminute-levelyou can view it in monitoring charts. Log in to Monitoring page (BeijingOrSingapore), select from the left navigation barOperations Management > MonitoringEnter the monitoring overview page, set the query conditions (for example, select the time range, workspace, etc.), then in the Modelsarea, locate the target model and click View Details to view the calling statistics results of the model. For details, see the Monitoring & Alerts docs.
Monitoring data is updated at the minute level and is for reference only, not for billing purposes.

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

You can refer to the following methods:
  1. Prompt Constraints: Clearly instruct in the prompt, for example: "Only return code, do not include any explanations, comments, or markdown markers."
  2. Settingsstopsequence: Use stop=["\n# 解释:", "说明", "Explanation:", "Note:"] etc. phrases to early-terminate when the Model begins generating explanatory text; for details, see Qwen API Reference。
Token Plan
Fine-tuning
Model Compression
Statistics and Monitoring
Support