You may need to pass custom parameters of plug-ins and workflows or the authentication token for plug-ins. This topic describes how to pass through custom parameters when calling an application.
Prerequisites
You must first obtain an API key and set the API key as an environment variable. If you need to use SDK, you must install the SDK.
Custom plug-in parameter pass-through
This section uses the Dormitory Convention Query Tool as an example to show how to pass through custom parameters for custom plug-ins when calling applications with API.
Make sure the corresponding plug-in is added to the application and the application is published. For more information about plug-ins, see Plug-in overview.
No authentication required
Go to Plug-in Center and click Modify Plug-in on the desired plug-in card.
On the Modify Custom Plug-in page, configure the interface information. Add a pass-through identifier to the parameter. For example, to set
article_index
as the pass-through parameter, addx-source: user
and click Save.Call the plug-in with the API. Use
biz_params
in theinput
object to pass the index number.Python
Sample request
import os from http import HTTPStatus # Recommended dashscope SDK version >= 1.14.0 from dashscope import Application import dashscope dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1' biz_params = { # Custom plug-in input parameter pass-through for agent applications, replace the custom plug-in ID with {your_plugin_code} "user_defined_params": { "{your_plugin_code}": { "article_index": 2}}} response = Application.call( # If the environment variable is not configured, you can replace the line below with your API key: api_key="sk-xxx". However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. api_key=os.getenv("DASHSCOPE_API_KEY"), app_id='YOUR_APP_ID', prompt='Dormitory Convention Content', biz_params=biz_params) if response.status_code != HTTPStatus.OK: print('request_id=%s, code=%s, message=%s\n' % (response.request_id, response.status_code, response.message)) else: print('request_id=%s\n output=%s\n usage=%s\n' % (response.request_id, response.output, response.usage))
Sample response
request_id=d97e3c58-7a75-9ea1-9ecf-d5be869b748e output={"text": "The second content of the dormitory convention is: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, respect each other, and treat each other sincerely. This reminds us to maintain good interpersonal relationships in dormitory life and create a harmonious and positive living and learning environment together. If you need to know more about the convention content, please tell me the specific ordinal number or continue to ask questions.", "finish_reason": "stop", "session_id": "8ec3fa6c59794ed3ab803b921aa38d7a", "thoughts": null, "doc_references": null} usage={"models": [{"model_id": "qwen-max", "input_tokens": 453, "output_tokens": 107}]}
Java
Sample request
package org.example; import com.alibaba.dashscope.app.*; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.exception.InputRequiredException; import com.alibaba.dashscope.exception.NoApiKeyException; import com.alibaba.dashscope.utils.JsonUtils; import io.reactivex.Flowable; import com.alibaba.dashscope.utils.Constants; public class Test { static { Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1"; } public static void streamCall() throws NoApiKeyException, InputRequiredException { String bizParams = "{\"user_defined_params\":{\"{your_plugin_code}\":{\"article_index\":2}}}"; ApplicationParam param = ApplicationParam.builder() // If the environment variable is not configured, you can replace the line below with your API key: api_key="sk-xxx". However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. .apiKey(System.getenv("DASHSCOPE_API_KEY")) .appId("YOUR_APP_ID") .prompt("Dormitory Convention Content") .bizParams(JsonUtils.parse(bizParams)) .build(); Application application = new Application(); Flowable<ApplicationResult> result = application.streamCall(param); result.blockingForEach(data -> { System.out.printf("requestId: %s, text: %s, finishReason: %s\n", data.getRequestId(), data.getOutput().getText(), data.getOutput().getFinishReason()); }); } public static void main(String[] args) { try { streamCall(); } catch (ApiException | NoApiKeyException | InputRequiredException e) { System.out.printf("Exception: %s", e.getMessage()); } System.exit(0); } }
Sample response
requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: Dormitory, finishReason: null requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second item of the dormitory convention, finishReason: null requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second content of the dormitory convention is: Dormitory members should help, finishReason: null requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second content of the dormitory convention is: Dormitory members should help each other, care for each other, learn from each other, finishReason: null requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second content of the dormitory convention is: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, finishReason: null requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second content of the dormitory convention is: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, respect each other, and treat each other sincerely., finishReason: null requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second content of the dormitory convention is: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, respect each other, and treat each other sincerely. This emphasizes the importance of harmonious coexistence and mutual progress among members in dormitory life. If you need, finishReason: null requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second content of the dormitory convention is: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, respect each other, and treat each other sincerely. This emphasizes the importance of harmonious coexistence and mutual progress among members in dormitory life. If you need to know other items, please tell me the ordinal number, finishReason: null requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second content of the dormitory convention is: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, respect each other, and treat each other sincerely. This emphasizes the importance of harmonious coexistence and mutual progress among members in dormitory life. If you need to know other items, please tell me the ordinal number., finishReason: null requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second content of the dormitory convention is: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, respect each other, and treat each other sincerely. This emphasizes the importance of harmonious coexistence and mutual progress among members in dormitory life. If you need to know other items, please tell me the ordinal number., finishReason: stop
Replace YOUR_APP_ID with the application ID and {YOUR_PLUGIN_ID} with the custom plug-in ID.
HTTP
cURL
Sample request
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \ --header "Authorization: Bearer $DASHSCOPE_API_KEY" \ --header 'Content-Type: application/json' \ --data '{ "input": { "prompt": "Dormitory Convention Content", "biz_params": { "user_defined_params": { "{your_plugin_code}": { "article_index": 2 } } } }, "parameters": {}, "debug":{} }'
Replace YOUR_APP_ID with the application ID.
Sample response
{"output": {"finish_reason":"stop", "session_id":"e151267ffded4fbdb13d91439011d31e", "text":"The second content of the dormitory convention is: “Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, respect each other, and treat each other sincerely.” This means that in dormitory life, everyone should support each other and create a harmonious and positive living environment together."}, "usage":{"models":[{"output_tokens":94,"model_id":"qwen-max","input_tokens":453}]}, "request_id":"a39fd2b5-7e2c-983e-84a1-1039f726f18a"}%
PHP
Sample request
<?php # If you have not configured the environment variable, replace the following line with your API key in the $api_key="sk-xxx" format. But this may increase the risk of leakage. $api_key = getenv("DASHSCOPE_API_KEY"); $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID. $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion"; //Replace {your_plugin_code} with the actual plug-in ID. // Construct request data. $data = [ "input" => [ 'prompt' => 'Dormitory Convention Content', 'biz_params' => [ 'user_defined_params' => [ '{your_plugin_code}' => [ 'article_index' => 2 ] ] ] ], ]; // Encode the data in the JSON format. $dataString = json_encode($data); // Check whether json_encode succeeded. if (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg()); } // Initialize cURL dialogue $ch = curl_init($url); // Specify cURL settings. 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 whether the cURL execution succeeded. if ($response === false) { die("cURL Error: " . curl_error($ch)); } // Obtain HTTP status code. $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Close uURL dialogue. curl_close($ch); // Decode response data. $response_data = json_decode($response, true); // Process the response. if ($status_code == 200) { if (isset($response_data['output']['text'])) { echo "{$response_data['output']['text']}\n"; } else { echo "No text in response.\n"; } }else { if (isset($response_data['request_id'])) { echo "request_id={$response_data['request_id']}\n";} echo "code={$status_code}\n"; if (isset($response_data['message'])) { echo "message={$response_data['message']}\n";} else { echo "message=Unknown error\n";} } ?>
Sample response
The second rule of the dormitory convention stipulates that dormitory members should help and care for each other, learn from each other, and improve together; they should be tolerant, respectful, and sincere with one another. This is to ensure that everyone can live and study in a harmonious and friendly environment. If you need more specific clauses or have any other questions, feel free to ask me!
Node.js
Install the dependencies:
npm install axios
Sample request
const axios = require('axios'); async function callDashScope() { // If you have not configured the environment variable, replace the following line with your API key in the apiKey='sk-xxx' format. But this may increase the risk of leakage. const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID';// Replace with the actual application ID. const pluginCode = 'YOUR_PLUGIN_CODE';// Replace with the actual plug-in ID. const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "Dormitory Convention Content", biz_params: { user_defined_params: { [pluginCode]: { // article_index is the variable of this 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();
Sample response
The third rule of the dormitory convention is as follows: Pay attention to electrical safety and eliminate fire hazards. It is strictly prohibited to use open flames, unauthorized electrical appliances, various stoves, and other prohibited items in the dormitory. Storing explosive or flammable materials and tampering with the power supply is not allowed. If you need more information about other rules, please let me know.
C#
Sample request
using System.Text; class Program { static async Task Main(string[] args) { // If you have not configured the environment variable, replace the following line with your API key in the apiKey="sk-xxx" format. But this may increase the risk of leakage. string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");; string appId = "YOUR_APP_ID";// Replace with the actual application ID. if (string.IsNullOrEmpty(apiKey)) { Console.WriteLine("Make sure you have specified DASHSCOPE_API_KEY."); return; } string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); string pluginCode = "{your_plugin_code}"; // Replace {your_plugin_code} with the actual plug-in ID. string jsonContent = $@"{{ ""input"": {{ ""prompt"": ""Dormitory Convention Content"", ""biz_params"": {{ ""user_defined_params"": {{ ""{pluginCode}"": {{ ""article_index"": 2 }} }} }} }}, ""parameters"": {{}}, ""debug"": {{}} }}"; HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await client.PostAsync(url, content); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine("Request successful:"); Console.WriteLine(responseBody); } else { Console.WriteLine($"Request failed with status code: {response.StatusCode}"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch (Exception ex) { Console.WriteLine($"Error calling DashScope: {ex.Message}"); } } } }
Sample response
{ "output": { "finish_reason": "stop", "session_id": "237ca6187c814f3b9e7461090a5f8b74", "text": "The second article of the convention is as follows: "In a dormitory, members should support, care for, and learn from each other, striving for mutual improvement; practice tolerance and modesty, respect one another, and treat each other sincerely." This indicates that dormitory members need to establish a positive and constructive relationship by helping, caring for, and supporting each other to create a harmonious living and learning environment. At the same time, it is important to understand and accept the differences between roommates, and communicate with a sincere attitude. If there are other specific terms or content you would like to know, please let me know!" }, "usage": { "models": [ { "output_tokens": 133, "model_id": "qwen-max", "input_tokens": 829 } ] }, "request_id": "64e8c359-d071-9d2e-bb94-187e86cc3a79" }
Go
Sample request
package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // If you have not configured the environment variable, replace the following line with your API key in the apiKey := "sk-xxx" format. But this may increase the risk of leakage. apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // Replace with the actual application ID. pluginCode := "YOUR_PLUGIN_CODE" // Replace with the actual plug-in ID. if apiKey == "" { fmt.Println("Make sure you have specified DASHSCOPE_API_KEY. ") return } url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId) // Create a request body. requestBody := map[string]interface{}{ "input": map[string]interface{}{ "prompt": "Dormitory Convention Content", "biz_params": map[string]interface{}{ "user_defined_params": map[string]interface{}{ pluginCode: map[string]interface{}{ "article_index": 2, }, }, }, }, "parameters": map[string]interface{}{}, "debug": map[string]interface{}{}, } jsonData, err := json.Marshal(requestBody) if err != nil { fmt.Printf("Failed to marshal JSON: %v\n", err) return } // Create an HTTP POST request. req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Failed to create request: %v\n", err) return } // Specify request header. req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") // Send the request. client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("Failed to send request: %v\n", err) return } defer resp.Body.Close() // Read the response. body, err := io.ReadAll(resp.Body) if err != nil { fmt.Printf("Failed to read response: %v\n", err) return } // Process the response. if resp.StatusCode == http.StatusOK { fmt.Println("Request successful:") fmt.Println(string(body)) } else { fmt.Printf("Request failed with status code: %d\n", resp.StatusCode) fmt.Println(string(body)) } }
Sample response
{ "output": { "finish_reason": "stop", "session_id": "860d2a4c1f3649ac880298537993cb51", "text": "The second rule of the dormitory convention is as follows: Dormitory members should help each other, care for each other, learn from each other, and improve together. They should be tolerant, humble, respectful, and treat each other with sincerity. This emphasizes that in dormitory life, roommates should maintain good mutual support relationships and also respect one another. Would you like to know the content of the other rules?" }, "usage": { "models": [ { "output_tokens": 84, "model_id": "qwen-max", "input_tokens": 876 } ] }, "request_id": "0a250055-90a4-992d-9276-e268ad35d1ab" }
Authentication required
Go to Plug-in Center and click Modify Plug-in on the desired plug-in card.
On the Modify Custom Plug-in page, enable authentication, select User-level Authentication.
Enter a Parameter Name and click Save.
Pass the user-level authentication token when making API calls.
Use
biz_params
to pass the relevant data and useuser_token
to pass the token information. After successful authentication, the application can query specific entries based on the index number and return the results.Python
Sample request
from http import HTTPStatus import os # Recommended dashscope SDK version >= 1.14.0 from dashscope import Application import dashscope dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1' biz_params = { # Custom plug-in authentication pass-through for agent applications, replace the custom plug-in ID with {your_plugin_code} and token with YOUR_TOKEN "user_defined_params": { "{your_plugin_code}": { "article_index": 2}}, "user_defined_tokens": { "{your_plugin_code}": { "user_token": "YOUR_TOKEN"}}} response = Application.call( # If the environment variable is not configured, you can replace the line below with your API key: api_key="sk-xxx". However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. api_key=os.getenv("DASHSCOPE_API_KEY"), app_id='YOUR_APP_ID', prompt='Dormitory Convention Content', biz_params=biz_params) if response.status_code != HTTPStatus.OK: print('request_id=%s, code=%s, message=%s\n' % (response.request_id, response.status_code, response.message)) else: print('request_id=%s\n output=%s\n usage=%s\n' % (response.request_id, response.output, response.usage))
Sample response
request_id=e928fe3b-3df3-9a3f-9ea4-884aed3aea3c output={"text": "The second content of the dormitory convention is: “Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, respect each other, and treat each other sincerely.” This emphasizes that dormitory members should establish harmonious, supportive, and respectful relationships.", "finish_reason": "stop", "session_id": "c3b909e48a0b4867a57b482dece9cbb7", "thoughts": null, "doc_references": null} usage={"models": [{"model_id": "qwen-max", "input_tokens": 432, "output_tokens": 82}]}
Java
Sample request
package org.example; import com.alibaba.dashscope.app.*; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.exception.InputRequiredException; import com.alibaba.dashscope.exception.NoApiKeyException; import com.alibaba.dashscope.utils.JsonUtils; import io.reactivex.Flowable; import com.alibaba.dashscope.utils.Constants; public class Test { static { Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1"; } public static void streamCall() throws NoApiKeyException, InputRequiredException { String bizParams = "{\"user_defined_params\":{\"{your_plugin_code}\":{\"article_index\":2}}," + "\"user_defined_tokens\":{\"{your_plugin_code}\":{\"user_token\":\"YOUR_TOKEN\"}}}"; ApplicationParam param = ApplicationParam.builder() // If the environment variable is not configured, you can replace the line below with your API key: api_key="sk-xxx". However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. .apiKey(System.getenv("DASHSCOPE_API_KEY")) .appId("YOUR_APP_ID") .prompt("Dormitory Convention Content") .bizParams(JsonUtils.parse(bizParams)) .build(); Application application = new Application(); Flowable<ApplicationResult> result = application.streamCall(param); result.blockingForEach(data -> { System.out.printf("requestId: %s, text: %s, finishReason: %s\n", data.getRequestId(), data.getOutput().getText(), data.getOutput().getFinishReason()); }); } public static void main(String[] args) { try { streamCall(); } catch (ApiException | NoApiKeyException | InputRequiredException e) { System.out.printf("Exception: %s", e.getMessage()); } System.exit(0); } }
Sample response
requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: Dormitory, finishReason: null requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second item of the dormitory convention, finishReason: null requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second content of the dormitory convention is: Dormitory members should help, finishReason: null requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second content of the dormitory convention is: Dormitory members should help each other, care for each other, learn from each other, finishReason: null requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second content of the dormitory convention is: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, finishReason: null requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second content of the dormitory convention is: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, respect each other, and treat each other sincerely., finishReason: null requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second content of the dormitory convention is: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, respect each other, and treat each other sincerely. This emphasizes the importance of harmonious coexistence and mutual progress among members in dormitory life. If you need, finishReason: null requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second content of the dormitory convention is: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, respect each other, and treat each other sincerely. This emphasizes the importance of harmonious coexistence and mutual progress among members in dormitory life. If you need to know other items, please tell me the ordinal number, finishReason: null requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second content of the dormitory convention is: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, respect each other, and treat each other sincerely. This emphasizes the importance of harmonious coexistence and mutual progress among members in dormitory life. If you need to know other items, please tell me the ordinal number., finishReason: null requestId: 48bb400a-d050-9f5c-afbd-c1adb25f6a43, text: The second content of the dormitory convention is: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, respect each other, and treat each other sincerely. This emphasizes the importance of harmonious coexistence and mutual progress among members in dormitory life. If you need to know other items, please tell me the ordinal number., finishReason: stop
Replace YOUR_APP_ID with the application ID, YOUR_PLUGIN_ID with the custom plug-in ID, and YOUR_TOKEN with the authentication token.
HTTP
cURL
Sample request
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \ --header "Authorization: Bearer $DASHSCOPE_API_KEY" \ --header 'Content-Type: application/json' \ --data '{ "input": { "prompt": "Dormitory Convention Content", "biz_params": { "user_defined_params": { "{your_plugin_code}": { "article_index": 2 } }, "user_defined_tokens": { "{your_plugin_code}": { "user_token": "YOUR_TOKEN" } } } }, "parameters": {}, "debug":{} }'
Replace YOUR_APP_ID with the application ID, YOUR_PLUGIN_ID with the custom plug-in ID, and YOUR_TOKEN with the authentication token.
Sample response
{"output":{"finish_reason":"stop", "session_id":"d3b5c3e269dc40479255a7a02df5c630", "text":"The second content of the dormitory convention is: “Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant and modest, respect each other, and treat each other sincerely.” This emphasizes the importance of harmonious coexistence and mutual progress among members in dormitory life."}, "usage":{"models":[{"output_tokens":80,"model_id":"qwen-max","input_tokens":432}]}, "request_id":"1f77154c-edc3-9003-b622-816fa2f849cf"}%
Node.js
Install the dependencies:
npm install axios
Sample request
const axios = require('axios'); async function callDashScope() { // If you have not configured the environment variable, replace the following line with your API key in the apiKey='sk-xxx' format. But this may increase the risk of leakage. const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID';// Replace with the actual application ID. const pluginCode = 'YOUR_PLUGIN_CODE';// Replace with the actual plug-in ID. const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "Dormitory Convention Content", biz_params: { user_defined_params: { [pluginCode]: { // article_index is the variable of this custom plug-in. Replace it with your actual plug-in variable. 'article_index': 6 } }, user_defined_tokens: { [pluginCode]: { // Replace YOUR_TOKEN with the actual authentication token, such as the API key. user_token: 'YOUR_TOKEN' } } } }, parameters: {}, debug: {} }; try { console.log("Sending request to DashScope API..."); const response = await axios.post(url, data, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' } }); if (response.status === 200) { if (response.data.output && response.data.output.text) { console.log(`${response.data.output.text}`); } } else { console.log("Request failed:"); if (response.data.request_id) { console.log(`request_id=${response.data.request_id}`); } console.log(`code=${response.status}`); if (response.data.message) { console.log(`message=${response.data.message}`); } else { console.log('message=Unknown error'); } } } catch (error) { console.error(`Error calling DashScope: ${error.message}`); if (error.response) { console.error(`Response status: ${error.response.status}`); console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();
Sample response
The sixth rule of the dormitory regulations states: Cultivate good habits regarding work and rest. Every dormitory member has the right to rest and the obligation to ensure others' right to rest. If you need to know more about the regulations, please provide further details.
C#
Sample request
using System.Text; class Program { static async Task Main(string[] args) { // If you have not configured the environment variable, replace the following line with your API key in the apiKey="sk-xxx" format. But this may increase the risk of leakage. string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");; string appId = "YOUR_APP_ID";// Replace with the actual application ID. if (string.IsNullOrEmpty(apiKey)) { Console.WriteLine("Make sure you have specified DASHSCOPE_API_KEY."); return; } string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); string pluginCode = "your_plugin_code"; // your_plugin_codeReplace with the actual plug-in ID. // Replace YOUR_TOKEN with the actual authentication token, such as the API key. string jsonContent = $@"{{ ""input"": {{ ""prompt"": ""Dormitory Convention Content"", ""biz_params"": {{ ""user_defined_params"": {{ ""{pluginCode}"": {{ ""article_index"": 2 }} }}, ""user_defined_tokens"": {{ ""{pluginCode}"": {{ ""user_token"": ""YOUR_TOKEN"" }} }} }} }}, ""parameters"": {{}}, ""debug"": {{}} }}"; HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await client.PostAsync(url, content); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine("Request successful:"); Console.WriteLine(responseBody); } else { Console.WriteLine($"Request failed with status code: {response.StatusCode}"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch (Exception ex) { Console.WriteLine($"Error calling DashScope: {ex.Message}"); } } } }
Sample response
{ "output": { "finish_reason": "stop", "session_id": "1a1913a9922a401f8eba36df8ea1a062", "text": "The second article of the dormitory convention states: Dormitory members should help, care for, and learn from each other, in order to improve together; they should also be tolerant, humble, mutually respectful, and sincere with one another. If you would like to know more detailed contents of the agreement, please specify further." }, "usage": { "models": [ { "output_tokens": 66, "model_id": "qwen-max", "input_tokens": 802 } ] }, "request_id": "04bac806-c5e6-9fab-a846-a66641862be9" }
Go
Sample request
package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // If you have not configured the environment variable, replace the following line with your API key in the apiKey := "sk-xxx" format. But this may increase the risk of leakage. apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // Replace with the actual application ID. pluginCode := "YOUR_PLUGIN_CODE" // Replace with the actual plug-in ID. if apiKey == "" { fmt.Println("Make sure you have specified DASHSCOPE_API_KEY. ") return } url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId) // Create a request body requestBody := map[string]interface{}{ "input": map[string]interface{}{ "prompt": "Dormitory Convention Content", "biz_params": map[string]interface{}{ "user_defined_params": map[string]interface{}{ pluginCode: map[string]interface{}{ "article_index": 10, }, }, "user_defined_tokens": map[string]interface{}{ pluginCode: map[string]interface{}{ "user_token": "YOUR_USER_TOKEN", // Replace with the actual authentication token, such as the API key. }, }, }, }, "parameters": map[string]interface{}{}, "debug": map[string]interface{}{}, } jsonData, err := json.Marshal(requestBody) if err != nil { fmt.Printf("Failed to marshal JSON: %v\n", err) return } // Create an HTTP POST request. req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Failed to create request: %v\n", err) return } // Specify request header. req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") // Send the request. client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("Failed to send request: %v\n", err) return } defer resp.Body.Close() // Read the response. body, err := io.ReadAll(resp.Body) if err != nil { fmt.Printf("Failed to read response: %v\n", err) return } // Process the response. if resp.StatusCode == http.StatusOK { fmt.Println("Request successful:") fmt.Println(string(body)) } else { fmt.Printf("Request failed with status code: %d\n", resp.StatusCode) fmt.Println(string(body)) } }
Sample response
{ "output": { "finish_reason": "stop", "session_id": "b8e051ba7e954ff8919208e7b84430fa", "text": "The tenth article of the dormitory convention states that dormitory members should work together to create and maintain a clean, tidy, aesthetic, and culturally rich dormitory environment. If you need to know the complete content, you may need to refer to other articles or directly consult the dormitory management department. Is there any specific part you would like to know more about?" }, "usage": { "models": [ { "output_tokens": 70, "model_id": "qwen-max", "input_tokens": 855 } ] }, "request_id": "0921ee34-2754-9616-a826-cea33a0e0a14" }
For workflow applications and agent orchestration applications
This section uses City Administrative Regions Query as an example to show how to pass through custom parameters for nodes.
Go to
, select or create a workflow or agent orchestration application.Set the
city
parameter in the Start node. Add and configure an LLM node.Insert the
city
variable in the User Prompt input box.Configure the End node and click Publish.
Use the API
Use
prompt
to pass thequery
parameter andbiz_params
for the custom parametercity
. The LLM can query the city administrative regions based on the city name parameter and return the results.Python
Sample request
import os from http import HTTPStatus from dashscope import Application import dashscope dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1' # Custom input parameter pass-through for workflow and agent orchestration applications biz_params = {"city": "Singapore"} response = Application.call( # If the environment variable is not configured, you can replace the line below with your API key: api_key="sk-xxx". However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. api_key=os.getenv("DASHSCOPE_API_KEY"), app_id='YOUR_APP_ID', prompt='Query the administrative divisions of this city', biz_params=biz_params # Pass business parameters ) if response.status_code != HTTPStatus.OK: print(f'request_id={response.request_id}, code={response.status_code}, message={response.message}') else: print(f'output={response.output}, usage={response.usage}')
Sample response
output={"text": "Singapore is a city-state and does not have traditional administrative regions like many other countries. However, it is divided into smaller areas for administrative purposes. These are known as planning regions, which include: 1. Central Region (Central Singapore) 2. North Region (North Singapore) 3. North-East Region (North-East Singapore) 4. East Region (East Singapore) 5. South Region (South Singapore) 6. West Region (West Singapore) Additionally, there are smaller districts and towns that are part of these regions. Each region and district has its own town council responsible for local administration.", "finish_reason": "stop", "session_id": "6a3bf88eacda43128f57d87e29323166", "thoughts": null, "doc_references": null}, usage={"models": null}
Replace YOUR_APP_ID with the application ID.
Java
Sample request
package org.example; import com.alibaba.dashscope.app.*; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.exception.InputRequiredException; import com.alibaba.dashscope.exception.NoApiKeyException; import com.alibaba.dashscope.utils.JsonUtils; import io.reactivex.Flowable; import com.alibaba.dashscope.utils.Constants; public class Test { static { Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1"; } public static void streamCall() throws NoApiKeyException, InputRequiredException { String bizParams = "{\"city\":\"Singapore\"}"; ApplicationParam param = ApplicationParam.builder() // If the environment variable is not configured, you can replace the line below with your API key: api_key="sk-xxx". However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. .apiKey(System.getenv("DASHSCOPE_API_KEY")) .appId("YOUR_APP_ID") .prompt("Query the administrative divisions of this city") .bizParams(JsonUtils.parse(bizParams)) .build(); Application application = new Application(); Flowable<ApplicationResult> result = application.streamCall(param); result.blockingForEach(data -> { System.out.printf("requestId: %s, text: %s, finishReason: %s\n", data.getRequestId(), data.getOutput().getText(), data.getOutput().getFinishReason()); }); } public static void main(String[] args) { try { streamCall(); } catch (ApiException | NoApiKeyException | InputRequiredException e) { System.out.printf("Exception: %s", e.getMessage()); } System.exit(0); } }
Sample response
requestId: 713ebb6e-8840-9f31-bd58-e7e931ef345d, text: Singapore is a city-state and does not have traditional administrative regions like many other countries. However, it is divided into smaller areas for administrative purposes. These are known as planning regions, which include: 1. Central Region (Central Singapore) 2. North Region (North Singapore) 3. North-East Region (North-East Singapore) 4. East Region (East Singapore) 5. South Region (South Singapore) 6. West Region (West Singapore) Additionally, there are smaller districts and towns that are part of these regions. Each region and district has its own town council responsible for local administration., finishReason: stop
Replace YOUR_APP_ID with the application ID.
HTTP
cURL
Sample request
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \ --header "Authorization: Bearer $DASHSCOPE_API_KEY" \ --header 'Content-Type: application/json' \ --data '{ "input": { "prompt": "Query the administrative divisions of this city", "biz_params": { "city": "Hangzhou"} }, "parameters": {} }'
Replace YOUR_APP_ID with the application ID.
Sample response
{"output":{"finish_reason":"stop","session_id":"c211219896004b50a1f6f66f2ec5413e", "text":"Hangzhou governs 10 districts, 1 county, and administers 2 county-level cities, which are: Shangcheng District, Gongshu District, Xihu District, Binjiang District, Xiaoshan District, Yuhang District, Linping District, Qiantang District, Fuyang District, Lin'an District, Tonglu County, Chun'an County, Jiande City, and Zhuji City. Note that Zhuji City is directly administered by Zhejiang Province and jointly managed by Hangzhou and Shaoxing."},"usage":{}, "request_id":"02c3c9e1-7912-9505-91aa-248d04fb1f5d"}
PHP
Sample request
<?php # If you have not configured the environment variable, replace the following line with your API key in the $api_key="sk-xxx" format. But this may increase the risk of leakage. $api_key = getenv("DASHSCOPE_API_KEY"); $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID. $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion"; // Construct request data. $data = [ "input" => [ 'prompt' => 'Query the administrative divisions of this city', 'biz_params' => [ 'city' => 'Hangzhou' ] ], ]; // Encode the data in the JSON format. $dataString = json_encode($data); // Check whether json_encode succeeded. if (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg()); } // Initialize cURL dialogue $ch = curl_init($url); // Specify cURL settings. 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 whether the cURL execution succeeded. if ($response === false) { die("cURL Error: " . curl_error($ch)); } // Obtain HTTP status code. $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Close uURL dialogue. curl_close($ch); // Decode response data. $response_data = json_decode($response, true); // Process the response. if ($status_code == 200) { if (isset($response_data['output']['text'])) { echo "{$response_data['output']['text']}\n"; } else { echo "No text in response.\n"; } } else { if (isset($response_data['request_id'])) { echo "request_id={$response_data['request_id']}\n"; } echo "code={$status_code}\n"; if (isset($response_data['message'])) { echo "message={$response_data['message']}\n"; } else { echo "message=Unknown error\n"; } }
Sample response
Hangzhou, the capital city of Zhejiang Province, has its administrative divisions mainly comprising 10 districts: Shangcheng District, Gongshu District, Xihu District, Binjiang District, Xiaoshan District, Yuhang District, Linping District, Qiantang District, Fuyang District, and Lin'an District. Each district has its own characteristics and development focus, such as: Shangcheng District and Gongshu District are located in downtown Hangzhou, known for their bustling commerce and rich history. Xihu District is famous for the beautiful West Lake and is also an important area for science, education, and culture. Binjiang District is renowned for its development in high-tech industries. Xiaoshan District and Yuhang District, among others, have rapidly emerged as new urban or economic development areas in recent years. Lin'an District and Fuyang District have retained more of their natural landscapes and rural features. Please note that China's administrative divisions may change according to national policies, so please refer to official sources for the latest information.
Node.js
Install the dependencies:
npm install axios
Sample request
const axios = require('axios'); async function callDashScope() { // If you have not configured the environment variable, replace the following line with your API key in the apiKey='sk-xxx' format. But this may increase the risk of leakage. const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID'; // Replace with the actual application ID. const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "Query the administrative divisions of this city", biz_params: { 'city': 'Hangzhou', }, }, parameters: {}, debug: {}, }; try { console.log("Sending request to DashScope API..."); const response = await axios.post(url, data, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' } }); if (response.status === 200) { if (response.data.output && response.data.output.text) { console.log(`${response.data.output.text}`); } } else { console.log("Request failed:"); if (response.data.request_id) { console.log(`request_id=${response.data.request_id}`); } console.log(`code=${response.status}`); if (response.data.message) { console.log(`message=${response.data.message}`); } else { console.log('message=Unknown error'); } } } catch (error) { console.error(`Error calling DashScope: ${error.message}`); if (error.response) { console.error(`Response status: ${error.response.status}`); console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();
Sample response
Hangzhou is the capital city of Zhejiang Province, and its administrative divisions include 10 districts. They are as follows: Shangcheng District (Shàngchéng Qū): Located in the southern part of central Hangzhou, this district is one of Hangzhou's oldest areas with rich cultural heritage. Gongshu District (Gǒngshù Qū): Formed by the merger of the former Xiacheng and Gongshu Districts, it is situated in the northern part of Hangzhou. Xihu District (Xīhú Qū): Famous for the West Lake, a World Cultural Heritage site, it offers abundant natural and cultural attractions. Binjiang District (Bīnjiāng Qū): Located on the southern bank of the Qiantang River, it is a hub for high-tech industries. Xiaoshan District (Xiāoshān Qū): Situated in the eastern part of Hangzhou, it is one of China's important manufacturing bases. Yuhang District (Yúháng Qū): Once home to Linping, one of China's four historic towns, it is now a significant economic development area in Hangzhou. Fuyang District (Fùyáng Qū): Located in the southwest of Hangzhou, it is named after the Fuchun River that flows through it. Lin'an District (Lín'ān Qū): Located in the western mountainous area of Hangzhou, it is renowned for its beautiful natural scenery. Qiantang District (Qiántáng Qū): Established in 2021, it includes the former Dajiangdong Industrial Cluster and parts of Xiaoshan District, aimed at promoting development in the eastern region of Hangzhou. Linping District (Lín Píng Qū): A new administrative district carved out from Yuhang District, mainly covering areas like the Linping Subdistrict of the former Yuhang District. The above information reflects the situation as of my latest update. Please note that administrative divisions may change, so refer to the latest official announcements for the most current information.
C#
Sample request
using System.Text; class Program { static async Task Main(string[] args) { //If you have not configured the environment variable, replace the following line with your API key in the apiKey="sk-xxx" format. But this may increase the risk of leakage. string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set."); string appId = "YOUR_APP_ID"; // Replace with the actual application ID. string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); string jsonContent = @"{ ""input"": { ""prompt"": ""Query the administrative divisions of this city"", ""biz_params"":{ ""city"":""Hangzhou"" } }, ""parameters"": {}, ""debug"": {} }"; HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await client.PostAsync(url, content); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine("Request successful:"); Console.WriteLine(responseBody); } else { Console.WriteLine($"Request failed with status code: {response.StatusCode}"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch (Exception ex) { Console.WriteLine($"Error calling DashScope: {ex.Message}"); } } } }
Sample response
{ "output": { "finish_reason": "stop", "session_id": "7a9ff57eec7d475fa5d487de5f5178d2", "text": "Hangzhou is the capital of Zhejiang Province and has jurisdiction over 10 districts: Shangcheng, Gongshu, Xihu, Binjiang, Xiaoshan, Yuhang, Linping, Qiantang, Fuyang, and Lin'an. Each district has its unique geographical location and development characteristics. For example, Xihu District is renowned for its beautiful natural scenery, particularly the famous West Lake located there, while Binjiang District is more known for its high-tech industry development. Furthermore, as the city continues to develop, administrative divisions may be adjusted, so please stay updated with the latest information from official announcements." }, "usage": { }, "request_id": "d2c2fcc9-f821-98c9-9430-8704a2a41225" }
Go
Sample request
package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // If you have not configured the environment variable, replace the following line with your API key in the apiKey := "sk-xxx" format. But this may increase the risk of leakage. apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // Replace with the actual application ID. if apiKey == "" { fmt.Println("Make sure you have specified DASHSCOPE_API_KEY. ") return } url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId) // Create a request body requestBody := map[string]interface{}{ "input": map[string]interface{}{ "prompt": "Query the administrative divisions of this city", "biz_params": map[string]interface{}{ "city": "Hangzhou", }, }, "parameters": map[string]interface{}{}, "debug": map[string]interface{}{}, } jsonData, err := json.Marshal(requestBody) if err != nil { fmt.Printf("Failed to marshal JSON: %v\n", err) return } // Create an HTTP POST request. req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Failed to create request: %v\n", err) return } // Specify request header. req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") // Send the request. client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("Failed to send request: %v\n", err) return } defer resp.Body.Close() // Read the response. body, err := io.ReadAll(resp.Body) if err != nil { fmt.Printf("Failed to read response: %v\n", err) return } // Process the response. if resp.StatusCode == http.StatusOK { fmt.Println("Request successful:") fmt.Println(string(body)) } else { fmt.Printf("Request failed with status code: %d\n", resp.StatusCode) fmt.Println(string(body)) } }
Sample response
{ "output": { "finish_reason": "stop", "session_id": "2dc3e1a9dcd248c6bb9ca92bffc3e745", "text": "Hangzhou, abbreviated as "Hang," is the capital city of Zhejiang Province. According to the latest administrative division adjustments, Hangzhou currently administers 10 districts, 2 county-level cities, and 1 county, specifically as follows: Districts (10): Shangcheng District, Gongshu District, Xihu District, Binjiang District, Xiaoshan District, Yuhang District, Linping District, Qiantang District, Fuyang District, Lin'an District. County-level Cities (2): Jiande City, Tonglu County (note that Tonglu is technically treated as a county-level city, but it is actually a county). County (1): Chun'an County. Please note that administrative regions may change over time, and for the most recent adjustments, it is recommended to refer to the official releases from the government. The above information is collated based on relatively recent data. For the latest changes, it is advisable to visit the official government website for the most accurate information." }, "usage": { }, "request_id": "d3c8f368-b645-9446-bfe4-20ca51821a02" }