All Products
Search
Document Center

Alibaba Cloud Model Studio:Make your first API call to Qwen

Last Updated:Feb 19, 2025

You can use APIs to call models in Model Studio, including OpenAI-compatible interfaces and DashScope SDK.

This topic uses Qwen as an example to guide you through your first API call. You will learn how to:

  • Obtain an API key.

  • Set up the development environment.

  • Make an API call to Qwen

Manage account

  1. Register an account: If you do not have an Alibaba Cloud account, you must first register for one.

  2. Activate Model Studio: Go to the Model Studio console, activate the service to obtain the free quota.

    image

  3. Obtain an API key: In the upper right corner of the console, select API-KEY. On the page that appears, create an API key.

    image

Set API key as environment variable

We recommend that you set the API key as an environment variable to avoid explicitly specifying it in the code, thus reducing the risk of leaks.

Steps

Linux

Permanent environment variable

To configure your API key as a permanent environment variable for the current user to use in new sessions, set it as a permanent environment variable.

  1. Run the following command to add the environment variable to the ~/.bashrc file:

    # Replace YOUR_DASHSCOPE_API_KEY with your API key.
    echo "export DASHSCOPE_API_KEY='YOUR_DASHSCOPE_API_KEY'" >> ~/.bashrc

    You can also edit the ~/.bashrc file manually.

    Edit manually

    Run the following command to open the ~/.bashrc file.

    nano ~/.bashrc

    Add the following content to the file.

    # Replace YOUR_DASHSCOPE_API_KEY with your API key.
    export DASHSCOPE_API_KEY="YOUR_DASHSCOPE_API_KEY"

    In the nano editor, press Ctrl+X and then Y. Press Enter to save and close the file.

  2. Run the following command to make the change take effect:

    source ~/.bashrc
  3. Create a session and run the following command to check whether the environment variable takes effect:

    echo $DASHSCOPE_API_KEY

Temporary environment variable

To use your API key as a temporary environment variable only for the current session, set it as a temporary environment variable.

  1. Run the following command:

    # Replace YOUR_DASHSCOPE_API_KEY with your API key.
    export DASHSCOPE_API_KEY="YOUR_DASHSCOPE_API_KEY"
  2. Run the following command to check whether the environment variable takes effect:

    echo $DASHSCOPE_API_KEY

macOS

Permanent environment variable

To configure your API key as a permanent environment variable for the current user to use in new sessions, set it as a permanent environment variable.

  1. Run the following command to check the default Shell type.

    echo $SHELL
  2. Perform the following operation based on your Shell type.

    Zsh
    1. Run the following command to add the environment variable to the ~/.zshrc file.

      # Replace YOUR_DASHSCOPE_API_KEY with your API key.
      echo "export DASHSCOPE_API_KEY='YOUR_DASHSCOPE_API_KEY'" >> ~/.zshrc

      You can also edit the ~/.zshrc file manually.

      Edit manually

      Run the following command to open the configuration file.

      nano ~/.zshrc

      Add the following content to the file.

      # Replace YOUR_DASHSCOPE_API_KEY with your API key.
      export DASHSCOPE_API_KEY="YOUR_DASHSCOPE_API_KEY"

      In the nano editor, press Ctrl+X and then Y. Press Enter to save and close the file.

    2. Run the following command to make the change take effect:

      source ~/.zshrc
    3. Create a session and run the following command to check whether the environment variable takes effect:

      echo $DASHSCOPE_API_KEY
    Bash
    1. Run the following command to add the environment variable to the ~/.bash_profile file.

      # Replace YOUR_DASHSCOPE_API_KEY with your API key.
      echo "export DASHSCOPE_API_KEY='YOUR_DASHSCOPE_API_KEY'" >> ~/.bash_profile

      You can also edit the ~/.bash_profile file manually.

      Edit manually

      Run the following command to open the file.

      nano ~/.bash_profile

      Add the following content to the file.

      # Replace YOUR_DASHSCOPE_API_KEY with your API key.
      export DASHSCOPE_API_KEY="YOUR_DASHSCOPE_API_KEY"

      In the nano editor, press Ctrl+X and then Y. Press Enter to save and close the file.

    2. Run the following command to make the change take effect:

      source ~/.bash_profile
    3. Create a session and run the following command to check whether the environment variable takes effect:

      echo $DASHSCOPE_API_KEY

Temporary environment variable

To use your API key as a temporary environment variable only for the current session, set it as a temporary environment variable.

The following commands work only for Zsh and Bash.
  1. Run the following command:

    # Replace YOUR_DASHSCOPE_API_KEY with your API key.
    export DASHSCOPE_API_KEY="YOUR_DASHSCOPE_API_KEY"
  2. Run the following command to check whether the environment variable takes effect:

    echo $DASHSCOPE_API_KEY

Windows

In Windows, you can set environment variable through System Properties, Command Line or PowerShell.

System Properties

Note
  • The environment variable configured in this way is permanently effective.

  • Modifying system environment variable requires administrative permissions.

  • After configuring environment variable, it will not immediately affect already open command windows, IDEs, or other running applications. You will need to restart these programs or open a new command line for the environment variables to take effect.

  1. Press Win+Q on your desktop. Enter "Edit the system environment variables" in the search box, and click to open the System Properties window.

  2. In the System Properties window, click Environment Variables. In the System Variables section, click New, enter DASHSCOPE_API_KEY as the variable name, and your actual API Key as the variable value.

    image

  3. Click OK on all three dialog boxes.

  4. Open CMD or Windows PowerShell and run the following command to check whether the environment variable takes effect.

    • CMD:

      echo %DASHSCOPE_API_KEY%

      image

    • Windows PowerShell:

      echo $env:DASHSCOPE_API_KEY

      image

CMD

Permanent environment variable

To configure your API key as a permanent environment variable for the current user to use in new sessions, set it as a permanent environment variable.

  1. Run the following command:

    # Replace YOUR_DASHSCOPE_API_KEY with your API key.
    setx DASHSCOPE_API_KEY "YOUR_DASHSCOPE_API_KEY"
  2. Create a new session.

  3. Run the following command to check whether the environment variable takes effect:

    echo %DASHSCOPE_API_KEY%

    image

Temporary environment variable

To use your API key as a temporary environment variable only for the current session, set it as a temporary environment variable.

  1. Run the following command:

    # Replace YOUR_DASHSCOPE_API_KEY with your API key.
    set DASHSCOPE_API_KEY="YOUR_DASHSCOPE_API_KEY"
  2. Run the following command in the current session to check whether the environment variable takes effect:

    echo %DASHSCOPE_API_KEY%

    image

PowerShell

Permanent environment variable

To configure your API key as a permanent environment variable for the current user to use in new sessions, set it as a permanent environment variable.

  1. Run the following command:

    # Replace YOUR_DASHSCOPE_API_KEY with your API key.
    [Environment]::SetEnvironmentVariable("DASHSCOPE_API_KEY", "YOUR_DASHSCOPE_API_KEY", [EnvironmentVariableTarget]::User)
  2. Create a session.

  3. Run the following command to check whether the environment variable takes effect:

    echo $env:DASHSCOPE_API_KEY

    image

Temporary environment variable

To use your API key as a temporary environment variable only for the current session, set it as a temporary environment variable.

  1. Run the following command:

    # Replace YOUR_DASHSCOPE_API_KEY with your API key.
    $env:DASHSCOPE_API_KEY = "YOUR_DASHSCOPE_API_KEY"
  2. Run the following command in the current session to check whether the environment variable takes effect:

    echo $env:DASHSCOPE_API_KEY

    image

Select development language

Choose the programming language or tool with which you are most comfortable.

Python

Step 1: Prepare Python environment

Check Python version

Run the following command in the terminal to check whether Python is installed:

Make sure that you have Python version 3.8 or higher, see Install Python.

python -V
pip --version

Take Windows CMD as an example:

image

FAQ

Q: An error occurs when executing python -V, pip --version:

  • 'python' is not recognized as an internal or external command, operable program or batch file.

  • 'pip' is not recognized as an internal or external command, operable program or batch file.

  • -bash: python: command not found

  • -bash: pip: command not found

A: Take the following steps:

Windows

  1. Make sure that you have installed Python in your computing environment and that you have added python.exe to PATH. image

  2. If you have installed Python and added the environment variable, but the error still occurs, close the current terminal and open a new terminal to try again.

Linux and macOS

  1. Make sure you have installed Python in your computing environment.

  2. If you have installed Python but the error still occurs, run which python pip to check whether python and pip exist in the system.

    • If the following result is returned, close the current terminal and open a new terminal to try again.

      /usr/bin/python
      /usr/bin/pip
    • If the following result is returned, run which python3 pip3 to check again.

      /usr/bin/which: no python in (/root/.local/bin:/root/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin)
      /usr/bin/which: no pip in (/root/.local/bin:/root/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin)

      If the following result is returned, run python3 -V, pip3 --version to check the version.

      /usr/bin/python3
      /usr/bin/pip3

Configure virtual environment (optional)

After Python is installed, you can set up a virtual environment to manage dependencies for OpenAI Python SDK or DashScope Python SDK. The virtual environment can avoid conflicts with your other projects.

  1. Create a virtual environment

    Run the following command to create a virtual environment named .venv:

    # If the operation fails, replace python with python3 and run again
    python -m venv .venv
  2. Activate the virtual environment

    For Windows:

    .venv\Scripts\activate

    For macOS or Linux:

    source .venv/bin/activate

Install OpenAI Python SDK or DashScope Python SDK

Install OpenAI Python SDK or DashScope Python SDK to call models in Model Studio.

OpenAI Python SDK

Run the following command:

# If the operation fails, replace pip with pip3 and run again
pip install -U openai

image

When the terminal displays Successfully installed ... openai-x.x.x, OpenAI Python SDK is installed.

DashScope Python SDK

Run the following command:

# If the operation fails, replace pip with pip3 and run again
pip install -U dashscope

image

When the terminal displays Successfully installed ... dashscope-x.x.x, DashScope Python SDK is installed.

Step 2: Call the API

OpenAI Python SDK

After installing Python and OpenAI Python SDK, take the following steps to send your API request.

  1. Create a new file named hello_qwen.py.

  2. Copy the following code into hello_qwen.py and save it.

    import os
    from openai import OpenAI
    
    try:
        client = OpenAI(
            # If the environment variable is not configured, replace the following line with your API key: api_key="sk-xxx",
            api_key=os.getenv("DASHSCOPE_API_KEY"),
            base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
        )
    
        completion = client.chat.completions.create(
            model="qwen-plus",  # Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
            messages=[
                {'role': 'system', 'content': 'You are a helpful assistant.'},
                {'role': 'user', 'content': 'Who are you?'}
                ]
        )
        print(completion.choices[0].message.content)
    except Exception as e:
        print(f"Error message: {e}")
        print("For more information, see: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code")
  3. Run python hello_qwen.py or python3 hello_qwen.py.

    Note

    The command used in this example needs to be executed in the directory where the Python file is located. If you want to execute it from any location, specify the specific file path before the file name.

    Sample response:

    I am a large language model created by Alibaba Cloud. I am called Qwen.

DashScope Python SDK

After installing Python and DashScope Python SDK, take the following steps to send your API request.

  1. Create a new file named hello_qwen.py.

  2. Copy the following code into hello_qwen.py and save it.

    import os
    from dashscope import Generation
    import dashscope
    dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
    
    messages = [
        {'role': 'system', 'content': 'You are a helpful assistant.'},
        {'role': 'user', 'content': 'Who are you?'}
        ]
    response = Generation.call(
        # If the environment variable is not configured, replace the following line with your API key: api_key = "sk-xxx",
        api_key=os.getenv("DASHSCOPE_API_KEY"), 
        model="qwen-plus",   # Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
        messages=messages,
        result_format="message"
    )
    
    if response.status_code == 200:
        print(response.output.choices[0].message.content)
    else:
        print(f"HTTP return code: {response.status_code}")
        print(f"Error code: {response.code}")
        print(f"Error message: {response.message}")
        print("For more information, see: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code")
  3. Run python hello_qwen.py or python3 hello_qwen.py.

    Note

    The command used in this example needs to be executed in the directory where the Python file is located. If you want to execute it from any location, specify the specific file path before the file name.

    Sample response:

    I am a large language model created by Alibaba Cloud. I am called Qwen.

Node.js

Step 1: Prepare Node.js environment

Check Node.js installation status

Run the following command in the terminal to check whether Node.js and npm are installed in the current computing environment:

node -v
npm -v

Take Windows CMD as an example:

image

This command displays your current Node.js version. If Node.js is not installed in your environment, you can download it from Node.js official website.

Install the SDK

Run the following command in the terminal:

npm install --save openai
# Or
yarn add openai
Note

If the installation fails, you can run the following command to configure a repository mirror:

npm config set registry https://registry.npmmirror.com/

Then, run the installation command to install the SDK again.

image

When the terminal displays added xx package in xxs, the OpenAI SDK is installed. You can run npm list openai to check the version information.

Step 2: Call the API

  1. Create a hello_qwen.mjs file.

  2. Copy the following code into the file.

    import OpenAI from "openai";
    
    try {
        const openai = new OpenAI(
            {
                // If the environment variable is not configured, replace the following line with your API key: apiKey: "sk-xxx",
                apiKey: process.env.DASHSCOPE_API_KEY,
                baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
            }
        );
        const completion = await openai.chat.completions.create({
            model: "qwen-plus",  // Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
            messages: [
                { role: "system", content: "You are a helpful assistant." },
                { role: "user", content: "Who are you?" }
            ],
        });
        console.log(completion.choices[0].message.content);
    } catch (error) {
        console.log(`Error message: ${error}`);
        console.log("For more information, see: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code");
    }
  3. Run the following command to send the API request:

    node hello_qwen.mjs
    Note
    • The command used in this example needs to be executed in the directory where hello_qwen.mjs resides. If you want to execute it from any location, specify the specific file path before the file name.

    • Ensure that the SDK is installed in the directory where hello_qwen.mjs resides. If the SDK is not in the same directory as the file, an error Cannot find package 'openai' imported from xxx will occur.

    Sample response:

    I am a language model created by Alibaba Cloud. I am called Qwen.

Java

Step 1: Prepare Java environment

Check Java version

Run the following command in the terminal:

java -version
# (Optional) If you use Maven to manage and build Java projects, ensure that Maven is correctly installed in your development environment
mvn --version

Take Windows CMD as an example:

image

DashScope Java SDK requires Java 8 or higher. The first line of the output shows your Java version. For example, openjdk version "16.0.1" 2021-04-20 indicates Java 16 is installed. If Java is not installed or the installed version is earlier than Java 8, go to Java Downloads to download and install the appropriate version.

Install the SDK

After you install Java, you can then install DashScope Java SDK. For information about the SDK versions, see DashScope Java SDK. Run the following command to include the Java SDK dependency in your project. Replace the-latest-version with the actual latest version number.

XML

  1. Open your Maven project's pom.xml file.

  2. Add the dependency information within the <dependencies> tag.

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>dashscope-sdk-java</artifactId>
        <!-- Please replace 'the-latest-version' with the latest version number: https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->
        <version>the-latest-version</version>
    </dependency>
  3. Save pom.xml.

  4. Use Maven commands, such as mvn compile or mvn clean install, to refresh your project's dependencies. DashScope Java SDK will be downloaded and integrated into your project automatically.

Take Windows IDEA as an example:

image

Gradle

  1. Open your Gradle project's build.gradle file.

  2. Add the dependency information within the dependencies block.

    dependencies {
        // Please replace 'the-latest-version' with the latest version number: https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java
        implementation group: 'com.alibaba', name: 'dashscope-sdk-java', version: 'the-latest-version'
    }
  3. Save build.gradle.

  4. Navigate to your project's root directory in the command line and run the following Gradle command to refresh your project dependencies. DashScope Java SDK will be downloaded and integrated into your project automatically.

    ./gradlew build --refresh-dependencies

Take Windows IDEA as an example:

image

Step 2: Call the API

You can run the following code to call the API.

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;
public class Main {
    public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
        Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.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("Who are you?")
                .build();
        GenerationParam param = GenerationParam.builder()
                // If the environment variable is not configured, replace the following line with your API key: .apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
                .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());
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.err.println("Error message: " + e.getMessage());
            System.out.println("For more information, see: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

Sample response:

I am a large language model created by Alibaba Cloud. I am called Qwen.

cURL

You call models in Model Studio by using OpenAI-compatible HTTP or DashScope HTTP protocols. For a list of supported models, see List of models.

Note

If you did not set the environment variable, replace -H "Authorization: Bearer $DASHSCOPE_API_KEY" \ with -H "Authorization: Bearer sk-xxx" \.

OpenAI-compatible HTTP

To send an API request, run the following command:

Windows

In CMD, execute:

curl -X POST "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions" ^
-H "Authorization: Bearer %DASHSCOPE_API_KEY%" ^
-H "Content-Type: application/json" ^
-d "{
    \"model\": \"qwen-plus\",
    \"messages\": [
        {
            \"role\": \"system\",
            \"content\": \"You are a helpful assistant.\"
        },
        {
            \"role\": \"user\",
            \"content\": \"Who are you?\"
        }
    ]
}"

Linux/macOS

In Terminal, execute:

curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen-plus",
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user", 
            "content": "Who are you?"
        }
    ]
}'

Sample response:

{
    "choices": [
        {
            "message": {
                "role": "assistant",
                "content": "I am a large language model created by Alibaba Cloud. I am called Qwen."
            },
            "finish_reason": "stop",
            "index": 0,
            "logprobs": null
        }
    ],
    "object": "chat.completion",
    "usage": {
        "prompt_tokens": 22,
        "completion_tokens": 16,
        "total_tokens": 38
    },
    "created": 1728353155,
    "system_fingerprint": null,
    "model": "qwen-plus",
    "id": "chatcmpl-39799876-eda8-9527-9e14-2214d641cf9a"
}

DashScope HTTP

To send an API request, run the following command:

Windows

In CMD, execute:

curl -X POST "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation" ^
-H "Authorization: Bearer %DASHSCOPE_API_KEY%" ^
-H "Content-Type: application/json" ^
-d "{
  \"model\": \"qwen-plus\",
  \"input\": {
    \"messages\": [
      {
        \"role\": \"system\",
        \"content\": \"You are a helpful assistant.\"
      },
      {
        \"role\": \"user\",
        \"content\": \"Who are you?\"
      }
    ]
  },
  \"parameters\": {
    \"result_format\": \"message\"
  }
}"

Linux/macOS

In Terminal, execute:

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen-plus",
    "input":{
        "messages":[      
            {
                "role": "system",
                "content": "You are a helpful assistant."
            },
            {
                "role": "user",
                "content": "Who are you?"
            }
        ]
    },
    "parameters": {
        "result_format":"message"
    }
}'

Sample response:

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": "I am a large language model created by Alibaba Cloud. I am called Qwen."
                }
            }
        ]
    },
    "usage": {
        "total_tokens": 38,
        "output_tokens": 16,
        "input_tokens": 22
    },
    "request_id": "87f776d7-3c82-9d39-b238-d1ad38c9b6a9"
}

Other languages

Call the API

package main

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

type Message struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}
type RequestBody struct {
	Model    string    `json:"model"`
	Messages []Message `json:"messages"`
}

func main() {
	// Create an HTTP client
	client := &http.Client{}
	// Construct the request body
	requestBody := RequestBody{
		// Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
		Model: "qwen-plus",
		Messages: []Message{
			{
				Role:    "system",
				Content: "You are a helpful assistant.",
			},
			{
				Role:    "user",
				Content: "Who are you?",
			},
		},
	}
	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		log.Fatal(err)
	}
	// Create a POST request
	req, err := http.NewRequest("POST", "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions", bytes.NewBuffer(jsonData))
	if err != nil {
		log.Fatal(err)
	}
	// Set request headers
	// If the environment variable is not configured, replace the following line with your API key: apiKey := "sk-xxx"
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")
	// Send the request
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	// Read the response body
	bodyText, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	// Print the content of the response
	fmt.Printf("%s\n", bodyText)
}
<?php
// Set the request URL
$url = 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions';
// If the environment variable is not configured, replace the following line with your API key: $apiKey = "sk-xxx";
$apiKey = getenv('DASHSCOPE_API_KEY');
// Set request headers
$headers = [
    'Authorization: Bearer '.$apiKey,
    'Content-Type: application/json'
];
// Set the request body
$data = [
    "model" => "qwen-plus",
    "messages" => [
        [
            "role" => "system",
            "content" => "You are a helpful assistant."
        ],
        [
            "role" => "user",
            "content" => "Who are you?"
        ]
    ]
];
// Initialize a cURL session
$ch = curl_init();
// Set cURL options
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);
// Execute the cURL session
$response = curl_exec($ch);
// Check whether an error occurs
if (curl_errno($ch)) {
    echo 'Curl error: ' . curl_error($ch);
}
// Close the cURL resource
curl_close($ch);
// Output the response result
echo $response;
?>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将下行替换为:string? apiKey = "sk-xxx";
        string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");

        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("API Key 未设置。请确保环境变量 'DASHSCOPE_API_KEY' 已设置。");
            return;
        }
        string url = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions";
        // 模型列表:https://www.alibabacloud.com/help/en/model-studio/getting-started/models
        string jsonContent = @"{
            ""model"": ""qwen-plus"",
            ""messages"": [
                {
                    ""role"": ""system"",
                    ""content"": ""You are a helpful assistant.""
                },
                {
                    ""role"": ""user"", 
                    ""content"": ""你是谁?""
                }
            ]
        }";

        // 发送请求并获取响应
        string result = await SendPostRequestAsync(url, jsonContent, apiKey);

        // 输出结果
        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}";
            }
        }
    }
}
using System.Net.Http.Headers;
using System.Text;

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

    static async Task Main(string[] args)
    {
        // If the environment variable is not configured, replace the following line with your API key: string? apiKey = "sk-xxx";
        string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");

        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("API Key is not set. Please ensure the environment variable 'DASHSCOPE_API_KEY' is set.");
            return;
        }
        string url = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions";
        // Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
        string jsonContent = @"{
            ""model"": ""qwen-plus"",
            ""messages"": [
                {
                    ""role"": ""system"",
                    ""content"": ""You are a helpful assistant.""
                },
                {
                    ""role"": ""user"", 
                    ""content"": ""Who are you?""
                }
            ]
        }";

        // Send the request and obtain the response
        string result = await SendPostRequestAsync(url, jsonContent, apiKey);

        // Output the result
        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"))
        {
            // Set request headers
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // Send the request and obtain the response
            HttpResponseMessage response = await httpClient.PostAsync(url, content);

            // Process the response
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStringAsync();
            }
            else
            {
                return $"Request failed: {response.StatusCode}";
            }
        }
    }
}

FAQ

Q: My free quota has run out. How to purchase tokens for the Qwen models?

A: You can go to Expenses and Costs. So long as your account has no overdue payments, you can call the Qwen models.

Note

Charges for using the Qwen models will appear on your bill one hour after the request.

What to do next