Request body | Sample requestSingle-round conversationPythonSample request import os
from http import HTTPStatus
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
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://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
else:
print(response.output.text)
JavaSample 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;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
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://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPCurlSample request curl -X POST https://dashscope-intl.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. PHPSample 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-intl.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";}
}
?>
Node.jsDependency: 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-intl.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#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-intl.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}");
}
}
}
}
GoSample 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-intl.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))
}
}
Multi-round conversationPass session_id or messages to implement multi-round conversation. For more information, see Multi-round conversation. Currently, only Agent Applications and Dialog Workflow Applications support multi-round conversation. PythonSample request import os
from http import HTTPStatus
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
def call_with_session():
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://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
return response
responseNext = 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='What skills do you have?',
session_id=response.output.session_id) # 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: https://www.alibabacloud.com/help/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()
JavaSample 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 java.util.Arrays;
import java.util.List;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void callWithSession()
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"))
// Replace with the 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("Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPCurlSample request (round 1) curl -X POST https://dashscope-intl.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": {}
}'
Sample request (round 2) curl -X POST https://dashscope-intl.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": {}
}'
PHPSample request (round 1) <?php
# If the environment variable is not configured, you can replace the next 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 the actual application ID
$url = "https://dashscope-intl.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";
};
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";
}
}
?>
Sample request (round 2) <?php
# If the environment variable is not configured, you can replace the next 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 the actual application ID
$url = "https://dashscope-intl.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 from the previous round of conversation
'session_id' => '2e658bcb514f4d30ab7500b4766a8d43'
]
];
// 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";
}
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.jsDependency: npm install axios
Sample request (round 1) 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-intl.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();
Sample request (round 2) 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-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
// Replace session_id with the actual session_id from the previous conversation
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();
C#Sample request (round 1) 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-intl.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 request (round 2) 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-intl.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}");
}
}
}
}
GoSample request (round 1) 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 make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope-intl.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 request (round 2) 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 make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create request body
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "What skills do you have?",
"session_id": "f7eea37f0c734c20998a021b688d6de2", // Replace with the actual session_id from the 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 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))
}
}
Replace YOUR_APP_ID with the actual application ID. For round 2, replace the session_id with the actual session_id returned from round 1. Parameter passingPythonSample request import os
from http import HTTPStatus
# Recommended dashscope SDK version >= 1.14.0
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
biz_params = {
# Custom plug-in input parameter passing for agent applications, replace your_plugin_code with your custom plug-in ID
"user_defined_params": {
"your_plugin_code": {
"article_index": 2}}}
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',
prompt='Dormitory convention 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'Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
else:
print('%s\n' % (response.output.text)) # Process text output only
# print('%s\n' % (response.usage))
JavaSample 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;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void appCall() throws NoApiKeyException, InputRequiredException {
String bizParams =
// Custom plug-in input parameter passing for agent applications, replace {your_plugin_code} with your custom plug-in ID
"{\"user_defined_params\":{\"{your_plugin_code}\":{\"article_index\":2}}}";
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("Dormitory convention 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("Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPCurlSample request curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "Dormitory convention content",
"biz_params":
{
"user_defined_params":
{
"{your_plugin_code}":
{
"article_index": 2
}
}
}
},
"parameters": {},
"debug":{}
}'
Replace YOUR_APP_ID with the actual application ID. PHPSample request <?php
# If environment variables are not configured, replace with the Dashscope API Key: $api_key="sk-xxx". However, it is not recommended to hard-code the API Key directly into the code in production environments to reduce the risk of API Key leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Replace with the actual application ID
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// Replace {your_plugin_code} with the actual plugin ID
// Construct request data
$data = [
"input" => [
'prompt' => 'Dormitory convention content',
'biz_params' => [
'user_defined_params' => [
'{your_plugin_code}' => [
'article_index' => 2
]
]
]
],
];
// Encode the 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);
// 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";}
}
?>
Node.jsDependency: 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 pluginCode = 'YOUR_PLUGIN_CODE';// Replace with the actual plug-in ID
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "Dormitory convention content",
biz_params: {
user_defined_params: {
[pluginCode]: {
// article_index is a variable for the custom plug-in, replace with the actual plug-in 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();
C#Sample request using System.Text;
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
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("Make sure you have set DASHSCOPE_API_KEY.");
return;
}
string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string pluginCode = "{your_plugin_code}"; // Replace {your_plugin_code} with the actual plug-in ID
string jsonContent = $@"{{
""input"": {{
""prompt"": ""Dormitory convention 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}");
}
}
}
}
GoSample 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
pluginCode := "YOUR_PLUGIN_CODE" // Replace with the actual plug-in ID
if apiKey == "" {
fmt.Println("Make sure you have set DASHSCOPE_API_KEY.")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create request body
requestBody := map[string]interface{}{
"input": map[string]interface{}{
"prompt": "Dormitory convention 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 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))
}
}
Streaming outputPythonSample request import os
from http import HTTPStatus
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
responses = Application.call(
# If environment variables are not configured, replace the following line with: 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=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID',
prompt='Who are you?',
stream=True, # Streaming output
incremental_output=True) # 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'Please refer to the documentation: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
else:
print(f'{response.output.text}\n') # Process to output only the text
JavaSample request // Recommended 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 implementation for streaming output results
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void streamCall() throws NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// If environment variables are not configured, replace the following line with: .apiKey("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.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// Replace with the actual application ID
.appId("YOUR_APP_ID")
.prompt("Who are you?")
// Incremental output
.incrementalOutput(true)
.build();
Application application = new Application();
// .streamCall(): Streaming output content
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("Please refer to the documentation: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPCurlSample request curl -X POST https://dashscope-intl.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 the actual application ID. PHPSample request <?php
// If environment variables are not configured, replace the following line with: $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 the actual application ID
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// Construct request data
$data = [
"input" => [
'prompt' => 'Who are you?'],
"parameters" => [
'incremental_output' => true]];// Incremental output
// 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, false); // Don't return the transferred 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' // Streaming output
]);
// Execute 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);
if ($status_code != 200) {
echo "HTTP Status Code: $status_code\n";
echo "Request Failed.\n";
}
?>
Node.jsDependency: npm install axios
Sample request 1. Output complete response const axios = require('axios');
async function callDashScope() {
// If environment variables are not configured, replace the following line with: apiKey='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.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// Replace with the actual application ID
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "Who are you?"
},
parameters: {
'incremental_output' : 'true' // 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' // Streaming output
},
responseType: 'stream' // For handling streaming responses
});
if (response.status === 200) {
// Process 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 panel to view the sample code: 2. Output only text field const axios = require('axios');
const { Transform } = require('stream');
async function callDashScope() {
// If environment variables are not configured, replace the following line with: apiKey='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.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID'; // Replace with the actual application ID
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: { prompt: "Who are you?" },
parameters: { incremental_output: true }, // 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' // Streaming output
},
responseType: 'stream' // For handling streaming responses
});
if (response.status === 200) {
// // Process streaming response SSE protocol parsing transformer
const sseTransformer = new Transform({
transform(chunk, encoding, callback) {
this.buffer += chunk.toString();
// Split by SSE events (two line feeds)
const events = this.buffer.split(/\n\n/);
this.buffer = events.pop() || ''; // Keep 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 line feed and push
this.push(textContent + '\n');
}
});
callback();
},
flush(callback) {
if (this.buffer) {
this.push(this.buffer + '\n');
}
callback();
}
});
sseTransformer.buffer = '';
// Pipeline processing
response.data
.pipe(sseTransformer)
.on('data', (textWithNewline) => {
process.stdout.write(textWithNewline); // Automatic line feed output
})
.on('end', () => console.log(""))
.on('error', err => console.error("Pipeline error:", err));
} else {
console.log("Request failed, 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#Sample request using System.Net;
using System.Text;
class Program
{
static async Task Main(string[] args)
{
// If environment variables are not configured, replace the following line with: apiKey="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.
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-intl.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}");
}
}
}
}
GoSample request package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
)
func main() {
// If environment variables are not configured, replace the following line with: apiKey := "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.
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-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create request body, where incremental_output indicates whether to enable 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 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, where X-DashScope-SSE set to enable indicates enabling streaming response
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-DashScope-SSE", "enable")
// 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()
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
}
}
}
Retrieve knowledge basePythonSample request import os
from http import HTTPStatus
# Recommended dashscope SDK version >= 1.20.11
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
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 YOUR_APP_ID with the application ID
prompt='Please recommend a mobile phone under 3000 yuan',
rag_options={
"pipeline_ids": ["YOUR_PIPELINE_ID1,YOUR_PIPELINE_ID2"], # Replace with actual knowledge base IDs, separate multiple IDs with 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'Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
else:
print('%s\n' % (response.output.text)) # Process text output only
# print('%s\n' % (response.usage))
JavaSample request // Recommended 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.Collections;
import java.util.List;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void streamCall() throws 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") // Replace with the actual application ID
.prompt("Please recommend a mobile phone around 3000 yuan")
.ragOptions(RagOptions.builder()
// Replace with the actual specified knowledge base IDs, separate multiple with commas
.pipelineIds(List.of("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 output only
}
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: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPCurlSample request curl -X POST https://dashscope-intl.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 mobile phone under 3000 yuan"
},
"parameters": {
"rag_options" : {
"pipeline_ids":["YOUR_PIPELINE_ID1"]}
},
"debug": {}
}'
Replace YOUR_APP_ID with the actual application ID, and YOUR_PIPELINE_ID1 with the specified knowledge base ID. PHPSample request <?php
# If the environment variable is not configured, you can replace the next 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 the actual application ID
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// Construct request data
$data = [
"input" => [
'prompt' => 'Please recommend a smartphone under 3000 yuan.'
],
"parameters" => [
'rag_options' => [
'pipeline_ids' => ['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'] // Replace with the specified knowledge base IDs; use commas to separate multiple IDs
]
]
];
// 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";
}
}
?>
Node.jsDependency: 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-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "Please recommend a mobile phone under 3000 yuan"
},
parameters: {
rag_options:{
pipeline_ids:['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'] // Replace with specified knowledge base IDs, separate multiple 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();
C#Sample request using System.Text;
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
// YOUR_PIPELINE_ID1 replace with specified knowledge base ID
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("Please make sure DASHSCOPE_API_KEY is set.");
return;
}
string url = $"https://dashscope-intl.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 mobile phone under 3000 yuan""
}},
""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}");
}
}
}
}
GoSample 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 make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create request body
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "Please recommend a mobile phone under 3000 yuan",
},
"parameters": map[string]interface{}{
"rag_options": map[string]interface{}{
"pipeline_ids": []string{"YOUR_PIPELINE_ID1"}, // Replace with specified 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))
}
}
View retrieval process: When making a call, add has_thoughts to the code and set it to True. The retrieval process will be returned in the thoughts field of output . |