Request body
|
Single-turn
Python
Request example
import os
from http import HTTPStatus
from dashscope import Application
response = Application.call(
# If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx").
# For security, we recommend using environment variables instead of hardcoding keys.
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='APP_ID', # Replace with your 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 the documentation: https://help.aliyun.com/en/model-studio/developer-reference/error-code')
else:
print(response.output.text)
Java
Request example
// We recommend using 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 not using an environment variable, set your API key directly (e.g., .apiKey("sk-xxx")).
// For security, we recommend using environment variables instead of hardcoding keys.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("APP_ID") // Replace with your application 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 the documentation: https://help.aliyun.com/en/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTP
curl
Request example
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "Who are you?"
},
"parameters": {},
"debug": {}
}'
Replace APP_ID with your application ID.
PHP
Request example
<?php
# If not using an environment variable, set your API key directly (e.g., $api_key="sk-xxx").
# For security, we recommend using environment variables instead of hardcoding keys.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with your application ID.
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
// Construct the request data
$data = [
"input" => [
'prompt' => 'Who are you?'
]
];
// 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";}
}
?>
Node.js
Install the required dependency: npm install axios
Request example
const axios = require('axios');
async function callDashScope() {
// If not using an environment variable, set your API key directly (e.g., apiKey='sk-xxx').
// For security, we recommend using environment variables instead of hardcoding keys.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';// Replace with your 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();
C#
Request example
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// If not using an environment variable, set your API key directly (e.g., apiKey="sk-xxx").
// For security, we recommend using environment variables instead of hardcoding keys.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "APP_ID"; // Replace with your 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}");
}
}
}
}
Go
Request example
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If not using an environment variable, set your API key directly (e.g., apiKey := "sk-xxx").
// For security, we recommend using environment variables instead of hardcoding keys.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // Replace with your application ID.
if apiKey == "" {
fmt.Println("Ensure the DASHSCOPE_API_KEY environment variable 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": "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 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
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))
}
}
Multi-turn
For multi-turn conversations, use a session_id to maintain the conversation context:
1. First request: Do not include a session_id. The API returns a new session_id in the response.
2. Subsequent requests: Include the session_id from the previous response to continue the conversation.
3. Validity period: The session_id expires after 1 hour of inactivity.
Python
Request example
import os
from http import HTTPStatus
from dashscope import Application
def call_with_session():
response = Application.call(
# If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx").
# For security, we recommend using environment variables instead of hardcoding keys.
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='APP_ID', # Replace with your 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 the documentation: https://help.aliyun.com/en/model-studio/developer-reference/error-code')
return response
responseNext = Application.call(
# If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx").
# For security, we recommend using environment variables instead of hardcoding keys.
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='APP_ID', # Replace with your application ID.
prompt='What are your skills?',
session_id=response.output.session_id) # 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'Refer to the documentation: 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()
Java
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 not using an environment variable, set your API key directly (e.g., .apiKey("sk-xxx")).
// For security, we recommend using environment variables instead of hardcoding keys.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// Replace with your application ID.
.appId("APP_ID")
.prompt("Who are you?")
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
param.setSessionId(result.getOutput().getSessionId());
param.setPrompt("What are your skills?");
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("Refer to the documentation: https://help.aliyun.com/en/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTP
curl
Request example (first turn)
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "Who are you?"
},
"parameters": {},
"debug": {}
}'
Request example (next turn)
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "What are your skills?",
"session_id":"4f8ef7233dc641aba496cb201fa59f8c"
},
"parameters": {},
"debug": {}
}'
PHP
Request example (first turn)
<?php
# If not using an environment variable, set your API key directly (e.g., $api_key="sk-xxx").
# For security, we recommend using environment variables instead of hardcoding keys.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with your application ID.
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
// Construct the request data
$data = [
"input" => [
'prompt' => 'Who are you?'
]
];
// 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";
};
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";}
}
?>
Request example (next turn)
<?php
# If not using an environment variable, set your API key directly (e.g., $api_key="sk-xxx").
# For security, we recommend using environment variables instead of hardcoding keys.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with your application ID.
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
// Construct the request data
$data = [
"input" => [
'prompt' => 'What are your skills?',
// Replace with the session_id from the previous turn.
'session_id' => '2e658bcb514f4d30ab7500b4766a8d43'
]
];
// 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";
};
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";}
}
?>
Node.js
Install the required dependency: npm install axios
Request example (first turn)
const axios = require('axios');
async function callDashScope() {
// If not using an environment variable, set your API key directly (e.g., apiKey='sk-xxx').
// For security, we recommend using environment variables instead of hardcoding keys.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';// Replace with your 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();
Request example (next turn)
const axios = require('axios');
async function callDashScope() {
// If not using an environment variable, set your API key directly (e.g., apiKey='sk-xxx').
// For security, we recommend using environment variables instead of hardcoding keys.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';// Replace with your application ID.
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
// Replace with the session_id from the previous turn.
const data = {
input: {
prompt: "What are your skills?",
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();
C#
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 not using an environment variable, set your API key directly (e.g., apiKey="sk-xxx").
// For security, we recommend using environment variables instead of hardcoding keys.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "APP_ID"; // Replace with your 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}");
}
}
}
}
Request example (next turn)
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// If not using an environment variable, set your API key directly (e.g., apiKey="sk-xxx").
// For security, we recommend using environment variables instead of hardcoding keys.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "APP_ID"; // Replace with your 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 are your skills?"",
""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}");
}
}
}
}
Go
Request example (first turn)
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If not using an environment variable, set your API key directly (e.g., apiKey := "sk-xxx").
// For security, we recommend using environment variables instead of hardcoding keys.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // Replace with your application ID.
if apiKey == "" {
fmt.Println("Ensure the DASHSCOPE_API_KEY environment variable 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": "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 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
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))
}
}
Request example (next turn)
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If not using an environment variable, set your API key directly (e.g., apiKey := "sk-xxx").
// For security, we recommend using environment variables instead of hardcoding keys.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // Replace with your application ID.
if apiKey == "" {
fmt.Println("Ensure the DASHSCOPE_API_KEY environment variable 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 are your skills?",
"session_id": "f7eea37f0c734c20998a021b688d6de2", // Replace with the session_id from the previous turn.
},
"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 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))
}
}
Replace APP_ID with your application ID. For subsequent turns, use the session_id returned in the previous response.
Streaming output
Use stream to enable streaming output.
Python
Request example
import os
from http import HTTPStatus
from dashscope import Application
responses = Application.call(
# If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx").
# For security, we recommend using environment variables instead of hardcoding keys.
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='APP_ID', # Replace with your application 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'Refer to the documentation: https://help.aliyun.com/en/model-studio/developer-reference/error-code')
else:
print(f'{response.output.text}\n') # Process the text-only output.
Java
Request example
// We recommend using 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;// For streaming output.
// Implement streaming output for agent application calls.
public class Main {
public static void streamCall() throws NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// If not using an environment variable, set your API key directly (e.g., .apiKey("sk-xxx")).
// For security, we recommend using environment variables instead of hardcoding keys.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// Replace with your application ID.
.appId("APP_ID")
.prompt("Who are you?")
// Enable incremental output.
.incrementalOutput(true)
.build();
Application application = new Application();
// Use .streamCall() for 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("Refer to the documentation: https://help.aliyun.com/en/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTP
curl
Request example
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/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 APP_ID with your application ID.
PHP
Request example
<?php
// If not using an environment variable, set your API key directly (e.g., $api_key="sk-xxx").
// For security, we recommend using environment variables instead of hardcoding keys.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with your application ID.
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
// Construct the request data
$data = [
"input" => [
'prompt' => 'Who are you?'],
"parameters" => [
'incremental_output' => true]];// Enable incremental output.
// 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, false); // Do not return the transferred data.
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $string) {
echo $string; // Process the 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 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);
if ($status_code != 200) {
echo "HTTP Status Code: $status_code\n";
echo "Request Failed.\n";
}
?>
Node.js
Install the required dependency: npm install axios
Request example
1. Output the full response
const axios = require('axios');
async function callDashScope() {
// If not using an environment variable, set your API key directly (e.g., apiKey='sk-xxx').
// For security, we recommend using environment variables instead of hardcoding keys.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';// Replace with your application ID.
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "Who are you?"
},
parameters: {
'incremental_output' : true // Enable incremental output.
},
debug: {}
};
try {
console.log("Sending request to DashScope API...");
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
'X-DashScope-SSE': 'enable' // Enable streaming output.
},
responseType: 'stream' // For handling streaming responses.
});
if (response.status === 200) {
// Handle the streaming response.
response.data.on('data', (chunk) => {
console.log(`Received chunk: ${chunk.toString()}`);
});
} 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();
Expand the following panel to view the content:
2. Output only the content of the text field
const axios = require('axios');
const { Transform } = require('stream');
async function callDashScope() {
// If not using an environment variable, set your API key directly (e.g., apiKey='sk-xxx').
// For security, we recommend using environment variables instead of hardcoding keys.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID'; // Replace with your application ID.
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: { prompt: "Who are you?" },
parameters: { incremental_output: true }, // Enable incremental output.
debug: {}
};
try {
console.log("Sending request to DashScope API...");
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
'X-DashScope-SSE': 'enable' // Enable streaming output.
},
responseType: 'stream' // For handling streaming responses.
});
if (response.status === 200) {
// Transform stream to parse the SSE protocol for streaming responses.
const sseTransformer = new Transform({
transform(chunk, encoding, callback) {
this.buffer += chunk.toString();
// Split by SSE events (two newline characters).
const events = this.buffer.split(/\n\n/);
this.buffer = events.pop() || ''; // Keep any incomplete part.
events.forEach(eventData => {
const lines = eventData.split('\n');
let textContent = '';
// Parse event content.
lines.forEach(line => {
if (line.startsWith('data:')) {
try {
const jsonData = JSON.parse(line.slice(5).trim());
if (jsonData.output?.text) {
textContent = jsonData.output.text;
}
} catch(e) {
console.error('JSON parsing error:', e.message);
}
}
});
if (textContent) {
// Add a newline and push it.
this.push(textContent + '\n');
}
});
callback();
},
flush(callback) {
if (this.buffer) {
this.push(this.buffer + '\n');
}
callback();
}
});
sseTransformer.buffer = '';
// Pipe processing.
response.data
.pipe(sseTransformer)
.on('data', (textWithNewline) => {
process.stdout.write(textWithNewline); // Output with automatic newlines.
})
.on('end', () => console.log(""))
.on('error', err => console.error("Pipe error:", err));
} else {
console.log("Request failed with status code:", response.status);
response.data.on('data', chunk => console.log(chunk.toString()));
}
} catch (error) {
console.error(`API call failed: ${error.message}`);
if (error.response) {
console.error(`Status code: ${error.response.status}`);
error.response.data.on('data', chunk => console.log(chunk.toString()));
}
}
}
callDashScope();
C#
Request example
using System.Net;
using System.Text;
class Program
{
static async Task Main(string[] args)
{
// If not using an environment variable, set your API key directly (e.g., apiKey="sk-xxx").
// For security, we recommend using environment variables instead of hardcoding keys.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "APP_ID"; // Replace with your 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 a 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}");
}
}
}
}
Go
Request example
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
)
func main() {
// If not using an environment variable, set your API key directly (e.g., apiKey := "sk-xxx").
// For security, we recommend using environment variables instead of hardcoding keys.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // Replace with your application ID.
if apiKey == "" {
fmt.Println("Ensure the DASHSCOPE_API_KEY environment variable is set.")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create the request body, where incremental_output enables the streaming response.
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" to enable the streaming response.
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
}
// Handle the 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
}
}
}
File Q&A
Pass the URLs of your files, such as documents, images, and videos, in the file_list parameter to enable the file Q&A feature.
Application configuration: Enable the Pre-parse Files switch in your application.
Python
Request example # The Dashscope SDK version must be 1.24.7 or later.
import os
from http import HTTPStatus
from dashscope import Application
responses = Application.call(
# If you have not configured an environment variable for your API key, replace the next line with api_key="sk-xxx". For security, do not hardcode your API Key in production code.
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID', # Replace YOUR_APP_ID with your application ID
prompt='Summarize the file content in one sentence',
stream=True, # Streaming output
incremental_output=True, # Incremental output
file_list=["https://dashscope.oss-cn-beijing.aliyuncs.com/audios/welcome.mp3"],
)
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/zh/model-studio/developer-reference/error-code')
else:
print('%s\n' % (response.output.text))
Response example This file is a short welcome
message that says, "Welcome
to Alibaba Cloud."
Java
Request example // The Dashscope SDK version must be 2.21.13 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 java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Main {
public static void appCall() throws NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// If you have not configured an environment variable for your API key, replace the next line with .apiKey("sk-xxx"). For security, do not hardcode your API Key in production code.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("YOUR_APP_ID") // Replace with your actual application ID
.prompt("Summarize the file content in one sentence")
.files(Arrays.asList(
"https://dashscope.oss-cn-beijing.aliyuncs.com/audios/welcome.mp3"))
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("%s\n",
result.getOutput().getText());// Process and output only the text
}
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/zh/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
Response example This file is a short welcome message that says, "Welcome to Alibaba Cloud."
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": "Summarize the file content in one sentence",
"file_list":["https://dashscope.oss-cn-beijing.aliyuncs.com/audios/welcome.mp3"]
},
"debug": {}
}'
Response example {
"output": {
"finish_reason": "stop",
"reject_status": false,
"session_id": "545547dddcbf4296af0173da1a6e5a74",
"text": "This file is a welcome message from Alibaba Cloud that says, \"Welcome to Alibaba Cloud.\""
},
"usage": {
"models": [
{
"input_tokens": 103,
"model_id": "qwen-plus-latest",
"output_tokens": 304
}
]
},
"request_id": "6900cfac-0aa5-4c6e-aa9c-7a69f7b4d5bc"
}
Visual understanding
Enable the visual understanding feature by passing an image URL or a Base64-encoded Data URL to the image_list parameter. The application must use the Image and Video Understanding model.
Note
To use a local image, encode it into a Base64 string and construct a Data URL in the data:[MIME_type];base64,{base64_image} format. The MIME_type must match the image format. For example, use image/png for PNG, image/jpeg for JPEG, and image/webp for WebP.
Python
URL request example import os
from http import HTTPStatus
# Use dashscope SDK version 1.20.14 or later.
from dashscope import Application
response = Application.call(
# If the environment variable is not set, replace the next line with api_key="sk-xxx" using your Model Studio API Key.
# Do not hardcode the API Key in production code to avoid security risks.
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='APP_ID', # Replace APP_ID with your application ID.
prompt='What is this?',
image_list=['https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg'],
)
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 and output only the text.
# print('%s\n' % (response.usage))
Base64 encoding example import os
import base64
from http import HTTPStatus
from dashscope import Application
# Encode the local image into a Base64 string.
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
# Encode the local image.
base64_image = encode_image("/path/to/your/image.jpeg") # Replace with the actual image path.
# Construct the Data URL. Note: The MIME type must match the image format.
data_url = f"data:image/jpeg;base64,{base64_image}"
# Call the application API.
response = Application.call(
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='APP_ID', # Replace APP_ID with your application ID.
prompt='What is in this image?',
image_list=[data_url], # Use the Data URL.
)
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))
Java
URL request example // Use dashscope SDK version 2.19.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 java.util.Arrays;
public class Main {
public static void appCall() throws NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// If the environment variable is not set, replace the next line with .apiKey("sk-xxx") using your Model Studio API Key.
// Do not hardcode the API Key in production code to avoid security risks.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("APP_ID") // Replace with your actual application ID.
.prompt("What is this?")
.images(Arrays.asList("https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"))
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("%s\n",
result.getOutput().getText());// Process and output only the text.
}
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);
}
}
Base64 encoding example // Use dashscope SDK version 2.19.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 java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
public class Main {
// Encode the local image into a Base64 string.
public static String encodeImage(String imagePath) throws IOException {
byte[] imageBytes = Files.readAllBytes(Paths.get(imagePath));
return Base64.getEncoder().encodeToString(imageBytes);
}
public static void appCall() throws NoApiKeyException, InputRequiredException, IOException {
// Encode the local image.
String base64Image = encodeImage("/path/to/your/image.jpeg"); // Replace with the actual image path.
// Construct the Data URL. Note: The MIME type must match the image format.
String dataUrl = "data:image/jpeg;base64," + base64Image;
ApplicationParam param = ApplicationParam.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("APP_ID") // Replace with your actual application ID.
.prompt("What is in this image?")
.images(Arrays.asList(dataUrl)) // Use the Data URL.
.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 | IOException 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);
}
}
HTTP
curl
URL request example curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/{APP_ID}/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "What is this?",
"image_list":["https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"]
},
"debug": {}
}'
Base64 encoding example # Encode the local image into a Base64 string.
base64_image=$(base64 -i /path/to/your/image.jpeg) # macOS/Linux
# Construct the Data URL. Note: The MIME type must match the image format.
data_url="data:image/jpeg;base64,${base64_image}"
# Call the application API.
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/{APP_ID}/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data "{
\"input\": {
\"prompt\": \"What is in this image?\",
\"image_list\": [\"${data_url}\"]
},
\"debug\": {}
}"
PHP
URL request example <?php
# If the environment variable is not set, replace the next line with $api_key="sk-xxx" using your Model Studio API Key.
# Do not hardcode the API Key in production code to avoid security risks.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = '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" => [
"prompt" => "What is this?",
"image_list" => ["https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"],
],
"debug" => [],
];
// 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);
// 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";}
}
?>
Base64 encoding example <?php
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID';
function encodeImage($imagePath) {
if (!file_exists($imagePath)) die("Error: Image file not found");
return base64_encode(file_get_contents($imagePath));
}
$base64Image = encodeImage("/path/to/your/image.jpeg");
$dataUrl = "data:image/jpeg;base64," . $base64Image;
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
$data = ["input" => ["prompt" => "What is in this image?", "image_list" => [$dataUrl]], "debug" => []];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Authorization: Bearer ' . $api_key]);
$response = curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status_code == 200) {
$response_data = json_decode($response, true);
echo $response_data['output']['text'];
}
?>
Node.js
Install the required dependency: npm install axios
URL request example import axios from 'axios';
async function callDashScope() {
// If the environment variable is not set, replace the next line with apiKey='sk-xxx' using your Model Studio API Key.
// Do not hardcode the API Key in production code to avoid security risks.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';// Replace with your actual application ID.
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "What is this?",
image_list: ["https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"],
},
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();
Base64 encoding example import axios from 'axios';
import fs from 'fs';
async function callWithBase64() {
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';
const imageBuffer = fs.readFileSync('/path/to/your/image.jpeg');
const base64Image = imageBuffer.toString('base64');
const dataUrl = `data:image/jpeg;base64,${base64Image}`;
const response = await axios.post(
`https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`,
{ input: { prompt: "What is in this image?", image_list: [dataUrl] } },
{ headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' } }
);
console.log(response.data.output.text);
}
callWithBase64();
C#
URL request example using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// If the environment variable is not set, replace the next line with apiKey="sk-xxx" using your Model Studio API Key.
// Do not hardcode the API Key in production code to avoid security risks.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
string appId = "APP_ID";// Replace with your actual application ID.
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("Make sure the DASHSCOPE_API_KEY environment variable 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"": ""What is this?"",
""image_list"": [""https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg""]
}},
""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}");
}
}
}
}
Base64 encoding example using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
var apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
var appId = "APP_ID";
byte[] imageBytes = File.ReadAllBytes("/path/to/your/image.jpeg");
var base64Image = Convert.ToBase64String(imageBytes);
var dataUrl = $"data:image/jpeg;base64,{base64Image}";
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
var json = $@"{{""input"": {{""prompt"": ""What is in this image?"", ""image_list"": [""{dataUrl}""]}}, ""debug"": {{}}}}";
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync($"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion", content);
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
}
Go
URL request example package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If the environment variable is not set, replace the next line with apiKey := "sk-xxx" using your Model Studio API Key.
// Do not hardcode the API Key in production code to avoid security risks.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // Replace with your actual application ID.
if apiKey == "" {
fmt.Println("Make sure the DASHSCOPE_API_KEY environment variable 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": "What is this?",
"image_list": []string{"https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"},
},
"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))
}
}
Base64 encoding example package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID"
imageData, _ := os.ReadFile("/path/to/your/image.jpeg")
base64Image := base64.StdEncoding.EncodeToString(imageData)
dataUrl := fmt.Sprintf("data:image/jpeg;base64,%s", base64Image)
requestBody := map[string]interface{}{
"input": map[string]interface{}{"prompt": "What is in this image?", "image_list": []string{dataUrl}},
}
jsonData, _ := json.Marshal(requestBody)
req, _ := http.NewRequest("POST", fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId), bytes.NewBuffer(jsonData))
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, _ := client.Do(req)
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
}
Pass custom parameters
Pass custom parameters using biz_params. For more information, see Call an agent application - Pass custom parameters.
Python
Request example
import os
from http import HTTPStatus
# Use dashscope SDK version 1.14.0 or later.
from dashscope import Application
biz_params = {
# Pass custom input parameters for the agent application's tool. Replace <TOOL_ID> with your tool ID.
"user_defined_params": {
"<TOOL_ID>": {
"article_index": 2}}}
response = Application.call(
# If the environment variable is not set, replace the next line with api_key="sk-xxx". Avoid hardcoding the API Key in production to reduce security risks.
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='APP_ID',
prompt='Dormitory rules',
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/zh/model-studio/developer-reference/error-code')
else:
print('%s\n' % (response.output.text))
Java
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 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 tool. Replace <TOOL_ID> with your tool ID.
"{\"user_defined_params\":{\"<TOOL_ID>\":{\"article_index\":2}}}";
ApplicationParam param = ApplicationParam.builder()
// If the environment variable is not set, replace the next line with .apiKey("sk-xxx"). Avoid hardcoding the API Key in production to reduce security risks.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("APP_ID")
.prompt("Dormitory rules")
.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/zh/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTP
Request example
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "Dormitory rules",
"biz_params":
{
"user_defined_params":
{
"<TOOL_ID>":
{
"article_index": 2
}
}
}
},
"parameters": {},
"debug":{}
}'
Replace APP_ID with your application ID. Replace <TOOL_ID> with your tool ID.
|