Request body app_idstring(required) Application ID. Get the application ID from the application card on the Application Management page.
In the Java SDK, this is appId. When calling via HTTP, put your actual application ID in the URL, replacing APP_ID.
promptstring(required) User input that guides the application to generate a response.
When calling via HTTP, put prompt in the input object.
session_idstring (optional) Conversation history identifier. Pass session_id to automatically carry cloud-stored conversation history. Requires prompt. Expires after 1 hour of inactivity.
In the Java SDK, this is setSessionId. When calling via HTTP, put session_id in the input object.
messagesarray(optional) Conversation context passed to the model, arranged in chronological order. For multi-turn conversations, pass messages instead of prompt or session_id. If you pass both session_id and messages, the model uses the content in messages and ignores session_id and prompt.
When calling via HTTP, put messages in the input object.
To use this parameter, your Python Dashscope SDK version must be at least 1.20.14, and your Java Dashscope SDK version must be at least 2.17.0.
Message types System Messageobject (optional) System message that sets the model's role, tone, task objectives, or constraints. Usually placed first in the messages array. Properties contentstring(required) System instruction that defines the model's role, behavior guidelines, response style, and task constraints. rolestring(required) Role of the system message, fixed as system. User Messageobject(required) User message that passes questions, instructions, or context to the model. Properties contentstring(required) Message content. Properties textstring(required) Input text. rolestring(required) Role of the user message, fixed as user. Assistant Messageobject (optional) Model response. Typically used as context passed back to the model in multi-turn conversations. Properties contentstring(required) Text content of the model response. rolestring(required) Role of the assistant message, fixed as assistant. workspace string (optional) Business space identifier. Related documentation: Get Workspace ID. You only need to pass the workspace ID when invoking applications in a sub-workspace.
When calling via HTTP, specify the X-DashScope-WorkSpace header.
stream boolean (optional) Default value is False Enable streaming output. Set to True to improve reading experience and reduce timeout risk. Parameter values:
False (default): The model returns all content at once after generation completes.
True (recommended): The model streams content incrementally. Read chunks in real time to assemble the complete response.
To implement streaming output with the Java SDK, use the streamCall interface. To implement streaming output via HTTP, set the X-DashScope-SSE header to enable.
incremental_output boolean (optional) Default value is False Enable incremental output in streaming mode. Set to True to improve reading experience. Parameter values:
False (default): Each output contains the full sequence generated so far.
I
I like
I like apple
I like apple.
True (recommended): Incremental output. Each chunk contains only new content. Read segments in real time to assemble the complete result.
I
like
apple
.
In the Java SDK, this is incrementalOutput. When calling via HTTP, put incremental_output in the parameters object.
flow_stream_mode string (optional) Default value is full_thoughts Streaming output mode for Workflow Application. Parameter values:
-
message_format (recommended):
Outputs results from specified nodes (either a Output node or an End node) in the message field.
ImportantIn the console application, enable the Stream switch for the target node to return results in streaming mode. If disabled, the node's final result is returned all at once.
In the Java SDK, this is FlowStreamMode.MESSAGE_FORMAT.
-
full_thoughts (default):
Outputs results from all nodes in the thoughts field.
ImportantWhen using this mode, you must also set the has_thoughts parameter to True.
In the Java SDK, this is FlowStreamMode.FULL_THOUGHTS.
-
agent_format:
Outputs results from specified nodes (LLM nodes or end nodes) in the textfield.
In the console application, enable the Response switch for the target node to return results in streaming mode.
ImportantDo not use this mode with parallel nodes, as it may cause content mixing. Ensure the enabled nodes have a clear execution order.
In the Java SDK, this is FlowStreamMode.AGENT_FORMAT.
Your Python SDK version must be at least 1.24.0, and your Java SDK version must be at least 2.21.0. When calling via HTTP, put flow_stream_mode in the parameters object.
biz_paramsobject (optional) Pass parameters for custom variables, nodes, or plugins.
In the Java SDK, this is bizParams. When calling via HTTP, put biz_params in the input object.
For Workflow Application, pass custom variables for the start node directly, for example: biz_params = {"city": "Hangzhou"}
For Agent Application, pass prompt variables or plugin variables using the following fields: Properties user_defined_params object (optional) Custom plugin parameters. Plugins cannot be duplicated. Maximum: 10. Properties tool_idstring (optional) Plugin ID, available on the plugin card. ${plugin_params}string (optional) The innermost object contains multiple key-value pairs. Each key-value pair represents a user-defined parameter name and its specified value. For example: "article_index": 2
Usage steps:
- Associate the specified plugin with your application and Publish the application.
- Pass plugin information through this parameter during API calls.
You can provide multiple key-value pairs, where each key is the plugin's TOOL_ID and the value is the parameter object required by that plugin. Example: "user_defined_params": {
"<TOOL_ID>": {
"article_index": 2},
"<TOOL_ID>": {
"article_index": 8}
}
user_defined_tokens object (optional) User-level authentication for custom plugins. Plugins cannot be duplicated. Maximum: 10. Properties tool_idstring (optional) Plugin ID, available on the plugin card. Pass through the <TOOL_ID> field. user_token string (optional) Pass the user authentication information required by this plugin, such as the actual value of DASHSCOPE_API_KEY. Usage steps:
- Associate the specified plugin with your application and Publish the application.
- Pass plugin user-level authentication information through this parameter during API calls.
You can provide multiple key-value pairs, where each key is the plugin's TOOL_ID and the value is the user_token object. has_thoughts boolean (optional) Default value is False Controls whether plugin invocation, knowledge retrieval appear in the thoughts field. Parameter values:
- True: Output included.
- False (default): Output not included.
In the Java SDK, this is hasThoughts. When calling via HTTP, put has_thoughts in the parameters object.
rag_options object (optional) Configure retrieval parameters, including retrieving specified knowledge bases or documents. NoteOnly Agent Application support this parameter.
In the Java SDK, this is ragOptions. When calling via HTTP, put rag_optionsin the parameters object.
Properties pipeline_ids array(required) A list containing one or more knowledge base IDs. Maximum of 5. Retrieves all documents within the specified knowledge bases. How to get:
- Knowledge Base page to get the knowledge base ID;
- Or through the CreateIndex API (supports only unstructured knowledge bases), which returns
Data.Id.
In the Java SDK, this is pipelineIds.
file_idsarray(optional) A list containing one or more unstructured document IDs. Maximum of 5. Retrieves unstructured documents within the specified knowledge bases. When passing document IDs, you must also pass the knowledge base ID that these documents belong to in the pipeline_ids field. How to get:
In the Java SDK, this is fileIds.
metadata_filterobject (optional) Filter unstructured documents by specifying one or more metadata key-value pairs within the specified knowledge base. Prerequisites: When passing metadata, you must also pass the knowledge base ID that this metadata belongs to in the pipeline_ids field. How to view:
- Visit the Knowledge Base page, click the View DetailsMetadata Information on the knowledge base card to view.
- Or through the ListChunks API to get.
This object consists of one or more key-value pairs: Combination logic: Different keys use "AND" logic. For example, "author": "John.Doe", "source": ["internal_wiki", "public_docs"] means filtering documents authored by "John.Doe" AND sourced from either "internal_wiki" OR "public_docs".
In the Java SDK, this is metadataFilter.
tags array (optional) A list containing one or more tags for unstructured documents. You can retrieve unstructured documents with this tag. How to view: | Single-turn conversationPythonRequest exampleimport 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(
# Configure API key: use environment variable or replace with your Model Studio API key (do not hard code in production).
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='APP_ID',# Replace with your actual application ID
prompt='Who are you?')
if response.status_code != HTTPStatus.OK:
print(f'request_id={response.request_id}')
print(f'code={response.status_code}')
print(f'message={response.message}')
print(f'See documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
else:
print(response.output.text)
JavaRequest example// We recommend 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 you have not configured an environment variable, replace the following line with .apiKey("sk-xxx") using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("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("See documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPcurlRequest examplecurl -X POST https://dashscope-intl.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 actual application ID.
PHPRequest example<?php
# If you have not configured an environment variable, replace the following line with $api_key="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = '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 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.jsInstall required dependencies:npm install axios
Request exampleconst axios = require('axios');
async function callDashScope() {
// If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';// Replace with your 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#Request exampleusing System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
//If you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments 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 = "APP_ID"; // Replace with your 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}");
}
}
}
}
GoRequest examplepackage main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If you have not configured an environment variable, replace the following line with apiKey := "sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // Replace with your actual application ID
if apiKey == "" {
fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope-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
}
// Handle 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 conversationEnable multi-turn conversations using session_id or messages. PythonRequest exampleimport 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(
# Configure API key: use environment variable or replace with your Model Studio API key (do not hard code in production).
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='APP_ID', # Replace with your actual application ID
prompt='Who are you?')
if response.status_code != HTTPStatus.OK:
print(f'request_id={response.request_id}')
print(f'code={response.status_code}')
print(f'message={response.message}')
print(f'See documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
return response
responseNext = Application.call(
# Configure API key: use environment variable or replace with your Model Studio API key (do not hard code in production).
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='APP_ID', # Replace with your 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'See documentation: https://www.alibabacloud.com/help/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()
JavaRequest exampleimport 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 you have not configured an environment variable, replace the following line with .apiKey("sk-xxx") using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// Replace with your actual 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 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("See documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPcurlRequest example (previous round of conversation)curl -X POST https://dashscope-intl.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-intl.aliyuncs.com/api/v1/apps/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": {}
}'
PHPRequest example (previous round of conversation)<?php
# If you have not configured an environment variable, replace the following line with $api_key="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = '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 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";
};
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 you have not configured an environment variable, replace the following line with $api_key="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = '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' => 'What skills do you have?',
// Replace with the actual session_id returned from the previous conversation
'session_id' => '2e658bcb514f4d30ab7500b4766a8d43'
]
];
// Encode data as JSON
$dataString = json_encode($data);
// Check if json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize cURL session
$ch = curl_init($url);
// Set cURL options
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// Execute request
$response = curl_exec($ch);
// Check if cURL execution succeeded
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// Get HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close cURL session
curl_close($ch);
// Decode response data
$response_data = json_decode($response, true);
// 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.jsInstall required dependencies:npm install axios
Sample request (previous conversation)const axios = require('axios');
async function callDashScope() {
// If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';// Replace with your 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();
Request example (next turn)const axios = require('axios');
async function callDashScope() {
// If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';// Replace with your 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#Request example (first turn)using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
//If you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments 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 = "APP_ID"; // Replace with your 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}");
}
}
}
}
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 you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments 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 = "APP_ID"; // Replace with your 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}");
}
}
}
}
GoRequest example (previous round of conversation)package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If you have not configured an environment variable, replace the following line with apiKey := "sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // Replace with your actual application ID
if apiKey == "" {
fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope-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
}
// Handle 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 you have not configured an environment variable, replace the following line with apiKey := "sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // Replace with your actual application ID
if apiKey == "" {
fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope-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
}
// Handle 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 actual application ID. Replace the session_id value in the next turn's input parameters with the actual session_id value returned from the previous conversation.
Pass parametersPass custom parameters using biz_params. PythonRequest exampleimport os
from http import HTTPStatus
# We recommend 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 = {
# Pass custom plug-in input parameters for agent applications. Replace <TOOL_ID> with your custom plug-in ID.
"user_defined_params": {
"<TOOL_ID>": {
"article_index": 2}}}
response = Application.call(
# Configure API key: use environment variable or replace with your Model Studio API key (do not hard code in production).
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='APP_ID',
prompt='Dormitory rules content',
biz_params=biz_params)
if response.status_code != HTTPStatus.OK:
print(f'request_id={response.request_id}')
print(f'code={response.status_code}')
print(f'message={response.message}')
print(f'See documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
else:
print('%s\n' % (response.output.text)) # Process to output only text
# print('%s\n' % (response.usage))
JavaRequest exampleimport 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 =
// Pass custom plug-in input parameters for agent applications. Replace <TOOL_ID> with your custom plug-in ID.
"{\"user_defined_params\":{\"<TOOL_ID>\":{\"article_index\":2}}}";
ApplicationParam param = ApplicationParam.builder()
// If you have not configured an environment variable, replace the following line with .apiKey("sk-xxx") using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("APP_ID")
.prompt("Dormitory rules content")
.bizParams(JsonUtils.parse(bizParams))
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("%s\n",
result.getOutput().getText());
}
public static void main(String[] args) {
try {
appCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("See documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPcurlRequest examplecurl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "Dormitory rules content",
"biz_params":
{
"user_defined_params":
{
"<TOOL_ID>":
{
"article_index": 2
}
}
}
},
"parameters": {},
"debug":{}
}'
Replace APP_ID with your actual application ID. Replace <TOOL_ID> with your plugin ID.
PHPRequest example<?php
# If you have not configured an environment variable, replace the following line with $api_key="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with your actual application ID
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
//Replace <TOOL_ID> with your actual plug-in ID
// Construct request data
$data = [
"input" => [
'prompt' => 'Dormitory rules content',
'biz_params' => [
'user_defined_params' => [
'<TOOL_ID>' => [
'article_index' => 2
]
]
]
],
];
// Encode data as JSON
$dataString = json_encode($data);
// Check if json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize cURL session
$ch = curl_init($url);
// Set cURL options
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// Execute request
$response = curl_exec($ch);
// Check if cURL execution succeeded
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// Get HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close cURL session
curl_close($ch);
// Decode response data
$response_data = json_decode($response, true);
// 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.jsInstall required dependencies:npm install axios
Request exampleconst axios = require('axios');
async function callDashScope() {
// If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';// Replace with your actual application ID
const pluginCode = 'TOOL_ID';// Replace with your actual plug-in ID
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "Dormitory rules content",
biz_params: {
user_defined_params: {
[pluginCode]: {
// article_index is a variable for the custom plug-in. Replace it with your 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#Request exampleusing System.Text;
class Program
{
static async Task Main(string[] args)
{
// If you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments 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 = "APP_ID";// Replace with your actual application ID
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("Make sure DASHSCOPE_API_KEY is set.");
return;
}
string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string pluginCode = "TOOL_ID"; // Replace TOOL_ID with your actual plug-in ID
string jsonContent = $@"{{
""input"": {{
""prompt"": ""Dormitory rules content"",
""biz_params"": {{
""user_defined_params"": {{
""{pluginCode}"": {{
""article_index"": 2
}}
}}
}}
}},
""parameters"": {{}},
""debug"": {{}}
}}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Request successful:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}
GoRequest examplepackage main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If you have not configured an environment variable, replace the following line with apiKey := "sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // Replace with your actual application ID
pluginCode := "TOOL_ID" // Replace with your actual plug-in ID
if apiKey == "" {
fmt.Println("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]interface{}{
"prompt": "Dormitory rules content",
"biz_params": map[string]interface{}{
"user_defined_params": map[string]interface{}{
pluginCode: map[string]interface{}{
"article_index": 2,
},
},
},
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// Create 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
}
// Handle 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 outputEnable streaming output using stream. PythonRequest exampleimport 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(
# Configure API key: use environment variable or replace with your Model Studio API key (do not hard code in production).
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='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'See documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
else:
print(f'{response.output.text}\n') # Process to output only text
JavaRequest example// We recommend dashscope SDK version >= 2.15.0
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.reactivex.Flowable;// Streaming output
// Implement streaming output for agent application calls
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 you have not configured an environment variable, replace the following line with .apiKey("sk-xxx") using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// Replace with your actual application ID
.appId("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("See documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPcurlRequest examplecurl -X POST https://dashscope-intl.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 actual application ID.
PHPRequest example<?php
// If you have not configured an environment variable, replace the following line with $api_key="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = '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?'],
"parameters" => [
'incremental_output' => true]];// Incremental output
// Encode data as JSON
$dataString = json_encode($data);
// Check if json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize cURL session
$ch = curl_init($url);
// Set cURL options
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); // Do not return transfer data
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $string) {
echo $string; // Handle 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 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);
if ($status_code != 200) {
echo "HTTP Status Code: $status_code\n";
echo "Request Failed.\n";
}
?>
Node.jsInstall required dependencies:npm install axios
Request example1. Output full response const axios = require('axios');
async function callDashScope() {
//If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';// Replace with your 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) {
// Handle 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 collapsible panel to view specific content: 2. Output only text field content const axios = require('axios');
const { Transform } = require('stream');
async function callDashScope() {
//If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID'; // Replace with your 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) {
// // Handle streaming response SSE protocol parsing transform stream
const sseTransformer = new Transform({
transform(chunk, encoding, callback) {
this.buffer += chunk.toString();
// Split by SSE events (two newlines)
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 newline and push
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); // Auto-wrap output
})
.on('end', () => console.log(""))
.on('error', err => console.error("Pipe 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#Request exampleusing System.Net;
using System.Text;
class Program
{
static async Task Main(string[] args)
{
//If you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments 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 = "APP_ID"; // Replace with your 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}");
}
}
}
}
GoRequest examplepackage main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
)
func main() {
// If you have not configured an environment variable, replace the following line with apiKey := "sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // Replace with your actual application ID
if apiKey == "" {
fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create request body, where incremental_output enables 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 is set to enable for 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
}
// Handle 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
}
}
}
Knowledge base retrievalWhen calling a Agent Application, use rag_options to enable knowledge base retrieval. PythonRequest exampleimport os
from http import HTTPStatus
# We recommend 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(
# Configure API key: use environment variable or replace with your Model Studio API key (do not hard code in production).
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='APP_ID', # Replace APP_ID with your application ID
prompt='Please recommend a phone under 3000 yuan',
rag_options={
"pipeline_ids": ["PIPELINE_ID1","PIPELINE_ID2"], # Replace with your actual knowledge base IDs, separated by commas for multiple
}
)
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'See documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
else:
print('%s\n' % (response.output.text)) # Process to output only text
# print('%s\n' % (response.usage))
JavaRequest example// We recommend dashscope SDK version >= 2.16.8;
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import java.util.Arrays;
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 you have not configured an environment variable, replace the following line with .apiKey("sk-xxx") using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("APP_ID") // Replace with your actual application ID
.prompt("Please recommend a phone around 3000 yuan")
.ragOptions(RagOptions.builder()
// Replace with your actual specified knowledge base IDs, separated by commas for multiple
.pipelineIds(Arrays.asList("PIPELINES_ID1", "PIPELINES_ID2"))
.build())
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("%s\n",
result.getOutput().getText());// Process to output only text
}
public static void main(String[] args) {
try {
streamCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("See documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPcurlRequest examplecurl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/{APP_ID}/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "Please recommend a phone under 3000 yuan"
},
"parameters": {
"rag_options" : {
"pipeline_ids":["PIPELINE_ID1"]}
},
"debug": {}
}'
Replace APP_ID with your actual application ID and PIPELINE_ID1 with your specified knowledge base ID.
PHPRequest example<?php
# If you have not configured an environment variable, replace the following line with $api_key="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = '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' => 'Please recommend a phone under 3000 yuan'
],
"parameters" => [
'rag_options' => [
'pipeline_ids' => ['PIPELINE_ID1','PIPELINE_ID2']//Replace with your specified knowledge base IDs, separated by commas for multiple
]
]
];
// Encode data as JSON
$dataString = json_encode($data);
// Check if json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize cURL session
$ch = curl_init($url);
// Set cURL options
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// Execute request
$response = curl_exec($ch);
// Check if cURL execution succeeded
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// Get HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close cURL session
curl_close($ch);
// Decode response data
$response_data = json_decode($response, true);
// 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.jsInstall required dependencies:npm install axios
Request exampleconst axios = require('axios');
async function callDashScope() {
// If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';//Replace with your actual application ID
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "Please recommend a phone under 3000 yuan"
},
parameters: {
rag_options:{
pipeline_ids:['PIPELINE_ID1','PIPELINE_ID2'] // Replace with your specified knowledge base IDs, separated by commas for multiple
}
},
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 exampleusing System.Text;
class Program
{
static async Task Main(string[] args)
{
// If you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments 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 = "APP_ID";// Replace with your actual application ID
// Replace PIPELINE_ID1 with your specified knowledge base ID
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("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 phone under 3000 yuan""
}},
""parameters"": {{
""rag_options"" : {{
""pipeline_ids"":[""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}");
}
}
}
}
GoRequest examplepackage main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If you have not configured an environment variable, replace the following line with apiKey := "sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // Replace with your actual application ID
if apiKey == "" {
fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create request body
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "Please recommend a phone under 3000 yuan",
},
"parameters": map[string]interface{}{
"rag_options": map[string]interface{}{
"pipeline_ids": []string{"PIPELINE_ID1"}, // Replace with your 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
}
// Handle 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 information: Add has_thoughts to your code and set it to True. The retrieval process information will be returned in the output field's thoughts field. |