Custom application parameter pass-through

Updated at:

Pass custom parameters, primarily to custom plugins and custom nodes, when calling Alibaba Cloud Model Studio's Agent Application and Workflow Application (which replace agent orchestration applications).

You must first obtain and configure an API key and configure the API key as an environment variable. If you call through an SDK, you must also install the DashScope SDK.

Custom plugin parameter pass-through

This article uses the dormitory convention content query tool as an example to show you how to call the custom plugin parameter pass-through feature of an application through an API.

NoteParameters for custom plugins are passed through an associated Agent Application or a plugin node in a Workflow Application.

The following example shows how to pass custom plugin parameters in an Agent Application.

Usage

Step 1: Create a custom plugin tool

If you have already created a plugin tool or imported a plugin, skip this step.

  1. Create a custom plugin: In the left-side navigation pane, choose Tools > Plug-in Management to go to the Plug-in Management page and click Create Plug-in. Enter the plugin information. If authentication is required, turn on the Enable Authentication switch and enter the authentication configuration.

    Example plugin description: Dormitory convention query tool, which can query a specific entry based on the entered numeric index.

    Example plugin URL: https://domitorgreement-plugin-example-icohrkdjxy.cn-beijing.fcapp.run

    Example authentication configuration: select User-level Authentication as the authentication type, Header as the location, and basic as Type.

    Note: The plugin description briefly explains the purpose of the plugin. It helps the large model determine whether the current task requires calling the current plugin. Describe it in natural language.

  2. Create a tool: Fill in the tool information and configure the input and output parameters. Note:

    1. The tool description helps the large model better understand the tool's functions and use cases. Describe it in natural language and provide usage examples where possible.
    2. A parameter name should be as meaningful as possible to help the large model understand what the parameter information to be identified is.
    3. A parameter description describes the function of the input parameter. Keep it concise and accurate to help the large model further understand how to obtain the parameter.
    4. You must select Business Pass-through as the passing method of the input parameter.

    In this example, the dormitory convention content index article_index is set as a business pass-through parameter.

    Enter Dormitory convention query tool as the tool name, select POST as the request method, and select application/json as the submission method. Set the type of the input parameter article_index to Number, the passing method to Body, and make it required. Enter article as the output parameter name, "Dormitory convention content" as the parameter description, and set the type to String.

  3. Click Test Tool. After the test runs successfully, publish the plugin.

Step 2: Associate the agent application with the specified plugin

Plugin tools can only be associated with Agent Applications in the same workspace.

  1. On the card of a published plugin, click Add to Agent and select the agent application to associate;
  2. Alternatively, click + Plugin in an application to associate the specified custom plugin;
  3. Then, publish the application directly.

Step 3: API call

  • When authentication is not required: To call a custom plugin through an API, use user_defined_params of biz_params to pass the custom plugin information, replace your_plugin_code with the actual plugin ID, and pass the key-value pairs of the input parameters configured in the plugin.

    The plugin ID can be obtained from the plugin card.

    In this example, the value 2 is passed to the dormitory convention index article_index parameter to query the content of the second dormitory convention, and the correct result is returned.

    Python

    Sample request
    import os
    import dashscope
    # dashscope 2.0.1 or later is required.
    from dashscope.v2 import DashScopeError
    client = dashscope.Client(
            # If the environment variable is not set, you can use your Model Studio API key by replacing the following line with api_key="sk-xxx". However, hardcoding the API key directly in code is not recommended in production environments to reduce the risk of API key leakage.
            api_key=os.getenv("DASHSCOPE_API_KEY"))
    biz_params = {
        # Pass the input parameters of the custom plugin for the agent application. Replace your_plugin_code with your custom plugin ID.
        "user_defined_params": {
            "your_plugin_code": {
                "article_index": 2}}}
    try:
        response = client.apps.completions.create(
                app_id='YOUR_APP_ID',
                prompt='Dormitory convention content',
                biz_params=biz_params)
        print('%s\n' % (response.text))  # Process and output only the text.
        # 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'For more information, see: https://help.aliyun.com/en/model-studio/developer-reference/error-code')
    
    Sample response
    The second article of the dormitory convention is as follows:
    "Roommates must help, care for, and learn from each other to achieve mutual improvement. They must be tolerant, forgiving, respectful, and sincere."
    This shows that in the dormitory, members should foster a positive living and learning atmosphere, help and support each other, and also learn to understand and respect others. If you need to learn about other articles of the convention, please let me know!
    

    Java

    Sample request
    import com.alibaba.dashscope.app.*;
    import com.alibaba.dashscope.exception.ApiException;
    import com.alibaba.dashscope.exception.InputRequiredException;
    import com.alibaba.dashscope.exception.NoApiKeyException;
    import com.alibaba.dashscope.utils.JsonUtils;
    public class Main {
        public static void appCall() throws NoApiKeyException, InputRequiredException {
            String bizParams =
                    // Pass the input parameters of the custom plugin for the agent application. Replace {your_plugin_code} with your custom plugin ID.
                    "{\"user_defined_params\":{\"{your_plugin_code}\":{\"article_index\":2}}}";
            ApplicationParam param = ApplicationParam.builder()
                    // If the environment variable is not set, you can use your Model Studio API key by replacing the following line with .apiKey("sk-xxx"). However, hardcoding the API key directly in code is not recommended in production environments to reduce the risk of API key leakage.
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .appId("YOUR_APP_ID")
                    .prompt("Dormitory convention content")
                    .bizParams(JsonUtils.parse(bizParams))
                    .build();
            Application application = new Application();
            ApplicationResult result = application.call(param);
            System.out.printf("%s\n",
                    result.getOutput().getText());
        }
        public static void main(String[] args) {
            try {
                appCall();
            } catch (ApiException | NoApiKeyException | InputRequiredException e) {
                System.out.printf("Exception: %s", e.getMessage());
                System.out.println("For more information, see: https://help.aliyun.com/en/model-studio/developer-reference/error-code");
            }
            System.exit(0);
        }
    }
    
    Sample response
    The second article of the dormitory convention is as follows:
    Article 2: Roommates must help, care for, and learn from each other to achieve mutual improvement. They must be tolerant, forgiving, respectful, and sincere.
    This emphasizes that in a shared living environment, roommates should maintain a positive and supportive relationship to create a harmonious atmosphere for living and learning. If you need to learn about other specific articles, please let me know.
    

    HTTP

    curl

    Sample request
    curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
    --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
    --header 'Content-Type: application/json' \
    --data '{
        "input": {
            "prompt": "Dormitory convention content",
            "biz_params":
            {
                "user_defined_params":
                {
                    "{your_plugin_code}":
                        {
                        "article_index": 2
                        }
                }
            }
        },
        "parameters":  {},
        "debug":{}
    }'
    

    Replace YOUR_APP_ID with the actual application ID.

    Sample response
    {"output":
    {"finish_reason":"stop",
    "session_id":"e151267ffded4fbdb13d91439011d31e",
    "text":"The second article of the dormitory convention is: \"Roommates must help, care for, and learn from each other to achieve mutual improvement. They must be tolerant, forgiving, respectful, and sincere.\" This means that in dormitory life, everyone must support each other to create a harmonious and positive living environment."},
    "usage":{"models":[{"output_tokens":94,"model_id":"qwen-max","input_tokens":453}]},
    "request_id":"a39fd2b5-7e2c-983e-84a1-1039f726f18a"}%
    

    PHP

    Sample request
    <?php
    # If the environment variable is not set, you can use your Model Studio API key by replacing the following line with $api_key="sk-xxx". However, hardcoding the API key directly in code is not recommended in production environments to reduce the risk of API key leakage.
    $api_key = getenv("DASHSCOPE_API_KEY");
    $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID
    $url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
    //Replace {your_plugin_code} with the actual plugin ID
    // Construct the request data
    $data = [
        "input" => [
            'prompt' => 'Dormitory convention content',
            'biz_params' => [
            'user_defined_params' => [
                '{your_plugin_code}' => [
                    'article_index' => 2
                    ]
                ]
            ]
        ],
    ];
    // Encode the data as JSON
    $dataString = json_encode($data);
    // Check whether json_encode succeeded
    if (json_last_error() !== JSON_ERROR_NONE) {
        die("JSON encoding failed with error: " . json_last_error_msg());
    }
    // Initialize a cURL session
    $ch = curl_init($url);
    // Set the cURL options
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $api_key
    ]);
    // Execute the request
    $response = curl_exec($ch);
    // Check whether the cURL execution succeeded
    if ($response === false) {
        die("cURL Error: " . curl_error($ch));
    }
    // Get the HTTP status code
    $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    // Close the cURL session
    curl_close($ch);
    // Decode the response data
    $response_data = json_decode($response, true);
    // Process the response
    if ($status_code == 200) {
        if (isset($response_data['output']['text'])) {
            echo "{$response_data['output']['text']}\n";
        } else {
            echo "No text in response.\n";
        }
    }else {
        if (isset($response_data['request_id'])) {
            echo "request_id={$response_data['request_id']}\n";}
        echo "code={$status_code}\n";
        if (isset($response_data['message'])) {
            echo "message={$response_data['message']}\n";}
        else {
            echo "message=Unknown error\n";}
    }
    ?>
    
    Sample response
    The second article of the dormitory convention states: Roommates must help, care for, and learn from each other to achieve mutual improvement. They must be tolerant, forgiving, respectful, and sincere. This is to ensure that everyone can live and study in a harmonious and friendly environment. If you want to learn about other specific articles or have other questions, feel free to ask me.
    

    Node.js

    Dependencies to install:
    npm install axios
    
    Sample request
    const axios = require('axios');
    async function callDashScope() {
        // If the environment variable is not set, you can use your Model Studio API key by replacing the following line with apiKey='sk-xxx'. However, hardcoding the API key directly in code is not recommended in production environments to reduce the risk of API key leakage.
        const apiKey = process.env.DASHSCOPE_API_KEY;
        const appId = 'YOUR_APP_ID';// Replace with the actual application ID
        const pluginCode = 'YOUR_PLUGIN_CODE';// Replace with the actual plugin ID
        const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
        const data = {
            input: {
                prompt: "Dormitory convention content",
                biz_params: {
                    user_defined_params: {
                        [pluginCode]: {
                            // article_index is a variable of the custom plugin. Replace it with your actual plugin 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 article of the dormitory convention is as follows:
    Pay attention to electrical safety and eliminate fire hazards. Open flames, non-compliant electrical appliances, various cookers, and other prohibited items are strictly forbidden in the dormitory. Flammable and explosive items must not be stored, and power sources must not be privately connected.
    If you need to learn more about the rules, please let me know.
    

    C#

    Sample request
    using System.Text;
    class Program
    {
        static async Task Main(string[] args)
        {
            // If the environment variable is not set, you can use your Model Studio API key by replacing the following line with apiKey="sk-xxx". However, hardcoding the API key directly in code is not recommended in 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 = "YOUR_APP_ID";// Replace with the actual application ID
            if (string.IsNullOrEmpty(apiKey))
            {
                Console.WriteLine("Please ensure that DASHSCOPE_API_KEY is set.");
                return;
            }
            string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
                string pluginCode = "{your_plugin_code}"; // Replace {your_plugin_code} with the actual plugin 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 dormitory convention is as follows:
    "Roommates must help, care for, and learn from each other to achieve mutual improvement. They must be tolerant, forgiving, respectful, and sincere."
    This indicates that in the dormitory, members need to establish a positive relationship, creating a harmonious living and learning environment by helping, caring for, and supporting each other. They should also learn to understand and accept differences between roommates and communicate with sincerity. If you want to learn about other articles or specific content, 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 the environment variable is not set, you can use your Model Studio API key by replacing the following line with apiKey := "sk-xxx". However, hardcoding the API key directly in code is not recommended in production environments to reduce the risk of API key leakage.
      apiKey := os.Getenv("DASHSCOPE_API_KEY")
      appId := "YOUR_APP_ID"           // Replace with the actual application ID
      pluginCode := "YOUR_PLUGIN_CODE" // Replace with the actual plugin ID
      if apiKey == "" {
          fmt.Println("Please ensure that DASHSCOPE_API_KEY is set.")
          return
      }
      url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
      // Create the request body
      requestBody := map[string]interface{}{
          "input": map[string]interface{}{
              "prompt": "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
      }
      // Set the request headers
      req.Header.Set("Authorization", "Bearer "+apiKey)
      req.Header.Set("Content-Type", "application/json")
      // Send the request
      client := &http.Client{}
      resp, err := client.Do(req)
      if err != nil {
          fmt.Printf("Failed to send request: %v\n", err)
          return
      }
      defer resp.Body.Close()
      // Read the response
      body, err := io.ReadAll(resp.Body)
      if err != nil {
          fmt.Printf("Failed to read response: %v\n", err)
          return
      }
      // Process the response
      if resp.StatusCode == http.StatusOK {
          fmt.Println("Request successful:")
          fmt.Println(string(body))
      } else {
          fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
          fmt.Println(string(body))
      }
    }
    
    Sample response
    {
        "output": {
            "finish_reason": "stop",
            "session_id": "860d2a4c1f3649ac880298537993cb51",
            "text": "The second article of the dormitory convention is as follows:
    Roommates must help, care for, and learn from each other to achieve mutual improvement. They must be tolerant, forgiving, respectful, and sincere.
    This emphasizes that in dormitory life, roommates should maintain a supportive relationship and respect each other. Would you like to learn about the content of other articles?"
        },
        "usage": {
            "models": [
                {
                    "output_tokens": 84,
                    "model_id": "qwen-max",
                    "input_tokens": 876
                }
            ]
        },
        "request_id": "0a250055-90a4-992d-9276-e268ad35d1ab"
    }
    
  • When authentication is required: To call a custom plugin through an API, the Authentication switch is turned on in the plugin and User-level Authentication is configured.

    The plugin ID is obtained from the plugin card.

    • Use user_defined_params of biz_params to pass the custom plugin information, replace your_plugin_code with the actual plugin ID, and pass the key-value pairs of the input parameters configured in the plugin.
    • Use user_defined_tokens of biz_params to pass the related information, replace your_plugin_code with the actual plugin ID, and fill in the authentication information as the value of user_token, such as the actual DASHSCOPE_API_KEY value.
    • After the authentication succeeds, the specific entry is queried based on the passed index parameter and the correct result is returned.

    In this example, the value 2 is passed to the dormitory convention index article_index parameter, and the value of user_token, YOUR_TOKEN, is replaced with the actual DASHSCOPE_API_KEY value. After the authentication succeeds, the content of the second dormitory convention is queried, and the correct result is returned.

    Python

    Sample request
    import os
    import dashscope
    # dashscope 2.0.1 or later is required.
    from dashscope.v2 import DashScopeError
    client = dashscope.Client(
                # If the environment variable is not set, you can use your Model Studio API key by replacing the following line with api_key="sk-xxx". However, hardcoding the API key directly in code is not recommended in production environments to reduce the risk of API key leakage.
                api_key=os.getenv("DASHSCOPE_API_KEY"))
    biz_params = {
        # Pass the authentication of the custom plugin for the agent application. Replace your_plugin_code with your custom plugin ID and YOUR_TOKEN with the authentication information, such as an API key.
        "user_defined_params": {
            "your_plugin_code": {
                "article_index": 2}},
        "user_defined_tokens": {
            "your_plugin_code": {
                "user_token": "YOUR_TOKEN"}}}
    try:
        response = client.apps.completions.create(
                    app_id='YOUR_APP_ID',
                    prompt='Dormitory convention content',
                    biz_params=biz_params)
        print('%s\n' % (response.text))  # Process and output only the text.
        # 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'For more information, see: https://help.aliyun.com/en/model-studio/developer-reference/error-code')
    
    Sample response
    The second article of the dormitory convention is as follows:
    Roommates must help, care for, and learn from each other to achieve mutual improvement. They must be tolerant, forgiving, respectful, and sincere.
    If you need to learn more about the rules, please let me know.
    

    Java

    Sample request
    import com.alibaba.dashscope.app.*;
    import com.alibaba.dashscope.exception.ApiException;
    import com.alibaba.dashscope.exception.InputRequiredException;
    import com.alibaba.dashscope.exception.NoApiKeyException;
    import com.alibaba.dashscope.utils.JsonUtils;
    public class Main {
        public static void appCall() throws NoApiKeyException, InputRequiredException {
            String bizParams =
                    // Replace {your_plugin_code} with the actual plugin ID, and YOUR_TOKEN with the actual token, such as an API key.
                    "{\"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 set, you can use your Model Studio API key by replacing the following line with .apiKey("sk-xxx"). However, hardcoding the API key directly in code is not recommended in production environments to reduce the risk of API key leakage.
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .appId("YOUR_APP_ID")
                    .prompt("Dormitory convention content")
                    .bizParams(JsonUtils.parse(bizParams))
                    .build();
            Application application = new Application();
            ApplicationResult result = application.call(param);
            System.out.printf("%s\n",
                    result.getOutput().getText());
        }
        public static void main(String[] args) {
            try {
                appCall();
            } catch (ApiException | NoApiKeyException | InputRequiredException e) {
                System.out.printf("Exception: %s", e.getMessage());
                System.out.println("For more information, see: https://help.aliyun.com/en/model-studio/developer-reference/error-code");
            }
            System.exit(0);
        }
    }
    
    Sample response
    The second article of the dormitory convention is as follows:
    Roommates must help, care for, and learn from each other to achieve mutual improvement. They must be tolerant, forgiving, respectful, and sincere.
    If you need to query more rules, please let me know.
    

    Replace YOUR_APP_ID with the application ID, your_plugin_code with the custom plugin ID, and YOUR_TOKEN with the authentication token.

    HTTP

    curl

    Sample request
    curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
    --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
    --header 'Content-Type: application/json' \
    --data '{
        "input": {
            "prompt": "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 actual application ID, your_plugin_code with the custom plugin ID, and YOUR_TOKEN with the authentication token.

    Sample response
    {"output":{"finish_reason":"stop",
    "session_id":"d3b5c3e269dc40479255a7a02df5c630",
    "text":"The second article of the dormitory convention is: \"Roommates must help, care for, and learn from each other to achieve mutual improvement. They must be tolerant, forgiving, respectful, and sincere.\" 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"}%
    

    PHP

    Sample request
    <?php
    # If the environment variable is not set, you can use your Model Studio API key by replacing the following line with $api_key="sk-xxx". However, hardcoding the API key directly in code is not recommended in production environments to reduce the risk of API key leakage.
    $api_key = getenv("DASHSCOPE_API_KEY");
    $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID
    $url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
    // Construct the request data
    $data = [
        "input" => [
            'prompt' => 'Dormitory convention content',
            'biz_params' => [
            'user_defined_params' => [
                '{your_plugin_code}' => [//Replace {your_plugin_code} with the actual plugin ID
                    'article_index' => 2
                    ]
                ],
            'user_defined_tokens' => [
                '{your_plugin_code}' => [//Replace {your_plugin_code} with the actual plugin ID
                    'user_token' => 'YOUR_TOKEN'//Replace with the actual token, such as an API key
                ]
            ]
            ]
        ],
    ];
    // Encode the data as JSON
    $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 a cURL session
    $ch = curl_init($url);
    // Set the cURL options
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $api_key
    ]);
    // Execute the request
    $response = curl_exec($ch);
    // Check whether the cURL execution succeeded
    if ($response === false) {
        die("cURL Error: " . curl_error($ch));
    }
    // Get the HTTP status code
    $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    // Close the cURL session
    curl_close($ch);
    // Decode the response data
    $response_data = json_decode($response, true);
    // Process the response
    if ($status_code == 200) {
        if (isset($response_data['output']['text'])) {
            echo "{$response_data['output']['text']}\n";
        } else {
            echo "No text in response.\n";
        }
    }else {
        if (isset($response_data['request_id'])) {
            echo "request_id={$response_data['request_id']}\n";}
        echo "code={$status_code}\n";
        if (isset($response_data['message'])) {
            echo "message={$response_data['message']}\n";}
        else {
            echo "message=Unknown error\n";}
    }
    ?>
    
    Sample response
    The second article of the dormitory convention is as follows:
    > Roommates must help, care for, and learn from each other to achieve mutual improvement. They must be tolerant, forgiving, respectful, and sincere.
    If you need to learn more about the convention or other information, feel free to let me know.
    

    Node.js

    Dependencies to install:
    npm install axios
    
    Sample request
    const axios = require('axios');
    async function callDashScope() {
        // If the environment variable is not set, you can use your Model Studio API key by replacing the following line with apiKey='sk-xxx'. However, hardcoding the API key directly in code is not recommended in production environments to reduce the risk of API key leakage.
        const apiKey = process.env.DASHSCOPE_API_KEY;
        const appId = 'YOUR_APP_ID';// Replace with the actual application ID
        const pluginCode = 'YOUR_PLUGIN_CODE';// Replace with the actual plugin ID
        const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
        const data = {
            input: {
                prompt: "Dormitory convention content",
                biz_params: {
                    user_defined_params: {
                        [pluginCode]: {
                            // article_index is a variable of the custom plugin. Replace it with your actual plugin variable.
                            'article_index': 6
                        }
                    },
                    user_defined_tokens: {
                        [pluginCode]: {
                            // Replace YOUR_TOKEN with the actual authentication information, such as an 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 article of the dormitory convention states: Develop good sleep habits. Every dormitory member has the right to rest and the obligation to ensure others' right to rest. If you need to learn more about the rules, please provide more details.
    

    C#

    Sample request
    using System.Text;
    class Program
    {
        static async Task Main(string[] args)
        {
            // If the environment variable is not set, you can use your Model Studio API key by replacing the following line with apiKey="sk-xxx". However, hardcoding the API key directly in code is not recommended in 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 = "YOUR_APP_ID";// Replace with the actual application ID
            if (string.IsNullOrEmpty(apiKey))
            {
                Console.WriteLine("Please ensure that DASHSCOPE_API_KEY is set.");
                return;
            }
            string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
                string pluginCode = "your_plugin_code"; // Replace your_plugin_code with the actual plugin ID
                // Replace YOUR_TOKEN with the actual token, such as an 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 is as follows:
    Roommates must help, care for, and learn from each other to achieve mutual improvement. They must be tolerant, forgiving, respectful, and sincere.
    If you need more details about the convention, please specify."
        },
        "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 the environment variable is not set, you can use your Model Studio API key by replacing the following line with apiKey := "sk-xxx". However, hardcoding the API key directly in code is not recommended in production environments to reduce the risk of API key leakage.
      apiKey := os.Getenv("DASHSCOPE_API_KEY")
      appId := "YOUR_APP_ID"           // Replace with the actual application ID
      pluginCode := "YOUR_PLUGIN_CODE" // Replace with the actual plugin ID
      if apiKey == "" {
          fmt.Println("Please ensure that DASHSCOPE_API_KEY is set.")
          return
      }
      url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
      // Create the request body
      requestBody := map[string]interface{}{
          "input": map[string]interface{}{
              "prompt": "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 an 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
      }
      // Set the request headers
      req.Header.Set("Authorization", "Bearer "+apiKey)
      req.Header.Set("Content-Type", "application/json")
      // Send the request
      client := &http.Client{}
      resp, err := client.Do(req)
      if err != nil {
          fmt.Printf("Failed to send request: %v\n", err)
          return
      }
      defer resp.Body.Close()
      // Read the response
      body, err := io.ReadAll(resp.Body)
      if err != nil {
          fmt.Printf("Failed to read response: %v\n", err)
          return
      }
      // Process the response
      if resp.StatusCode == http.StatusOK {
          fmt.Println("Request successful:")
          fmt.Println(string(body))
      } else {
          fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
          fmt.Println(string(body))
      }
    }
    
    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 dormitory environment that is clean, tidy, aesthetically pleasing, and of high cultural taste. To understand the full content of the dormitory convention, you may need to review other articles or directly consult the dormitory management department. Is there any other specific content you would like to know about?"
        },
        "usage": {
            "models": [
                {
                    "output_tokens": 70,
                    "model_id": "qwen-max",
                    "input_tokens": 855
                }
            ]
        },
        "request_id": "0921ee34-2754-9616-a826-cea33a0e0a14"
    }
    

Custom node parameter pass-through

This article uses the querying the administrative divisions of a city by city name example to show you how to call the custom node parameter pass-through feature of an application through an API.

NoteCustom node parameters of an application are passed through the start node of a Workflow Application.

The following example shows how to pass the custom parameters of the start node in a Workflow Application.

Usage

Step 1: Configure custom node parameters

Go to the Application Management page in the Model Studio console, select a Workflow Application and customize the parameters of the start node (this example sets a String variable named city). Then, insert the city and query variables into the Prompt and publish the application.

Step 2: API call

When calling, pass city through the biz_params field and query through the prompt field.

Python

Sample request
import os
import dashscope
from dashscope.v2 import DashScopeError

client = dashscope.Client(
    # If the environment variable is not set, you can use your Model Studio API key by replacing the following line with api_key="sk-xxx". However, hardcoding the API key directly in code is not recommended in production environments to reduce the risk of API key leakage.
    api_key=os.getenv("DASHSCOPE_API_KEY"))
# Pass custom parameters for the workflow application
biz_params = {"city": "Hangzhou"}
try:
    response = client.apps.completions.create(
        app_id='YOUR_APP_ID',  # Replace with the actual application ID
        prompt='Query the administrative divisions of this city',
        biz_params=biz_params  # Pass the business parameters
    )
    print(f'{response.text}')  # Process and output only the text.
except DashScopeError as e:
    print(f'request_id={e.request_id}')
    print(f'code={e.code}')
    print(f'message={e.message}')
    print(f'For more information, see: https://help.aliyun.com/en/model-studio/developer-reference/error-code')
Sample response
Hangzhou, as the capital city of Zhejiang Province, has the following administrative divisions including 10 municipal districts: Shangcheng, Gongshu, Xihu, Binjiang, Xiaoshan, Yuhang, Linping, Qiantang, Fuyang, and Lin'an. Each district has its own unique characteristics and development priorities.
- Shangcheng District: Located in the central area of Hangzhou, it is one of the political, economic, and cultural centers of Hangzhou.
- Gongshu District: Known for its canal culture, it has numerous historical and cultural heritage sites.
- Xihu District: The famous West Lake Scenic Area is located in this district, making it an important destination for sightseeing.
- Binjiang District: A gathering place for high-tech industries, where well-known companies such as Alibaba are located.
- Xiaoshan District: An administrative district in the southeast with rapid economic development, especially in manufacturing.
- Yuhang District: Has developed rapidly in recent years, especially in the internet economy, and Alibaba's headquarters is also located here (Note: Alibaba's headquarters is actually in Binjiang District).
- Linping District: A newly established administrative district aimed at promoting comprehensive economic and social development in the area.
- Qiantang District: Also a result of recent administrative division adjustments, it emphasizes combining innovative development with ecological protection.
- Fuyang District: Located to the southwest of Hangzhou, it is known for its rich natural landscapes and long history and culture.
- Lin'an District: Located in the west of Hangzhou, it is famous for its beautiful ecology and has a profound cultural heritage.
Please note that specific city planning may change over time. Refer to the latest official information.

Java

Sample request
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import io.reactivex.Flowable;
public class Main {
    public static void appCall() throws NoApiKeyException, InputRequiredException {
        String bizParams =
                "{\"city\":\"Hangzhou\"}";
        ApplicationParam param = ApplicationParam.builder()
                // If the environment variable is not set, you can use your Model Studio API key by replacing the following line with .apiKey("sk-xxx"). However, hardcoding the API key directly in code is not recommended in production environments 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();
        ApplicationResult result = application.call(param);
        System.out.printf("%s\n",
                result.getOutput().getText());
    }
    public static void main(String[] args) {
        try {
            appCall();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.printf("Exception: %s", e.getMessage());
            System.out.println("For more information, see: https://help.aliyun.com/en/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}
Sample response
Hangzhou is the capital city of Zhejiang Province, and its administrative divisions mainly include 10 municipal districts: Shangcheng, Gongshu, Xihu, Binjiang, Xiaoshan, Yuhang, Linping, Qiantang, Fuyang, and Lin'an. Each district has its own characteristics and development priorities.
- Shangcheng District: Located in the center of Hangzhou, it has many historical and cultural heritage sites.
- Gongshu District: Famous for its Grand Canal culture, it is also an important commercial and residential area.
- Xihu District: Known for its beautiful natural scenery, including the famous West Lake Scenic Area.
- Binjiang District: A high-tech industry cluster where the Hangzhou National High-Tech Industry Development Zone is located.
- Xiaoshan District: Has experienced rapid economic development, with particularly outstanding performance in manufacturing.
- Yuhang District: Has grown rapidly in recent years with the development of high-tech companies such as Alibaba.
- Linping District: Formed in 2021 from part of the original Yuhang District, it focuses on ecological development and technological innovation.
- Qiantang District: Also a new district established in 2021, it is positioned as a new hub for transportation and industrial development in eastern Hangzhou.
- Fuyang District: A historic and cultural city, and also one of the major centers for the papermaking industry.
- Lin'an District: Located in western Hangzhou, it has a high forest coverage rate and a good ecological environment.
These areas together form the unique geographic pattern and socio-economic structure of Hangzhou. If you are interested in a specific area or need more detailed information, please let me know!

HTTP

curl

Sample request
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "Query the administrative divisions of this city",
        "biz_params": {
        "city": "Hangzhou"}
    },
    "parameters":  {}
}'

Replace YOUR_APP_ID with the actual application ID.

Sample response
{"output":{"finish_reason":"stop","session_id":"c211219896004b50a1f6f66f2ec5413e",
"text":"Hangzhou administers 10 districts, 1 county, and 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: Zhuji City is directly administered by Zhejiang Province and jointly managed by Hangzhou and Shaoxing cities."},"usage":{},
"request_id":"02c3c9e1-7912-9505-91aa-248d04fb1f5d"}

PHP

Sample request
<?php
# If the environment variable is not set, you can use your Model Studio API key by replacing the following line with $api_key="sk-xxx". However, hardcoding the API key directly in code is not recommended in production environments to reduce the risk of API key leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Replace with the actual application ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
// Construct the request data
$data = [
    "input" => [
        'prompt' => 'Query the administrative divisions of this city',
        'biz_params' => [
            'city' => 'Hangzhou'
        ]
    ],
];
// Encode the data as JSON
$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 a cURL session
$ch = curl_init($url);
// Set the cURL options
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $api_key
]);
// Execute the request
$response = curl_exec($ch);
// Check whether the cURL execution succeeded
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}
// Get the HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL session
curl_close($ch);
// Decode the response data
$response_data = json_decode($response, true);
// Process the response
if ($status_code == 200) {
    if (isset($response_data['output']['text'])) {
        echo "{$response_data['output']['text']}\n";
    } else {
        echo "No text in response.\n";
    }
} else {
    if (isset($response_data['request_id'])) {
        echo "request_id={$response_data['request_id']}\n";
    }
    echo "code={$status_code}\n";
    if (isset($response_data['message'])) {
        echo "message={$response_data['message']}\n";
    } else {
        echo "message=Unknown error\n";
    }
}
Sample response
Hangzhou is the capital city of Zhejiang Province, and its administrative divisions mainly include 10 municipal districts: Shangcheng, Gongshu, Xihu, Binjiang, Xiaoshan, Yuhang, Linping, Qiantang, Fuyang, and Lin'an.
Each district has its own characteristics and development priorities. For example:
- **Shangcheng** and **Gongshu** districts are located in the center of Hangzhou, with bustling commerce and a long history.
- **Xihu District** is famous for the beautiful West Lake and is also an important scientific, educational, and cultural area.
- **Binjiang District** is known for its high-tech industry development.
- **Xiaoshan District**, **Yuhang District**, and others are new urban areas or economic development zones that have risen rapidly in recent years with urban development.
- **Lin'an District**, **Fuyang District**, and other places have largely preserved their natural scenery and rural character.
Please note that administrative divisions in China may be adjusted according to national policies. Obtain the latest information through official channels.

Node.js

Dependencies to install:
npm install axios
Sample request
const axios = require('axios');
async function callDashScope() {
    // If the environment variable is not set, you can use your Model Studio API key by replacing the following line with apiKey='sk-xxx'. However, hardcoding the API key directly in code is not recommended in production environments to reduce the risk of API key leakage.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'YOUR_APP_ID'; // Replace with the actual application ID
    const url = `https://dashscope.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 of Zhejiang Province, and its administrative divisions include 10 municipal districts. They are as follows:
1. Shangcheng District (Shàngchéng Qū): Located in the south-central part of Hangzhou, it is one of the oldest areas with the richest cultural heritage.
2. Gongshu District (Gǒngshù Qū): A new district formed by the merger of the former Xiacheng and Gongshu districts, located in the northern part of Hangzhou.
3. Xihu District (Xīhú Qū): Famous for the West Lake, a UNESCO World Heritage site, it boasts rich natural and cultural landscapes.
4. Binjiang District (Bīnjiāng Qū): Situated on the south bank of the Qiantang River, it is a hub for high-tech industries.
5. Xiaoshan District (Xiāoshān Qū): Located in the eastern part of Hangzhou, it is one of China's major manufacturing bases.
6. Yuhang District (Yúháng Qū): Once home to Linping, one of China's four famous ancient towns, it has now become a key economic development zone in Hangzhou.
7. Fuyang District (Fùyáng Qū): Located in the southwest of Hangzhou, named after the Fuchun River that flows through it.
8. Lin'an District (Lín'ān Qū): Situated in the mountainous area west of Hangzhou, it is known for its beautiful natural scenery.
9. Qiantang District (Qiántáng Qū): Established in 2021 from the former Dajiangdong Industrial Cluster and parts of Xiaoshan District, it aims to promote development in eastern Hangzhou.
10. Linping District (Lín Píng Qū): A new administrative district separated from Yuhang, primarily covering the area of the former Linping Sub-district.
The above information reflects the situation as of my last update. Please note that administrative divisions may be adjusted, and refer to the latest official announcements for the most accurate information.

C#

Sample request
using System.Text;
class Program
{
    static async Task Main(string[] args)
    {
        //If the environment variable is not set, you can use your Model Studio API key by replacing the following line with apiKey="sk-xxx". However, hardcoding the API key directly in code is not recommended in 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 = "YOUR_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}");
            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 it has 10 municipal 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 known for its beautiful natural scenery, especially the famous West Lake located there, while Binjiang District is better known for its high-tech industries. Additionally, as the city develops, administrative divisions may be adjusted. Please refer to the latest information released by official sources."
    },
    "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 the environment variable is not set, you can use your Model Studio API key by replacing the following line with apiKey := "sk-xxx". However, hardcoding the API key directly in code is not recommended in production environments to reduce the risk of API key leakage.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "YOUR_APP_ID" // Replace with the actual application ID
	if apiKey == "" {
		fmt.Println("Please ensure that DASHSCOPE_API_KEY is set.")
		return
	}
	url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
	// Create the request body
	requestBody := map[string]interface{}{
		"input": map[string]interface{}{
			"prompt": "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
	}
	// Set the request headers
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")
	// Send the request
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Printf("Failed to send request: %v\n", err)
		return
	}
	defer resp.Body.Close()
	// Read the response
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Failed to read response: %v\n", err)
		return
	}
	// Process the response
	if resp.StatusCode == http.StatusOK {
		fmt.Println("Request successful:")
		fmt.Println(string(body))
	} else {
		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
		fmt.Println(string(body))
	}
}
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 governs 10 municipal districts, 2 county-level cities, and 1 county, as follows:
- Municipal districts (10): Shangcheng, Gongshu, Xihu, Binjiang, Xiaoshan, Yuhang, Linping, Qiantang, Fuyang, and Lin'an.
- County-level cities (2): Jiande City and Tonglu County (note that Tonglu is treated as a county-level city here, but strictly speaking it is a county).
- Counties (1): Chun'an County.
Please note that administrative divisions may change over time. Refer to the latest official announcements. The above information is compiled from recent data. For the latest changes, we recommend visiting the official government website for the most accurate information."
    },
    "usage": {
    },
    "request_id": "d3c8f368-b645-9446-bfe4-20ca51821a02"
}

Custom plugins: Steps for creating a custom plugin.

Invoke an agent application, Invoke a workflow application: How to invoke applications and more usage.

Application invocation API: The complete parameter list and invocation examples.