Skip to content

Make your first API call to Qwen

Reference, synced 2026-06-13.

flowchart TD
  n0["Models"]
  n1["Overview"]
  n2["Products"]
  n3["Solutions"]
  n4["Pricing"]
  n5["Resources"]
  n6["Partners"]
  n7["Support"]
  n8["Language"]
  n0 --> n1
  n1 --> n2
  n2 --> n3
  n3 --> n4
  n4 --> n5
  n5 --> n6
  n6 --> n7
  n7 --> n8

Free access Accelerate Delivery with Fixed-Cost Agentic CodingWatch how it works

Models

Empowering AI innovation for both enterprises and developers with Alibaba Cloud’s best-in-class Qwen models, AI-native apps, and AI solutions.

Alibaba Cloud Model Studio \ Enterprise-grade large model service and application development platform.

Try Visual Model \ Supports image understanding, image generation, and video generation.

Models

HappyHorse-1.0-T2V \ Cinematic creative generation, ultimate dynamic details Qwen3-VL-Plus \ Native VL, spatial reasoning, 1M-context video analysis Wan2.7-VideoEdit \ Supports both localized and global editing with prompt

Qwen3.6-Plus \ Native multimodal, 1M context, agentic coding Wan2.7-Image-Pro \ Interactive editing, long-text rendering, precise prompt following Qwen-Plus \ Balanced intelligence, efficient inference, production-ready performance

Qwen-Image-2.0 \ Professional infographics, exquisite photorealism Z-Image-Turbo \ Ultra-fast image generation, high throughput, cost-optimized inference Qwen3-Coder-Next \ Multi-turn tool interactions, future-ready development support

Wan2.7-T2V \ High-fidelity T2V, 15s duration, advanced camera control Wan2.7-I2V \ Cinematic I2V with emotional depth and visceral impact Wan2.7-R2V \ Up to 5 mixed image/video inputs and audio timbre cloning

GenAI Application

Qoder \ Intelligent coding assistant, available for enterprise-dedicated deployment. Qoder CN \ AI-powered coding assistant that boosts developer productivity with intelligent code completion, AI chat, multi-file editing, and task automation.

AI Service

Model Experience \ Experience full-scale, multimodal model capabilities online. Platform for AI \ An AI-native algorithm engineering platform for end-to-end modeling, training, and inference service deployment. Fine-tune Video Generation Model \ Customize Wan’s text-to-video capabilities through model fine-tuning to meet your unique requirements.

AI Use Case

AI Savings Plan Hot \ Save up to 47% on AI costs. Limited-time offer tailored to your usage. AI Video Creation \ Elevate your professional video production with Wan 2.6.

AI Token Plan \ One plan. Multiple models. Big Savings with a Fixed Subscription. AI Image Creation \ All-in-one creative suite for copywriting, image generation, and poster design.

Overview

As a global full-stack AI leader, Alibaba Cloud aims to make computing accessible to everyone and help worldwide customers accelerate innovation.

Why Alibaba Cloud

About Alibaba Cloud \ AI Powered Cloud Technology Our Global Network \ Explore our global presence and deployment regions around the world Our Global Offices \ With offices in 4 continents, we're always close to where it matters.

Asia Accelerator \ Accelerate Success in Asia with Alibaba Cloud Go Global \ Benefits of our Global Alliance Trust Center \ Empowering enterprises with a secure, compliant, and globally trusted cloud infrastructure

Customers and Insights

Olympic Games \ Alibaba Cloud Powers Olympic Games with AI-powered cloud technology Case Studies \ Learn how customers are scaling their businesses on Alibaba Cloud Analyst Reports \ Learn what the top industry analyst firms are saying about Alibaba Cloud

What's New

Events and Webinars \ Quick access to upcoming and on-demand events Product Updates \ Stay informed of the latest innovations Press Room \ Latest news and media releases

Products

Featured ProductsAI & Machine Learning Computing Container Storage Networking & CDN Security Middleware Database Analytics ComputingMedia ServicesEnterprise Services & Cloud CommunicationDomain Names and WebsitesEnd User ComputingServerlessDeveloper ToolsMigration & O&M ManagementApsara Stack

Alibaba Cloud Model Studio \ Supercharge your AI journey effortlessly with industry-leading GenAI models ApsaraDB RDS \ Store and manage your business data, with automated monitoring and backups Certificate Management Service (Original SSL Certificate) \ Create a safe and secure connection between your website and users

Elastic Compute Service (ECS) \ Host websites anywhere and scale enterprise workloads Container Service for Kubernetes (ACK) \ Run and scale containerized applications on managed Kubernetes infrastructure Object Storage Service (OSS) \ Store large amounts of data in the cloud and access it anywhere, anytime

Simple Application Server (SAS) \ All-in-one services for fast deployment Elastic IP Address (EIP) \ Manage your public IPs independently to improve internet network quality Domain Names and Website \ Get the perfect domain name to suit your every need

Solutions

Solutions by Industry Technical Solutions AI WebsitesNetworking Security and ComplianceData and AnalyticsEnterprise Service and ApplicationCloud MigrationCloud NativeHybrid CloudSMB solutions

Financial Services \ Innovate faster with Alibaba Cloud Games \ Grow your game rapidly with high global availability

New Retail \ Alibaba Cloud enables digital retail transformation to fuel growth and realize an omnichannel customer experience throughout the consumer journey. Media and Entertainment \ Ready your content for today's media market with a digitalized media journey

Supply Chain \ Power your supply chain with intelligent, efficient, and reliable solutions Sports \ Digitizing the sports industry with intelligent tech

Sustainability \ Achieve a sustainable future with low-carbon and energy-efficient technologies

Pricing

Flexible options like pay-as-you-go and clear billing rules to meet diverse business needs.

Overview & Tools

Pricing Calculator \ Get an instant pricing estimate based on your usage and needs Free Trial \ Try our 80+ cloud products for free.

Pricing Options \ Get the most out of Alibaba Cloud with flexible pricing

Optimize your cost

Migrate & Save \ Superior Performance At Lower Pricing. Save up to 50%. Promotion Center \ Unlock the latest Alibaba Cloud offers & promos

Resources

Official documentation, extensive tools, training resources, and a community to grow and innovate in the cloud.

Technical Resources

Documentation \ Product guides and FAQs Architecture Center \ Design reliable, secure, and efficient cloud architecture. Intelligent Solution Explorer \ Find the right solution for you, powered by AI

Blog \ Latest cloud insights and developer trends Whitepapers \ Research that explores the how and why behind our technology

Training&Certification

Alibaba Cloud Academy \ Build cloud skills and earn certifications with expert-led training.

Developer Hub

Alibaba Cloud Project Hub \ Explore real-world projects built by developers using our platform. Our Developer MVPs \ Celebrating the developers who lead, build, and inspire our community

Partners

Partner-first strategy offering collaborative product, sales, and service models, plus high-quality partner solutions that complement Alibaba Cloud’s capabilities.

Marketplace

AI Alliance for ISVs \ Partner with us to build and grow AI solutions together ISV Benefits \ Unlock resources, market access, and go-to-market support as an ISV partner

Alibaba Cloud Marketplace \ Explore ready-to-deploy solutions from our partners and ISVs

Find a Partner

Partner Hub \ Find your ideal partner in no time

Become a Partner

Partner Network \ A partner portal for Alibaba Cloud Channel, Technology, MSP partner and other partner programs

Support

Full-lifecycle support and expert services, from cloud advisory and migration to operations.

Support & Professional Services

Professional Services \ Expert-led services to design, migrate, and optimize your cloud journey Support Plans \ Flexible support for every stage — from startup to enterprise

Partner Support Program \ Priority technical support for partners, with dedicated managers and faster issue resolution

Contact us

Connect With Us \

Talk to a sales expert and get a custom quote for your business

Language

  • English
  • 简体中文
  • 繁體中文
  • 日本語
  • Bahasa Indonesia

Locale

Visit aliyun.com

Documentation

Alibaba Cloud Model Studio

User Guide (Models) User Guide (Application) API Reference (Models) API Reference (Application)

Search for Help Content

Getting Started

The Beginner's Guide

Well-Architected Framework

AI & Machine Learning

Platform For AI

Alibaba Cloud Model Studio

DashVector

Artificial Intelligence Recommendation

OpenSearch

Image Search

Machine Translation

Intelligent Speech Interaction

Optimization Solver

Intelligent Computing LINGJUN

Computing

Elastic Compute Service

Elastic GPU Service

Elastic Container Instance

Dedicated Host

Compute Nest

Simple Application Server

Cloud Box

Auto Scaling

Elastic High Performance Computing

Batch Compute (Deprecated)

Function Compute

Serverless App Engine

ENS

Elastic Desktop Service

App Streaming

WUYING Terminal

Cloud Phone

Edge Network Acceleration

Alibaba Cloud Linux

AgentBay

Container

Container Service for Kubernetes

Container Compute Service

Container Registry

Storage

Object Storage Service

Cloud Parallel File Storage

File Storage NAS

Tablestore

Storage Capacity Unit

Simple Log Service

Cloud Backup

Intelligent Media Management

Drive and Photo Service

Data Transport

Cloud Storage Gateway

Data Online Migration

Hybrid Cloud Storage Array

Storage Services Overview

Backup and Disaster Recovery Center

Networking and CDN

Server Load Balancer

Elastic IP Address

Internet Shared Bandwidth

Data Transfer Plan

Virtual Private Cloud

NAT Gateway

PrivateLink

Alibaba Cloud DNS PrivateZone

Network Intelligence Service

Cloud Data Transfer

IPv6 Gateway

Anycast Elastic IP Address

Cloud Enterprise Network

Global Accelerator

VPN Gateway

Smart Access Gateway

Express Connect

CDN

Edge Security Acceleration

Cloud Network Well-architected Design Guidelines

Security

Anti-DDoS

Web Application Firewall

Cloud Firewall

Security Center

Bastionhost

Secure Access Service Edge

Certificate Management Service

Key Management Service

Data Security Center

Identity as a Service

Fraud Detection

AI Guardrails

Captcha

Blockchain as a Service

ID Verification

Managed Security Service

Middleware

Enterprise Distributed Application Service

Microservices Engine

Alibaba Cloud Service Mesh

SchedulerX

ApsaraMQ for RocketMQ

ApsaraMQ for Kafka

ApsaraMQ for RabbitMQ

ApsaraMQ for MQTT

Simple Message Queue (formerly MNS)

CloudFlow

EventBridge

Application Real-Time Monitoring Service

Managed Service for Prometheus

Managed Service for Grafana

Managed Service for OpenTelemetry

Performance Testing

Databases

ApsaraDB Console

PolarDB

ApsaraDB RDS

ApsaraDB for OceanBase (Deprecated)

Tair (Redis® OSS-Compatible)

Lindorm

Time Series Database

ApsaraDB for MongoDB

ApsaraDB for HBase

ApsaraDB for Memcache

ApsaraDB for MyBase

AnalyticDB

ApsaraDB for ClickHouse

ApsaraDB for SelectDB

Data Transmission Service

Database Autonomy Service

Data Management

Database Gateway - Deprecated

ApsaraDB for Cassandra - Deprecated

Analytics Computing

MaxCompute

Hologres

Realtime Compute for Apache Flink

Elasticsearch

Vector Retrieval Service for Milvus

E-MapReduce

Data Lake Formation

DataV

Quick BI

Quick Audience

Quick Tracking

DataWorks

DataHub

Dataphin

Media Services

ApsaraVideo VOD

ApsaraVideo Live

Intelligent Media Services

ApsaraVideo Media Processing

Apsara Video SDK

Enterprise Services & Cloud Communication

Energy Expert

CloudQuotation

Salesforce on Alibaba Cloud

GoChina ICP Filing Assistant

Marketplace

Alibaba Mail

Direct Mail

Short Message Service

Voice Service

Phone Number Verification Service

Cell Phone Number Service

Chat App Message Service

Financial Intelligence Engine

Domain Names and Websites

Domain Names

ICP Filing

Alibaba Cloud DNS

End User Computing

Elastic Desktop Service

App Streaming

WUYING Terminal

Cloud Phone

AgentBay

Internet of Things

IoT Platform

Serverless

Serverless App Engine

CloudFlow

EventBridge

Simple Message Queue (formerly MNS)

Function Compute

Developer Tools

OpenAPI Explorer

Alibaba Cloud SDK

Cloud Shell

Resource Orchestration Service

Alibaba Cloud CLI

BSS OpenAPI

Terraform

Pulumi

Ticket System API

Mobile Platform as a Service

Alibaba Cloud DevOps

API Gateway

Cloud Control API

AI Coding Assistant Lingma

Cloud Skills Portal

Migration & O&M Management

CloudOps Orchestration Service

Cloud Monitor

Intelligent Advisor

Cloud Governance Center

ActionTrail

Cloud Config

Resource Access Management

Resource Management

Cloud Architect Design Tools

Migration Hub

Server Migration Center

Service Catalog

Logic Composer

Quota Center

CloudSSO

HTTPDNS

Solutions

SAP

SuperApp

OpenLake

Membership Service

Expenses and Costs

Account Center

More

Support

Legal

Tech Share Terms and Conditions

After Sales Support

China Gateway Program

Service Level Objectives

Management Console

Security Control

Alibaba Cloud Model Studio supports API calls to models through OpenAI-compatible interfaces and the DashScope SDK.

To call the Qwen API:

  • Get an API key

  • Set up your local development environment

  • Call the Qwen API

Account setup

  1. Create an account: If you do not have an Alibaba Cloud account, create one.

If you encounter issues, see Register an Alibaba Cloud account.

  1. Activate Model Studio: Use your Alibaba Cloud account to go to Alibaba Cloud Model Studio. Read and accept the Terms of Service to activate the service. If no Terms of Service dialog appears, the service is already activated.

  2. Get an API key: Go to the API Key page and click Create API key. Then use the API key to call models.

  3. Get your workspace ID: When calling models in the Singapore, Germany (Frankfurt), or China (Hong Kong) region, you need to include the workspace ID (WorkspaceId) in the Base URL. You can find it on the Workspace Management page.

Set your API key as an environment variable

Store your API key in an environment variable to avoid hardcoding credentials and reduce security risks.

Steps

Linux

macOS

Windows

Permanent environment variable

Temporary environment variable

To make the API key available in all future sessions, export it permanently.

  1. Run the following command to add the environment variable to the ~/.bashrc file:
bash
# 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.

zsh
nano ~/.bashrc

Add the following content to the file.

bash
# 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.

  1. Run the following command to make the change take effect:
bash
  1. Create a session and run the following command to check whether the environment variable takes effect:
bash
echo $DASHSCOPE_API_KEY

To use the API key only in the current session, export it temporarily.

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

Permanent environment variable

Temporary environment variable

To make the API key available in all future sessions, export it permanently.

  1. Run the following command to check the default Shell type.
bash
echo $SHELL
  1. Perform the following operation based on your Shell type.

Zsh

Bash

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

    zsh
    # 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.

    zsh
    nano ~/.zshrc

    Add the following content to the file.

    bash
    # 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:

    zsh
  3. Create a session and run the following command to check whether the environment variable takes effect:

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

    zsh
    # 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.

    bash
    nano ~/.bash_profile

    Add the following content to the file.

    bash
    # 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.

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

    zsh
  6. Create a session and run the following command to check whether the environment variable takes effect:

    zsh
    echo $DASHSCOPE_API_KEY

To use the API key only in the current session, export it temporarily.

The following commands work only for Zsh and Bash.

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

In Windows, you can export environment variables using System Properties, Command Line, or PowerShell.

System Properties

CMD

PowerShell

Note

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

  • Modifying system environment variable requires administrative permissions.

  • After configuring the environment variable, it will not affect already-running programs. Restart IDEs and command windows, or open a new command line, to load the new variable.

  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.

  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:

      powershell
      echo %DASHSCOPE_API_KEY%
    • Windows PowerShell:

      powershell
      echo $env:DASHSCOPE_API_KEY

Permanent environment variable

Temporary environment variable

To make the API key available in all future sessions, export it permanently.

  1. Run the following command:
bash
# Replace YOUR_DASHSCOPE_API_KEY with your API key.
setx DASHSCOPE_API_KEY "YOUR_DASHSCOPE_API_KEY"
  1. Create a new session.

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

bash
echo %DASHSCOPE_API_KEY%

To use the API key only in the current session, export it temporarily.

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

Permanent environment variable

Temporary environment variable

To make the API key available in all future sessions, export it permanently.

  1. Run the following command:
powershell
# Replace YOUR_DASHSCOPE_API_KEY with your API key.
[Environment]::SetEnvironmentVariable("DASHSCOPE_API_KEY", "YOUR_DASHSCOPE_API_KEY", [EnvironmentVariableTarget]::User)
  1. Create a session.

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

powershell
echo $env:DASHSCOPE_API_KEY

To use the API key only in the current session, export it temporarily.

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

Choose a development language

Select a language or tool to call model APIs.

Python

Node.js

Java

curl

Other languages

Step 1: Set up Python

Check your Python version

Run this command to check whether Python and pip are installed:

Python 3.8 or later is required. For installation instructions, see Install Python.

bash
python -V
pip --version

For example, on Windows Command Prompt:

FAQ

Q: The commands python -V and pip --version return errors:

  • '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

Try these solutions:

Windows

Linux and macOS

  1. Confirm that you installed Python by following Install Python, and added python.exe to the PATH environment variable.

  2. If Python and PATH are correctly configured but the error persists, close your current terminal and open a new one.

  3. Confirm that you installed Python by following Install Python.

  4. If Python is installed but the error persists, run which python pip to check whether python and pip exist in your system.

    • If this result appears, close the current terminal window, open a new terminal window, and try again.

      bash
      /usr/bin/python
      /usr/bin/pip
    • If this result is returned, run the which python3 pip3 query again.

      bash
      /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 returned result is shown, use python3 -V and pip3 --version to check the version.

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

Set up a virtual environment (optional)

If Python is already installed, you can create a virtual environment to install the OpenAI Python SDK or the DashScope Python SDK and avoid dependency conflicts.

  1. Create a virtual environment

Create a virtual environment named .venv:

shell
# If this fails, replace python with python3
python -m venv .venv
  1. Activate the virtual environment

On Windows, activate the virtual environment:

shell
.venv\Scripts\activate

On macOS or Linux, run:

shell

Install the OpenAI Python SDK or DashScope Python SDK

You can call models on Model Studio using the OpenAI Python SDK or the DashScope Python SDK.

Install the OpenAI Python SDK

Install the DashScope Python SDK

Install or upgrade the OpenAI Python SDK:

bash
# If this fails, replace pip with pip3
pip install -U openai

Look for Successfully installed ... openai-x.x.x to confirm installation.

Install or upgrade the DashScope Python SDK:

bash
# If this fails, replace pip with pip3
pip install -U dashscope

Look for Successfully installed ... dashscope-x.x.x to confirm installation.

Step 2: Call the API

OpenAI Python SDK

DashScope Python SDK

With Python and the OpenAI Python SDK installed, send your first API request.

  1. Create a file named hello_qwen.py.

  2. Copy this code into hello_qwen.py and save it.

python
import os
from openai import OpenAI

try:
       client = OpenAI(
           # If the environment variable is not configured, replace with: api_key="sk-xxx"
           api_key=os.getenv("DASHSCOPE_API_KEY"),
           # The following URL is for the Singapore region. When calling, replace WorkspaceId with your actual workspace ID. URLs vary by region.
           base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
       )

       completion = client.chat.completions.create(
           model="qwen-plus",
           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("See: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code")
  1. Run python hello_qwen.py or python3 hello_qwen.py from the command line.

If you see No such file or directory, specify the full path to the file.

The output is:

plaintext
I am a large-scale language model developed by Alibaba Cloud. My name is Qwen.

With Python and the DashScope Python SDK installed, send your first API request.

  1. Create a file named hello_qwen.py.

  2. Copy this code into hello_qwen.py and save it.

python
import os
from dashscope import Generation
import dashscope

# The following URL is for the Singapore region. When calling, replace WorkspaceId with your actual workspace ID. URLs vary by region.
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': 'Who are you?'}\
]
response = Generation.call(
       # Singapore, US (Virginia), and China (Beijing) API keys are not interchangeable. Get your API key: https://www.alibabacloud.com/help/model-studio/get-api-key
       # If the environment variable is not configured, replace with: api_key = "sk-xxx"
       api_key=os.getenv("DASHSCOPE_API_KEY"),
       model="qwen-plus",
       messages=messages,
       result_format="message"
)

if response.status_code == 200:
       print(response.output.choices[0].message.content)
else:
       print(f"HTTP status code: {response.status_code}")
       print(f"Error code: {response.code}")
       print(f"Error message: {response.message}")
       print("See: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code")
  1. Run python hello_qwen.py or python3 hello_qwen.py from the command line.

Note

The command in this example must be executed from the directory containing the Python file. To run it from elsewhere, specify the full path.

The output is:

plaintext
I am a large-scale language model from Alibaba Cloud. My name is Qwen.

Step 1: Set up your Node.js environment

Check your Node.js installation

Check whether Node.js and npm are installed:

shell
node -v
npm -v

For example, on Windows Command Prompt:

This prints your current Node.js version. If Node.js is not installed, download it from the Node.js official website.

Install the model calling SDK

Run this command in your terminal:

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

Note

If installation fails, configure a registry mirror:

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

After configuring the mirror, rerun the SDK installation command.

Look for added xx package in xxs to confirm installation. Check version: npm list openai.

Step 2: Call the model API

  1. Create a file named hello_qwen.mjs.

  2. Copy this code into the file.

nodejs
import OpenAI from "openai";

try {
       const openai = new OpenAI(
           {
               // If the environment variable is not configured, replace with: apiKey: "sk-xxx"
               apiKey: process.env.DASHSCOPE_API_KEY,
               // The following URL is for the Singapore region. When calling, replace WorkspaceId with your actual workspace ID. URLs vary by region.
               baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
           }
       );
       const completion = await openai.chat.completions.create({
           model: "qwen-plus",
           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("See: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code");
}
  1. Run this command to send an API request.
shell
node hello_qwen.mjs

Note

  • Run this command from the directory containing hello_qwen.mjs. To run it from any location, specify the full path to the file.

  • Ensure the SDK is installed in the same directory as hello_qwen.mjs. If they are in different directories, you will see Cannot find package 'openai' imported from xxx.

After successful execution, the output is:

plaintext
I am a language model from Alibaba Cloud. My name is Qwen.

Step 1: Set up your Java environment

Check your Java version

Run this command in your terminal:

bash
java -version
# (Optional) If you use Maven to manage and build Java projects, ensure Maven is installed
mvn --version

For example, on Windows Command Prompt:

Java 8 or later is required for the DashScope Java SDK. For example, openjdk version "16.0.1" 2021-04-20 means Java 16. If Java is not installed or the version is below Java 8, download and install it from Java downloads.

Install the model calling SDK

Install the DashScope Java SDK. For the latest version, see DashScope Java SDK. Add this dependency, replacing the-latest-version with the latest version number.

XML

Gradle

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

  2. Add this dependency to the <dependencies> tag:

xml
<dependency>
       <groupId>com.alibaba</groupId>
       <artifactId>dashscope-sdk-java</artifactId>
       
       <version>the-latest-version</version>
</dependency>
  1. Save the pom.xml file.

  2. Run a Maven command such as mvn compile or mvn clean install to update dependencies. Maven will automatically download and add the DashScope Java SDK to your project.

For example, in IntelliJ IDEA on Windows:

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

  2. Add this dependency to the dependencies block:

gradle
dependencies {
       // 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'
}
  1. Save the build.gradle file.

  2. In your terminal, navigate to your project root directory and run this Gradle command to update dependencies. It will automatically download and add the DashScope Java SDK to your project.

shell
./gradlew build --refresh-dependencies

For example, in IntelliJ IDEA on Windows:

Step 2: Call the API

Run this code to call the model API.

java
import java.util.Arrays;
import java.lang.System;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.protocol.Protocol;
public class Main {
    public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
        // The following URL is for the Singapore region. When calling, replace WorkspaceId with your actual workspace ID. URLs vary by region.
        Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content("You are a helpful assistant.")
                .build();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content("Who are you?")
                .build();
        GenerationParam param = GenerationParam.builder()
                // Singapore, US (Virginia), and China (Beijing) API keys are not interchangeable. Get your API key: https://www.alibabacloud.com/help/model-studio/get-api-key
                // If the environment variable is not configured, replace with: .apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // Model list: https://www.alibabacloud.com/help/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("See: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

The output is:

plaintext
I am a large-scale language model developed by Alibaba Cloud. My name is Qwen.

Call models on Model Studio using OpenAI-compatible or DashScope HTTP endpoints. For supported models, see Model list.

Note

If DASHSCOPE_API_KEY is not set, replace -H "Authorization: Bearer $DASHSCOPE_API_KEY" with -H "Authorization: Bearer sk-xxx".

OpenAI-compatible HTTP

DashScope HTTP

The URL in this example uses the Singapore region, replace WorkspaceId with your actual workspace ID. URLs vary by region. If you use the China (Beijing) region, replace the URL with https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions.

Send the API request:

Windows

Run this command in Command Prompt:

curl
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\": \"qwen-plus\",
    \"messages\": [\
        {\
            \"role\": \"system\",\
            \"content\": \"You are a helpful assistant.\"\
        },\
        {\
            \"role\": \"user\",\
            \"content\": \"Who are you?\"\
        }\
    ]
}"

Linux and macOS

Run this command in Terminal:

curl
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": "qwen-plus",
    "messages": [\
        {\
            "role": "system",\
            "content": "You are a helpful assistant."\
        },\
        {\
            "role": "user",\
            "content": "Who are you?"\
        }\
    ]
}'

After sending the API request, you receive this response:

json
{
    "choices": [\
        {\
            "message": {\
                "role": "assistant",\
                "content": "I am a large-scale language model from Alibaba Cloud. My name is 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"
}

The URL in this example uses the Singapore region, replace WorkspaceId with your actual workspace ID. URLs vary by region.

  • If you use the US (Virginia) region, replace the URL with https://dashscope-us.aliyuncs.com/api/v1/services/aigc/text-generation/generation.

  • If you use the China (Beijing) region, replace the URL with https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation.

Send the API request:

Windows

Run this command in Command Prompt:

curl
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\": \"qwen-plus\",
  \"input\": {
    \"messages\": [\
      {\
        \"role\": \"system\",\
        \"content\": \"You are a helpful assistant.\"\
      },\
      {\
        \"role\": \"user\",\
        \"content\": \"Who are you?\"\
      }\
    ]
  },
  \"parameters\": {
    \"result_format\": \"message\"
  }
}"

Linux and macOS

Run this command in Terminal:

curl
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": "qwen-plus",
    "input":{
        "messages":[\
            {\
                "role": "system",\
                "content": "You are a helpful assistant."\
            },\
            {\
                "role": "user",\
                "content": "Who are you?"\
            }\
        ]
    },
    "parameters": {
        "result_format":"message"
    }
}'

After sending the API request, you receive this response:

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

Call the model API

Go

PHP

C#

Go

go
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{}
	// Build the request body
	requestBody := RequestBody{
		// Model list: https://www.alibabacloud.com/help/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)
	}
	// The following URL is for the Singapore region. When calling, replace WorkspaceId with your actual workspace ID. URLs vary by region.
	req, err := http.NewRequest("POST", "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions", bytes.NewBuffer(jsonData))
	if err != nil {
		log.Fatal(err)
	}
	// Set request headers
	// Singapore, US (Virginia), and China (Beijing) API keys are not interchangeable. Get your API key: https://www.alibabacloud.com/help/model-studio/get-api-key
	// If the environment variable is not configured, replace with: 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 response
	fmt.Printf("%s\n", bodyText)
}

PHP

php
<?php
// The following URL is for the Singapore region. When calling, replace WorkspaceId with your actual workspace ID. URLs vary by region.
$url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions';
// Singapore, US (Virginia), and China (Beijing) API keys are not interchangeable. Get your API key: https://www.alibabacloud.com/help/model-studio/get-api-key
// If the environment variable is not configured, replace with: $apiKey = "sk-xxx"
$apiKey = getenv('DASHSCOPE_API_KEY');
// Set request headers
$headers = [\
    'Authorization: Bearer '.$apiKey,\
    'Content-Type: application/json'\
];
// Set 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 for errors
if (curl_errno($ch)) {
    echo 'Curl error: ' . curl_error($ch);
}
// Close the cURL resource
curl_close($ch);
// Output the response
echo $response;
?>

C#

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

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

    static async Task Main(string[] args)
    {
        // Singapore, US (Virginia), and China (Beijing) API keys are not interchangeable. Get your API key: https://www.alibabacloud.com/help/model-studio/get-api-key
        // If the environment variable is not configured, replace with: string? apiKey = "sk-xxx"
        string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");

        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("API Key not set. Make sure the 'DASHSCOPE_API_KEY' environment variable is set.");
            return;
        }
        // The following URL is for the Singapore region. When calling, replace WorkspaceId with your actual workspace ID. URLs vary by region.
        string url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions";
        // Model list: https://www.alibabacloud.com/help/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 get 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 get the response
            HttpResponseMessage response = await httpClient.PostAsync(url, content);

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

API reference

  • For the input and output parameters, see Qwen API reference.

  • For other models, see Model list.

FAQ

How do I fix theModel.AccessDenied error after calling the model API?

A: This error occurs because you are using an API key from a sub-workspace. A sub-workspace cannot access applications or models in the default workspace. To use a sub-workspace API key, the root account administrator must grant model authorization for the corresponding sub-workspace (for example, this topic uses the Qwen-Plus model). For detailed steps, see Configure model calling permissions.

Next steps

Explore more modelsThe example code uses qwen-plus. Model Studio also supports other Qwen models. See the Model list for supported models and their API references.
Learn advanced featuresThe example code covers basic Q&A only. To learn more about the Qwen API, such as streaming output, structured output, and function calling, see the Text generation model overview.
Try models in the browserIf you want to interact with models through a dialog box, like on Qwen Chat, go to the Playground (Singapore, US (Virginia), China (Beijing), China (Hong Kong), or Germany (Frankfurt)).

Previous: Product introductionNext: Recommended models

Is this page helpful?

Account setup

Set your API key as an environment variable

Choose a development language

API reference

FAQ

How do I fix the Model.AccessDenied error after calling the model API?

Next steps

Contact Us

Sales Support

Live-chat with our sales team or get in touch with a business development professional in your region.

Contact Sales

Technical Support

Open a ticket and get quick help from our technical team.

Open a Ticket >

Connect & Report Abuse

We look forward to your suggestion.

Post a Suggestion > Report Abuse >

\ \ Hi, I'm Alibaba Cloud AI Assistant!\ \ I can help with questions and solutions.

Why Alibaba Cloud

About Alibaba Cloud

Asia Accelerator

Our Global Network

Global Offices

Trust Center

Case Studies

Analyst Reports

Products & Pricings

Pricing Calculator

ECS

SAS

Model Studio

Database

Security

SMS

Solutions

Financial Services

Retail Services

Media Services

Gaming Services

ISV Solutions

Engage

Developer Community

Partner Network

Startups

Marketplace

Join Alibaba Cloud

Resources & Support

Developer Learning Hub

Documentation Center

Training & Certification

Service Notices

Submit a Ticket

Security Report

Qwen Cloud

Careers About Us Privacy Policy Legal Integrity Compliance Reporting Channel Service Notices Links

© 2009-2026 Copyright by Alibaba Cloud All rights reserved

© 2009-2026 Copyright by Alibaba Cloud All rights reserved

Careers About Us Privacy Policy Legal Integrity Compliance Reporting Channel Service Notices Links