This document describes the input and output parameters for calling Alibaba Cloud Model Studio applications (agents and workflows) with the DashScope API, and provides call examples for typical scenarios.
This document applies only to the Singapore region.
HTTP API callsRequest URL: POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion
Replace APP_ID with your actual application ID
SDK callsPython/Java SDK: The correct endpoint is configured by default in this documentCustom endpoint: You can configure it with the base_url parameter
Request body
app_idstring(required)The application identifier.You can obtain the application ID from the application card on the My Applications page.
It is appId in the Java SDK. When calling via HTTP, put the actual application ID into the URL and replace APP_ID.
promptstring(required)The user's input instruction, used to guide the application to generate a reply.
When calling via HTTP, put prompt in the input object.
session_idstring (optional)The identifier of the conversation history.When session_id is passed, the request automatically carries the conversation history stored in the cloud. In this case, you must pass prompt.The ID automatically expires after 1 consecutive hour without any requests.
It is setSessionId in the Java SDK. When calling via HTTP, put session_id in the input object.
messagesarray(optional)The context passed to the model, arranged in conversation order.When using the messages parameter for multi-turn conversations, you do not need to pass prompt or session_id.If both session_id and messages are passed, the model prioritizes the content in messages and ignores session_id and prompt.
When calling via HTTP, put messages into the input object.
To use this parameter, the Python DashScope SDK version must be at least 2.0.1, and the Java DashScope SDK version must be at least 2.17.0.
Message type
System Messageobject (optional)System message, used to define the model's role, tone, task objectives, or constraints. Typically placed first in the messages array.
Property
contentstring(required)System instruction, used to specify the model's role, behavioral rules, response style, and task constraints.rolestring(required)The role of the system message, fixed to system.
User Messageobject(required)User message, used to pass questions, instructions, or context to the model.
Property
contentstring(required)Message content.
Property
textstring(required)The input text.
rolestring(required)The role of the user message, fixed to user.
Assistant Messageobject (optional)The model's reply. Typically passed back to the model as context in multi-turn conversations.
Property
contentstring(required)The text content of the model's reply.rolestring(required)The role of the assistant message, fixed to assistant.
workspacestring (optional)Business space identifier. Related documentation: Obtain Workspace ID.Pass workspace ID only when calling an application in a sub-business space.
When calling via HTTP, specify X-DashScope-WorkSpace in the header.
streamboolean (optional) Default value is FalseWhether to respond in streaming output mode.It is recommended to set it to True, which improves the reading experience and reduces the risk of timeout.Parameter Value:
False (default): The model returns all the generated content all at once after generation is complete.
True (recommended): Outputs while generating, returning a data chunk each time part of the content is generated. You need to read these chunks in real time one by one to assemble the complete response.
To implement streaming output with the Java SDK, call the streamCall interface; to implement streaming output via HTTP, specify X-DashScope-SSE as enable in the Header.
incremental_outputboolean (optional) Default value: FalseWhether to enable incremental output in streaming output mode.It is recommended to set it to True, which improves the reading experience.Parameter Value:
False (default): Outputs the entire sequence generated so far each time, and the last output is the complete generated result.
Copy
II likeI like appleI like apple.
True (recommended): Incremental output, meaning subsequent output does not include content that has already been output. You need to read these fragments in real time one by one to obtain the complete result.
Copy
Ilikeapple.
In the Java SDK, it is incrementalOutput. When calling via HTTP, put incremental_output in the parameters object.
message_format (recommended):Outputs the result of the specified node (the Output node or the End node) in the message field.
In the console application, turn on the Streaming output switch of the target node to return results in a streaming manner; when it is not enabled, the final result of the node is returned all at once.
In the Java SDK, it is FlowStreamMode.MESSAGE_FORMAT.
full_thoughts (default):Outputs the results of all nodes in the thoughts field.
When using this mode, you must also set the has_thoughts parameter to True.
In the Java SDK, it is FlowStreamMode.FULL_THOUGHTS.
agent_format:Outputs the result of the specified node (an LLM node or the End node) in the text field.In the console application, turn on the Response switch of the target node to return results in a streaming manner.
Do not use this mode on parallel nodes, as it may result in mixed content. Make sure the nodes with the switch enabled have a clear execution order.
In the Java SDK, it is FlowStreamMode.AGENT_FORMAT.
The Python SDK version must be 2.0.1 or later, and the Java SDK version must be 2.21.0 or later. When calling via HTTP, put flow_stream_mode in the parameters object.
biz_paramsobject (optional)When the application passes parameters via custom variables, nodes, or plug-ins, use this field.
In the Java SDK, it is bizParams. When calling via HTTP, put biz_params in the input object.
Custom variables of the start node of a workflow application are passed directly. Example:
Copy
biz_params = {"city": "杭州"}
Agent applications pass prompt variables or plug-in variable parameters via the following fields:
Property
user_defined_paramsobject (optional)Represents custom plug-in parameter information.Each plug-in added to an application must be unique, with a maximum of 10 plug-ins.
Property
tool_idstring (Optional)The plug-in ID, which you can obtain from the plug-in card.${plugin_params}string (Optional)The multiple key-value pairs contained in the innermost part of the object. Each key-value pair represents a user-defined parameter name to pass and its specified value. For example:
Copy
"article_index": 2
Usage Steps:
Associate the specified plug-in in the application and publish the application.
The API call passes plug-in information through this parameter.
You can provide multiple key-value pairs, where each key is the plug-in's TOOL_ID and the value is the parameter object required by the plug-in. Example:
user_defined_tokensobject (Optional)Represents the user-level authentication information for custom plug-ins.Each plug-in added to an application must be unique, with a maximum of 10 plug-ins.
Property
tool_idstring (Optional)The plug-in ID, which you can obtain from the plug-in card. Pass it through the <TOOL_ID> field.user_tokenstring (Optional)Passes the user authentication information required by the plug-in, such as the actual value of DASHSCOPE_API_KEY.
Usage Steps:
Associate the specified plug-in in the application and publish the application.
The API call passes the plug-in user-level authentication information through this parameter.
You can provide multiple key-value pairs, where each key is the plug-in's TOOL_ID and the value is a user_token object.
has_thoughtsboolean (Optional) Default value: FalseWhether to output the process of plug-in calls and knowledge retrieval, which can be viewed in the thoughts field.Parameter Value:
True: output.
False (default): no output.
In the Java SDK, it is hasThoughts. When calling via HTTP, put has_thoughts in the parameters object.
rag_optionsobject (Optional)Used to configure retrieval-related parameters, including but not limited to retrieving from specified knowledge bases or documents.
Only agent applications support this parameter.
In the Java SDK, it is ragOptions. When calling via HTTP, put rag_options in the parameters object.
Property
pipeline_idsarray (Required)A list containing one or more knowledge base IDs. The maximum is 5.Retrieves all documents in the specified knowledge bases.How to obtain:
Obtain the knowledge base ID on the knowledge base page;
Or from the Data.Id returned by the CreateIndex API (only unstructured knowledge bases are supported).
In the Java SDK, this is pipelineIds.
file_idsarray (Optional)A list containing one or more unstructured document IDs. The upper limit is 5.Retrieve unstructured documents within the specified knowledge base.When passing document IDs, you must also pass the knowledge base IDs to which these documents belong in the pipeline_ids field.How to obtain:
Or from the IDs returned when importing documents via the AddFile API.
In the Java SDK, this is fileIds.
metadata_filterobject (Optional)The metadata used to filter unstructured documents. By specifying one or more key-value pairs, you can retrieve unstructured documents with the specified metadata from the specified knowledge base.Prerequisites:When passing metadata, you must also pass the knowledge base IDs to which the metadata belongs in the pipeline_ids field.How to view:
Visit the Knowledge Base page and click View Details Meta Information on the knowledge base card to view it.
This object consists of one or more key-value pairs:
Key: String type, representing the name of the metadata.
Value:
Single-value match: the value is a String, indicating that only documents whose field value exactly equals this string are retrieved.
Example: "author": "John.Doe"
Multiple-value "OR" match: the value is an Array or List containing multiple String values. This indicates retrieving documents whose field value matches any value in the array (logic is OR).
Combined logic: The logic between different keys is "AND". For example, "author": "John.Doe", "source": ["internal_wiki", "public_docs"] means filtering documents whose author is "John.Doe" and whose source is "internal_wiki" or "public_docs".
In the Java SDK, this is metadataFilter.
tagsarray (Optional)A list containing one or more unstructured document tags.Retrieve unstructured documents with the specified tags.How to view:
import osimport dashscopefrom dashscope import DashScopeError# The following is the configuration for the Singapore region. Replace {WorkspaceId} with your workspace ID. The region value varies by region.client = dashscope.Client( # If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx"). However, it is not recommended to hardcode your API key in code in production environments, to reduce the risk of API key leakage. api_key=os.getenv("DASHSCOPE_API_KEY"), workspace="{WorkspaceId}", region="ap-southeast-1",)try: response = client.apps.completions.create( app_id='APP_ID', # Replace with the actual application ID prompt='你是谁?') print(response.text)except DashScopeError as e: print(f'request_id={e.request_id}') print(f'code={e.code}') print(f'message={e.message}') print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
Request example
Copy
// Recommended dashscope SDK version >= 2.12.0import 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("你是谁?") .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("请参考文档:https://www.alibabacloud.com/help/model-studio/developer-reference/error-code"); } System.exit(0); }}
<?php# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。$api_key = getenv("DASHSCOPE_API_KEY");$application_id = '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' => '你是谁?' ]];// Encode data as JSON$dataString = json_encode($data);// Check if json_encode was successfulif (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg());}// Initialize the cURL session$ch = curl_init($url);// Set cURL optionscurl_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 whether cURL succeededif ($response === false) { die("cURL Error: " . curl_error($ch));}// Get HTTP status code$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);// Close the cURL sessioncurl_close($ch);// Decode response data$response_data = json_decode($response, true);// Handle responseif ($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";}}?>
Install the required dependencies:
Copy
npm install axios
Request example
Copy
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 the actual application ID const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "你是谁?" }, 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();
Request example
Copy
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 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"": ""你是谁?"" }, ""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
Copy
package mainimport ( "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 the actual application ID if apiKey == "" { fmt.Println("请确保设置了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]string{ "prompt": "你是谁?", }, "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)) }}
Enable multi-turn conversations via session_id or messages.
Python
Java
HTTP
Request example
Copy
import osimport dashscopefrom dashscope import DashScopeError# The following is the configuration for the Singapore region. Replace {WorkspaceId} with your workspace ID. The region value varies by region.client = dashscope.Client( # If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx"). However, it is not recommended to hardcode your API key in code in production environments, to reduce the risk of API key leakage. api_key=os.getenv("DASHSCOPE_API_KEY"), workspace="{WorkspaceId}", region="ap-southeast-1",)def call_with_session(): try: response = client.apps.completions.create( app_id='APP_ID', # Replace with the actual application ID prompt='你是谁?') responseNext = client.apps.completions.create( app_id='APP_ID', # Replace with the actual application ID prompt='你有什么技能?', session_id=response.session_id) # The session_id from the previous response print('%s\n session_id=%s\n' % (responseNext.text, responseNext.session_id)) # print('%s\n' % (response.usage)) except DashScopeError as e: print(f'request_id={e.request_id}') print(f'code={e.code}') print(f'message={e.message}') print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')if __name__ == '__main__': call_with_session()
Request example
Copy
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 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 the actual application ID .appId("APP_ID") .prompt("你是谁?") .build(); Application application = new Application(); ApplicationResult result = application.call(param); param.setSessionId(result.getOutput().getSessionId()); param.setPrompt("你有什么技能?"); 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("请参考文档:https://www.alibabacloud.com/help/model-studio/developer-reference/error-code"); } System.exit(0); }}
<?php# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。$api_key = getenv("DASHSCOPE_API_KEY");$application_id = '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' => '你是谁?' ]];// Encode data as JSON$dataString = json_encode($data);// Check if json_encode was successfulif (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg());}// Initialize the cURL session$ch = curl_init($url);// Set cURL optionscurl_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 whether cURL succeededif ($response === false) { die("cURL Error: " . curl_error($ch));}// Get HTTP status code$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);// Close the cURL sessioncurl_close($ch);// Decode response data$response_data = json_decode($response, true);// Handle responseif ($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)
Copy
<?php# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。$api_key = getenv("DASHSCOPE_API_KEY");$application_id = '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' => '你有什么技能?', // 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 was successfulif (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg());}// Initialize the cURL session$ch = curl_init($url);// Set cURL optionscurl_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 whether cURL succeededif ($response === false) { die("cURL Error: " . curl_error($ch));}// Get HTTP status code$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);// Close the cURL sessioncurl_close($ch);// Decode response data$response_data = json_decode($response, true);// Handle responseif ($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";}}?>
Install the required dependencies:
Copy
npm install axios
Request example (previous turn)
Copy
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 the actual application ID const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "你是谁?" }, 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)
Copy
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 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: "你有什么技能?", 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();
Request example (previous turn)
Copy
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 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"": ""你是谁?"" }, ""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)
Copy
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 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"": ""你有什么技能?"", ""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}"); } } }}
Request example (previous turn)
Copy
package mainimport ( "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 the actual application ID if apiKey == "" { fmt.Println("请确保设置了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]string{ "prompt": "你是谁?", }, "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)
Copy
package mainimport ( "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 the actual application ID if apiKey == "" { fmt.Println("请确保设置了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]string{ "prompt": "你有什么技能?", "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 the actual application ID. For the next turn, replace the value of the input parameter session_id with the session_id value returned in the previous turn.
Pass custom parameters through biz_params.
Python
Java
HTTP
Request example
Copy
import os# The Dashscope SDK version must be 2.0.1 or later.import dashscopefrom dashscope import DashScopeError# The following is the configuration for the Singapore region. Replace {WorkspaceId} with your workspace ID. The region value varies by region.client = dashscope.Client( # If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx"). However, it is not recommended to hardcode your API key in code in production environments, to reduce the risk of API key leakage. api_key=os.getenv("DASHSCOPE_API_KEY"), workspace="{WorkspaceId}", region="ap-southeast-1",)biz_params = { # Pass the custom plugin input parameters of the agent application. Replace <TOOL_ID> with your custom plugin ID. "user_defined_params": { "<TOOL_ID>": { "article_index": 2}}}try: response = client.apps.completions.create( app_id='APP_ID', prompt='寝室公约内容', biz_params=biz_params) print('%s\n' % (response.text)) # Process the text-only output # print('%s\n' % (response.usage))except DashScopeError as e: print(f'request_id={e.request_id}') print(f'code={e.code}') print(f'message={e.message}') print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
Request example
Copy
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 = // 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("寝室公约内容") .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("请参考文档:https://www.alibabacloud.com/help/model-studio/developer-reference/error-code"); } System.exit(0); }}
Replace APP_ID with the actual application ID. Replace <TOOL_ID> with the plug-in ID.
Request example
Copy
<?php# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。$api_key = getenv("DASHSCOPE_API_KEY");$application_id = 'APP_ID'; // Replace with the 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' => '寝室公约内容', 'biz_params' => [ 'user_defined_params' => [ '<TOOL_ID>' => [ 'article_index' => 2 ] ] ] ],];// Encode data as JSON$dataString = json_encode($data);// Check if json_encode was successfulif (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg());}// Initialize the cURL session$ch = curl_init($url);// Set cURL optionscurl_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 whether cURL succeededif ($response === false) { die("cURL Error: " . curl_error($ch));}// Get HTTP status code$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);// Close the cURL sessioncurl_close($ch);// Decode response data$response_data = json_decode($response, true);// Handle responseif ($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";}}?>
Install the required dependencies:
Copy
npm install axios
Request example
Copy
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 the actual application ID const pluginCode = 'TOOL_ID';// Replace with the actual plug-in ID const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "寝室公约内容", 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();
Request example
Copy
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 the actual application ID if (string.IsNullOrEmpty(apiKey)) { Console.WriteLine("请确保设置了 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 = "TOOL_ID"; // Replace TOOL_ID with your actual plug-in ID string jsonContent = $@"{{ ""input"": {{ ""prompt"": ""寝室公约内容"", ""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}"); } } }}
Request example
Copy
package mainimport ( "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 the actual application ID pluginCode := "TOOL_ID" // Replace with the actual plug-in ID if apiKey == "" { fmt.Println("请确保设置了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": "寝室公约内容", "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)) }}
Enable streaming output through stream.
Python
Java
HTTP
Request example
Copy
import osimport dashscopefrom dashscope import DashScopeError# The following is the configuration for the Singapore region. Replace {WorkspaceId} with your workspace ID. The region value varies by region.client = dashscope.Client( # If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx"). However, it is not recommended to hardcode your API key in code in production environments, to reduce the risk of API key leakage. api_key=os.getenv("DASHSCOPE_API_KEY"), workspace="{WorkspaceId}", region="ap-southeast-1",)try: stream = client.apps.completions.create( app_id='APP_ID', prompt='你是谁?', stream=True, # Enable streaming output incremental_output=True) # Enable incremental output for partial in stream: print(f'{partial.text}\n') # Process the text-only outputexcept DashScopeError as e: print(f'request_id={e.request_id}') print(f'code={e.code}') print(f'message={e.message}') print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
Request example
Copy
// Recommended dashscope SDK version >= 2.15.0import 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 callsimport 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 the actual application ID .appId("APP_ID") .prompt("你是谁?") // 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("请参考文档:https://www.alibabacloud.com/help/model-studio/developer-reference/error-code"); } System.exit(0); }}
<?php// If the environment variable is unset, insert your Model Studio API key: $api_key="sk-xxx". Avoid hardcoding API keys in production to reduce the risk of key exposure.$api_key = getenv("DASHSCOPE_API_KEY");$application_id = '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' => '你是谁?'], "parameters" => [ 'incremental_output' => true]];// Incremental output// Encode data as JSON$dataString = json_encode($data);// Check if json_encode was successfulif (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg());}// Initialize the cURL session$ch = curl_init($url);// Set cURL optionscurl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); // Do not return transfer datacurl_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 the request$response = curl_exec($ch);// Check whether cURL succeededif ($response === false) { die("cURL Error: " . curl_error($ch));}// Get HTTP status code$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);// Close the cURL sessioncurl_close($ch);if ($status_code != 200) { echo "HTTP Status Code: $status_code\n"; echo "Request Failed.\n";}?>
Install the required dependencies:
Copy
npm install axios
Request example
1. Output the complete response
Copy
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 the actual application ID const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "你是谁?" }, 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 the details:
2. Output only the text field content
Copy
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 the actual application ID const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "你是谁?" }, 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解析错误:', 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("管道错误:", err)); } else { console.log("请求失败,状态码:", response.status); response.data.on('data', chunk => console.log(chunk.toString())); } } catch (error) { console.error(`API调用失败: ${error.message}`); if (error.response) { console.error(`状态码: ${error.response.status}`); error.response.data.on('data', chunk => console.log(chunk.toString())); } }}callDashScope();
Request example
Copy
using 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 the actual application ID string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); client.DefaultRequestHeaders.Add("X-DashScope-SSE", "enable"); string jsonContent = @"{ ""input"": { ""prompt"": ""你是谁"" }, ""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}"); } } }}
Request example
Copy
package mainimport ( "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 the actual application ID if apiKey == "" { fmt.Println("请确保设置了DASHSCOPE_API_KEY。") return } url := fmt.Sprintf("https://dashscope.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": "你是谁?", }, "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 } }}
When calling an agent application, use rag_options to enable knowledge base retrieval.
Python
Java
HTTP
Request example
Copy
import os# The Dashscope SDK version must be 2.0.1 or later.import dashscopefrom dashscope import DashScopeError# The following is the configuration for the Singapore region. Replace {WorkspaceId} with your workspace ID. The region value varies by region.client = dashscope.Client( # If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx"). However, it is not recommended to hardcode your API key in code in production environments, to reduce the risk of API key leakage. api_key=os.getenv("DASHSCOPE_API_KEY"), workspace="{WorkspaceId}", region="ap-southeast-1",)try: response = client.apps.completions.create( app_id='APP_ID', # Replace APP_ID with the actual application ID prompt='请帮我推荐一款3000元以下的手机', rag_options={ "pipeline_ids": ["PIPELINE_ID1","PIPELINE_ID2"], # Replace with the actual knowledge base IDs. Use commas to separate multiple IDs } ) print('%s\n' % (response.text)) # Process the text-only output # print('%s\n' % (response.usage))except DashScopeError as e: print(f'request_id={e.request_id}') print(f'code={e.code}') print(f'message={e.message}') print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
Request example
Copy
// 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.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 the actual application ID .prompt("请帮我推荐一款3000元左右的手机") .ragOptions(RagOptions.builder() // Replace with actual specified knowledge base IDs, separate multiple with commas .pipelineIds(Arrays.asList("PIPELINES_ID1", "PIPELINES_ID2")) .build()) .build(); Application application = new Application(); ApplicationResult result = application.call(param); System.out.printf("%s\n", result.getOutput().getText());// Process text 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("请参考文档:https://www.alibabacloud.com/help/model-studio/developer-reference/error-code"); } System.exit(0); }}
Replace APP_ID with the actual application ID, and PIPELINE_ID1 with the specified knowledge base ID.
Request example
Copy
<?php# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。$api_key = getenv("DASHSCOPE_API_KEY");$application_id = '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' => '请帮我推荐一款3000元以下的手机' ], "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 was successfulif (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg());}// Initialize the cURL session$ch = curl_init($url);// Set cURL optionscurl_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 whether cURL succeededif ($response === false) { die("cURL Error: " . curl_error($ch));}// Get HTTP status code$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);// Close the cURL sessioncurl_close($ch);// Decode response data$response_data = json_decode($response, true);// Handle responseif ($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";}}?>
Install the required dependencies:
Copy
npm install axios
Request example
Copy
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 the actual application ID const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "请帮我推荐一款3000元以下的手机" }, 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();
Request example
Copy
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 the actual application ID // Replace PIPELINE_ID1 with your specified knowledge base ID if (string.IsNullOrEmpty(apiKey)) { Console.WriteLine("请确保设置了 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 jsonContent = $@"{{ ""input"": {{ ""prompt"": ""请帮我推荐一款3000元以下的手机"" }}, ""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}"); } } }}
Request example
Copy
package mainimport ( "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 the actual application ID if apiKey == "" { fmt.Println("请确保设置了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]string{ "prompt": "请帮我推荐一款3000元以下的手机", }, "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)) }}
To view the retrieval process information: add has_thoughts in the code and set it to True when calling, and the retrieval process information will be returned in the thoughts field of output.
Response object
status_codestringThe returned status code.200 indicates a successful request; otherwise, the request failed.If the request fails, use code to obtain the error code and message to obtain the error details.
The Java SDK does not return this parameter. A call failure throws an exception whose message contains the contents of status_code and message.
request_idstringThe unique identifier of this call.
The Java SDK returns this parameter as requestId.
codestringThe error code; empty when the call succeeds.
Only the Python SDK returns this parameter.
messagestringThe error details; ignored if the request succeeds.
Only the Python SDK returns this parameter.
outputobjectThe call result information.
output property
textstringThe reply content generated by the model.finish_reasonstringCompletion reason.stop indicates a natural stop (a preset stop token is encountered); null indicates a forced interruption (such as reaching the maximum length limit or manual stopping).session_idstringThe unique identifier of the current conversation.Pass it in subsequent requests to carry the conversation history.thoughtsarrayWhen calling, set the has_thoughts parameter to True, and you can view the process of plug-in calls and knowledge retrieval, or the thinking process of the deep thinking model in thoughts.
thoughts property
thoughtstringThe thinking process of the model.When a deep thinking model is selected in the agent application on the console and the application is successfully published, if the has_thoughts parameter is set to True in an API call, the thinking process of the model will be returned in this field.reasoningContentstringThe thinking process of the model.When a deep thinking model is selected in the workflow application on the console and the application is successfully published, if the has_thoughts parameter is set to True in an API call, the thinking process of the model will be returned in this field.action_typestringThe execution step type returned by the model. For example, API indicates executing an API plug-in, agentRag indicates executing knowledge retrieval, and reasoning indicates executing the thinking process of the deep thinking model.action_namestringThe name of the executed action, such as knowledge retrieval, API plug-in, or thinking process.actionstringThe executed step.action_input_streamstringThe streaming result of the input parameters.action_inputstringThe input parameters of the plug-in.observationstringThe process of retrieval or the plug-in.
doc_referencesarrayThe information of documents cited by the model from the retrieved documents.Only when the Show Source switch is turned on and the application is published in the agent application on the Model Studio console can doc_references contain valid information.
doc_references property
index_idstringThe index of the retrieved documents cited by the model, such as [1].titlestringThe title of the text chunk cited by the model.doc_idstringThe ID of the document cited by the model.doc_namestringThe name of the document cited by the model.textstringThe specific text content cited by the model.biz_idstringThe business association identifier cited by the model.imagesarrayThe list of image URLs cited by the model.
usageobjectThe data information used in this request.
usage property
modelsarrayThe model information for this call.
models property
model_idstringThe model ID called by this application.input_tokensintegerThe length of the user input text after being converted into tokens.output_tokensintegerThe length of the model-generated reply after being converted into tokens.
Response example with a specified knowledge baseWhen calling the application knowledge base feature, if you want the output to include information about the retrieved documents cited by the model, go to the agent application in the Model Studio console, click Retrieve Configuration, turn on the Show Source switch, and publish the application.
Error response exampleWhen an access request fails, the output indicates the cause of the error via code and message.The following shows an error response example returned when a correct API-KEY is not provided.