You can integrate Alibaba Cloud Model Studio agent applications into your business systems using the DashScope SDK (a unified API for Alibaba Cloud model services) or HTTP requests.
Prerequisites
Before you begin, complete the following three steps to set up your development environment.
Obtain credentials
API key: Go to the API Key Management page and create and obtain an API key.
Alibaba Cloud Model Studio application ID: Go to the Application Management page, create an agent application, and copy its APP_ID from the application card.
Install the DashScope SDK
Skip this step if you use HTTP APIs.
Select and run the installation command for your programming language.
Python
Run the following command to install or upgrade the DashScope Python SDK:
# Install the SDK in your Python 3 environment python3 -m pip install -U dashscopeJava
Run the following command to add the Java SDK dependency. Replace
the-latest-versionwith the latest version number. For the latest version number, visit the DashScope Java SDK page.XML
Run the following command to add the Java SDK dependency.
1. Add the dependency
Add the following content to the
pom.xmlfile under the<dependencies>section:<dependency> <groupId>com.alibaba</groupId> <artifactId>dashscope-sdk-java</artifactId> <!-- Replace 'the-latest-version' with the latest version number: https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java --> <version>the-latest-version</version> </dependency>2. Update the project
Save the
pom.xmlfile. Your IDE (such as IntelliJ IDEA or Eclipse) usually detects the change automatically and prompts you to reload Maven dependencies.If no prompt appears, you can do one of the following:
Manually reload or update the Maven project in your IDE.
Alternatively, run the following command in the project root directory:
mvn clean install.
Gradle
Add the dependency
In your
build.gradlefile, add the following dependency to thedependenciesblock: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' }
Synchronize the project
Save the
build.gradlefile. Your IDE (such as IntelliJ IDEA) usually displays an icon. Click it to synchronize the Gradle project.Alternatively, you can force a dependency refresh from the command line in the project root directory:
./gradlew build --refresh-dependencies
Configure environment variables (recommended)
To protect your credentials and avoid hard-coding them in your code, we recommend that you configure the API key as an environment variable. The SDK reads the API key from this variable automatically.
Quick start
Python
Sample request
import os
from http import HTTPStatus
from dashscope import Application
response = Application.call(
# If environment variables are not configured, you can replace the following line with api_key="sk-xxx". However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID',# Replace with the actual application ID
prompt='Who are you?')
if response.status_code != HTTPStatus.OK:
print(f'request_id={response.request_id}')
print(f'code={response.status_code}')
print(f'message={response.message}')
print(f'Refer to: https://help.aliyun.com/en/model-studio/developer-reference/error-code')
else:
print(response.output.text)Sample response
I am a large language model developed by Alibaba Cloud, named Qwen. I am designed to help users generate various types of text, such as articles, stories, poems, stories, etc., and can be adjusted and optimized according to different scenarios and needs. In addition, I can also answer various questions, provide information and explanations, and assist in learning and research. If you have any needs, please feel free to ask me questions at any time!
Java
Sample request
// Recommended dashscope SDK version >= 2.12.0
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
public class Main {
public static void appCall()
throws ApiException, NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// If environment variables are not configured, you can replace the following line with .apiKey("sk-xxx"). However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("YOUR_APP_ID")
.prompt("Who are you?")
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("text: %s\n",
result.getOutput().getText());
}
public static void main(String[] args) {
try {
appCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("message: "+e.getMessage());
System.out.println("Refer to: https://help.aliyun.com/en/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}Sample response
text: I am a large language model developed by Alibaba Cloud, named Qwen.
HTTP
curl
Sample request
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "Who are you?"
},
"parameters": {},
"debug": {}
}' Replace YOUR_APP_ID with the actual application ID.
Sample response
{"output":{"finish_reason":"stop",
"session_id":"232ea2e9e6ef448db6b14465c06a9a56",
"text":"I am a super-large-scale language model developed by Alibaba Cloud, and my name is Qwen. I am an AI assistant who can answer questions, create text, express opinions, and even write code. If you have any questions or need assistance, please don't hesitate to let me know, and I will do my best to provide you with the help you need."},
"usage":{"models":[{"output_tokens":51,"model_id":"qwen-max","input_tokens":121}]},
"request_id":"661c9cad-e59c-9f78-a262-78eff243f151"}%
PHP
Sample request
<?php
# If the environment variable is not configured, you can replace the following line with your API Key: $api_key="sk-xxx". However, it is not recommended to hardcode the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Replace with your actual application ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
// Construct request data
$data = [
"input" => [
'prompt' => 'Who are you?'
]
];
// Encode data as JSON
$dataString = json_encode($data);
// Check if json_encode was successful
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize curl session
$ch = curl_init($url);
// Set curl options
curl_setopt($ch, curlOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, curlOPT_POSTFIELDS, $dataString);
curl_setopt($ch, curlOPT_RETURNTRANSFER, true);
curl_setopt($ch, curlOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// Execute the request
$response = curl_exec($ch);
// Check if curl execution was successful
if ($response === false) {
die("curl Error: " . curl_error($ch));
}
// Get HTTP status code
$status_code = curl_getinfo($ch, curlINFO_HTTP_CODE);
// Close curl session
curl_close($ch);
// Decode response data
$response_data = json_decode($response, true);
// Handle response
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
}}
else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";}
else {
echo "message=Unknown error\n";}
}
?>Sample response
I am a super-large-scale language model developed by Alibaba Cloud, and my name is Qwen.
Node.js
Dependency:
npm install axios
Sample request
const axios = require('axios');
async function callDashScope() {
// If environment variables are not configured, you can replace the following line with apiKey='sk-xxx'. However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// Replace with the actual application ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "Who are you?"
},
parameters: {},
debug: {}
};
try {
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
console.log(`${response.data.output.text}`);
} else {
console.log(`request_id=${response.headers['request_id']}`);
console.log(`code=${response.status}`);
console.log(`message=${response.data.message}`);
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();Sample response
I am a large-scale language model developed by Alibaba Cloud, and my name is Qwen.
C#
Sample request
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
//If environment variables are not configured, you can replace the following line with apiKey="sk-xxx". However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "YOUR_APP_ID"; // Replace with the actual application ID
string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string jsonContent = @"{
""input"": {
""prompt"": ""Who are you?""
},
""parameters"": {},
""debug"": {}
}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Request successful:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}Sample response
{
"output": {
"finish_reason": "stop",
"session_id": "c274e14a58d9492f9baeffdc003a97c5",
"text": "I am a super-large-scale language model developed by Alibaba Cloud, and my name is Qwen. I am designed to assist users in generating various types of text, such as articles, stories, poems, etc., and can adapt and innovate according to different scenarios and needs. Additionally, I am capable of answering a wide range of questions, providing information and explanations, and helping users solve problems and acquire knowledge. If you have any questions or need assistance, please feel free to let me know anytime!"
},
"usage": {
"models": [
{
"output_tokens": 79,
"model_id": "qwen-plus",
"input_tokens": 74
}
]
},
"request_id": "5c4b86b1-cd2d-9847-8d00-3fba8f187bc6"
}
Go
Sample request
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If environment variables are not configured, you can replace the following line with apiKey := "sk-xxx". However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // Replace with the actual application ID
if apiKey == "" {
fmt.Println("Please ensure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create request body
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "Who are you?",
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// Create HTTP POST request
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// Set request headers
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
// Read response
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// Process response
if resp.StatusCode == http.StatusOK {
fmt.Println("Request successful:")
fmt.Println(string(body))
} else {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
Sample response
{
"output": {
"finish_reason": "stop",
"session_id": "6105c965c31b40958a43dc93c28c7a59",
"text": "I am Qwen, an AI assistant developed by Alibaba Cloud. I am designed to answer various questions, provide information, and engage in conversations with users. Is there anything I can help you with?"
},
"usage": {
"models": [
{
"output_tokens": 36,
"model_id": "qwen-plus",
"input_tokens": 74
}
]
},
"request_id": "f97ee37d-0f9c-9b93-b6bf-bd263a232bf9"
}
Core features
Multi-turn conversation
Unlike single-turn conversations, multi-turn conversations enable large language models to reference historical information, resulting in more natural and realistic interactions.
Cloud storage | Self-managed |
When you pass the | You must maintain a |
Required parameters:
| Required parameter: Optional parameter:
|
Priority rule: If both | |
Cloud storage
Python
Request example
import os
from http import HTTPStatus
from dashscope import Application
def call_with_session():
response = Application.call(
# If you do not configure environment variables, replace the following line with api_key="sk-xxx". However, we do not recommend hard-coding the API key in production code to reduce the risk of exposure.
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID', # Replace with your actual application ID
prompt='Who are you?')
if response.status_code != HTTPStatus.OK:
print(f'request_id={response.request_id}')
print(f'code={response.status_code}')
print(f'message={response.message}')
print(f'For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-code')
return response
responseNext = Application.call(
# If you do not configure environment variables, replace the following line with api_key="sk-xxx". However, we do not recommend hard-coding the API key in production code to reduce the risk of exposure.
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID', # Replace with your actual application ID
prompt='What skills do you have?',
session_id=response.output.session_id) # Use the session_id from the previous response
if responseNext.status_code != HTTPStatus.OK:
print(f'request_id={responseNext.request_id}')
print(f'code={responseNext.status_code}')
print(f'message={responseNext.message}')
print(f'For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-code')
else:
print('%s\n session_id=%s\n' % (responseNext.output.text, responseNext.output.session_id))
# print('%s\n' % (response.usage))
if __name__ == '__main__':
call_with_session()Response example
I have many skills to help you complete various tasks. Here are some of my main skills:
1. **Information retrieval**: Provide weather, news, historical facts, scientific knowledge, and more.
2. **Language processing**: Translate text, correct grammar errors, and generate articles and stories.
3. **Technical problem solving**: Answer programming, software usage, and technical troubleshooting questions.
4. **Learning support**: Help with math, physics, chemistry, and other subjects.
5. **Life advice**: Offer suggestions on health, diet, travel, shopping, and more.
6. **Entertainment interaction**: Tell jokes, play word games, and engage in casual chats.
7. **Schedule management**: Remind you of important dates, schedule events, and set reminders.
8. **Data analysis**: Explain charts and provide data analysis suggestions.
9. **Emotional support**: Listen to your feelings and provide comfort and support.
If you have specific needs or questions, just tell me, and I will do my best to help you!
session_id=98ceb3ca0c4e4b05a20a00f913050b42Java
Request example
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void callWithSession()
throws ApiException, NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// If you do not configure environment variables, replace the following line with .apiKey("sk-xxx"). However, we do not recommend hard-coding the API key in production code to reduce the risk of exposure.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// Replace with your actual application ID
.appId("YOUR_APP_ID")
.prompt("Who are you?")
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
param.setSessionId(result.getOutput().getSessionId());
param.setPrompt("What skills do you have?");
result = application.call(param);
System.out.printf("%s\n session_id: %s\n",
result.getOutput().getText(), result.getOutput().getSessionId());
}
public static void main(String[] args) {
try {
callWithSession();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}Response example
I have many skills to help you. Here are some of my main skills:
1. **Multilingual understanding and generation**: I can understand and generate text in multiple languages, including Chinese and English.
2. **Information retrieval and synthesis**: I can search for relevant information based on your questions and organize and summarize it.
3. **Writing assistance**: Whether writing articles, reports, or creative content, I can provide support.
4. **Programming assistant**: For programmers, I can help answer programming-related questions and provide code examples.
5. **Education tutoring**: When you encounter difficulties during learning, I can act as an assistant to help you, covering subjects from math to history.
6. **Life advice**: I can also provide suggestions on topics like healthy eating and travel planning.
7. **Emotional communication**: Although I am an AI, I strive to communicate warmly and supportively.
If you have any specific needs or want to learn more about a particular topic, feel free to ask!HTTP
curl
Request example (first turn)
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "Who are you?"
},
"parameters": {},
"debug": {}
}' Response example
{
"output": {
"finish_reason": "stop",
"session_id": "4f8ef7233dc641aba496cb201fa59f8c",
"text": "I am Tongyi Qwen, an AI assistant developed by Alibaba Cloud. I am designed to answer questions, provide information, and engage in conversations with users. Is there anything I can help you with?"
},
"usage": {
"models": [
{
"output_tokens": 36,
"model_id": "qwen-plus",
"input_tokens": 75
}
]
},
"request_id": "e571b14a-423f-9278-8d1e-d86c418801e0"
}Request example (second turn)
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "What skills do you have?",
"session_id":"4f8ef7233dc641aba496cb201fa59f8c"
},
"parameters": {},
"debug": {}
}' Response example
{
"output": {
"finish_reason": "stop",
"session_id": "4f8ef7233dc641aba496cb201fa59f8c",
"text": "As an AI assistant, I have many skills to help you complete various tasks, including but not limited to:
1. **Knowledge retrieval**: I can help you find information on various topics, such as science, history, culture, and technology.
2. **Language translation**: I can translate text between different languages.
3. **Text generation**: I can generate articles, stories, poems, news articles, and more.
4. **Question answering**: I can answer academic, general knowledge, and technical questions.
5. **Conversational interaction**: I can hold natural, fluent conversations and provide emotional support or entertainment.
6. **Code writing and debugging**: I can help you write code and resolve programming issues.
7. **Data analysis**: I can help analyze data and provide statistical results and visualization suggestions.
8. **Creative inspiration**: I can provide creative ideas for design, advertising copy, marketing strategies, and more.
If you have any specific needs or questions, feel free to ask!"
},
"usage": {
"models": [
{
"output_tokens": 208,
"model_id": "qwen-plus",
"input_tokens": 125
}
]
},
"request_id": "9de2c3ed-e1f0-9963-85f4-8f289203418b"
}PHP
Request example (first turn)
<?php
# If you do not configure environment variables, replace the following line with $api_key="sk-xxx". However, we do not recommend hard-coding the API key in production code to reduce the risk of exposure.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Replace with your actual application ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
// Construct request data
$data = [
"input" => [
'prompt' => 'Who are you?'
]
];
// Encode data as JSON
$dataString = json_encode($data);
// Check if json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize cURL session
$ch = curl_init($url);
// Set cURL options
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// Execute request
$response = curl_exec($ch);
// Check if cURL execution succeeded
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// Get HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close cURL session
curl_close($ch);
// Decode response data
$response_data = json_decode($response, true);
// Process response
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
};
if (isset($response_data['output']['session_id'])) {
echo "session_id={$response_data['output']['session_id']}\n";
}
}else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";}
else {
echo "message=Unknown error\n";
}
}
?>Response example
I am a large-scale language model developed by Alibaba Cloud, and my name is Tongyi Qwen.
session_id=2e658bcb514f4d30ab7500b4766a8d43Request example (second turn)
<?php
# If you do not configure environment variables, replace the following line with $api_key="sk-xxx". However, we do not recommend hard-coding the API key in production code to reduce the risk of exposure.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Replace with your actual application ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
// Construct request data
$data = [
"input" => [
'prompt' => 'What skills do you have?',
// Replace with the session_id returned in the first response
'session_id' => '2e658bcb514f4d30ab7500b4766a8d43'
]
];
// Encode data as JSON
$dataString = json_encode($data);
// Check if json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize cURL session
$ch = curl_init($url);
// Set cURL options
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// Execute request
$response = curl_exec($ch);
// Check if cURL execution succeeded
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// Get HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close cURL session
curl_close($ch);
// Decode response data
$response_data = json_decode($response, true);
// Process response
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
};
if (isset($response_data['output']['session_id'])) {
echo "session_id={$response_data['output']['session_id']}\n";
}
}else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";}
else {
echo "message=Unknown error\n";
}
}
?>Response example
I have many skills, including but not limited to:
1. **Multilingual capability**: I can understand and generate text in multiple languages.
2. **Writing and creation**: I can help you write articles, stories, poems, and other creative content.
3. **Knowledge Q&A**: I can answer common-sense and professional questions across various fields.
4. **Code writing and understanding**: I can write simple programs and help explain or debug code.
5. **Logical reasoning**: I can solve logic-based problems and puzzles.
6. **Emotional support**: I can provide positive psychological support and encouragement.
7. **Game and entertainment**: I can participate in word games or other forms of interactive entertainment.
My goal is to be your helpful assistant and support you whenever needed. If you have any specific needs or want to try a feature, feel free to tell me!
session_id=2e658bcb514f4d30ab7500b4766a8d43Node.js
Install the required dependencies:
npm install axiosRequest example (previous conversation)
const axios = require('axios');
async function callDashScope() {
// If you do not configure environment variables, replace the following line with apiKey='sk-xxx'. However, we do not recommend hard-coding the API key in production code to reduce the risk of exposure.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// Replace with your actual application ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "Who are you?"
},
parameters: {},
debug: {}
};
try {
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
console.log(`${response.data.output.text}`);
console.log(`session_id=${response.data.output.session_id}`);
} else {
console.log(`request_id=${response.headers['request_id']}`);
console.log(`code=${response.status}`);
console.log(`message=${response.data.message}`);
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();Response example
I am Tongyi Qwen, an AI assistant developed by Alibaba Cloud. I can answer questions, provide information, and interact with users. Is there anything I can help you with?
session_id=fe4ce8b093bf46159ea9927a7b22f0d3Request example (second turn)
const axios = require('axios');
async function callDashScope() {
// If you do not configure environment variables, replace the following line with apiKey='sk-xxx'. However, we do not recommend hard-coding the API key in production code to reduce the risk of exposure.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// Replace with your actual application ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
// Replace session_id with the session_id from the previous turn
const data = {
input: {
prompt: "What skills do you have?",
session_id: 'fe4ce8b093bf46159ea9927a7b22f0d3',
},
parameters: {},
debug: {}
};
try {
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
console.log(`${response.data.output.text}`);
console.log(`session_id=${response.data.output.session_id}`);
} else {
console.log(`request_id=${response.headers['request_id']}`);
console.log(`code=${response.status}`);
console.log(`message=${response.data.message}`);
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();Response example
I have a variety of skills to help you with different tasks and problems. Here are some of my main skill areas:
1. **Information Query and Retrieval**: I can help you find specific information, data, or news.
2. **Writing and Creation**: This includes writing articles, stories, poems, reports, and more.
3. **Language Translation**: I can provide translation services between different languages.
4. **Educational Tutoring**: I can answer academic questions and help you understand complex concepts.
5. **Technical Support**: I can solve technical difficulties you encounter while using a computer.
6. **Life Advice**: I can offer advice on subjects such as health, diet, and travel.
7. **Entertainment and Interaction**: This includes telling jokes, playing word games, and other fun activities.
If you have a specific need or want to learn more about a particular area, please let me know!
session_id=fe4ce8b093bf46159ea9927a7b22f0d3C#
Request example (first turn)
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// If you have not configured the environment variable, replace the following line with your Model Studio API key: apiKey="sk-xxx". However, we do not recommend hard coding the API key directly into your code in a production environment to reduce the risk of API key exposure.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "YOUR_APP_ID"; // Replace with your actual application ID
string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string jsonContent = @"{
""input"": {
""prompt"": ""Who are you?""
},
""parameters"": {},
""debug"": {}
}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Request successful:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}Response example
{
"output": {
"finish_reason": "stop",
"session_id": "7b830e4cc8fe44faad0e648f9b71435f",
"text": "I am Qwen, an AI assistant developed by Alibaba Cloud. I am designed to answer various questions, provide information, and engage in conversations with users. Is there anything I can do for you?"
},
"usage": {
"models": [
{
"output_tokens": 36,
"model_id": "qwen-plus",
"input_tokens": 75
}
]
},
"request_id": "53691ae5-be17-96c6-a830-8f0f92329028"
}Request example (second turn)
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// If you do not configure environment variables, replace the following line with apiKey="sk-xxx". However, we do not recommend hard-coding the API key in production code to reduce the risk of exposure.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "YOUR_APP_ID"; // Replace with your actual application ID
string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string jsonContent = @"{
""input"": {
""prompt"": ""What skills do you have?"",
""session_id"": ""7b830e4cc8fe44faad0e648f9b71435f""
},
""parameters"": {},
""debug"": {}
}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Request successful:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}Response example
{
"output": {
"finish_reason": "stop",
"session_id": "7b830e4cc8fe44faad0e648f9b71435f",
"text": "I have many skills, including the following:
- Answering knowledge-based questions across a wide range of fields.
- Providing learning resources and suggestions.
- Assisting with technical issues.
- Engaging in multilingual communication.
- Helping plan itineraries and activities.
- Offering practical advice for daily life.
If you have any specific needs or questions, feel free to ask!"
},
"usage": {
"models": [
{
"output_tokens": 70,
"model_id": "qwen-plus",
"input_tokens": 123
}
]
},
"request_id": "da5044ed-461e-9e91-8ca5-38a3c72a8306"
}Go
Request Example (Previous Turn)
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If you do not configure environment variables, replace the following line with apiKey := "sk-xxx". However, we do not recommend hard-coding the API key in production code to reduce the risk of exposure.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // Replace with your actual application ID
if apiKey == "" {
fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create request body
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "Who are you?",
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// Create HTTP POST request
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// Set request headers
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
// Read response
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// Process response
if resp.StatusCode == http.StatusOK {
fmt.Println("Request successful:")
fmt.Println(string(body))
} else {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
Response example
{
"output": {
"finish_reason": "stop",
"session_id": "f7eea37f0c734c20998a021b688d6de2",
"text": "I am Tongyi Qwen, an AI assistant developed by Alibaba Cloud. I am designed to answer questions, provide information, and engage in conversations with users. Is there anything I can help you with?"
},
"usage": {
"models": [
{
"output_tokens": 36,
"model_id": "qwen-plus",
"input_tokens": 75
}
]
},
"request_id": "fa65e14a-ab63-95b2-aa43-035bf5c51835"
}Request example (second turn)
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If you have not configured an environment variable, you can replace the following line with your Model Studio API key: apiKey := "sk-xxx". However, we do not recommend hard coding your API key directly in the code in a production environment to reduce the risk of API key exposure.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // Replace with your actual application ID
if apiKey == "" {
fmt.Println("Make sure that DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create the request body
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "What skills do you have?",
"session_id": "f7eea37f0c734c20998a021b688d6de2", // Replace with the session_id from your actual previous conversation
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// Create an HTTP POST request
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// Configure request headers
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
// Read the response
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// Process the response
if resp.StatusCode == http.StatusOK {
fmt.Println("Request successful:")
fmt.Println(string(body))
} else {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
Response example
{
"output": {
"finish_reason": "stop",
"session_id": "f7eea37f0c734c20998a021b688d6de2",
"text": "I have multiple capabilities, including the following:\n\n- Answering knowledge-based questions in fields such as science, history, and culture.\n- Providing practical advice, such as travel tips, health tips, and study methods.\n- Assisting with writing and editing tasks, such as writing articles, editing documents, and creating stories or poems.\n- Performing multilingual translation between multiple languages.\n- Engaging in natural and fluent conversations to accompany users and answer their questions.\n\nIf you have any specific requirements, please let me know!"
},
"usage": {
"models": [
{
"output_tokens": 104,
"model_id": "qwen-plus",
"input_tokens": 125
}
]
},
"request_id": "badccade-9f54-986b-8d8c-75ef15e9616c"
}Replace YOUR_APP_ID with your actual application ID. In the next request, replace the session_id field value in the input parameters with the session_id value returned from the previous request.Self-managed
Python
Request example
# The DashScope software development kit (SDK) version must be 1.20.14 or later.
import os
from http import HTTPStatus
from dashscope import Application
messages = [
{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': 'Who are you?'},
{"role": "assistant","content": "I am a large language model developed by Alibaba Cloud. My name is Qwen."},
{"role": "user","content": "What can you do?"}
]
response = Application.call(
# If the environment variable is not configured, replace the following line with api_key="sk-xxx" and use your Model Studio API key. Do not hard-code the API key into your code in a production environment to reduce the risk of API key leakage.
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID', # Replace with your actual application ID.
messages=messages)
if response.status_code != HTTPStatus.OK:
print(f'request_id={response.request_id}')
print(f'code={response.status_code}')
print(f'message={response.message}')
print(f'For more information, see https://help.aliyun.com/document_detail/2541321.html')
else:
print('%s\n' % (response.output.text))Response example
As Qwen, I can help you with various tasks, including but not limited to:
1. Answering questions: I can provide accurate information and answers on topics ranging from scientific knowledge and technical challenges to general life questions.
2. Creating text: I can generate creative content such as stories, poems, and articles based on given conditions.
3. Programming assistant: I can assist with learning to code, explain code logic, and help debug program errors.
4. Language translation: I support translation services between multiple languages.
5. Providing suggestions: I can offer advice or solutions when you need to make a decision.
6. Emotional interaction: I can engage in conversations, listen, and provide positive responses and support.
In short, my goal is to be a capable assistant in your work and life. If you have any specific needs, feel free to let me know!Java
Request example
// The DashScope SDK version must be 2.17.0 or later.
import java.util.ArrayList;
import java.util.List;
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
public class Main {
public static void appCall()
throws ApiException, NoApiKeyException, InputRequiredException {
List<Message> messages = new ArrayList<>();
messages.add(Message.builder().role("system").content("You are a helpful assistant.").build());
messages.add(Message.builder().role("user").content("Who are you?").build());
messages.add(Message.builder().role("assistant").content("I am a large language model developed by Alibaba Cloud. My name is Qwen.").build());
messages.add(Message.builder().role("user").content("What can you do?").build());
ApplicationParam param = ApplicationParam.builder()
// If the environment variable is not configured, replace the following line with .apiKey("sk-xxx") and use your Model Studio API key. Do not hard-code the API key into your code in a production environment to reduce the risk of API key leakage.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("YOUR_APP_ID")
.messages(messages)
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("text: %s\n",
result.getOutput().getText());
}
public static void main(String[] args) {
try {
appCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("message: "+e.getMessage());
System.out.println("For more information, see https://help.aliyun.com/document_detail/2541321.html");
}
System.exit(0);
}
}Response example
text: I can help you with various tasks, including but not limited to:
1. Answering questions: I will do my best to provide accurate answers to academic questions, general knowledge inquiries, and questions in professional fields.
2. Creating text: I can write content such as stories, official documents, emails, and scripts. Just provide me with some basic information and requirements.
3. Table processing: I can help you organize data and create or modify tables.
4. Code writing: I support writing and explaining code in multiple programming languages.
5. Multilingual translation: I can translate between different languages.
6. Simulated conversations: I can play different roles to engage in simulated conversations with users.
If you have any specific needs, feel free to let me know!HTTP
curl
Request example
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"messages":[
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Who are you?"
},
{
"role": "assistant",
"content": "I am a large language model developed by Alibaba Cloud. My name is Qwen."
},
{
"role": "user",
"content": "What can you do?"
}
]
},
"parameters": {},
"debug": {}
}' Response example
{"output":
{"finish_reason":"stop","session_id":"990ca89d89794826976d7499ad10cddb",
"text":"I can help you with various tasks, including but not limited to:\n\n1. Answering questions: I will do my best to provide accurate answers to questions about academic knowledge, practical skills, or general common sense.\n2. Creating text: I can help you write content such as stories, official documents, emails, and scripts. Just tell me your specific requirements.\n3. Expressing opinions: For subjective questions, I can also offer my own views and discuss them with you.\n4. Games and entertainment: We can play text-based games together, or I can tell you a joke to help you relax.\n\nIn short, you can ask me for help with anything related to language!"},"usage":{"models":[{"output_tokens":126,"model_id":"qwen-max","input_tokens":86}]},"request_id":"3908c4a3-8d7a-9e51-81a5-0fc366582990"}% PHP
Request example
<?php
# If the environment variable is not configured, replace the following line with $api_key="sk-xxx" and use your Model Studio API key. Do not hard-code the API key into your code in a production environment to reduce the risk of API key leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Replace with your actual application ID.
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
// Construct the request data.
$data = [
"input" => [
"messages" => [
[
"role" => "system",
"content" => "You are a helpful assistant."
],
[
"role" => "user",
"content" => "Who are you?"
],
[
"role" => "assistant",
"content" => "I am a large language model developed by Alibaba Cloud. My name is Qwen."
],
[
"role" => "user",
"content" => "What can you do?"
]
]
]
];
// Encode the data as JSON.
$dataString = json_encode($data);
// Check if json_encode was successful.
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize a cURL session.
$ch = curl_init($url);
// Set cURL options.
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// Execute the request.
$response = curl_exec($ch);
// Check if the cURL execution was successful.
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// Get the HTTP status code.
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL session.
curl_close($ch);
// Decode the response data.
$response_data = json_decode($response, true);
// Handle the response.
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
}
} else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";
}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";
} else {
echo "message=Unknown error\n";
}
}
?>Response example
I can help you with various tasks, such as:
1. Answering questions: I will do my best to provide accurate answers to questions about academic topics, practical knowledge, or entertainment trivia.
2. Creating text: This includes, but is not limited to, writing stories, official documents, and emails.
3. Providing suggestions: I can offer guidance and advice on topics such as travel recommendations, learning methods, and career planning.
4. Engaging in conversation: We can chat, share feelings, and even have interesting discussions.
If you need help with anything, just let me know!Node.js
Install the required dependency:
npm install axiosRequest example
const axios = require('axios');
async function callDashScope() {
// If the environment variable is not configured, replace the following line with apiKey='sk-xxx' and use your Model Studio API key. Do not hard-code the API key into your code in a production environment to reduce the risk of API key leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// Replace with your actual application ID.
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
"input": {
"messages":[
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Who are you?"
},
{
"role": "assistant",
"content": "I am a large language model developed by Alibaba Cloud. My name is Qwen."
},
{
"role": "user",
"content": "What can you do?"
}
]
},
parameters: {},
debug: {}
};
try {
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
console.log(`${response.data.output.text}`);
} else {
console.log(`request_id=${response.headers['request_id']}`);
console.log(`code=${response.status}`);
console.log(`message=${response.data.message}`);
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();Response example
I can help you with various tasks, including but not limited to:
1. Answering questions: I will do my best to provide accurate answers to questions about academic knowledge, practical information, or general common sense.
2. Creating text: I can help you write content such as stories, official documents, emails, and scripts, as long as you provide enough background information and requirements.
3. Providing suggestions: If you need advice on certain decisions, such as choosing a travel destination, selecting a gift, or finding learning methods, I can offer suggestions based on your description.
4. Language translation: I support text translation between multiple languages.
5. Code writing and explanation: For programming-related questions, I can help write simple programs or explain complex concepts.
6. Engaging in conversation: In addition to the functions above, I can also engage in daily conversations with users to share ideas.
If you have any specific needs, feel free to let me know!C#
Request example
using System.Text;
class Program
{
static async Task Main(string[] args)
{
// If the environment variable is not configured, replace the following line with apiKey="sk-xxx" and use your Model Studio API key. Do not hard-code the API key into your code in a production environment to reduce the risk of API key leakage.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
string appId = "YOUR_APP_ID";// Replace with your actual application ID.
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("Make sure that the DASHSCOPE_API_KEY is set.");
return;
}
string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string jsonContent = $@"{{
""input"": {{
""messages"": [
{{
""role"": ""system"",
""content"": ""You are a helpful assistant.""
}},
{{
""role"": ""user"",
""content"": ""Who are you?""
}},
{{
""role"": ""assistant"",
""content"": ""I am a large language model developed by Alibaba Cloud. My name is Qwen.""
}},
{{
""role"": ""user"",
""content"": ""What can you do?""
}}
]
}},
""parameters"": {{}},
""debug"": {{}}
}}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}Response example
{
"output": {
"finish_reason": "stop",
"session_id": "a6d041ca3d084a7ca9eff1c456afad70",
"text": "As Qwen, I can help you with various tasks, including but not limited to:\n\n1. Answering questions: I provide answers to various knowledge-based questions.\n2. Text generation: I write text content such as articles, stories, and poems.\n3. Language translation: I perform translation work between different languages.\n4. Conversational exchange: I engage in natural and fluent conversations with users.\n5. Providing suggestions: I offer suggestions or solutions based on user needs.\n\nIf you have any specific requirements, please let me know, and I will do my best to assist you."
},
"usage": {
"models": [
{
"output_tokens": 102,
"model_id": "qwen-max",
"input_tokens": 87
}
]
},
"request_id": "27fb8a01-70d5-974f-bb0a-e9408a9c1772"
}Go
Request example
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If the environment variable is not configured, replace the following line with apiKey := "sk-xxx" and use your Model Studio API key. Do not hard-code the API key into your code in a production environment to reduce the risk of API key leakage.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // Replace with your actual application ID.
if apiKey == "" {
fmt.Println("Make sure that the DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create the request body.
requestBody := map[string]interface{}{
"input": map[string]interface{}{
"messages": []interface{}{
map[string]string{
"role": "system",
"content": "You are a helpful assistant.",
},
map[string]string{
"role": "user",
"content": "Who are you?",
},
map[string]string{
"role": "assistant",
"content": "I am a large language model developed by Alibaba Cloud. My name is Qwen.",
},
map[string]string{
"role": "user",
"content": "What can you do?",
},
},
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// Create an HTTP POST request.
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// Set the request headers.
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send the request.
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
// Read the response.
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// Handle the response.
if resp.StatusCode == http.StatusOK {
fmt.Println("Request successful:")
fmt.Println(string(body))
} else {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
Response example
{
"output": {
"finish_reason": "stop",
"session_id": "2ae51a5eac3b4b269834cf0695330a05",
"text": "I can help you with various tasks, including but not limited to:\n\n1. Answering questions: I provide answers to knowledge-based questions in various fields.\n2. Text creation: I write stories, articles, poems, and more.\n3. Programming assistant: I offer guidance and code examples for programming.\n4. Conversational chat: I engage in daily conversations and provide companionship.\n5. Translation services: I provide translation support between multiple languages.\n6. Information query: I can look up information such as news, weather forecasts, and historical data.\n7. Tutoring: I help answer questions and provide learning suggestions.\n\nIf you have any specific needs or questions, feel free to let me know, and I will do my best to help you!"
},
"usage": {
"models": [
{
"output_tokens": 132,
"model_id": "qwen-max",
"input_tokens": 87
}
]
},
"request_id": "1289eb09-e4ed-9f9e-98ca-805c83b333a1"
}Streaming output
A large language model receives input and generates intermediate results step by step. It outputs these results in real time. This approach is called streaming output. It lets you view content as the model generates it, which reduces wait time.
How to enable streaming output
Set the appropriate parameter based on your calling method:
Python SDK: Set the
streamparameter toTrue.Java SDK: Use the
streamCallmethod.HTTP: In the
Header, setX-DashScope-SSEtoenable.
By default, streaming output returns non-incremental content. Each response includes all content generated up to that point. To return incremental content, set the corresponding parameter:
Python SDK: Set the
incremental_outputparameter toTrue.Java SDK: Use the
incrementalOutputmethod and set it totrue.HTTP: In the
parametersobject, use theincremental_outputparameter and set it totrue.
Example call
If your agent application uses a deep thinking model such as Qwen3, the output order is “think first, then answer.” Set the has_thoughts parameter to True to return the thinking process in the thoughts field.
You can enable thinking mode for the Qwen3 model in two ways. First, turn on the Thinking mode toggle in your application and publish the application. Second, set
enable_thinkingtotruein your API call. If both are set, the API parameter takes precedence.Other thinking models enable thinking mode by default. You cannot disable it.
Python
Request example
import os
from http import HTTPStatus
from dashscope import Application
responses = Application.call(
# If you have not configured an environment variable, replace the next line with your DashScope API key: api_key="sk-xxx". Do not hard-code your API key in production code to reduce the risk of exposure.
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID',
prompt='Who are you?',
stream=True, # Enable streaming output
incremental_output=True) # Enable incremental output
for response in responses:
if response.status_code != HTTPStatus.OK:
print(f'request_id={response.request_id}')
print(f'code={response.status_code}')
print(f'message={response.message}')
print(f'For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-code')
else:
print(f'{response.output.text}\n') # Process only the text fieldResponse example
I am a large language model from Alibaba Cloud. My name is Qwen.Java
Request example
// We recommend using DashScope SDK version 2.15.0 or later.
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.reactivex.Flowable;// Streaming output
// Call an agent application to get streaming output
public class Main {
public static void streamCall() throws NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// If you have not configured an environment variable, replace the next line with your DashScope API key: .apiKey("sk-xxx"). Do not hard-code your API key in production code to reduce the risk of exposure.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// Replace with your actual application ID
.appId("YOUR_APP_ID")
.prompt("Who are you?")
// Enable incremental output
.incrementalOutput(true)
.build();
Application application = new Application();
// .streamCall(): Return streaming output
Flowable<ApplicationResult> result = application.streamCall(param);
result.blockingForEach(data -> {
System.out.printf("%s\n",
data.getOutput().getText());
});
}
public static void main(String[] args) {
try {
streamCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}Response example
I am a super-large-scale language model developed by Alibaba Cloud. My name is Qwen.HTTP
curl
Request example
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--header 'X-DashScope-SSE: enable' \
--data '{
"input": {
"prompt": "Who are you?"
},
"parameters": {
"incremental_output":true
},
"debug": {}
}'Replace YOUR_APP_ID with your actual application ID.
Response example
id:1
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"I am"},"usage":{"models":[{"input_tokens":203,"output_tokens":1,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}
id:2
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"from"},"usage":{"models":[{"input_tokens":203,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}
id:3
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"Alibaba"},"usage":{"models":[{"input_tokens":203,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}
id:4
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"Cloud"},"usage":{"models":[{"input_tokens":203,"output_tokens":4,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}
id:5
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"a super-large-scale language"},"usage":{"models":[{"input_tokens":203,"output_tokens":8,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}
id:6
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"model. My name is"},"usage":{"models":[{"input_tokens":203,"output_tokens":12,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}
id:7
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"Qwen"},"usage":{"models":[{"input_tokens":203,"output_tokens":16,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}
id:8
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"."},"usage":{"models":[{"input_tokens":203,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}
id:9
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":203,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}PHP
Request example
<?php
// If you have not configured an environment variable, replace the next line with your DashScope API key: $api_key="sk-xxx". Do not hard-code your API key in production code to reduce the risk of exposure.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Replace with your actual application ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
// Build the request payload
$data = [
"input" => [
'prompt' => 'Who are you?'],
"parameters" => [
'incremental_output' => true]];// Enable incremental output
// Encode the payload as JSON
$dataString = json_encode($data);
// Check if json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize cURL
$ch = curl_init($url);
// Set cURL options
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); // Do not return the transfer data
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $string) {
echo $string; // Process streaming data
return strlen($string);
});
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key,
'X-DashScope-SSE: enable' // Enable streaming output
]);
// Execute the request
$response = curl_exec($ch);
// Check if cURL execution succeeded
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// Get the HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL handle
curl_close($ch);
if ($status_code != 200) {
echo "HTTP Status Code: $status_code\n";
echo "Request Failed.\n";
}
?>Response example
id:1
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":"I am Alibaba"},"usage":{"models":[{"input_tokens":58,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"}
id:2
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":"Cloud"},"usage":{"models":[{"input_tokens":58,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"}
id:3
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":"developed"},"usage":{"models":[{"input_tokens":58,"output_tokens":4,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"}
id:4
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":"a super-large-scale language"},"usage":{"models":[{"input_tokens":58,"output_tokens":8,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"}
id:5
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":"model. My name is"},"usage":{"models":[{"input_tokens":58,"output_tokens":12,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"}
id:6
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":"Qwen"},"usage":{"models":[{"input_tokens":58,"output_tokens":16,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"}
id:7
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":"."},"usage":{"models":[{"input_tokens":58,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"}
id:8
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":58,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"}
Node.js
Install required dependencies:
npm install axiosRequest example
Expand the collapsible panel to view details:
Response example
1. Output full response
id:1
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"null","text":"Hello!"},"usage":{"models":[{"input_tokens":56,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"}
id:2
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"null","text":"How can"},"usage":{"models":[{"input_tokens":56,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"}
id:3
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"null","text":"I help"},"usage":{"models":[{"input_tokens":56,"output_tokens":4,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"}
id:4
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"null","text":"you?"},"usage":{"models":[{"input_tokens":56,"output_tokens":7,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"}
id:5
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":56,"output_tokens":7,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"}2. Output only the text field
I am a super-large-scale language model developed by Alibaba Cloud. My name is Qwen.C#
Request example
using System.Net;
using System.Text;
class Program
{
static async Task Main(string[] args)
{
// If you have not configured an environment variable, replace the next line with your DashScope API key: apiKey="sk-xxx". Do not hard-code your API key in production code to reduce the risk of exposure.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "YOUR_APP_ID"; // Replace with your actual application ID
string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
client.DefaultRequestHeaders.Add("X-DashScope-SSE", "enable");
string jsonContent = @"{
""input"": {
""prompt"": ""Who are you?""
},
""parameters"": {""incremental_output"": true},
""debug"": {}
}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
try
{
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Content = content;
HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Request successful:");
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
using (var stream = await response.Content.ReadAsStreamAsync())
using (var reader = new StreamReader(stream))
{
string? line; // Declare as nullable string
while ((line = await reader.ReadLineAsync()) != null)
{
if (line.StartsWith("data:"))
{
string data = line.Substring(5).Trim();
Console.WriteLine(data);
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
}
}
}
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}Response example
2025-02-14 16:22:08:482
Request successful:
2025-02-14 16:22:09:098
{"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"I am"},"usage":{"models":[{"input_tokens":51,"output_tokens":1,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
2025-02-14 16:22:09:099
{"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"from"},"usage":{"models":[{"input_tokens":51,"output_tokens":2,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
2025-02-14 16:22:09:172
{"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"Alibaba"},"usage":{"models":[{"input_tokens":51,"output_tokens":3,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
2025-02-14 16:22:09:172
{"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"Cloud's large language"},"usage":{"models":[{"input_tokens":51,"output_tokens":7,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
2025-02-14 16:22:09:463
{"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"model. My name is"},"usage":{"models":[{"input_tokens":51,"output_tokens":11,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
2025-02-14 16:22:09:618
{"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"Qwen"},"usage":{"models":[{"input_tokens":51,"output_tokens":15,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
2025-02-14 16:22:09:777
{"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":". I am your AI assistant,"},"usage":{"models":[{"input_tokens":51,"output_tokens":19,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
2025-02-14 16:22:09:932
{"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"and I can answer questions, create text,"},"usage":{"models":[{"input_tokens":51,"output_tokens":23,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
2025-02-14 16:22:10:091
{"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"such as writing stories, official documents,"},"usage":{"models":[{"input_tokens":51,"output_tokens":27,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
2025-02-14 16:22:10:244
{"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"emails, and scripts,"},"usage":{"models":[{"input_tokens":51,"output_tokens":31,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
2025-02-14 16:22:10:389
{"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"express opinions, play games, and more."},"usage":{"models":[{"input_tokens":51,"output_tokens":35,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
2025-02-14 16:22:10:525
{"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"."},"usage":{"models":[{"input_tokens":51,"output_tokens":39,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
2025-02-14 16:22:10:662
{"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":51,"output_tokens":39,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
2025-02-14 16:22:10:902Go
Request example
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
)
func main() {
// If you have not configured an environment variable, replace the next line with your DashScope API key: apiKey := "sk-xxx". Do not hard-code your API key in production code to reduce the risk of exposure.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // Replace with your actual application ID
if apiKey == "" {
fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Build the request body. Set incremental_output to enable streaming.
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "Who are you?",
},
"parameters": map[string]interface{}{
"incremental_output": true,
},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// Create an HTTP POST request
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// Set request headers. Set X-DashScope-SSE to enable streaming.
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-DashScope-SSE", "enable")
// Send the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
return
}
// Process streaming response
reader := io.Reader(resp.Body)
buf := make([]byte, 1024)
for {
n, err := reader.Read(buf)
if n > 0 {
data := string(buf[:n])
lines := strings.Split(data, "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if len(line) >= 5 && line[:5] == "data:" {
timestamp := time.Now().Format("2006-01-02 15:04:05.000")
fmt.Printf("%s: %s\n", timestamp, line[5:])
} else if len(line) > 0 {
fmt.Println(line)
}
}
}
if err != nil {
if err == io.EOF {
break
}
fmt.Printf("Error reading response: %v\n", err)
break
}
}
}
Response example
id:1
event:result
:HTTP_STATUS/200
2025-02-13 18:21:09.050: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":"I am"},"usage":{"models":[{"input_tokens":262,"output_tokens":1,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
id:2
event:result
:HTTP_STATUS/200
2025-02-13 18:21:10.016: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":"Q"},"usage":{"models":[{"input_tokens":262,"output_tokens":2,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
id:3
event:result
:HTTP_STATUS/200
2025-02-13 18:21:10.016: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":"w"},"usage":{"models":[{"input_tokens":262,"output_tokens":3,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
id:4
event:result
:HTTP_STATUS/200
2025-02-13 18:21:10.016: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":"en, an AI assistant"},"usage":{"models":[{"input_tokens":262,"output_tokens":7,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
id:5
event:result
:HTTP_STATUS/200
2025-02-13 18:21:10.017: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" developed by Alibaba Cloud"},"usage":{"models":[{"input_tokens":262,"output_tokens":11,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
id:6
event:result
:HTTP_STATUS/200
2025-02-13 18:21:10.017: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":". I"},"usage":{"models":[{"input_tokens":262,"output_tokens":15,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
id:7
event:result
:HTTP_STATUS/200
2025-02-13 18:21:10.017: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" am designed to answer"},"usage":{"models":[{"input_tokens":262,"output_tokens":19,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
id:8
event:result
:HTTP_STATUS/200
2025-02-13 18:21:10.018: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" various questions, provide"},"usage":{"models":[{"input_tokens":262,"output_tokens":23,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
id:9
event:result
:HTTP_STATUS/200
2025-02-13 18:21:10.102: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" information, and"},"usage":{"models":[{"input_tokens":262,"output_tokens":27,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
id:10
event:result
:HTTP_STATUS/200
2025-02-13 18:21:10.257: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" converse with users. Do you"},"usage":{"models":[{"input_tokens":262,"output_tokens":31,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
id:11
event:result
:HTTP_STATUS/200
2025-02-13 18:21:10.414: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" need help?"},"usage":{"models":[{"input_tokens":262,"output_tokens":34,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
id:12
event:result
:HTTP_STATUS/200
2025-02-13 18:21:10.481: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":262,"output_tokens":34,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}Pass custom parameters
Agents can adapt to various business scenarios using custom prompt variables to guide output, plugin parameters to extend capabilities, and user-level authentication parameters for access control. When you make a call, use the biz_params parameter to pass these custom parameters for flexible responses.
Description | Instructions |
Type: Passes custom prompt variables. Use this to pass variables that are inserted into the prompt. You can define the variables in the console and pass their specific values during the API call. Example: Prompt: Please recommend three local dishes for {{city}}. Display only the dish names, separated by commas. Parameters: Effective prompt: Please recommend three local dishes for Beijing. Display only the dish names, separated by commas. | In the console, perform the following steps:
Important Ensure that the custom variable name added in the application matches the name passed in the API call. |
Type: Passes custom plugin parameters. Use this to pass business data, such as a city or date, that the plugin needs to execute its task. | In the console, perform the following steps:
|
user_defined_tokens Type: Passes custom user-level authentication parameters for a plugin. This parameter is used for user identity verification when calling a plugin, such as a |
The following are API call examples:
Prompt variables
Steps
In the console, add a custom variable to the agent application, reference it in the prompt, and then publish the application. Example:

Make an API call. The following are examples:
Python
Sample request
from http import HTTPStatus import os # We recommend using DashScope SDK version 1.14.0 or later. from dashscope import Application biz_params = { # Custom variable parameters for the agent application. Replace them with your actual parameters. You can pass multiple key-value pairs separated by commas. "user_prompt_params":{ "city": "Beijing"}} response = Application.call( # If you have not configured an environment variable, you can replace the next line with api_key="sk-xxx" and use your Model Studio API key. However, we do not recommend hard coding the API key into your code in a production environment. This helps reduce the risk of API key leaks. api_key=os.getenv("DASHSCOPE_API_KEY"), app_id='YOUR_APP_ID', # Replace this with your actual application ID, which you can find on the application card. prompt='food recommendations', biz_params=biz_params) if response.status_code != HTTPStatus.OK: print(f'request_id={response.request_id}') print(f'code={response.status_code}') print(f'message={response.message}') print(f'For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-code') else: print('%s\n' % (response.output.text)) # Process the text-only output # print('%s\n' % (response.usage))Sample response
Peking Duck, Zhajiangmian, DouzhiJava
Sample request
import com.alibaba.dashscope.app.*; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.exception.InputRequiredException; import com.alibaba.dashscope.exception.NoApiKeyException; import com.alibaba.dashscope.utils.JsonUtils; public class Main { public static void appCall() throws NoApiKeyException, InputRequiredException { String bizParams = // Pass custom variable parameters for the agent application. Replace them with your actual variable parameters. You can pass multiple key-value pairs separated by commas. "{\"user_prompt_params\":{\"city\":\"Beijing\"}}"; ApplicationParam param = ApplicationParam.builder() // If you have not configured an environment variable, you can replace the next line with .apiKey("sk-xxx") and use your Model Studio API key. However, we do not recommend hard coding the API key into your code in a production environment. This helps reduce the risk of API key leaks. .apiKey(System.getenv("DASHSCOPE_API_KEY")) .appId("YOUR_APP_ID") // Replace this with your actual application ID, which you can find on the application card. .prompt("food recommendations") .bizParams(JsonUtils.parse(bizParams)) .build(); Application application = new Application(); ApplicationResult result = application.call(param); System.out.printf("%s\n", result.getOutput().getText()); } public static void main(String[] args) { try { appCall(); } catch (ApiException | NoApiKeyException | InputRequiredException e) { System.out.printf("Exception: %s", e.getMessage()); System.out.println("For more information, see https://help.aliyun.com/en/model-studio/error-code"); } System.exit(0); } }Sample response
Peking Duck, Zhajiangmian, DouzhiHTTP
curl
Sample request
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \ --header "Authorization: Bearer $DASHSCOPE_API_KEY" \ --header 'Content-Type: application/json' \ --data '{ "input": { "prompt": "food recommendations", "biz_params": { "user_prompt_params":{"city": "Beijing"} } }, "parameters": {}, "debug":{} }'Replace YOUR_APP_ID with your actual application ID, which you can find on the application card.
The user_prompt_params parameter supports multiple custom key-value pairs separated by commas.
Sample response
{ "output": { "finish_reason": "stop", "session_id": "1ad91249a37148389ac042530002ec94", "text": "Peking Duck, Zhajiangmian, Douzhi" }, "usage": { "models": [ { "output_tokens": 11, "model_id": "qwen-turbo", "input_tokens": 78 } ] }, "request_id": "4fd714e5-dc35-9933-98f4-0ed314918c1f" }PHP
Sample request
<?php # If you have not configured an environment variable, you can replace the next line with $api_key="sk-xxx" and use your Model Studio API key. However, we do not recommend hard coding the API key into your code in a production environment. This helps reduce the risk of API key leaks. $api_key = getenv("DASHSCOPE_API_KEY"); $application_id = 'YOUR_APP_ID'; // Replace this with your actual application ID. $url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion"; // The user_prompt_params parameter supports multiple custom key-value pairs separated by commas. // Construct the request data $data = [ "input" => [ 'prompt' => 'food recommendations', 'biz_params' => [ 'user_prompt_params' => [ 'city' => "Beijing" ] ] ], ]; // Encode the data in JSON format $dataString = json_encode($data); // Check if json_encode was successful if (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg()); } // Initialize the cURL session $ch = curl_init($url); // Set the cURL options curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key ]); // Execute the request $response = curl_exec($ch); // Check if the cURL execution was successful if ($response === false) { die("cURL Error: " . curl_error($ch)); } // Get the HTTP status code $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Close the cURL session curl_close($ch); // Decode the response data $response_data = json_decode($response, true); // Process the response if ($status_code == 200) { if (isset($response_data['output']['text'])) { echo "{$response_data['output']['text']}\n"; } else { echo "No text in response.\n"; } }else { if (isset($response_data['request_id'])) { echo "request_id={$response_data['request_id']}\n";} echo "code={$status_code}\n"; if (isset($response_data['message'])) { echo "message={$response_data['message']}\n";} else { echo "message=Unknown error\n";} } ?>Sample response
Peking Duck, Zhajiangmian, DouzhiNode.js
Install the following dependency:
npm install axiosSample request
const axios = require('axios'); async function callDashScope() { // If you have not configured an environment variable, you can replace the next line with apiKey='sk-xxx' and use your Model Studio API key. However, we do not recommend hard coding the API key into your code in a production environment. This helps reduce the risk of API key leaks. const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID';// Replace this with your actual application ID. const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`; // The user_prompt_params parameter supports multiple custom key-value pairs separated by commas. const data = { input: { prompt: "food recommendations", biz_params: { user_prompt_params: { 'city': 'Beijing' } } }, parameters: {}, debug: {} }; try { console.log("Sending request to DashScope API..."); const response = await axios.post(url, data, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' } }); if (response.status === 200) { if (response.data.output && response.data.output.text) { console.log(`${response.data.output.text}`); } } else { console.log("Request failed:"); if (response.data.request_id) { console.log(`request_id=${response.data.request_id}`); } console.log(`code=${response.status}`); if (response.data.message) { console.log(`message=${response.data.message}`); } else { console.log('message=Unknown error'); } } } catch (error) { console.error(`Error calling DashScope: ${error.message}`); if (error.response) { console.error(`Response status: ${error.response.status}`); console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();Sample response
Peking Duck, Zhajiangmian, DouzhiC#
Sample request
using System.Text; class Program { static async Task Main(string[] args) { // If you have not configured an environment variable, you can replace the next line with apiKey="sk-xxx" and use your Model Studio API key. However, we do not recommend hard coding the API key into your code in a production environment. This helps reduce the risk of API key leaks. string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");; string appId = "YOUR_APP_ID";// Replace this with your actual application ID. // The user_prompt_params parameter supports multiple custom key-value pairs separated by commas. if (string.IsNullOrEmpty(apiKey)) { Console.WriteLine("Make sure that the DASHSCOPE_API_KEY is set."); return; } string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); string jsonContent = $@"{{ ""input"": {{ ""prompt"": ""food recommendations"", ""biz_params"": {{ ""user_prompt_params"": {{ ""city"": ""Beijing"" }} }} }}, ""parameters"": {{}}, ""debug"": {{}} }}"; HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await client.PostAsync(url, content); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine("Request successful:"); Console.WriteLine(responseBody); } else { Console.WriteLine($"Request failed with status code: {response.StatusCode}"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch (Exception ex) { Console.WriteLine($"Error calling DashScope: {ex.Message}"); } } } }Sample response
{ "output": { "finish_reason": "stop", "session_id": "de5b3942acce40ba8739338518c01b9e", "text": "Peking Duck, Zhajiangmian, Douzhi" }, "usage": { "models": [ { "output_tokens": 11, "model_id": "qwen-turbo", "input_tokens": 78 } ] }, "request_id": "86f89865-b851-9d5f-b96d-181d8d402f85" }Go
Sample request
package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // If you have not configured an environment variable, you can replace the next line with apiKey := "sk-xxx" and use your Model Studio API key. However, we do not recommend hard coding the API key into your code in a production environment. This helps reduce the risk of API key leaks. apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // Replace this with your actual application ID. if apiKey == "" { fmt.Println("Make sure that the DASHSCOPE_API_KEY is set.") return } url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId) // Create the request body. The user_prompt_params parameter supports multiple custom key-value pairs separated by commas. requestBody := map[string]interface{}{ "input": map[string]interface{}{ "prompt": "food recommendations", "biz_params": map[string]interface{}{ "user_prompt_params": map[string]interface{}{ "city": "Beijing", }, }, }, "parameters": map[string]interface{}{}, "debug": map[string]interface{}{}, } jsonData, err := json.Marshal(requestBody) if err != nil { fmt.Printf("Failed to marshal JSON: %v\n", err) return } // Create an HTTP POST request. req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Failed to create request: %v\n", err) return } // Set the request headers. req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") // Send the request. client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("Failed to send request: %v\n", err) return } defer resp.Body.Close() // Read the response. body, err := io.ReadAll(resp.Body) if err != nil { fmt.Printf("Failed to read response: %v\n", err) return } // Process the response. if resp.StatusCode == http.StatusOK { fmt.Println("Request successful:") fmt.Println(string(body)) } else { fmt.Printf("Request failed with status code: %d\n", resp.StatusCode) fmt.Println(string(body)) } }Sample response
{ "output": { "finish_reason": "stop", "session_id": "26daaa1561ba482c8248502db55df3d3", "text": "Peking Duck, Zhajiangmian, Douzhi" }, "usage": { "models": [ { "output_tokens": 11, "model_id": "qwen-turbo", "input_tokens": 78 } ] }, "request_id": "405ab32b-9277-9408-ac1f-711845d334ce" }
Plugin business parameters
This section uses the Dormitory Rules Query Tool as an example of passing plugin parameters through an API. It shows how to query dormitory rules by passing the index of the associated plugin (the article_index parameter).
<YOUR_TOOL_ID> with the ID of the associated plugin, which you can find on the plugin card. Pass the key-value pairs for the input parameters configured in the plugin. In this example, the parameter is article_index and its value is 2.Python
Sample request
import os
from http import HTTPStatus
# We recommend using DashScope SDK version 1.14.0 or later.
from dashscope import Application
biz_params = {
# Pass custom input parameters for the agent application's plugin. Replace <YOUR_TOOL_ID> with your custom plugin ID.
"user_defined_params": {
"<YOUR_TOOL_ID>": {
"article_index": 2}}}
response = Application.call(
# If you have not configured an environment variable, you can replace the next line with api_key="sk-xxx" and use your Model Studio API key. However, we do not recommend hard coding the API key into your code in a production environment. This helps reduce the risk of API key leaks.
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID',
prompt='dormitory rules content',
biz_params=biz_params)
if response.status_code != HTTPStatus.OK:
print(f'request_id={response.request_id}')
print(f'code={response.status_code}')
print(f'message={response.message}')
print(f'For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-code')
else:
print('%s\n' % (response.output.text)) # Process the text-only output
# print('%s\n' % (response.usage))Sample response
Article 2 of the dormitory rules is as follows:
"Dormitory members should help, care for, and learn from each other to improve together. They should be tolerant, humble, respectful, and treat each other with sincerity."
This means that members should foster a positive living and learning atmosphere in the dormitory by helping and supporting each other, while also learning to understand and respect others. To know about other articles of the rules, please let me know!Java
Sample request
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
public class Main {
public static void appCall() throws NoApiKeyException, InputRequiredException {
String bizParams =
// Pass custom input parameters for the agent application's plugin. Replace <YOUR_TOOL_ID> with your custom plugin ID.
"{\"user_defined_params\":{\"<YOUR_TOOL_ID>\":{\"article_index\":2}}}";
ApplicationParam param = ApplicationParam.builder()
// If you have not configured an environment variable, you can replace the next line with .apiKey("sk-xxx") and use your Model Studio API key. However, we do not recommend hard coding the API key into your code in a production environment. This helps reduce the risk of API key leaks.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("YOUR_APP_ID")
.prompt("dormitory rules content")
.bizParams(JsonUtils.parse(bizParams))
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("%s\n",
result.getOutput().getText());
}
public static void main(String[] args) {
try {
appCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-code");
}
System.exit(0);
}
} Sample response
Article 2 of the dormitory rules is as follows:
Article 2: Dormitory members should help, care for, and learn from each other to improve together. They should be tolerant, humble, respectful, and treat each other with sincerity.
This rule emphasizes that roommates should maintain positive relationships in a shared living environment and create a harmonious atmosphere for living and studying through mutual help and support. To know more specific articles, please let me know.HTTP
curl
Sample request
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "dormitory rules content",
"biz_params":
{
"user_defined_params":
{
"<YOUR_TOOL_ID>":
{
"article_index": 2
}
}
}
},
"parameters": {},
"debug":{}
}'Replace YOUR_APP_ID with your application ID. Replace <YOUR_TOOL_ID> with your plugin ID.
Sample response
{"output":
{"finish_reason":"stop",
"session_id":"e151267ffded4fbdb13d91439011d31e",
"text":"Article 2 of the dormitory rules states: \"Dormitory members should help, care for, and learn from each other to improve together. They should be tolerant, humble, respectful, and treat each other with sincerity.\" This means that in dormitory life, everyone should support each other to create a harmonious and positive living environment."},
"usage":{"models":[{"output_tokens":94,"model_id":"qwen-max","input_tokens":453}]},
"request_id":"a39fd2b5-7e2c-983e-84a1-1039f726f18a"}%PHP
Sample request
<?php
# If you have not configured an environment variable, you can replace the next line with $api_key="sk-xxx" and use your Model Studio API key. However, we do not recommend hard coding the API key into your code in a production environment. This helps reduce the risk of API key leaks.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Replace this with your actual application ID.
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
// Replace <YOUR_TOOL_ID> with the actual plugin ID.
// Construct the request data
$data = [
"input" => [
'prompt' => 'dormitory rules content',
'biz_params' => [
'user_defined_params' => [
'<YOUR_TOOL_ID>' => [
'article_index' => 2
]
]
]
],
];
// Encode the data in JSON format
$dataString = json_encode($data);
// Check if json_encode was successful
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize the cURL session
$ch = curl_init($url);
// Set the cURL options
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// Execute the request
$response = curl_exec($ch);
// Check if the cURL execution was successful
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// Get the HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL session
curl_close($ch);
// Decode the response data
$response_data = json_decode($response, true);
// Process the response
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
}
}else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";}
else {
echo "message=Unknown error\n";}
}
?>Sample response
Article 2 of the dormitory rules states: Dormitory members should help, care for, and learn from each other to improve together. They should be tolerant, humble, respectful, and treat each other with sincerity. This is to ensure that everyone can live and study in a harmonious and friendly environment. To know more specific articles or have other questions, feel free to ask me at any time!Node.js
Install the following dependency:
npm install axiosSample request
const axios = require('axios');
async function callDashScope() {
// If you have not configured an environment variable, you can replace the next line with apiKey='sk-xxx' and use your Model Studio API key. However, we do not recommend hard coding the API key into your code in a production environment. This helps reduce the risk of API key leaks.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// Replace this with your actual application ID.
const pluginCode = 'YOUR_TOOL_ID';// Replace this with your actual plugin ID.
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "dormitory rules content",
biz_params: {
user_defined_params: {
[pluginCode]: {
// article_index is a variable of the custom plugin. Replace it with your actual plugin variable.
'article_index': 3
}
}
}
},
parameters: {},
debug: {}
};
try {
console.log("Sending request to DashScope API...");
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
if (response.data.output && response.data.output.text) {
console.log(`${response.data.output.text}`);
}
} else {
console.log("Request failed:");
if (response.data.request_id) {
console.log(`request_id=${response.data.request_id}`);
}
console.log(`code=${response.status}`);
if (response.data.message) {
console.log(`message=${response.data.message}`);
} else {
console.log('message=Unknown error');
}
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
Sample response
Article 3 of the dormitory rules is as follows:
Pay attention to electrical safety and prevent fire hazards. The use of open flames, unauthorized electrical appliances, various stoves, and other prohibited items is strictly forbidden in the dormitory. Do not store explosive or flammable items, or privately connect to power sources.
To know more rules, please let me know.C#
Sample request
using System.Text;
class Program
{
static async Task Main(string[] args)
{
// If you have not configured an environment variable, you can replace the next line with apiKey="sk-xxx" and use your Model Studio API key. However, we do not recommend hard coding the API key into your code in a production environment. This helps reduce the risk of API key leaks.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
string appId = "YOUR_APP_ID";// Replace this with your actual application ID.
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("Make sure that the DASHSCOPE_API_KEY is set.");
return;
}
string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string pluginCode = "YOUR_TOOL_ID"; // Replace YOUR_TOOL_ID with the actual plugin ID.
string jsonContent = $@"{{
""input"": {{
""prompt"": ""dormitory rules content"",
""biz_params"": {{
""user_defined_params"": {{
""{pluginCode}"": {{
""article_index"": 2
}}
}}
}}
}},
""parameters"": {{}},
""debug"": {{}}
}}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Request successful:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}Sample response
{
"output": {
"finish_reason": "stop",
"session_id": "237ca6187c814f3b9e7461090a5f8b74",
"text": "Article 2 of the dormitory rules is as follows:\n\n\"Dormitory members should help, care for, and learn from each other to improve together. They should be tolerant, humble, respectful, and treat each other with sincerity.\"\n\nThis means that in the dormitory, members need to establish a positive relationship by helping, caring for, and supporting each other to create a harmonious living and learning environment. They should also learn to understand and accept differences between roommates and communicate with a sincere attitude. If you want to know about other articles or specific content, please let me know!"
},
"usage": {
"models": [
{
"output_tokens": 133,
"model_id": "qwen-max",
"input_tokens": 829
}
]
},
"request_id": "64e8c359-d071-9d2e-bb94-187e86cc3a79"
}Go
Sample request
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If you have not configured an environment variable, you can replace the next line with apiKey := "sk-xxx" and use your Model Studio API key. However, we do not recommend hard coding the API key into your code in a production environment. This helps reduce the risk of API key leaks.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // Replace this with your actual application ID.
pluginCode := "YOUR_TOOL_ID" // Replace this with your actual plugin ID.
if apiKey == "" {
fmt.Println("Make sure that the DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create the request body.
requestBody := map[string]interface{}{
"input": map[string]interface{}{
"prompt": "dormitory rules content",
"biz_params": map[string]interface{}{
"user_defined_params": map[string]interface{}{
pluginCode: map[string]interface{}{
"article_index": 2,
},
},
},
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// Create an HTTP POST request.
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// Set the request headers.
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send the request.
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
// Read the response.
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// Process the response.
if resp.StatusCode == http.StatusOK {
fmt.Println("Request successful:")
fmt.Println(string(body))
} else {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
Sample response
{
"output": {
"finish_reason": "stop",
"session_id": "860d2a4c1f3649ac880298537993cb51",
"text": "Article 2 of the dormitory rules is as follows:\n\nDormitory members should help, care for, and learn from each other to improve together. They should be tolerant, humble, respectful, and treat each other with sincerity.\n\nThis rule emphasizes that roommates should maintain a good, mutually supportive relationship and respect each other in dormitory life. Do you want to know the content of other articles?"
},
"usage": {
"models": [
{
"output_tokens": 84,
"model_id": "qwen-max",
"input_tokens": 876
}
]
},
"request_id": "0a250055-90a4-992d-9276-e268ad35d1ab"
}Plugin user-level authentication parameters
This section uses the Dormitory Rules Query Tool as an example of passing plugin parameters through an API. It shows how to query dormitory rules by passing the index of the associated plugin (the article_index parameter) and user-level authentication information.
<YOUR_TOOL_ID> with the ID of the associated plugin, which you can find on the plugin card. Pass the key-value pairs for the input parameters configured in the plugin. In this example, the parameter is article_index and its value is 2.Python
Sample request
from http import HTTPStatus
import os
# We recommend using DashScope SDK version 1.14.0 or later.
from dashscope import Application
biz_params = {
# Pass custom authentication for the agent application's plugin. Replace <YOUR_TOOL_ID> with your custom plugin ID and replace YOUR_TOKEN with the authentication information, such as an API key.
"user_defined_params": {
"<YOUR_TOOL_ID>": {
"article_index": 2}},
"user_defined_tokens": {
"<YOUR_TOOL_ID>": {
"user_token": "YOUR_TOKEN"}}}
response = Application.call(
# If you have not configured an environment variable, you can replace the next line with api_key="sk-xxx" and use your Model Studio API key. However, we do not recommend hard coding the API key into your code in a production environment. This helps reduce the risk of API key leaks.
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID',
prompt='dormitory rules content',
biz_params=biz_params)
if response.status_code != HTTPStatus.OK:
print(f'request_id={response.request_id}')
print(f'code={response.status_code}')
print(f'message={response.message}')
print(f'For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-code')
else:
print('%s\n' % (response.output.text)) # Process the text-only output
# print('%s\n' % (response.usage))Sample response
Article 2 of the dormitory rules is as follows:
Dormitory members should help, care for, and learn from each other to improve together. They should be tolerant, humble, respectful, and treat each other with sincerity.
To know more about the rules, please let me know.Java
Sample request
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
public class Main {
public static void appCall() throws NoApiKeyException, InputRequiredException {
String bizParams =
// Replace <YOUR_TOOL_ID> with the actual plugin ID and replace YOUR_TOKEN with the actual token, such as an API key.
"{\"user_defined_params\":{\"<YOUR_TOOL_ID>\":{\"article_index\":2}}," +
"\"user_defined_tokens\":{\"<YOUR_TOOL_ID>\":{\"user_token\":\"YOUR_TOKEN\"}}}";
ApplicationParam param = ApplicationParam.builder()
// If you have not configured an environment variable, you can replace the next line with .apiKey("sk-xxx") and use your Model Studio API key. However, we do not recommend hard coding the API key into your code in a production environment. This helps reduce the risk of API key leaks.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("YOUR_APP_ID")
.prompt("dormitory rules content")
.bizParams(JsonUtils.parse(bizParams))
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("%s\n",
result.getOutput().getText());
}
public static void main(String[] args) {
try {
appCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}Sample response
Article 2 of the dormitory rules is as follows:
Dormitory members should help, care for, and learn from each other to improve together. They should be tolerant, humble, respectful, and treat each other with sincerity.
To query more rules, please let me know.HTTP
curl
Sample request
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "dormitory rules content",
"biz_params":
{
"user_defined_params":
{
"<YOUR_TOOL_ID>":
{
"article_index": 2
}
},
"user_defined_tokens":
{
"<YOUR_TOOL_ID>":
{
"user_token": "YOUR_TOKEN"
}
}
}
},
"parameters": {},
"debug":{}
}'
Replace YOUR_APP_ID with your actual application ID. Replace <YOUR_TOOL_ID> with the actual plugin ID.
Sample response
{"output":{"finish_reason":"stop",
"session_id":"d3b5c3e269dc40479255a7a02df5c630",
"text":"Article 2 of the dormitory rules is: \"Dormitory members should help, care for, and learn from each other to improve together. They should be tolerant, humble, respectful, and treat each other with sincerity.\" This rule emphasizes the importance of harmonious coexistence and mutual progress among members in dormitory life."},
"usage":{"models":[{"output_tokens":80,"model_id":"qwen-max","input_tokens":432}]},
"request_id":"1f77154c-edc3-9003-b622-816fa2f849cf"}%PHP
Sample request
<?php
# If you have not configured an environment variable, you can replace the next line with $api_key="sk-xxx" and use your Model Studio API key. However, we do not recommend hard coding the API key into your code in a production environment. This helps reduce the risk of API key leaks.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Replace this with your actual application ID.
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
// Construct the request data
$data = [
"input" => [
'prompt' => 'dormitory rules content',
'biz_params' => [
'user_defined_params' => [
'<YOUR_TOOL_ID>' => [// Replace <YOUR_TOOL_ID> with the actual plugin ID.
'article_index' => 2
]
],
'user_defined_tokens' => [
'<YOUR_TOOL_ID>' => [// Replace <YOUR_TOOL_ID> with the actual plugin ID.
'user_token' => 'YOUR_TOKEN'// Replace this with the actual token, such as an API key.
]
]
]
],
];
// Encode the data in JSON format
$dataString = json_encode($data);
// Check if json_encode was successful
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize the cURL session
$ch = curl_init($url);
// Set the cURL options
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// Execute the request
$response = curl_exec($ch);
// Check if the cURL execution was successful
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// Get the HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL session
curl_close($ch);
// Decode the response data
$response_data = json_decode($response, true);
// Process the response
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
}
}else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";}
else {
echo "message=Unknown error\n";}
}
?>Sample response
Article 2 of the dormitory rules is as follows:
> Dormitory members should help, care for, and learn from each other to improve together. They should be tolerant, humble, respectful, and treat each other with sincerity.
To know more about the rules or other information, please let me know at any time!Node.js
You need to install the following dependency:
npm install axiosSample request
const axios = require('axios');
async function callDashScope() {
// If you have not configured an environment variable, you can replace the next line with apiKey='sk-xxx' and use your Model Studio API key. However, we do not recommend hard coding the API key into your code in a production environment. This helps reduce the risk of API key leaks.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// Replace this with your actual application ID.
const pluginCode = 'YOUR_TOOL_ID';// Replace this with your actual plugin ID.
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "dormitory rules content",
biz_params: {
user_defined_params: {
[pluginCode]: {
// article_index is a variable of the custom plugin. Replace it with your actual plugin variable.
'article_index': 6
}
},
user_defined_tokens: {
[pluginCode]: {
// Replace YOUR_TOKEN with the actual authentication information, such as an API key.
user_token: 'YOUR_TOKEN'
}
}
}
},
parameters: {},
debug: {}
};
try {
console.log("Sending request to DashScope API...");
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
if (response.data.output && response.data.output.text) {
console.log(`${response.data.output.text}`);
}
} else {
console.log("Request failed:");
if (response.data.request_id) {
console.log(`request_id=${response.data.request_id}`);
}
console.log(`code=${response.status}`);
if (response.data.message) {
console.log(`message=${response.data.message}`);
} else {
console.log('message=Unknown error');
}
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();Sample response
Article 6 of the dormitory rules states: Develop good daily routines. Every dormitory member has the right to rest and the obligation to ensure others can rest. To know more about the rules, please provide more details.C#
Sample request
using System.Text;
class Program
{
static async Task Main(string[] args)
{
// If you have not configured an environment variable, you can replace the next line with apiKey="sk-xxx" and use your Model Studio API key. However, we do not recommend hard coding the API key into your code in a production environment. This helps reduce the risk of API key leaks.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
string appId = "YOUR_APP_ID";// Replace this with your actual application ID.
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("Make sure that the DASHSCOPE_API_KEY is set.");
return;
}
string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string pluginCode = "YOUR_TOOL_ID"; // Replace this with the actual plugin ID.
// Replace YOUR_TOKEN with the actual token, such as an API key.
string jsonContent = $@"{{
""input"": {{
""prompt"": ""dormitory rules content"",
""biz_params"": {{
""user_defined_params"": {{
""{pluginCode}"": {{
""article_index"": 2
}}
}},
""user_defined_tokens"": {{
""{pluginCode}"": {{
""user_token"": ""YOUR_TOKEN""
}}
}}
}}
}},
""parameters"": {{}},
""debug"": {{}}
}}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Request successful:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}Sample response
{
"output": {
"finish_reason": "stop",
"session_id": "1a1913a9922a401f8eba36df8ea1a062",
"text": "Article 2 of the dormitory rules is as follows:\n\nDormitory members should help, care for, and learn from each other to improve together. They should be tolerant, humble, respectful, and treat each other with sincerity.\n\nFor more detailed information about the rules, please specify."
},
"usage": {
"models": [
{
"output_tokens": 66,
"model_id": "qwen-max",
"input_tokens": 802
}
]
},
"request_id": "04bac806-c5e6-9fab-a846-a66641862be9"
}Go
Sample request
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If you have not configured an environment variable, you can replace the next line with apiKey := "sk-xxx" and use your Model Studio API key. However, we do not recommend hard coding the API key into your code in a production environment. This helps reduce the risk of API key leaks.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // Replace this with your actual application ID.
pluginCode := "YOUR_TOOL_ID" // Replace this with your actual plugin ID.
if apiKey == "" {
fmt.Println("Make sure that the DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create the request body.
requestBody := map[string]interface{}{
"input": map[string]interface{}{
"prompt": "dormitory rules content",
"biz_params": map[string]interface{}{
"user_defined_params": map[string]interface{}{
pluginCode: map[string]interface{}{
"article_index": 10,
},
},
"user_defined_tokens": map[string]interface{}{
pluginCode: map[string]interface{}{
"user_token": "YOUR_USER_TOKEN", // Replace this with the actual authentication token, such as an API key.
},
},
},
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// Create an HTTP POST request.
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// Set the request headers.
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send the request.
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
// Read the response.
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// Process the response.
if resp.StatusCode == http.StatusOK {
fmt.Println("Request successful:")
fmt.Println(string(body))
} else {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
Sample response
{
"output": {
"finish_reason": "stop",
"session_id": "b8e051ba7e954ff8919208e7b84430fa",
"text": "Article 10 of the dormitory rules states that dormitory members should work together to create and maintain a clean, tidy, beautiful, and culturally refined dormitory environment. To understand the complete dormitory rules, you may need to check other articles or consult the dormitory management department directly. Is there any other specific content you would like to know?"
},
"usage": {
"models": [
{
"output_tokens": 70,
"model_id": "qwen-max",
"input_tokens": 855
}
]
},
"request_id": "0921ee34-2754-9616-a826-cea33a0e0a14"
}Advanced features
Retrieve from a knowledge base
The knowledge base feature powers Model Studio’s retrieval-augmented generation (RAG) capability. It helps large language models (LLMs) access private knowledge and stay up to date with the latest information. You can specify a retrieval scope when calling an agent application to improve response accuracy. For more information, see Create and use a knowledge base.
Prerequisites
In the Model Studio console, enable your agent application and turn on the knowledge base switch. Then, publish the application.
Specify a retrieval scope
You can retrieve from a specific knowledge base in three ways:
In your application, click Configure knowledge base to associate a specific knowledge base, and then publish the application.
Do not associate a knowledge base in your application. Instead, pass the knowledge base ID in the
rag_optionsparameter during the API call.Associate a knowledge base in your application and pass the knowledge base ID in the
rag_optionsparameter during the API call.In this case, only the knowledge base passed in the API call is used for retrieval. For example, if your web-based agent application is linked to Knowledge Base A, but your API call specifies only Knowledge Base B, then only Knowledge Base B is retrieved, not Knowledge Base A.
Obtain the knowledge base ID (pipeline_ids): You can find it on the Knowledge Base page. You can also obtain it from the
Data.Idfield in the response from the CreateIndex API call (for unstructured knowledge bases only).The knowledge base can be one already associated with your agent application, or one that is not yet associated.
For example, you can use Bailian Series Mobile Product Introduction.docx as an unstructured data knowledge base file.
Python
Request example
import os from http import HTTPStatus # We recommend DashScope SDK version >= 1.20.11 from dashscope import Application response = Application.call( # If you have not set an environment variable, replace the next line with: api_key="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure. api_key=os.getenv("DASHSCOPE_API_KEY"), app_id='YOUR_APP_ID', # Replace YOUR_APP_ID with your actual application ID prompt='Please recommend a smartphone under ¥3,000', rag_options={ "pipeline_ids": ["YOUR_PIPELINE_ID1","YOUR_PIPELINE_ID2"], # Replace with actual knowledge base IDs, separated by commas } ) if response.status_code != HTTPStatus.OK: print(f'request_id={response.request_id}') print(f'code={response.status_code}') print(f'message={response.message}') print(f'For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-code') else: print('%s\n' % (response.output.text)) # Process text-only output # print('%s\n' % (response.usage))Response example
Based on your budget, I recommend the **Bailian Zephyr Z9**. Its reference price ranges from ¥2,499 to ¥2,799—well within your budget. It features a lightweight 6.4-inch 1080 × 2340 pixel display, 128 GB storage, and 6 GB RAM—ideal for everyday use. It also includes a 4,000 mAh battery and a 30× digital zoom lens, delivering strong performance for both photography and battery life. If you value portability and all-around functionality, the Bailian Zephyr Z9 is an excellent choice.Java
Request example
// We recommend DashScope SDK version >= 2.16.8 import com.alibaba.dashscope.app.*; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.exception.InputRequiredException; import com.alibaba.dashscope.exception.NoApiKeyException; import java.util.Arrays; public class Main { public static void streamCall() throws NoApiKeyException, InputRequiredException { ApplicationParam param = ApplicationParam.builder() // If you have not set an environment variable, replace the next line with: .apiKey("sk-xxx"). However, avoid hard-coding your API key in production code to reduce the risk of exposure. .apiKey(System.getenv("DASHSCOPE_API_KEY")) .appId("YOUR_APP_ID") // Replace with your actual application ID .prompt("Please recommend a smartphone around ¥3,000") .ragOptions(RagOptions.builder() // Replace with actual knowledge base IDs, separated by commas .pipelineIds(Arrays.asList("PIPELINES_ID1", "PIPELINES_ID2")) .build()) .build(); Application application = new Application(); ApplicationResult result = application.call(param); System.out.printf("%s\n", result.getOutput().getText());// Process text-only output } public static void main(String[] args) { try { streamCall(); } catch (ApiException | NoApiKeyException | InputRequiredException e) { System.out.printf("Exception: %s", e.getMessage()); System.out.println("For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-code"); } System.exit(0); } }Response example
Within a ¥3,000 budget, I recommend the **Bailian Zephyr Z9**, priced between ¥2,499 and ¥2,799—perfect for your needs. Key features include the following: - **Lightweight design**: A 6.4-inch screen ideal for one-handed use. - **Balanced performance**: 128 GB storage and 6 GB RAM—enough for daily tasks. - **All-day battery**: A 4,000 mAh battery meets typical usage needs. - **Strong camera**: A 30× digital zoom lens captures distant details. If you prioritize gaming or have other special requirements, let me know—I’ll tailor my suggestions!HTTP
curl
Request example
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/{YOUR_APP_ID}/completion \ --header "Authorization: Bearer $DASHSCOPE_API_KEY" \ --header 'Content-Type: application/json' \ --data '{ "input": { "prompt": "Please recommend a smartphone under ¥3,000" }, "parameters": { "rag_options" : { "pipeline_ids":["YOUR_PIPELINE_ID1"]} }, "debug": {} }'Replace YOUR_APP_ID with your actual application ID. Replace YOUR_PIPELINE_ID1 with your actual knowledge base ID.
Response example
{"output":{"finish_reason":"stop","session_id":"d1208af96f9a4d8390e9b29e86f0623c", "text":"Within a ¥3,000 price range, I recommend the Bailian Zephyr Z9.\nThis phone is priced between ¥2,499 and ¥2,799—perfectly matching your budget.\nIt features a lightweight 6.4-inch 1080 × 2340 pixel display, paired with 128 GB of storage and 6 GB of RAM—enough for everyday apps and multitasking.\nPlus, it has a 4,000 mAh battery to last you all day, and a 30× digital zoom lens to capture life's little details.\nIn short, the Bailian Zephyr Z9 delivers great value, design, and features."}, "usage":{"models":[{"output_tokens":158,"model_id":"qwen-max","input_tokens":1025}]}, "request_id":"eb2d40f7-bede-9d48-88dc-08abdcdd0351"}%PHP
Request example
<?php # If you have not set an environment variable, replace the next line with: $api_key="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure. $api_key = getenv("DASHSCOPE_API_KEY"); $application_id = 'YOUR_APP_ID'; // Replace with your actual application ID $url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion"; // Build request data $data = [ "input" => [ 'prompt' => 'Please recommend a smartphone under ¥3,000' ], "parameters" => [ 'rag_options' => [ 'pipeline_ids' => ['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2']//Replace with your actual knowledge base IDs, separated by commas ] ] ]; // Encode data as JSON $dataString = json_encode($data); // Check if json_encode succeeded if (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg()); } // Initialize cURL session $ch = curl_init($url); // Set cURL options curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key ]); // Execute request $response = curl_exec($ch); // Check if cURL execution succeeded if ($response === false) { die("cURL Error: " . curl_error($ch)); } // Get HTTP status code $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Close cURL session curl_close($ch); // Decode response data $response_data = json_decode($response, true); // Process response if ($status_code == 200) { if (isset($response_data['output']['text'])) { echo "{$response_data['output']['text']}\n"; } else { echo "No text in response.\n"; } }else { if (isset($response_data['request_id'])) { echo "request_id={$response_data['request_id']}\n";} echo "code={$status_code}\n"; if (isset($response_data['message'])) { echo "message={$response_data['message']}\n";} else { echo "message=Unknown error\n";} } ?>Response example
Within a ¥3,000 budget, I recommend the **Bailian Zephyr Z9**, priced between ¥2,499 and ¥2,799—ideal for your needs. It features a lightweight design with a 6.4-inch 1080 × 2340 pixel display, 128 GB storage, and 6 GB RAM—great for everyday use. Its 4,000 mAh battery lasts all day, and its 30× digital zoom lens captures distant details—lightweight, powerful, and versatile.Node.js
Install dependencies:
npm install axiosRequest example
const axios = require('axios'); async function callDashScope() { // If you have not set an environment variable, replace the next line with: apiKey='sk-xxx'. However, avoid hard-coding your API key in production code to reduce the risk of exposure. const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID';//Replace with your actual application ID const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "Please recommend a smartphone under ¥3,000" }, parameters: { rag_options:{ pipeline_ids:['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'] // Replace with your actual knowledge base IDs, separated by commas } }, debug: {} }; try { const response = await axios.post(url, data, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' } }); if (response.status === 200) { console.log(`${response.data.output.text}`); } else { console.log(`request_id=${response.headers['request_id']}`); console.log(`code=${response.status}`); console.log(`message=${response.data.message}`); } } catch (error) { console.error(`Error calling DashScope: ${error.message}`); if (error.response) { console.error(`Response status: ${error.response.status}`); console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();Response example
Within a ¥3,000 budget, I recommend the **Bailian Zephyr Z9**, priced at ¥3,999–¥4,299. But with promotions or discounts, it may fall within your budget. ### Bailian Zephyr Z9 — Lightweight and portable - **Screen**: 6.4-inch, 1080 × 2340 pixels - **Storage & RAM**: 128 GB / 6 GB RAM - **Battery**: 4,000 mAh - **Camera**: 30× digital zoom lens This phone is lightweight and portable—ideal for everyday use—and offers solid battery life. If you value cost-effectiveness and daily usability, the Bailian Zephyr Z9 is a great pick. If your budget is strict, watch for e-commerce promotions—or consider similar phones from other brands. Hope this helps!C#
Request example
using System.Text; class Program { static async Task Main(string[] args) { // If you have not set an environment variable, replace the next line with: apiKey="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure. string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");; string appId = "YOUR_APP_ID";// Replace with your actual application ID // Replace YOUR_PIPELINE_ID1 with your actual knowledge base ID if (string.IsNullOrEmpty(apiKey)) { Console.WriteLine("Make sure DASHSCOPE_API_KEY is set."); return; } string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); string jsonContent = $@"{{ ""input"": {{ ""prompt"": ""Please recommend a smartphone under ¥3,000"" }}, ""parameters"": {{ ""rag_options"" : {{ ""pipeline_ids"":[""YOUR_PIPELINE_ID1""] }} }}, ""debug"": {{}} }}"; HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await client.PostAsync(url, content); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } else { Console.WriteLine($"Request failed with status code: {response.StatusCode}"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch (Exception ex) { Console.WriteLine($"Error calling DashScope: {ex.Message}"); } } } }Response example
{ "output": { "finish_reason": "stop", "session_id": "2344ddc540ec4c5fa110b92d813d3807", "text": "Based on your budget, I recommend the **Bailian Zephyr Z9**. Its reference price ranges from ¥2,499 to ¥2,799—within your budget. It features a 6.4-inch 1080 × 2340 pixel display, 128 GB storage, and 6 GB RAM—enough for everyday use. Plus, its 4,000 mAh battery lasts all day, and its 30× digital zoom lens captures distant scenes. This is a lightweight, versatile option." }, "usage": { "models": [ { "output_tokens": 121, "model_id": "qwen-max", "input_tokens": 1841 } ] }, "request_id": "99fceedf-2034-9fb0-aaad-9c837136801f" }Go
Request example
package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // If you have not set an environment variable, replace the next line with: apiKey := "sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure. apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // Replace with your actual application ID if apiKey == "" { fmt.Println("Make sure DASHSCOPE_API_KEY is set.") return } url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId) // Build request body requestBody := map[string]interface{}{ "input": map[string]string{ "prompt": "Please recommend a smartphone under ¥3,000", }, "parameters": map[string]interface{}{ "rag_options": map[string]interface{}{ "pipeline_ids": []string{"YOUR_PIPELINE_ID1"}, // Replace with your actual knowledge base ID }, }, "debug": map[string]interface{}{}, } jsonData, err := json.Marshal(requestBody) if err != nil { fmt.Printf("Failed to marshal JSON: %v\n", err) return } // Create HTTP POST request req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Failed to create request: %v\n", err) return } // Set request headers req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") // Send request client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("Failed to send request: %v\n", err) return } defer resp.Body.Close() // Read response body, err := io.ReadAll(resp.Body) if err != nil { fmt.Printf("Failed to read response: %v\n", err) return } // Process response if resp.StatusCode == http.StatusOK { fmt.Println("Request successful:") fmt.Println(string(body)) } else { fmt.Printf("Request failed with status code: %d\n", resp.StatusCode) fmt.Println(string(body)) } }Response example
{ "output": { "finish_reason": "stop", "session_id": "fadbb4d1fe094ade88985620363506e6", "text": "Based on your budget, I recommend the **Bailian Zephyr Z9**, priced between ¥2,499 and ¥2,799—ideal for a sub-¥3,000 budget. It features a lightweight 6.4-inch 1080 × 2340 pixel display, 128 GB storage, and 6 GB RAM—meeting everyday needs. Its 4,000 mAh battery ensures all-day use, and its 30× digital zoom lens captures distant details—a high-value choice." }, "usage": { "models": [ { "output_tokens": 119, "model_id": "qwen-max", "input_tokens": 1055 } ] }, "request_id": "3a755dd7-58a0-9a5e-8a07-b85b1db838a6" }Retrieve from a specific unstructured data document: Pass the knowledge base ID, document ID, document tags, or document metadata (key-value pairs) in the
rag_optionsparameter.Document IDs, tags, and metadata apply only to unstructured data documents.
How to obtain them:
Document ID (file_ids): You can find the ID in the document list on the Application Data page. You can also obtain it from the ID returned by the AddFile API after you import a document.
Document tags: You can view the tags on the Application Data page for unstructured documents. You can also obtain them using the DescribeFile API.
Document metadata: On the Knowledge Base page, open a knowledge base and view the metadata (Meta info) for unstructured documents.
You can pass multiple document IDs. However, only documents with built indexes are supported.
To use a document ID, you must also pass the ID of the knowledge base to which it belongs. Otherwise, the retrieval fails.
Retrieval is performed only on the specified documents. For example, if your web-based agent application references Knowledge Base A, but your API call specifies a document ID and its knowledge base ID (Knowledge Base B), then only the documents from Knowledge Base B are retrieved, not the documents from Knowledge Base A.
For example, you can use Bailian Series Mobile Product Introduction.docx as an unstructured data knowledge base file.
Python
Request example
import os from http import HTTPStatus # We recommend DashScope SDK version >= 1.20.11 from dashscope import Application response = Application.call( # If you have not set an environment variable, replace the next line with: api_key="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure. api_key=os.getenv("DASHSCOPE_API_KEY"), app_id='YOUR_APP_ID', # Replace YOUR_APP_ID with your actual application ID prompt='Please recommend a smartphone under ¥3,000', rag_options={ "pipeline_ids": ["YOUR_PIPELINE_ID1", "YOUR_PIPELINE_ID2"], # Replace with actual knowledge base IDs, separated by commas "file_ids": ["YOUR_FILE_ID1", "YOUR_FILE_ID2"], # Replace with actual unstructured document IDs, separated by commas "metadata_filter": { # Document metadata key-value pairs, separated by commas "key1": "value1", "key2": "value2" }, "tags": ["tag1", "tag2"] # Document tags, separated by commas } ) if response.status_code != HTTPStatus.OK: print(f'request_id={response.request_id}') print(f'code={response.status_code}') print(f'message={response.message}') print(f'For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-code') else: print('%s\n' % (response.output))Response example
{ "text": "Within a ¥3,000 budget, I recommend the **Bailian Zephyr Z9**. Key features include the following:\n\n- **Screen**: 6.4-inch, 1080 × 2340 pixels—ideal for daily use and entertainment.\n- **Memory & storage**: 6 GB RAM + 128 GB storage—enough for most users’ smoothness and storage needs.\n- **Battery**: 4,000 mAh—lasts all day.\n- **Camera**: 30× digital zoom lens—captures distant details.\n- **Other features**: Lightweight and portable—easy to carry.\n\nIts reference price is ¥2,499–¥2,799—perfect for your budget and great value. Hope this helps!", "finish_reason": "stop", "session_id": "10bdea3d1435406aad8750538b701bee", "thoughts": null, "doc_references": null }Java
Request example
// We recommend DashScope SDK version >= 2.16.8 import com.alibaba.dashscope.app.*; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.exception.InputRequiredException; import com.alibaba.dashscope.exception.NoApiKeyException; import com.google.gson.JsonObject; import java.util.Arrays; public class Main { public static void streamCall() throws NoApiKeyException, InputRequiredException { JsonObject metadataFilter = new JsonObject(); metadataFilter.addProperty("key1", "value1"); // Metadata key-value pair metadataFilter.addProperty("key2", "value2"); // Add more with repeated addProperty calls ApplicationParam param = ApplicationParam.builder() // If you have not set an environment variable, replace the next line with: .apiKey("sk-xxx"). However, avoid hard-coding your API key in production code to reduce the risk of exposure. .apiKey(System.getenv("DASHSCOPE_API_KEY")) .appId("YOUR_APP_ID") // Replace with your actual application ID .prompt("Please recommend a smartphone around ¥3,000") .ragOptions(RagOptions.builder() .pipelineIds(Arrays.asList("PIPELINES_ID1","PIPELINES_ID2")) // Replace with actual knowledge base IDs, separated by commas .fileIds(Arrays.asList("FILE_ID1", "FILE_ID2")) // Replace with actual unstructured document IDs, separated by commas .tags(Arrays.asList("tags1", "tags2")) // Replace with actual document tag IDs, separated by commas .metadataFilter(metadataFilter) .build()) .build(); Application application = new Application(); ApplicationResult result = application.call(param); System.out.printf("%s\n", result.getOutput().getText());// Process text-only output } public static void main(String[] args) { try { streamCall(); } catch (ApiException | NoApiKeyException | InputRequiredException e) { System.out.printf("Exception: %s", e.getMessage()); System.out.println("For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-code"); } System.exit(0); } }Response example
Based on your budget, I recommend the **Bailian Zephyr Z9**, priced between ¥2,499 and ¥2,799—ideal for a ¥3,000 budget. ### Bailian Zephyr Z9 highlights: - **Screen**: 6.4-inch, 1080 × 2340 pixels—crisp and clear visuals. - **Storage & RAM**: 128 GB storage and 6 GB RAM—enough for daily tasks. - **Battery**: 4,000 mAh—lasts all day. - **Camera**: 30× digital zoom lens—captures distant details. - **Design**: Lightweight and portable—ideal for fashion-conscious users. This phone offers great value and balanced specs—and looks stunning too. A top pick in this price range. Hope this helps! Let me know if you need more details or have other questions.HTTP
curl
Request example
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/{YOUR_APP_ID}/completion \ --header "Authorization: Bearer $DASHSCOPE_API_KEY" \ --header 'Content-Type: application/json' \ --data '{ "input": { "prompt": "Please recommend a smartphone around ¥3,000" }, "parameters": { "rag_options" : { "pipeline_ids":["YOUR_PIPELINE_ID1"], "file_ids":["YOUR_FILE_ID1"], "metadata_filter":{ "name":"Alice"}, "tags":"smartphone" } }, "debug": {} }'Replace YOUR_APP_ID with your actual application ID. Replace YOUR_PIPELINE_ID1 with your actual knowledge base ID. Replace YOUR_FILE_ID1 with your actual unstructured document ID. Replace the metadata key-value pairs with your actual metadata.
Response example
{"output":{"finish_reason":"stop","session_id":"f2f114864dd24a458f923aab0ec99a1d", "text":"Based on your budget, I recommend the “Tongyi Vivid 7”. It features a 6.5-inch 1080 × 2400 pixel full-screen display and AI-powered smart photography—capturing professional-grade photos with rich color and detail.\n\nHardware includes 8 GB RAM and 128 GB storage—ensuring smooth operation. Its 4,500 mAh battery meets typical daily needs.\n\nSide-mounted fingerprint unlocking is both convenient and secure. Its reference price is ¥2,999–¥3,299—within your budget."}, "usage":{"models":[{"output_tokens":141,"model_id":"qwen-plus","input_tokens":1610}]}, "request_id":"d815d3d1-8cef-95e2-b895-89fc8d0e0f84"}%PHP
Request example
<?php # If you have not set an environment variable, replace the next line with: $api_key="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure. $api_key = getenv("DASHSCOPE_API_KEY"); $application_id = 'YOUR_APP_ID'; // Replace with your actual application ID $url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion"; // Build request data $data = [ "input" => [ 'prompt' => 'Please recommend a smartphone under ¥3,000' ], "parameters" => [ 'rag_options' => [ 'pipeline_ids' => ['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'],// Replace with your actual knowledge base IDs, separated by commas 'file_ids' => ['YOUR_FILE_ID1','YOUR_FILE_ID2'],// Replace with your actual document IDs, separated by commas "metadata_filter" => [ // Metadata key-value pairs "key1" => "value1", "key2" => "value2" ], "tags" => ["tag1", "tag2"] // Document tags ] ] ]; // Encode data as JSON $dataString = json_encode($data); // Check if json_encode succeeded if (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg()); } // Initialize cURL session $ch = curl_init($url); // Set cURL options curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key ]); // Execute request $response = curl_exec($ch); // Check if cURL execution succeeded if ($response === false) { die("cURL Error: " . curl_error($ch)); } // Get HTTP status code $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Close cURL session curl_close($ch); // Decode response data $response_data = json_decode($response, true); // Process response if ($status_code == 200) { if (isset($response_data['output']['text'])) { echo "{$response_data['output']['text']}\n"; } else { echo "No text in response.\n"; } }else { if (isset($response_data['request_id'])) { echo "request_id={$response_data['request_id']}\n";} echo "code={$status_code}\n"; if (isset($response_data['message'])) { echo "message={$response_data['message']}\n";} else { echo "message=Unknown error\n";} } ?>Response example
Based on your budget, I recommend the **Bailian Zephyr Z9**, priced between ¥2,499 and ¥2,799—ideal for a sub-¥3,000 budget. It features a lightweight 6.4-inch 1080 × 2340 pixel design, 128 GB storage, and 6 GB RAM—meeting everyday needs. Its 4,000 mAh battery lasts all day, and its 30× digital zoom lens captures distant details—a lightweight, powerful choice.Node.js
Install dependencies:
npm install axiosRequest example
const axios = require('axios'); async function callDashScope() { // If you have not set an environment variable, replace the next line with: apiKey='sk-xxx'. However, avoid hard-coding your API key in production code to reduce the risk of exposure. const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID';//Replace with your actual application ID const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "Please recommend a smartphone under ¥3,000" }, parameters: { rag_options:{ pipeline_ids:['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'], // Replace with your actual knowledge base IDs, separated by commas file_ids:['YOUR_FILE_ID1','YOUR_FILE_ID2'], // Replace with your actual file IDs, separated by commas metadata_filter:{ // Metadata key-value pairs, separated by commas 'key1':'value1', 'key2':'value2' }, tags: ['tag1', 'tag2'] // Document tags, separated by commas } }, debug: {} }; try { const response = await axios.post(url, data, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' } }); if (response.status === 200) { console.log(`${response.data.output.text}`); } else { console.log(`request_id=${response.headers['request_id']}`); console.log(`code=${response.status}`); console.log(`message=${response.data.message}`); } } catch (error) { console.error(`Error calling DashScope: ${error.message}`); if (error.response) { console.error(`Response status: ${error.response.status}`); console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();Response example
Within a ¥3,000 budget, I recommend the **Bailian Zephyr Z9**, priced between ¥2,499 and ¥2,799. It features a lightweight, portable design, a 6.4-inch 1080 × 2340 pixel display, 128 GB storage, and 6 GB RAM—meeting everyday needs. Its 4,000 mAh battery lasts all day, and its 30× digital zoom lens captures distant details—a high-value choice.C#
Request example
using System.Text; class Program { static async Task Main(string[] args) { // If you have not set an environment variable, replace the next line with: apiKey="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure. string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");; string appId = "YOUR_APP_ID";// Replace with your actual application ID // Replace YOUR_PIPELINE_ID1 with your actual knowledge base ID, YOUR_FILE_ID1 with your actual unstructured document ID if (string.IsNullOrEmpty(apiKey)) { Console.WriteLine("Make sure DASHSCOPE_API_KEY is set."); return; } string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); string jsonContent = $@"{{ ""input"": {{ ""prompt"": ""Please recommend a smartphone under ¥3,000"" }}, ""parameters"": {{ ""rag_options"" : {{ ""pipeline_ids"":[""YOUR_PIPELINE_ID1""], ""file_ids"":[""YOUR_FILE_ID1""], ""metadata_filter"":{{ ""name"":""Alice"" }}, ""tags"":""smartphone"" }} }}, ""debug"": {{}} }}"; HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await client.PostAsync(url, content); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } else { Console.WriteLine($"Request failed with status code: {response.StatusCode}"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch (Exception ex) { Console.WriteLine($"Error calling DashScope: {ex.Message}"); } } } }Response example
{ "output": { "finish_reason": "stop", "session_id": "be9b5a1964fe41c9bbfd8674226bd238", "text": "Based on your budget, I recommend the **Bailian Zephyr Z9**, priced between ¥2,499 and ¥2,799—ideal for a sub-¥3,000 budget.\n\n### Highlights\n- **Lightweight design**: 6.4-inch screen, 1080 × 2340 pixel resolution—elegant and easy to carry.\n- **Balanced performance**: 6 GB RAM and 128 GB storage—meets everyday needs.\n- **Long-lasting battery**: 4,000 mAh—keeps you going all day.\n- **Outstanding photography**: 30× digital zoom—captures distant scenery and fine details.\n\nIf you want high value, basic features, and some flair, the Bailian Zephyr Z9 is a great pick." }, "usage": { "models": [ { "output_tokens": 180, "model_id": "qwen-max", "input_tokens": 1055 } ] }, "request_id": "d0811195-0b3f-931e-90b8-323a65053d9c" }Go
Request example
package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // If you have not set an environment variable, replace the next line with: apiKey := "sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure. apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // Replace with your actual application ID if apiKey == "" { fmt.Println("Make sure DASHSCOPE_API_KEY is set.") return } url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId) // Build request body requestBody := map[string]interface{}{ "input": map[string]string{ "prompt": "Please recommend a smartphone under ¥3,000", }, "parameters": map[string]interface{}{ "rag_options": map[string]interface{}{ "pipeline_ids": []string{"YOUR_PIPELINE_ID1"}, // Replace with your actual unstructured knowledge base ID "file_ids": []string{"YOUR_FILE_ID1"}, // Replace with your actual unstructured document ID "metadata_filter": map[string]string{ "name": "Alice", // Metadata key-value pair }, "tags": "smartphone", // Unstructured document tag }, }, "debug": map[string]interface{}{}, } jsonData, err := json.Marshal(requestBody) if err != nil { fmt.Printf("Failed to marshal JSON: %v\n", err) return } // Create HTTP POST request req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Failed to create request: %v\n", err) return } // Set request headers req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") // Send request client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("Failed to send request: %v\n", err) return } defer resp.Body.Close() // Read response body, err := io.ReadAll(resp.Body) if err != nil { fmt.Printf("Failed to read response: %v\n", err) return } // Process response if resp.StatusCode == http.StatusOK { fmt.Println("Request successful:") fmt.Println(string(body)) } else { fmt.Printf("Request failed with status code: %d\n", resp.StatusCode) fmt.Println(string(body)) } }Response example
{ "output": { "finish_reason": "stop", "session_id": "9de268b3d84748b5ac6321aba72b6ecd", "text": "Based on your budget, I recommend the **Bailian Zephyr Z9**, priced between ¥2,499 and ¥2,799—ideal for a sub-¥3,000 budget. Key features include the following:\n\n- Lightweight 6.4-inch 1080 × 2340 pixel screen design.\n- 128 GB storage and 6 GB RAM—meets everyday needs.\n- 4,000 mAh battery—lasts all day.\n- Rear camera with 30× digital zoom lens—captures distant details.\n\nIf you don’t need high-end photography or gaming, the Bailian Zephyr Z9 is a great choice." }, "usage": { "models": [ { "output_tokens": 156, "model_id": "qwen-max", "input_tokens": 1055 } ] }, "request_id": "8940b597-92e1-9471-b4eb-896e563c479d" }
Retrieve specific data from a structured data document by passing the knowledge base ID and key-value pairs for structured data fields—such as table header and value—in the
rag_optionsparameter.Retrieve structured data key-value pairs (structured_filter): On the Knowledge Base page, open a knowledge base and click View index to view index information for structured documents.
Python
Request example
import os from http import HTTPStatus # We recommend DashScope SDK version >= 1.20.11 from dashscope import Application response = Application.call( # If you have not set an environment variable, replace the next line with: api_key="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure. api_key=os.getenv("DASHSCOPE_API_KEY"), app_id='YOUR_APP_ID', # Replace YOUR_APP_ID with your actual application ID prompt='Please recommend a smartphone under ¥3,000', rag_options={ "pipeline_ids": ["YOUR_PIPELINE_ID1", "YOUR_PIPELINE_ID2"], # Replace with actual knowledge base IDs, separated by commas "structured_filter": { # Structured data key-value pairs, corresponding to structured data, separated by commas "key1": "value1", "key2": "value2" } } ) if response.status_code != HTTPStatus.OK: print(f'request_id={response.request_id}') print(f'code={response.status_code}') print(f'message={response.message}') print(f'For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-code') else: print('%s\n' % (response.output))Response example
{ "text": "I recommend the \"Bailian\" smartphone—it costs ¥2,999, fitting your budget. If you need more details—like performance or design—let me know.", "finish_reason": "stop", "session_id": "80a3b868b5ce42c8a12f01dccf8651e2", "thoughts": null, "doc_references": null }Java
Request example
// We recommend DashScope SDK version >= 2.16.8 import com.alibaba.dashscope.app.*; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.exception.InputRequiredException; import com.alibaba.dashscope.exception.NoApiKeyException; import com.google.gson.JsonObject; import java.util.Arrays; public class Main { public static void streamCall() throws NoApiKeyException, InputRequiredException { JsonObject structureFilter = new JsonObject(); structureFilter.addProperty("key1", "value1"); // Structured data key-value pair structureFilter.addProperty("key2", "value2"); // Add more with repeated addProperty calls ApplicationParam param = ApplicationParam.builder() // If you have not set an environment variable, replace the next line with: .apiKey("sk-xxx"). However, avoid hard-coding your API key in production code to reduce the risk of exposure. .apiKey(System.getenv("DASHSCOPE_API_KEY")) .appId("YOUR_APP_ID") // Replace with your actual application ID .prompt("Please recommend a smartphone around ¥3,000") .ragOptions(RagOptions.builder() .pipelineIds(Arrays.asList("PIPELINE_ID1","PIPELINE_ID2")) // Replace with actual knowledge base IDs, separated by commas .structuredFilter(structureFilter) .build()) .build(); Application application = new Application(); ApplicationResult result = application.call(param); System.out.printf("%s\n", result.getOutput().getText());// Process text-only output } public static void main(String[] args) { try { streamCall(); } catch (ApiException | NoApiKeyException | InputRequiredException e) { System.out.printf("Exception: %s", e.getMessage()); System.out.println("For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-code"); } System.exit(0); } }Response example
I recommend the "Bailian" smartphone—it costs ¥2,999.00, fitting your budget. If you need more details about this phone—like specs or performance—let me know, and I’ll provide more information.HTTP
curl
Request example
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \ --header "Authorization: Bearer $DASHSCOPE_API_KEY" \ --header 'Content-Type: application/json' \ --data '{ "input": { "prompt": "Please recommend a smartphone around ¥3,000" }, "parameters": { "rag_options" : { "pipeline_ids":["YOUR_PIPELINE_ID1"], "structured_filter":{ "price":"2999"} } }, "debug": {} }'Replace YOUR_APP_ID with your actual application ID. Replace YOUR_PIPELINE_ID1 with your actual knowledge base ID.
Response example
{"output":{"finish_reason":"stop","session_id":"d6bc4206f9cc4d368d534f8aa4e502bc", "text":"I recommend a smartphone close to ¥3,000:\n\n- **Bailian smartphone**, priced at ¥2,999.\n\nThis phone offers great value and fits your budget.\nIf you need more details—like camera performance or processor model—let me know, and I’ll provide more information."}, "usage":{"models":[{"output_tokens":73,"model_id":"qwen-max","input_tokens":235}]},"request_id":"934e1258-219c-9ef1-8982-fc1bcefb8f11"}%PHP
Request example
<?php # If you have not set an environment variable, replace the next line with: $api_key="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure. $api_key = getenv("DASHSCOPE_API_KEY"); $application_id = 'YOUR_APP_ID'; // Replace with your actual application ID $url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion"; // Build request data $data = [ "input" => [ 'prompt' => 'Please recommend a smartphone under ¥3,000' ], "parameters" => [ 'rag_options' => [ 'pipeline_ids' => ['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'],// Replace with your actual knowledge base IDs, separated by commas "structured_filter" => [ // Structured data key-value pairs, separated by commas "key1" => "value1", "key2" => "value2" ] ] ] ]; // Encode data as JSON $dataString = json_encode($data); // Check if json_encode succeeded if (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg()); } // Initialize cURL session $ch = curl_init($url); // Set cURL options curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key ]); // Execute request $response = curl_exec($ch); // Check if cURL execution succeeded if ($response === false) { die("cURL Error: " . curl_error($ch)); } // Get HTTP status code $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Close cURL session curl_close($ch); // Decode response data $response_data = json_decode($response, true); // Process response if ($status_code == 200) { if (isset($response_data['output']['text'])) { echo "{$response_data['output']['text']}\n"; } else { echo "No text in response.\n"; } }else { if (isset($response_data['request_id'])) { echo "request_id={$response_data['request_id']}\n";} echo "code={$status_code}\n"; if (isset($response_data['message'])) { echo "message={$response_data['message']}\n";} else { echo "message=Unknown error\n"; } } ?>Response example
I recommend the "Bailian" smartphone—it costs ¥2,999, fitting your budget. If you need more details about this phone, let me know.Node.js
Install dependencies:
npm install axiosRequest example
const axios = require('axios'); async function callDashScope() { // If you have not set an environment variable, replace the next line with: apiKey='sk-xxx'. However, avoid hard-coding your API key in production code to reduce the risk of exposure. const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID'; // Replace with your actual application ID // Replace YOUR_PIPELINE_ID1 with your actual knowledge base ID, separate multiple IDs with commas const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "Please recommend a smartphone under ¥3,000" }, parameters: { rag_options:{ pipeline_ids:['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'], structured_filter:{ 'key1':'value1', 'key2':'value2' } } }, debug: {} }; try { const response = await axios.post(url, data, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' } }); if (response.status === 200) { console.log(`${response.data.output.text}`); } else { console.log(`request_id=${response.headers['request_id']}`); console.log(`code=${response.status}`); console.log(`message=${response.data.message}`); } } catch (error) { console.error(`Error calling DashScope: ${error.message}`); if (error.response) { console.error(`Response status: ${error.response.status}`); console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();Response example
I recommend the "Bailian" smartphone—it costs ¥2,999, fitting your budget. If you need more details or have other specific needs, let me know!C#
Request example
using System.Text; class Program { static async Task Main(string[] args) { // If you have not set an environment variable, replace the next line with: apiKey="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure. string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");; string appId = "YOUR_APP_ID";// Replace with your actual application ID // Replace YOUR_PIPELINE_ID1 with your actual knowledge base ID if (string.IsNullOrEmpty(apiKey)) { Console.WriteLine("Make sure DASHSCOPE_API_KEY is set."); return; } string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); string jsonContent = $@"{{ ""input"": {{ ""prompt"": ""Please recommend a smartphone under ¥3,000"" }}, ""parameters"": {{ ""rag_options"" : {{ ""pipeline_ids"":[""YOUR_PIPELINE_ID1""], ""structured_filter"":{{ ""price"":""2999"" }} }} }}, ""debug"": {{}} }}"; HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await client.PostAsync(url, content); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } else { Console.WriteLine($"Request failed with status code: {response.StatusCode}"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch (Exception ex) { Console.WriteLine($"Error calling DashScope: {ex.Message}"); } } } }Response example
{ "output": { "finish_reason": "stop", "session_id": "108e9104568e44f1915fb3d3d44fdc92", "text": "I recommend the \"Bailian\" smartphone—it costs ¥2,999.00, fitting your budget. If you need more details about this phone or other suggestions, let me know." }, "usage": { "models": [ { "output_tokens": 38, "model_id": "qwen-max", "input_tokens": 104 } ] }, "request_id": "d6d103f4-5c22-9782-9682-45d51a5607f9" }Go
Request example
package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // If you have not set an environment variable, replace the next line with: apiKey := "sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure. apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // Replace with your actual application ID if apiKey == "" { fmt.Println("Make sure DASHSCOPE_API_KEY is set.") return } url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId) // Build request body requestBody := map[string]interface{}{ "input": map[string]string{ "prompt": "Please recommend a smartphone under ¥3,000", }, "parameters": map[string]interface{}{ "rag_options": map[string]interface{}{ "pipeline_ids": []string{"YOUR_PIPELINE_ID1"}, // Replace with your actual structured knowledge base ID "structured_filter": map[string]string{ "price": "2999", // Structured data key-value pair }, }, }, "debug": map[string]interface{}{}, } jsonData, err := json.Marshal(requestBody) if err != nil { fmt.Printf("Failed to marshal JSON: %v\n", err) return } // Create HTTP POST request req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Failed to create request: %v\n", err) return } // Set request headers req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") // Send request client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("Failed to send request: %v\n", err) return } defer resp.Body.Close() // Read response body, err := io.ReadAll(resp.Body) if err != nil { fmt.Printf("Failed to read response: %v\n", err) return } // Process response if resp.StatusCode == http.StatusOK { fmt.Println("Request successful:") fmt.Println(string(body)) } else { fmt.Printf("Request failed with status code: %d\n", resp.StatusCode) fmt.Println(string(body)) } }Response example
{ "output": { "finish_reason": "stop", "session_id": "9e0a031b51d1492e8b613ca391b445b0", "text": "I recommend the \"Bailian\" smartphone—it costs ¥2,999.00, fitting your budget. If you need more details about this phone or other recommendations, let me know." }, "usage": { "models": [ { "output_tokens": 39, "model_id": "qwen-max", "input_tokens": 104 } ] }, "request_id": "036abd4f-10c8-9709-881d-8cc9f8095d54" }
View information
View retrieval process information: When you make an API call, add the
has_thoughtsparameter to your code and set its value to `True`. The retrieval process information is then returned in thethoughtsfield of theoutputobject.View source references: Click Knowledge base, and then click Configure. Turn on the Show source references switch, and then publish the application. The source references will then appear in the response.

Deep thinking
If you select the deep thinking model in your agent application and successfully publish it, then:
Enable thinking mode:
To enable thinking mode and obtain its output, you can configure it in one of two ways.
Console settings
For Qwen3 models: In the console, make sure the thinking mode switch is turned on, then republish the application.
For other models: Thinking mode is enabled by default. No action is required.
API parameter settings
For Qwen3 models: Set the enable_thinking parameter to true.
For other models: The enable_thinking parameter has no effect.
Priority: If you use both methods, the API parameter setting takes precedence.
Retrieve the thinking process:
Set the has_thoughts parameter to true.
Processing the response:
Thinking process: Is returned in the
thoughtfield of the response.Final reply: Is returned in the
textfield of the response.
Deep thinking models may produce long thinking processes. To reduce the risk of a timeout, use streaming output. See the following examples.
Python
Request example
import os
from http import HTTPStatus
from dashscope import Application
try:
response = Application.call(
# If you have not set an environment variable, replace the next line with: api_key="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure.
api_key=os.getenv('DASHSCOPE_API_KEY'),
app_id='YOUR_APP_ID',# Replace with your actual application ID
prompt='Who are you?',# Replace with your actual input
stream=True, # Stream output: True enables streaming; False (default) disables it
incremental_output=True, # Incremental output: True enables it; False (default) disables it
has_thoughts=True # Return thinking process: True returns it; False (default) does not
)
except Exception as e:
print(f"API request failed: {str(e)}")
exit(1)
# Store full thinking process
reasoning_content = []
# Store full reply
answer_content = ""
# Track whether we've started replying
is_answering = False
def print_section(title):
"""Print a section header with decoration"""
print(f"\n{'=' * 20} {title} {'=' * 20}\n", flush=True)
print_section("Thinking process")
for chunk in response:
if chunk.status_code != HTTPStatus.OK:
print(f'request_id={chunk.request_id}')
print(f'code={chunk.status_code}')
print(f'message={chunk.message}')
print(f'For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-code')
continue
# Skip empty chunks
if not chunk.output or (not chunk.output.thoughts and not chunk.output.text):
continue
# Process thinking steps
if chunk.output.thoughts:
for it in chunk.output.thoughts:
if it.action_type == 'reasoning':# DeepSeek-R1 models use 'reasoning' for action_type; output appears in 'thought'
content = str(it.thought) if not isinstance(it.thought, str) else it.thought
reasoning_content.append(content)
print(content, end="", flush=True)
# Process reply
if chunk.output.text:
if not is_answering:
print_section("Full reply")
is_answering = True
answer_content += str(chunk.output.text)
print(chunk.output.text, end="", flush=True)
# Final results
final_reasoning = "".join(reasoning_content)
final_answer = "".join(answer_content)
# Uncomment the following lines to print full thinking and reply
#print_section("Full thinking process")
#print(final_reasoning)
#print_section("Full reply")
#print(final_answer)Response example
==================== Thinking process ====================
Hmm, the user asked “Who are you?” I need to answer in Chinese. First, I’ll introduce myself as an AI assistant developed by DeepSeek. Then I’ll explain my functions—answering questions, providing information, helping with learning, etc. Keep it conversational, not too formal. Mention that I’m based on a large language model, but keep technical terms simple. Also note that the user might be testing my ability, so keep answers concise, friendly, and natural. Check for any missing key points—like the correct company name and emphasis on helpfulness. Finally, ensure formatting is clean, without markdown, and paragraphs are well spaced.
==================== Full reply ====================
Hello! I’m DeepSeek-R1, an intelligent assistant developed by DeepSeek. I’m here to help you with questions, information lookup, and learning support.Java
Request example
// We recommend DashScope SDK version >= 2.15.0
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.reactivex.Flowable;// Streaming output
// Agent application call with streaming output
public class Main {
public static void streamCall() throws NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// If you have not set an environment variable, replace the next line with: .apiKey("sk-xxx"). However, avoid hard-coding your API key in production code to reduce the risk of exposure.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// Replace with your actual application ID
.appId("YOUR_APP_ID")
.prompt("Hello")
.hasThoughts(true)
// Incremental output
.incrementalOutput(true)
.build();
Application application = new Application();
// .streamCall(): stream output
Flowable<ApplicationResult> result = application.streamCall(param);
result.blockingForEach(data -> {
System.out.printf("%s\n",
data.getOutput());
});
}
public static void main(String[] args) {
try {
streamCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("For more information, see https://help.aliyun.com/en/model-studio/error-code");
}
System.exit(0);
}
}Response example
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=Okay, user, actionType=reasoning, response=Okay, user, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=Greeting, actionType=reasoning, response=Greeting, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=Say, actionType=reasoning, response=Say, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought="Hello", I need to be friendly, actionType=reasoning, response="Hello", I need to be friendly, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=Respond first. First, actionType=reasoning, response=Respond first. First, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=confirm the user's needs, actionType=reasoning, response=confirm the user's needs, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=may just be testing or wanting, actionType=reasoning, response=may just be testing or wanting, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=start a conversation. To, actionType=reasoning, response=start a conversation. To, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=stay enthusiastic and use, actionType=reasoning, response=stay enthusiastic and use, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=Chinese replies. Can, actionType=reasoning, response=Chinese replies. Can, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=ask what they need, actionType=reasoning, response=ask what they need, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=help, or do they have specific, actionType=reasoning, response=help, or do they have specific, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=questions. Also, pay attention, actionType=reasoning, response=questions. Also, pay attention, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=to using appropriate emojis to increase, actionType=reasoning, response=to using appropriate emojis to increase, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=familiarity. Check, actionType=reasoning, response=familiarity. Check, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=if there are any special things to note, actionType=reasoning, response=if there are any special things to note, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=such as the user's special identity, actionType=reasoning, response=such as the user's special identity, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=or needs, but currently, actionType=reasoning, response=or needs, but currently, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=it looks like a normal greeting. Simply, actionType=reasoning, response=it looks like a normal greeting. Simply, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=respond, avoiding, actionType=reasoning, response=respond, avoiding, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=complex sentences. Stay, actionType=reasoning, response=complex sentences. Stay, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=natural, making users feel, actionType=reasoning, response=natural, making users feel, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=valued.\n\nNow, actionType=reasoning, response=valued.\n\nNow, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=organize language: welcome, actionType=reasoning, response=organize language: welcome, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=user, ask what help, actionType=reasoning, response=user, ask what help, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=they need. Use, actionType=reasoning, response=they need. Use, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=friendly emoji, such as a smiley face, actionType=reasoning, response=friendly emoji, such as a smiley face, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=. Ensure wording, actionType=reasoning, response=. Ensure wording, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=is concise, letting the conversation, actionType=reasoning, response=is concise, letting the conversation, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=continue easily. For example, actionType=reasoning, response=continue easily. For example, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought="Hello! What can I, actionType=reasoning, response="Hello! What can I, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=help you?", actionType=reasoning, response=help you?", actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought= This is both, actionType=reasoning, response= This is both, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=direct and open, actionType=reasoning, response=direct and open, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=encouraging further conversation, actionType=reasoning, response=encouraging further conversation, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=., actionType=reasoning, response=., actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=Hello!, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=, actionType=reasoning, response=, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=What can I help you?, finishReason=null, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=, actionType=reasoning, response=, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)
ApplicationOutput(text=, finishReason=stop, sessionId=380427d07790470c8e63e0d28dfa98bb, thoughts=[ApplicationOutput.Thought(thought=, actionType=reasoning, response=, actionName=Thinking process, action=reasoning, actionInputStream=null, actionInput=null, observation=null)], docReferences=null, workflowMessage=null)curl
Replace YOUR_APP_ID with your actual application ID.
To pass your API key directly, replace $DASHSCOPE_API_KEY with your actual key.
In the request header, set X-DashScope-SSE to enable to enable streaming output.
Add the
has_thoughtsparameter to theparametersobject to specify whether to return the thinking process. Set the value to true to return the thinking process, or set it to false (the default) to omit it.You can add the
incremental_outputparameter to theparametersobject to specify whether to enable incremental output. Set the value to true to enable incremental output. The default value is false.
Request example
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--header 'X-DashScope-SSE: enable' \
--data '{
"input": {
"prompt": "Hello"
},
"parameters": {
"has_thoughts":true,
"incremental_output":true
},
"debug": {}
}'Response example
id:1
event:result
:HTTP_STATUS/200
data:{"output":{"thoughts":[{"action":"reasoning","thought":"Hmm","action_type":"reasoning","response":"Hmm","action_name":"Thinking process"}],"session_id":"ea188f5f795a485f8956e3af0212ba29","finish_reason":"null","text":""},"usage":{"models":[{"input_tokens":31,"output_tokens":3,"model_id":"deepseek-r1"}]},"request_id":"b4b0b65f-4378-93b6-8ca2-7936b2725bc8"}
id:2
event:result
:HTTP_STATUS/200
data:{"output":{"thoughts":[{"action":"reasoning","thought":",","action_type":"reasoning","response":",","action_name":"Thinking process"}],"session_id":"ea188f5f795a485f8956e3af0212ba29","finish_reason":"null","text":""},"usage":{"models":[{"input_tokens":31,"output_tokens":4,"model_id":"deepseek-r1"}]},"request_id":"b4b0b65f-4378-93b6-8ca2-7936b2725bc8"}
id:3
event:result
:HTTP_STATUS/200
data:{"output":{"thoughts":[{"action":"reasoning","thought":"user","action_type":"reasoning","response":"user","action_name":"Thinking process"}],"session_id":"ea188f5f795a485f8956e3af0212ba29","finish_reason":"null","text":""},"usage":{"models":[{"input_tokens":31,"output_tokens":5,"model_id":"deepseek-r1"}]},"request_id":"b4b0b65f-4378-93b6-8ca2-7936b2725bc8"}
......
id:320
event:result
:HTTP_STATUS/200
data:{"output":{"thoughts":[{"action":"reasoning","thought":"","action_type":"reasoning","response":"","action_name":"Thinking process"}],"session_id":"ea188f5f795a485f8956e3af0212ba29","finish_reason":"null","text":"question"},"usage":{"models":[{"input_tokens":31,"output_tokens":322,"model_id":"deepseek-r1"}]},"request_id":"b4b0b65f-4378-93b6-8ca2-7936b2725bc8"}
id:321
event:result
:HTTP_STATUS/200
data:{"output":{"thoughts":[{"action":"reasoning","thought":"","action_type":"reasoning","response":"","action_name":"Thinking process"}],"session_id":"ea188f5f795a485f8956e3af0212ba29","finish_reason":"null","text":"?"},"usage":{"models":[{"input_tokens":31,"output_tokens":323,"model_id":"deepseek-r1"}]},"request_id":"b4b0b65f-4378-93b6-8ca2-7936b2725bc8"}
id:322
event:result
:HTTP_STATUS/200
data:{"output":{"thoughts":[{"action":"reasoning","thought":"","action_type":"reasoning","response":"","action_name":"Thinking process"}],"session_id":"ea188f5f795a485f8956e3af0212ba29","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":31,"output_tokens":324,"model_id":"deepseek-r1"}]},"request_id":"b4b0b65f-4378-93b6-8ca2-7936b2725bc8"}Long-term memory
Alibaba Cloud Model Studio’s agent applications retain some of your conversation history. However, due to large language model (LLM) attention limits, they may forget details. To address this, store important information in long-term memory. Your application will then reference that memory in future conversations.
Steps
Step 1: Enable the long-term memory featurelong-term memory
Go to the Application Management page. Find your agent application, turn on the long-term memory switch, and then publish the application.
Step 2: Create a memory
Call the CreateMemory API to create a memory. From the response, retrieve a unique memoryId.
Step 3: Save conversation information
Pass the memoryId you retrieved earlier. The system automatically analyzes your conversation and saves key information as memory linked to that memoryId.
Step 4: Use long-term memory in conversations
Each time you interact with the agent, provide the same memoryId. The system retrieves the corresponding memory content based on the provided memoryId and passes it along with the current question to the model to generate a response.
Example
Python
Request example (create memory content)
# DashScope SDK version ≥ 1.22.1
from http import HTTPStatus
import os
from dashscope import Application
response = Application.call(
# If you have not set an environment variable, replace the next line with: api_key="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure.
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID', # Enter your actual application ID
prompt='User food preference: noodles',
memory_id='YOUR_MEMORY_ID') # Enter your actual memory ID
if response.status_code != HTTPStatus.OK:
print(f'request_id={response.request_id}')
print(f'code={response.status_code}')
print(f'message={response.message}')
print(f'For more information, see https://help.aliyun.com/en/model-studio/error-code')
else:
print('%s\n' % (response.output.text)) # Process text-only output
# print('%s\n' % (response.usage))Response example
Got it—you love noodles! If you’d like recommendations or info about noodle recipes or restaurants, tell me more. For example: What kind of noodles do you prefer—ramen, spaghetti, or something regional? Or do you have special taste preferences? That way, I can help better.Request example (call again)
# DashScope SDK version ≥ 1.22.1
from http import HTTPStatus
import os
from dashscope import Application
response = Application.call(
# If you have not set an environment variable, replace the next line with: api_key="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure.
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID', # Enter your actual application ID
prompt='Food recommendation',
memory_id='YOUR_MEMORY_ID') # Enter your actual memory ID
if response.status_code != HTTPStatus.OK:
print(f'request_id={response.request_id}')
print(f'code={response.status_code}')
print(f'message={response.message}')
print(f'For more information, see https://help.aliyun.com/en/model-studio/error-code')
else:
print('%s\n' % (response.output.text)) # Process text-only output
# print('%s\n' % (response.usage))Response example
Since you love noodles, here are some dishes to try:
1. **Zhajiangmian**: A classic Beijing dish—noodles topped with savory yellow bean sauce and minced pork. Rich and flavorful.
2. **Dandan noodles**: A Sichuan favorite—spicy, numbing, and refreshing. Perfect if you enjoy bold flavors.
3. **Daoxiao noodles**: A Shanxi specialty—hand-cut noodles cooked right into boiling water. Chewy and satisfying.
4. **Spaghetti**: For variety, try Western-style pasta—like tomato meat sauce or creamy mushroom pasta.
Hope this helps! Let me know if you have specific tastes or other needs.Java
Request example (create memory content)
// DashScope SDK version ≥ 2.17.0
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
public class Main {
public static void callWithMemory() throws NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// If you have not set an environment variable, replace the next line with: .apiKey("sk-xxx"). However, avoid hard-coding your API key in production code to reduce the risk of exposure.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("YOUR_APP_ID") // Replace with your actual application ID
.prompt("User food preference: noodles")
.memoryId("YOUR_MEMORY_ID") // Replace with your actual memory ID
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("%s\n",
result.getOutput().getText()); // Process text-only output
}
public static void main(String[] args) {
try {
callWithMemory();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("For more information, see https://help.aliyun.com/en/model-studio/error-code");
}
System.exit(0);
}
}Response example
Got it—you love noodles! If you need noodle recommendations, recipes, or places to eat, just ask—I’m happy to help!Request example (call again)
// DashScope SDK version ≥ 2.17.0
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
public class Main {
public static void callWithMemory() throws NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// If you have not set an environment variable, replace the next line with: .apiKey("sk-xxx"). However, avoid hard-coding your API key in production code to reduce the risk of exposure.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("YOUR_APP_ID") // Replace with your actual application ID
.prompt("Food recommendation")
.memoryId("YOUR_MEMORY_ID") // Replace with your actual memory ID
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("text: %s\n",
result.getOutput().getText()); // Process text-only output
}
public static void main(String[] args) {
try {
callWithMemory();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("For more information, see https://help.aliyun.com/en/model-studio/error-code");
}
System.exit(0);
}
}Response example
Since you love noodles, here are some tasty options:
1. **Zhajiangmian**: A Beijing classic—noodles with savory yellow bean sauce and minced pork. Fresh veggies like cucumber and bean sprouts add crunch.
2. **Dandan noodles**: A spicy Sichuan snack—thin noodles in rich broth, topped with chili oil, peanuts, and scallions. Refreshing and bold.
3. **Daoxiao noodles**: A Shanxi staple—thick, chewy noodles served with hearty meat-and-vegetable stews.
4. **Youpo noodles**: A Shaanxi favorite—hand-pulled noodles tossed in hot oil, chili flakes, soy sauce, and vinegar. Aroma first!
5. **Spaghetti**: For global flair, try Italian pasta—like classic tomato meat sauce or creamy mushroom pasta.
Hope these ideas delight you! Tell me if you have special requests or want to try something specific.HTTP
curl
Request example (create memory content)
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "User food preference: noodles",
"memory_id": "YOUR_MEMORY_ID"
},
"parameters": {},
"debug": {}
}' Replace YOUR_APP_ID with your actual application ID.
Response example
{
"output": {
"finish_reason": "stop",
"session_id": "36ca92e5689f4dfbab889525da8a784b",
"text": "Got it—you prefer noodles. So when recommending food or giving advice, I’ll focus more on noodle options. Do you have a favorite type—like ramen, spaghetti, or a regional specialty? Or would you like suggestions for new noodle dishes to try? I’m happy to help!"
},
"usage": {
"models": [
{
"output_tokens": 70,
"model_id": "qwen-max",
"input_tokens": 119
}
]
},
"request_id": "050acdc4-d427-969e-8ba8-aa95075c2d9a"
}Request example (call again)
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "Food recommendation",
"memory_id": "YOUR_MEMORY_ID"
},
"parameters": {},
"debug": {}
}' Replace YOUR_APP_ID with your actual application ID.
Response example
{"output":{"finish_reason":"stop",
"session_id":"12677d7f5e5d423ca30db6ff77a4710d",
"text":"Considering your love of noodles, here are some delicious options:\n\n
1. **Beijing Zhajiangmian**: A classic northern dish—noodles with savory yellow bean sauce and minced pork, topped with cucumber ribbons and tofu skin for texture.\n\n
2. **Sichuan Dandan noodles**: A fiery favorite—thin noodles in rich broth, topped with chili oil, peanuts, and preserved vegetables. Bold and addictive.\n\n
3. **Shanxi Daoxiao noodles**: Known for their unique preparation—noodles shaved directly into boiling water. Served with hearty tomato-egg or beef stews.\n\n
4. **Shaanxi Liangpi**: Technically a cold noodle dish—chewy wheat noodles with tangy vinegar, spicy chili oil, and crisp cucumber. Perfect for summer.\n\n
5. **Jiangnan Yangchun noodles**: Simple yet elegant—clear broth with fine noodles, sprinkled with scallions and a touch of lard. Light but deeply flavorful.\n\n
6. **Italian pasta**: For global variety, try classic tomato meat sauce or creamy mushroom pasta—delicious and easy to make.\n\n
Hope these satisfy your cravings—feel free to pick one to try!"},
"usage":{"models":[{"output_tokens":269,"model_id":"qwen-max","input_tokens":139}]},
"request_id":"f7792da2-02f6-999c-85f1-a76de85fb99f"}%Error response example
{"code":"InvalidApiKey","message":"Invalid API-key provided.","request_id":"2637fcf9-32b1-9f4e-b0e9-1724d4aea00e"}PHP
Request example (create memory content)
<?php
# If you have not set an environment variable, replace the next line with: $api_key="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Replace with your actual application ID
$memory_id = 'YOUR_MEMORY_ID'; // Replace with your actual memory ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/{$application_id}/completion";
// Build request data
$data = [
"input" => [
'prompt' => 'User food preference: noodles',
'memory_id' => $memory_id
]
];
// Encode data as JSON
$dataString = json_encode($data);
// Check if json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize cURL session
$ch = curl_init($url);
// Set cURL options
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// Execute request
$response = curl_exec($ch);
// Check if cURL execution succeeded
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// Get HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close cURL session
curl_close($ch);
// Decode response data
$response_data = json_decode($response, true);
// Process response
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
}
}else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";}
else {
echo "message=Unknown error\n";
}
}
?>Response example
Got it—you love noodles! If you’re looking for new noodle recipes or great places to eat, let me know more details—I’ll do my best to help. For example: Are you cooking at home or dining out?Request example (call again)
<?php
# If you have not set an environment variable, replace the next line with: $api_key="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Replace with your actual application ID
$memory_id = 'YOUR_MEMORY_ID'; // Replace with your actual memory ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/{$application_id}/completion";
// Build request data
$data = [
"input" => [
'prompt' => 'Food recommendation',
'memory_id' => $memory_id
]
];
// Encode data as JSON
$dataString = json_encode($data);
// Check if json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize cURL session
$ch = curl_init($url);
// Set cURL options
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// Execute request
$response = curl_exec($ch);
// Check if cURL execution succeeded
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// Get HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close cURL session
curl_close($ch);
// Decode response data
$response_data = json_decode($response, true);
// Process response
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
}
}else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";}
else {
echo "message=Unknown error\n";
}
}
?>Response example
Since you love noodles, here are some tasty options:
1. **Zhajiangmian** – A classic Beijing dish—noodles with savory yellow bean sauce and minced pork. Rich and delicious.
2. **Daoxiao noodles** – A Shanxi specialty—hand-cut noodles boiled right in the pot. Great with various broths or sauces.
3. **Dandan noodles** – A Sichuan street food favorite—spicy, fragrant, and packed with flavor. Topped with chili oil, peanuts, and preserved veggies.
4. **Lanzhou hand-pulled noodles** – Originating from Gansu Province, famous for its springy, handmade noodles served in rich beef broth with thin beef slices and scallions.
Hope these inspire you! Let me know if you want more details—or have other requests.Node.js
Install dependencies:
npm install axiosRequest example (create memory content)
const axios = require('axios');
async function callDashScope() {
// If you have not set an environment variable, replace the next line with: apiKey='sk-xxx'. However, avoid hard-coding your API key in production code to reduce the risk of exposure.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// Replace with your actual application ID
const memoryId = 'YOUR_MEMORY_ID';// Replace with your actual memory ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "User food preference: noodles",
memory_id: memoryId
},
parameters: {},
debug: {}
};
try {
console.log("Sending request to DashScope API...");
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
if (response.data.output && response.data.output.text) {
console.log(`${response.data.output.text}`);
}
} else {
console.log("Request failed:");
if (response.data.request_id) {
console.log(`request_id=${response.data.request_id}`);
}
console.log(`code=${response.status}`);
if (response.data.message) {
console.log(`message=${response.data.message}`);
} else {
console.log('message=Unknown error');
}
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();Response example
Got it—you love noodles! If you want to try new noodle dishes or find local specialties, let me know—I’ll give you some suggestions!Request example (call again)
const axios = require('axios');
async function callDashScope() {
// If you have not set an environment variable, replace the next line with: apiKey='sk-xxx'. However, avoid hard-coding your API key in production code to reduce the risk of exposure.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// Replace with your actual application ID
const memoryId = 'YOUR_MEMORY_ID';// Replace with your actual memory ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "Food recommendation",
memory_id: memoryId
},
parameters: {},
debug: {}
};
try {
console.log("Sending request to DashScope API...");
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
if (response.data.output && response.data.output.text) {
console.log(`${response.data.output.text}`);
}
} else {
console.log("Request failed:");
if (response.data.request_id) {
console.log(`request_id=${response.data.request_id}`);
}
console.log(`code=${response.status}`);
if (response.data.message) {
console.log(`message=${response.data.message}`);
} else {
console.log('message=Unknown error');
}
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();Response example
Since you love noodles, here are some suggestions:
1. **Daoxiao noodles**: Famous for their chewy texture and shape—great with rich broths or savory sauces.
2. **Dandan noodles**: A Sichuan spicy dish—peanut sauce, chili oil, and minced pork make it flavorful and layered.
3. **Zhajiangmian**: A Beijing classic—yellow bean sauce and minced pork over noodles. Delicious and hearty.
4. **Spaghetti**: For international variety, try tomato meat sauce or creamy mushroom pasta.
Hope this helps! Let me know if you need more details or specific recommendations.C#
Request example (create memory content)
using System.Text;
class Program
{
static async Task Main(string[] args)
{
// If you have not set an environment variable, replace the next line with: apiKey="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
string appId = "YOUR_APP_ID";// Replace with your actual application ID
string memoryId = "YOUR_MEMORY_ID";//Replace with your actual memory ID
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("Make sure DASHSCOPE_API_KEY is set.");
return;
}
string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string jsonContent = $@"{{
""input"": {{
""prompt"": ""User food preference: noodles"",
""memory_id"":""{memoryId}""
}},
""parameters"": {{}},
""debug"": {{}}
}}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}Response example
{
"output": {
"finish_reason": "stop",
"session_id": "c24255e945b94f22bc3fe5fb515177c3",
"text": "Got it—you prefer noodles. If you want recommendations or info about tasty noodle dishes or restaurants, tell me more. For example: Where are you now? What cuisine do you like—Sichuan, northern Chinese, etc.? Or do you have special needs—like vegetarian options? That way, I can help better."
},
"usage": {
"models": [
{
"output_tokens": 59,
"model_id": "qwen-max",
"input_tokens": 146
}
]
},
"request_id": "f732635f-3082-9dfe-9c09-df679d6d5b2e"
}Request example (call again)
using System.Text;
class Program
{
static async Task Main(string[] args)
{
// If you have not set an environment variable, replace the next line with: apiKey="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
string appId = "YOUR_APP_ID";// Replace with your actual application ID
string memoryId = "YOUR_MEMORY_ID";//Replace with your actual memory ID
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("Make sure DASHSCOPE_API_KEY is set.");
return;
}
string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string jsonContent = $@"{{
""input"": {{
""prompt"": ""Food recommendation"",
""memory_id"":""{memoryId}""
}},
""parameters"": {{}},
""debug"": {{}}
}}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}Response example
{
"output": {
"finish_reason": "stop",
"session_id": "665c16a3d10b48a0bb0ba92d42b6707b",
"text": "Since you love noodles, here are some suggestions:\n\n1. **Dandan noodles** – A Sichuan classic—spicy, numbing, and aromatic.\n2. **Zhajiangmian** – A Beijing favorite—savory yellow bean sauce and minced pork over noodles.\n3. **Daoxiao noodles** – A Shanxi signature—wide, chewy noodles served with hearty stews.\n4. **Hot dry noodles** – A Wuhan breakfast staple—sesame paste-based, topped with scallions and bean sprouts.\n5. **Beef ramen** – A famous Lanzhou dish—clear broth, tender beef, and springy noodles.\n\nIf you want global options, try Italian pasta or Japanese udon. Hope this helps! Let me know your taste preferences—I’ll tailor more suggestions."
},
"usage": {
"models": [
{
"output_tokens": 196,
"model_id": "qwen-max",
"input_tokens": 142
}
]
},
"request_id": "305c5058-708e-94ce-b8ee-3bf539e5f35c"
}Go
Request example (create memory content)
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If you have not set an environment variable, replace the next line with: apiKey := "sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // Replace with your actual application ID
if apiKey == "" {
fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Build request body
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "User food preference: noodles",
"memory_id": "YOUR_MEMORY_ID", // Replace with your actual memory ID
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// Create HTTP POST request
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// Set request headers
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
// Read response
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// Process response
if resp.StatusCode == http.StatusOK {
fmt.Println("Request successful:")
fmt.Println(string(body))
} else {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
Response example
{
"output": {
"finish_reason": "stop",
"session_id": "2e2ac5be49d2469794f310a92f34c9c7",
"text": "Got it—you love noodles! If you want noodle recommendations or recipes, just ask—I’m happy to help! For example: Do you prefer Chinese noodles, Italian pasta, or something else?"
},
"usage": {
"models": [
{
"output_tokens": 53,
"model_id": "qwen-max",
"input_tokens": 119
}
]
},
"request_id": "3f1c66ba-1d19-98f2-89a5-4c3b53c80258"
}Request example (call again)
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If you have not set an environment variable, replace the next line with: apiKey := "sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // Replace with your actual application ID
if apiKey == "" {
fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Build request body
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "Food recommendation",
"memory_id": "YOUR_MEMORY_ID", // Replace with your actual memory ID
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// Create HTTP POST request
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// Set request headers
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
// Read response
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// Process response
if resp.StatusCode == http.StatusOK {
fmt.Println("Request successful:")
fmt.Println(string(body))
} else {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
Response example
{
"output": {
"finish_reason": "stop",
"session_id": "dcb3e991be904cfcb11b9b06109d4c73",
"text": "Since you love noodles, here are some styles to try:\n\n1. **Zhajiangmian**: A Beijing classic—noodles with savory yellow bean sauce and minced pork. Chewy and delicious.\n2. **Dandan noodles**: A Sichuan favorite—spicy, numbing, and refreshing. Topped with peanut crumbles and chili oil.\n3. **Daoxiao noodles**: A Shanxi specialty—wide, chewy noodles served with hearty meat-and-vegetable stews.\n4. **Spaghetti**: For global variety, try classic tomato meat sauce or creamy mushroom chicken pasta.\n\nHope this helps! Let me know if you prefer a certain flavor—or want more details.</text>
},
"usage": {
"models": [
{
"output_tokens": 167,
"model_id": "qwen-max",
"input_tokens": 142
}
]
},
"request_id": "08b629ce-b3dd-96b6-8177-6443893e0b66"
}Upload files (documents, images, videos, or audio)
In your agent application, you can upload files such as documents, images, videos, or audio, and ask questions based on their content.
Scenarios
Text parsing: You can extract text content from documents, images, videos, or audio, and combine the extracted content with large language models to answer questions.
Visual understanding: You can use the Qwen-VL series models to analyze image content (objects, scenes, and actions) without requiring text input.
To upload files and interact with large language models via the console, see Upload files.
For API usage, see below.
Text parsing
Step 1: Prepare files
Your files must meet these requirements.
You can upload up to 10 files, including local documents, images, videos, or audio files in the following formats:
Document (Up to 100 MB): .doc, .docx, .wps, .ppt, .pptx, .xls, .xlsx, .md, .txt, .pdf
Image (Up to 20 MB): .png, .jpg, .jpeg, .bmp, .gif
Currently, only local images that contain text are supported.
Videos (Up to 512 MB): .mp4, .mkv, .avi, .mov, .wmv
Audio (Up to 512 MB): .aac, .amr, .flac, .flv, .m4a, .mp3, .mpeg, .ogg, .opus, .wav, .webm, .wma
Step 2: Get a session file ID
You can obtain a session file ID starting with “file_session” using the API to obtain a session file ID.
Ensure the file status is FILE_IS_READY.
Step 3: Call your application via API
In the console agent application, you can select any model, turn on the dynamic file parsing switch, and then publish the application.
NoteYour agent application and the uploaded files must be in the same workspace.
When calling the API, you must pass the session file ID obtained in Step 2 in the
session_file_idsparameter. For example:In the Java SDK, this parameter is named
sessionFileIds. When you make an HTTP call, includesession_file_idsImportantThe session file ID must start with “
file_session_”, and its file status must be FILE_IS_READY. Otherwise, the call will fail.Python
Request example
import os from http import HTTPStatus # We recommend DashScope SDK version >= 1.20.14 from dashscope import Application response = Application.call( # If you have not set an environment variable, replace the next line with: api_key="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure. api_key=os.getenv("DASHSCOPE_API_KEY"), app_id='YOUR_APP_ID', # Replace YOUR_APP_ID with your actual application ID prompt='Please recommend a smartphone under ¥3,000 based on the following file', rag_options={ "session_file_ids": ["FILE_ID1"], # Replace FILE_ID1 with your actual temporary file ID, separated by commas } ) if response.status_code != HTTPStatus.OK: print(f'request_id={response.request_id}') print(f'code={response.status_code}') print(f'message={response.message}') print(f'For more information, see https://help.aliyun.com/en/model-studio/error-code') else: print('%s\n' % (response.output.text)) # Process text-only output # print('%s\n' % (response.usage))Response example
Based on your budget, I recommend the **Tongyi Vivid 7**. Key features include the following: - **Screen**: 6.5 inches, 1080 × 2400 pixels - **Storage & memory**: 128 GB storage, 8 GB RAM - **Battery**: 4,500 mAh - **Special features**: AI-powered smart photography, side-mounted fingerprint unlock - **Reference price**: ¥2,999–¥3,299 The Tongyi Vivid 7 offers great value, solid performance, and practical features—ideal for users who love photography. Hope this helps!Java
Request example
// We recommend DashScope SDK version >= 2.17.0 import com.alibaba.dashscope.app.*; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.exception.InputRequiredException; import com.alibaba.dashscope.exception.NoApiKeyException; import java.util.Arrays; public class Main { public static void appCall() throws NoApiKeyException, InputRequiredException { ApplicationParam param = ApplicationParam.builder() // If you have not set an environment variable, replace the next line with: .apiKey("sk-xxx"). However, avoid hard-coding your API key in production code to reduce the risk of exposure. .apiKey(System.getenv("DASHSCOPE_API_KEY")) .appId("YOUR_APP_ID") // Replace with your actual application ID .prompt("Please recommend a smartphone around ¥3,000 based on the following file") .ragOptions(RagOptions.builder() .sessionFileIds(Arrays.asList("FILE_ID1", "FILE_ID2")) // Replace with your actual temporary file IDs, separated by commas .build()) .build(); Application application = new Application(); ApplicationResult result = application.call(param); System.out.printf("%s\n", result.getOutput().getText());// Process text-only output } public static void main(String[] args) { try { appCall(); } catch (ApiException | NoApiKeyException | InputRequiredException e) { System.out.printf("Exception: %s", e.getMessage()); System.out.println("For more information, see https://help.aliyun.com/en/model-studio/error-code"); } System.exit(0); } }Response example
Based on your budget (around ¥3,000), I recommend the **Tongyi Vivid 7**. ### Tongyi Vivid 7 — Smart photography experience - **Screen**: 6.5 inches, 1080 × 2400 pixels - **Storage & memory**: 128 GB storage, 8 GB RAM - **Battery**: 4,500 mAh - **Special features**: AI-powered smart photography, side-mounted fingerprint unlock - **Reference price**: ¥2,999–¥3,299 This phone delivers excellent screen quality, ample storage and RAM, and strong battery life. Its AI smart photography feature brings professional-grade photos. Overall, it’s ideal for daily use—and fits your budget perfectly.HTTP
curl
Request example
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/{YOUR_APP_ID}/completion \ --header "Authorization: Bearer $DASHSCOPE_API_KEY" \ --header 'Content-Type: application/json' \ --data '{ "input": { "prompt": "Please recommend a smartphone under ¥3,000 based on the following file" }, "parameters": { "rag_options" : { "session_file_ids":["FILE_ID1"]} }, "debug": {} }'Response example
{"output":{"finish_reason":"stop","session_id":"fb0081f56ace400bb4f1c12f6b5d1247", "text":"Based on your budget (under ¥3,000), I recommend the **Tongyi Vivid 7**.\n\n### Why?\n- **Great value**: Reference price ¥2,999–¥3,299—fits your budget.\n- **Smart photography**: AI-powered tech captures pro-level photos—perfect for photo lovers.\n- **Balanced specs**: 6.5-inch 1080 × 2400 pixel screen, 8 GB RAM + 128 GB storage—smooth daily use.\n- **All-day battery**: 4,500 mAh—meets full-day needs.\n- **Secure & fast**: Side-mounted fingerprint unlock—convenient and safe.\n\nIn short, the Tongyi Vivid 7 excels in value and photo quality—ideal for budget-conscious users who love photography."},"usage":{"models":[{"output_tokens":201,"model_id":"qwen-max","input_tokens":1594}]},"request_id":"596f5055-2736-985d-8024-5849df5b799b"}%PHP
Request example
<?php # If you have not set an environment variable, replace the next line with: $api_key="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure. $api_key = getenv("DASHSCOPE_API_KEY"); $application_id = 'YOUR_APP_ID'; // Replace with your actual application ID $url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion"; // Build request data $data = [ "input" => [ 'prompt' => 'Please recommend a smartphone under ¥3,000 based on the following file' ], "parameters" => [ 'rag_options' => [ 'session_file_ids' => ['FILE_ID1']//Replace with your actual temporary file ID, separated by commas ] ] ]; // Encode data as JSON $dataString = json_encode($data); // Check if json_encode succeeded if (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg()); } // Initialize cURL session $ch = curl_init($url); // Set cURL options curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key ]); // Execute request $response = curl_exec($ch); // Check if cURL execution succeeded if ($response === false) { die("cURL Error: " . curl_error($ch)); } // Get HTTP status code $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Close cURL session curl_close($ch); // Decode response data $response_data = json_decode($response, true); // Process response if ($status_code == 200) { if (isset($response_data['output']['text'])) { echo "{$response_data['output']['text']}\n"; } else { echo "No text in response.\n"; } }else { if (isset($response_data['request_id'])) { echo "request_id={$response_data['request_id']}\n";} echo "code={$status_code}\n"; if (isset($response_data['message'])) { echo "message={$response_data['message']}\n";} else { echo "message=Unknown error\n"; } } ?>Response example
Based on your budget (under ¥3,000), I recommend the **Tongyi Vivid 7**. Key features include the following: - **Screen**: 6.5 inches, 1080 × 2400 pixels - **Storage & memory**: 128 GB storage, 8 GB RAM - **Battery**: 4,500 mAh - **Special features**: AI-powered smart photography, side-mounted fingerprint unlock - **Reference price**: ¥2,999–¥3,299 The Tongyi Vivid 7 delivers great value and top-tier performance—especially in photography. Ideal for users who want both affordability and high-quality photos. Hope this helps! Let me know if you have other questions.Node.js
Install dependencies:
npm install axiosRequest example
const axios = require('axios'); async function callDashScope() { // If you have not set an environment variable, replace the next line with: apiKey='sk-xxx'. However, avoid hard-coding your API key in production code to reduce the risk of exposure. const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID';//Replace with your actual application ID const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "Please recommend a smartphone under ¥3,000 based on the following file" }, parameters: { rag_options:{ session_file_ids:['YOUR_FILE_ID1'] // Replace with your actual temporary file ID, separate multiple IDs with commas } }, debug: {} }; try { const response = await axios.post(url, data, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' } }); if (response.status === 200) { console.log(`${response.data.output.text}`); } else { console.log(`request_id=${response.headers['request_id']}`); console.log(`code=${response.status}`); console.log(`message=${response.data.message}`); } } catch (error) { console.error(`Error calling DashScope: ${error.message}`); if (error.response) { console.error(`Response status: ${error.response.status}`); console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();Response example
Based on your budget (under ¥3,000), I recommend the **Tongyi Vivid 7**. ### Why? - **Great screen**: 6.5-inch 1080 × 2400 pixel full-screen display—crisp visuals. - **AI smart photography**: Automatically enhances color and detail—capture pro-level photos easily. - **Ample memory & storage**: 8 GB RAM + 128 GB storage—handles daily tasks and entertainment. - **All-day battery**: 4,500 mAh—lasts all day. - **Fast, secure unlock**: Side-mounted fingerprint sensor—quick and convenient. - **Great value**: Reference price ¥2,999–¥3,299—within your budget. In short, if you care about photography and value, the Tongyi Vivid 7 is a great choice. Of course, check official channels or authorized retailers for the latest pricing and offers.C#
Request example
using System.Text; class Program { static async Task Main(string[] args) { // If you have not set an environment variable, replace the next line with: apiKey="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure. string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");; string appId = "YOUR_APP_ID";// Replace with your actual application ID // Replace FILE_ID1 with your actual temporary file ID if (string.IsNullOrEmpty(apiKey)) { Console.WriteLine("Make sure DASHSCOPE_API_KEY is set."); return; } string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); string jsonContent = $@"{{ ""input"": {{ ""prompt"": ""Please recommend a smartphone under ¥3,000 based on the following file"" }}, ""parameters"": {{ ""rag_options"" : {{ ""session_file_ids"":[""FILE_ID1""] }} }}, ""debug"": {{}} }}"; HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await client.PostAsync(url, content); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } else { Console.WriteLine($"Request failed with status code: {response.StatusCode}"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch (Exception ex) { Console.WriteLine($"Error calling DashScope: {ex.Message}"); } } } }Response example
{ "output": { "finish_reason": "stop", "session_id": "11c4c233714d45129fb9b63a7e708fb8", "text": "Based on your budget (under ¥3,000), I recommend the **Tongyi Vivid 7**. Key features include the following:\n\n- **Screen**: 6.5 inches, 1080 × 2400 pixels\n- **Storage & memory**: 128 GB storage, 8 GB RAM\n- **Battery**: 4,500 mAh\n- **Special features**: AI-powered smart photography, side-mounted fingerprint unlock\n- **Reference price**: ¥2,999–¥3,299\n\nThough its top-tier version slightly exceeds ¥3,000, its outstanding value and photography performance make it a great choice. Watch for promotions on e-commerce sites or official channels to get it at a lower price." }, "usage": { "models": [ { "output_tokens": 177, "model_id": "qwen-max", "input_tokens": 1594 } ] }, "request_id": "663c2641-bfe3-908e-a10f-5ccb819cb136" }Go
Request example
package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // If you have not set an environment variable, replace the next line with: apiKey := "sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure. apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // Replace with your actual application ID if apiKey == "" { fmt.Println("Make sure DASHSCOPE_API_KEY is set.") return } url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId) // Build request body requestBody := map[string]interface{}{ "input": map[string]string{ "prompt": "Please recommend a smartphone under ¥3,000 based on the following file", }, "parameters": map[string]interface{}{ "rag_options": map[string]interface{}{ "session_file_ids": []string{"FILE_ID1"}, // Replace with your actual temporary file ID }, }, "debug": map[string]interface{}{}, } jsonData, err := json.Marshal(requestBody) if err != nil { fmt.Printf("Failed to marshal JSON: %v\n", err) return } // Create HTTP POST request req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Failed to create request: %v\n", err) return } // Set request headers req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") // Send request client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("Failed to send request: %v\n", err) return } defer resp.Body.Close() // Read response body, err := io.ReadAll(resp.Body) if err != nil { fmt.Printf("Failed to read response: %v\n", err) return } // Process response if resp.StatusCode == http.StatusOK { fmt.Println("Request successful:") fmt.Println(string(body)) } else { fmt.Printf("Request failed with status code: %d\n", resp.StatusCode) fmt.Println(string(body)) } }Response example
{ "output": { "finish_reason": "stop", "session_id": "846db8ba50514d69bfa0faebd639cb33", "text": "Based on your budget, I recommend the **Tongyi Vivid 7 — Smart Photography Experience**. It has a 6.5-inch full-screen display, 8 GB RAM and 128 GB storage, AI-powered smart photography, and a 4,500 mAh battery—meeting everyday needs. Its side-mounted fingerprint unlock is both convenient and secure. Reference price: ¥2,999–¥3,299—fitting your budget. Hope this helps!" }, "usage": { "models": [ { "output_tokens": 106, "model_id": "qwen-max", "input_tokens": 1594 } ] }, "request_id": "af305d07-a24a-9163-a015-4ec52909ec55" }
Get a session file ID via API
Visual understanding
Steps
In the console agent application, you can select the Qwen-VL series models, turn on the visual switch, and then publish the application.
When calling the API, you can pass image URLs in the
image_listparameter. You can pass multiple URLs. For example:In the Java SDK, use images. In HTTP calls, place image_list inside the input object.
Python
Request example
import os from http import HTTPStatus # We recommend DashScope SDK version >= 1.20.14 from dashscope import Application response = Application.call( # If you have not set an environment variable, replace the next line with: api_key="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure. api_key=os.getenv("DASHSCOPE_API_KEY"), app_id='YOUR_APP_ID', # Replace YOUR_APP_ID with your actual application ID prompt='What scene does this image depict?', image_list=["https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"], # Replace with your actual image URL, separated by commas ) if response.status_code != HTTPStatus.OK: print(f'request_id={response.request_id}') print(f'code={response.status_code}') print(f'message={response.message}') print(f'For more information, see https://help.aliyun.com/en/model-studio/error-code') else: print('%s\n' % (response.output.text)) # Process text-only output # print('%s\n' % (response.usage))Response example
This image depicts a woman and a dog interacting on a beach. The woman sits on the sand, smiling warmly as she shakes hands with the dog. The background shows ocean and sky, with sunlight shining down—creating a warm, harmonious mood.Java
Request example
// We recommend DashScope SDK version >= 2.17.0 import com.alibaba.dashscope.app.*; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.exception.InputRequiredException; import com.alibaba.dashscope.exception.NoApiKeyException; import java.util.Arrays; import java.util.List; public class Main { public static void appCall() throws NoApiKeyException, InputRequiredException { ApplicationParam param = ApplicationParam.builder() // If you have not set an environment variable, replace the next line with: .apiKey("sk-xxx"). However, avoid hard-coding your API key in production code to reduce the risk of exposure. .apiKey(System.getenv("DASHSCOPE_API_KEY")) .appId("YOUR_APP_ID") // Replace with your actual application ID .prompt("What scene does this image depict?") .images(Arrays.asList("https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg")) // Replace with your actual image URL, separated by commas .build(); Application application = new Application(); ApplicationResult result = application.call(param); System.out.printf("%s\n", result.getOutput().getText());// Process text-only output } public static void main(String[] args) { try { appCall(); } catch (ApiException | NoApiKeyException | InputRequiredException e) { System.out.printf("Exception: %s", e.getMessage()); System.out.println("For more information, see https://help.aliyun.com/en/model-studio/error-code"); } System.exit(0); } }Response example
This image depicts a woman and a dog interacting on a beach. The woman sits on the sand, smiling warmly as she shakes hands with the dog. The background shows ocean and sky, with sunlight shining down—creating a warm, harmonious mood.HTTP
curl
Request example
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/{YOUR_APP_ID}/completion \ --header "Authorization: Bearer $DASHSCOPE_API_KEY" \ --header 'Content-Type: application/json' \ --data '{ "input": { "prompt": "What scene does this image depict?", "image_list":["https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"] }, "debug": {} }'Response example
{ "output": { "finish_reason": "stop", "session_id": "6c67678038e14f138f384e477e7126f6", "text": "This image depicts a woman and a dog interacting on a beach. The woman sits on the sand, smiling warmly as she shakes hands with the dog. The background shows ocean and sky, with sunlight shining down—creating a warm, harmonious mood." }, "usage": { "models": [ { "output_tokens": 49, "model_id": "qwen-vl-max", "input_tokens": 1305 } ] }, "request_id": "4a8a6a76-eecd-9298-a0fb-16a4c8f9a205" }PHP
Request example
<?php # If you have not set an environment variable, replace the next line with: $api_key="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure. $api_key = getenv("DASHSCOPE_API_KEY"); $application_id = 'YOUR_APP_ID'; // Replace with your actual application ID $url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion"; // Build request data $data = [ "input" => [ 'prompt' => 'What scene does this image depict?', 'image_list' => ['https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg']//Replace with your actual image URL, separated by commas ] ]; // Encode data as JSON $dataString = json_encode($data); // Check if json_encode succeeded if (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg()); } // Initialize cURL session $ch = curl_init($url); // Set cURL options curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key ]); // Execute request $response = curl_exec($ch); // Check if cURL execution succeeded if ($response === false) { die("cURL Error: " . curl_error($ch)); } // Get HTTP status code $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Close cURL session curl_close($ch); // Decode response data $response_data = json_decode($response, true); // Process response if ($status_code == 200) { if (isset($response_data['output']['text'])) { echo "{$response_data['output']['text']}\n"; } else { echo "No text in response.\n"; } } else { if (isset($response_data['request_id'])) { echo "request_id={$response_data['request_id']}\n";} echo "code={$status_code}\n"; if (isset($response_data['message'])) { echo "message={$response_data['message']}\n";} else { echo "message=Unknown error\n"; } } ?>Response example
This image depicts a woman and a dog interacting on a beach. The woman sits on the sand, smiling warmly as she shakes hands with the dog. The background shows ocean and sky, with sunlight shining down—creating a warm, harmonious mood.Node.js
Install dependencies:
npm install axiosRequest example
const axios = require('axios'); async function callDashScope() { // If you have not set an environment variable, replace the next line with: apiKey='sk-xxx'. However, avoid hard-coding your API key in production code to reduce the risk of exposure. const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID';//Replace with your actual application ID const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "What scene does this image depict?", image_list:['https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg'] // Replace with your actual image URL, separate multiple URLs with commas }, debug: {} }; try { const response = await axios.post(url, data, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' } }); if (response.status === 200) { console.log(`${response.data.output.text}`); } else { console.log(`request_id=${response.headers['request_id']}`); console.log(`code=${response.status}`); console.log(`message=${response.data.message}`); } } catch (error) { console.error(`Error calling DashScope: ${error.message}`); if (error.response) { console.error(`Response status: ${error.response.status}`); console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();Response example
This image depicts a woman and a dog interacting on a beach. The woman sits on the sand, smiling warmly as she shakes hands with the dog. The background shows ocean and sky, with sunlight shining down—creating a warm, harmonious mood.C#
Request example
using System.Text; class Program { static async Task Main(string[] args) { // If you have not set an environment variable, replace the next line with: apiKey="sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure. string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");; string appId = "YOUR_APP_ID";// Replace with your actual application ID if (string.IsNullOrEmpty(apiKey)) { Console.WriteLine("Make sure DASHSCOPE_API_KEY is set."); return; } string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion"; // Replace image_list with your actual image URL—if multiple, separate with commas using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); string jsonContent = $@"{{ ""input"": {{ ""prompt"": ""What scene does this image depict?"", ""image_list"":[""https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"" ] }}, ""debug"": {{}} }}"; HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await client.PostAsync(url, content); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } else { Console.WriteLine($"Request failed with status code: {response.StatusCode}"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch (Exception ex) { Console.WriteLine($"Error calling DashScope: {ex.Message}"); } } } }Response example
{ "output": { "finish_reason": "stop", "session_id": "5149b58d713e49ed80c30372aee377ae", "text": "This image depicts a woman and a dog interacting on a beach. The woman sits on the sand, smiling warmly as she shakes hands with the dog. The background shows ocean and sky, with sunlight shining down—creating a warm, harmonious mood." }, "usage": { "models": [ { "output_tokens": 49, "model_id": "qwen-vl-max", "input_tokens": 1305 } ] }, "request_id": "702810f5-d21d-9b74-8b4f-e58d0a8da413" }Go
Request example
package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // If you have not set an environment variable, replace the next line with: apiKey := "sk-xxx". However, avoid hard-coding your API key in production code to reduce the risk of exposure. apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // Replace with your actual application ID if apiKey == "" { fmt.Println("Make sure DASHSCOPE_API_KEY is set.") return } url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId) // Build request body requestBody := map[string]interface{}{ "input": map[string]interface{}{ "prompt": "What scene does this image depict?", "image_list": []string{"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"}, // Replace with your actual image URL, separate multiple URLs with commas }, "debug": map[string]interface{}{}, } jsonData, err := json.Marshal(requestBody) if err != nil { fmt.Printf("Failed to marshal JSON: %v\n", err) return } // Create HTTP POST request req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Failed to create request: %v\n", err) return } // Set request headers req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") // Send request client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("Failed to send request: %v\n", err) return } defer resp.Body.Close() // Read response body, err := io.ReadAll(resp.Body) if err != nil { fmt.Printf("Failed to read response: %v\n", err) return } // Process response if resp.StatusCode == http.StatusOK { fmt.Println("Request successful:") fmt.Println(string(body)) } else { fmt.Printf("Request failed with status code: %d\n", resp.StatusCode) fmt.Println(string(body)) } }Response example
{ "output": { "finish_reason": "stop", "session_id": "8a3d495588d34c2e99ea42b12d265c31", "text": "This image depicts a woman and a dog interacting on a beach. The woman wears a plaid shirt and sits on the sand, engaging closely with her pet dog. The dog wears a collar and extends its front paw to shake hands with the woman—friendly and gentle. The background shows vast ocean and sky, with sunlight shining down—creating a warm, harmonious mood. This photo captures a beautiful moment of friendship between human and animal." }, "usage": { "models": [ { "output_tokens": 88, "model_id": "qwen-vl-max", "input_tokens": 2554 } ] }, "request_id": "22db4110-6c7b-9b06-8769-c8a1a3edfd39" }
API Reference
For a complete list of parameters, refer to the Workflow and Legacy Agent Application API.
Error codes
If the call fails and returns an error message, see error messages for troubleshooting steps.
References
For converting a model's text response to speech when an application is invoked, see Real-time speech synthesis - CosyVoice/Sambert.
For building and using applications, see Agent applications.
For using the prompt supporting tool within an application, see Prompt engineering.
For use in a frontend production environment, see Add an AI assistant to your website in 10 minutes.




