すべてのプロダクト
Search
ドキュメントセンター

:カスタムアプリケーションパラメーターのパススルー

最終更新日:Nov 27, 2026

Alibaba Cloud Model Studio の エージェント および ワークフロー (エージェントオーケストレーションアプリケーションに代わるアプリケーション)を呼び出す際に、主にカスタムプラグインおよびカスタムノード向けにカスタムパラメーターを渡します。

API Keyの取得と設定およびAPI Keyの環境変数への設定を完了している必要があります。SDK経由で呼び出す場合は、DashScope SDKのインストールも必要です。サンプルコード内のDASHSCOPE_API_HOSTを取得したAPI Hostに置き換えてください。

カスタムプラグインパラメーター

この記事では、寮規則照会ツールを例に、API を使用してカスタムプラグインにパラメーターを渡す方法を説明します。

注記カスタムプラグインのパラメーターは、関連付けられた エージェント または ワークフロー の プラグインノード経由で渡されます。

以下の例では、エージェント のカスタムプラグインパラメーターを渡す方法を示します。

使用方法

ステップ 1:カスタムプラグインの作成

すでにプラグインタールを作成済みまたはプラグインをインポート済みの場合は、このステップをスキップしてください。

  1. カスタムプラグインを作成します。Model Studio コンソールの プラグイン ページにアクセスし、Add Custom Plug-in をクリックします。プラグイン情報を入力します。認証が必要な場合は、認証の有効化 スイッチをオンにして設定を行います。

    プラグイン説明の例:寮規約検索ツール。入力された数値インデックスで特定のエントリを検索できます。

    プラグインURLの例:https://domitorgreement-plugin-example-icohrkdjxy.cn-beijing.fcapp.run

    認証設定の例:認証タイプとしてUser-level Authentication、場所としてHeader、Typeとしてbasicを選択します。

    注意:プラグインの説明はプラグインの用途を簡潔に記述したもので、大規模モデルが現在のタスクに対してこのプラグインを呼び出すかどうかを判断するのに役立ちます。自然言語で記述してください。

  2. ツールの作成:ツール情報を入力し、入出力パラメータを設定します。注意:

    1. ツールの説明は、大規模モデルがツールの機能と使用シナリオをよりよく理解するのに役立ちます。自然言語で記述し、可能な場合は使用例も示してください。
    2. 意味のあるパラメータ名を使用することで、大規模モデルが識別が必要なパラメータ情報を理解しやすくなります。
    3. パラメータの説明は入力パラメータの機能を説明するものです。簡潔かつ正確に記述し、大規模モデルがパラメータの取得方法をさらに理解できるようにします。
    4. 入力パラメータの受け渡し方式としては、必ずBusiness Pass-throughを選択してください。

    この例では、寮規約コンテンツのインデックスarticle_indexをビジネスパススルーパラメータとして設定します。

    ツール名にDormitory convention query toolを入力し、リクエストメソッドとしてPOST、送信方式としてapplication/jsonを選択します。入力パラメータarticle_indexのタイプをNumber、受け渡し方式をBodyに設定し、必須としてマークします。出力パラメータの名前にはarticleを、説明には"寮規約コンテンツ"を入力し、タイプをStringに設定します。

  3. Test Toolをクリックし、実行が成功したらプラグインを公開します。

Step 2: 指定したプラグインをエージェントアプリケーションに関連付ける

プラグインツールは、同一ビジネススペース内のエージェントアプリケーションにのみ関連付けることができます。

  1. 公開済みプラグインのカードでAdd to Agentをクリックし、関連付けるエージェントアプリケーションを選択します;
  2. アプリケーション内の+ Plug-inをクリックして、指定したカスタムプラグインを関連付けることもできます;
  3. その後、アプリケーションをそのまま公開します。

Step 3: API呼び出し

  • 認証が不要な場合:API経由でカスタムプラグインを呼び出し、biz_paramsのuser_defined_paramsを使用してカスタムプラグインの情報を渡します。your_plugin_codeを実際のプラグインIDに置き換え、プラグインで設定した入力パラメータのキーと値のペアを渡してください。

    プラグインIDはプラグインのカードから取得できます。

    この例では、値2をarticle_indexパラメータ(寮規約インデックス)として渡して2番目の寮規約を検索し、正しい結果が返されます。

    Python

    リクエストサンプル
    import os
    import dashscope
    # dashscope 2.0.1 or later is required.
    from dashscope import DashScopeError
    
    # The following is the configuration for the Singapore (ap-southeast-1) region. The region value varies by region.
    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". We recommend using an environment variable in production to avoid leaking your API key.
            api_key=os.getenv("DASHSCOPE_API_KEY"),
            region="ap-southeast-1")
    biz_params = {
        # Pass the input parameters for the agent application's custom plugin. Replace `your_plugin_code` with your plugin ID.
        "user_defined_params": {
            "your_plugin_code": {
                "article_index": 2}}}
    try:
        response = client.apps.completions.create(
                app_id='YOUR_APP_ID',
                prompt='寝室公约内容',
                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'See the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
    
    応答サンプル
    寝室公约的第二条规定如下:
    
    "寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。"
    
    这表明在寝室内,成员之间应该培养一种积极正面的生活和学习氛围,彼此帮助和支持,同时也要学会理解和尊重他人。如果您需要了解公约的其他条款,请告诉我!
    

    Java

    リクエストサンプル
    import com.alibaba.dashscope.app.*;
    import com.alibaba.dashscope.exception.ApiException;
    import com.alibaba.dashscope.exception.InputRequiredException;
    import com.alibaba.dashscope.exception.NoApiKeyException;
    import com.alibaba.dashscope.utils.JsonUtils;
    import com.alibaba.dashscope.utils.Constants;
    
    public class Main {
      static {
            Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
        }
        public static void appCall() throws NoApiKeyException, InputRequiredException {
            String bizParams =
                    // Pass the input parameters for the agent application's custom plugin. Replace `{your_plugin_code}` with your plugin ID.
                    "{\"user_defined_params\":{\"{your_plugin_code}\":{\"article_index\":2}}}";
            ApplicationParam param = ApplicationParam.builder()
                    // If you have not configured an environment variable, replace the following line with .apiKey("sk-xxx") using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .appId("YOUR_APP_ID")
                    .prompt("寝室公约内容")
                    .bizParams(JsonUtils.parse(bizParams))
                    .build();
    
            Application application = new Application();
            ApplicationResult result = application.call(param);
            System.out.printf("%s\n",
                    result.getOutput().getText());
        }
    
        public static void main(String[] args) {
            try {
                appCall();
            } catch (ApiException | NoApiKeyException | InputRequiredException e) {
                System.out.printf("Exception: %s", e.getMessage());
                System.out.println("请参考文档:https://www.alibabacloud.com/help/model-studio/developer-reference/error-code");
            }
            System.exit(0);
        }
    }
    
    応答サンプル
    寝室公约的第二条规定如下:
    
    第二条 寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。
    
    这强调了在共同生活环境中,室友之间应该保持积极正面的关系,通过相互帮助和支持来营造一个和谐的生活和学习氛围。如果有更多具体的条款需要了解,请告知我。
    

    HTTP

    curl

    リクエストサンプル
    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": "寝室公约内容",
            "biz_params":
            {
                "user_defined_params":
                {
                    "{your_plugin_code}":
                        {
                        "article_index": 2
                        }
                }
            }
        },
        "parameters":  {},
        "debug":{}
    }'
    

    YOUR_APP_ID は実際のアプリケーション ID に置き換えてください。

    応答サンプル
    {"output":
    {"finish_reason":"stop",
    "session_id":"e151267ffded4fbdb13d91439011d31e",
    "text":"寝室公约的第二条内容是:“寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。”这意呀着在寝室生活中,大家要彼此支持,共同创造一个和谐、积极向上的生活环境。"},
    "usage":{"models":[{"output_tokens":94,"model_id":"qwen-max","input_tokens":453}]},
    "request_id":"a39fd2b5-7e2c-983e-84a1-1039f726f18a"}%
    

    PHP

    リクエストサンプル
    <?php
    
    # 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
    $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 your plugin ID.
    // Construct request data
    $data = [
        "input" => [
            'prompt' => '寝室公约内容',
            'biz_params' => [
            'user_defined_params' => [
                '{your_plugin_code}' => [
                    'article_index' => 2
                    ]
                ]
            ]
        ],
    ];
    // Encode data as JSON
    $dataString = json_encode($data);
    
    // Check if json_encode was successful
    if (json_last_error() !== JSON_ERROR_NONE) {
        die("JSON encoding failed with error: " . json_last_error_msg());
    }
    
    // Initialize the cURL session
    $ch = curl_init($url);
    
    // Set cURL options
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $api_key
    ]);
    
    // Execute the request
    $response = curl_exec($ch);
    
    // Check whether cURL succeeded
    if ($response === false) {
        die("cURL Error: " . curl_error($ch));
    }
    
    // Get HTTP status code
    $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    // Close the cURL session
    curl_close($ch);
    // Decode response data
    $response_data = json_decode($response, true);
    // Handle response
    if ($status_code == 200) {
        if (isset($response_data['output']['text'])) {
            echo "{$response_data['output']['text']}\n";
        } else {
            echo "No text in response.\n";
        }
    }else {
        if (isset($response_data['request_id'])) {
            echo "request_id={$response_data['request_id']}\n";}
        echo "code={$status_code}\n";
        if (isset($response_data['message'])) {
            echo "message={$response_data['message']}\n";}
        else {
            echo "message=Unknown error\n";}
    }
    ?>
    
    応答サンプル
    寝室公约的第二条规定:寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。这是为了保证大家能在一个和谐友爱的环境中生活和学习。如果有更多具体的条款需要了解,或者有其他问题,随时可以问我!
    

    Node.js

    必要な依存関係のインストール:
    npm install axios
    
    リクエストサンプル
    const axios = require('axios');
    
    async function callDashScope() {
        // If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
        const apiKey = process.env.DASHSCOPE_API_KEY;
        const appId = '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: "寝室公约内容",
                biz_params: {
                    user_defined_params: {
                        [pluginCode]: {
                            // article_index is a variable for the custom plug-in, replace with the actual plug-in variable
                            'article_index': 3
                        }
                    }
                }
            },
            parameters: {},
            debug: {}
        };
    
        try {
            console.log("Sending request to DashScope API...");
    
            const response = await axios.post(url, data, {
                headers: {
                    'Authorization': `Bearer ${apiKey}`,
                    'Content-Type': 'application/json'
                }
            });
    
            if (response.status === 200) {
                if (response.data.output && response.data.output.text) {
                    console.log(`${response.data.output.text}`);
                }
            } else {
                console.log("Request failed:");
                if (response.data.request_id) {
                    console.log(`request_id=${response.data.request_id}`);
                }
                console.log(`code=${response.status}`);
                if (response.data.message) {
                    console.log(`message=${response.data.message}`);
                } else {
                    console.log('message=Unknown error');
                }
            }
        } catch (error) {
            console.error(`Error calling DashScope: ${error.message}`);
            if (error.response) {
                console.error(`Response status: ${error.response.status}`);
                console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
            }
        }
    }
    callDashScope();
    
    応答サンプル
    寝室公约的第三条规定如下:
    
    注意安全用电,杜绝火灾隐患。寝室内严禁使用明火、违规电器、各种灶具以及其他违规物品,不得存放易爆、易燃物品,私接电源。
    
    如果您需要了解更多的规定,请告诉我。
    

    C#

    リクエストサンプル
    using System.Text;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            // If you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
            string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
            string appId = "YOUR_APP_ID";// Replace with the actual application ID
    
            if (string.IsNullOrEmpty(apiKey))
            {
                Console.WriteLine("请确保设置了 DASHSCOPE_API_KEY。");
                return;
            }
    
            string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
    
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
                string pluginCode = "{your_plugin_code}"; // Replace `{your_plugin_code}` with your plugin ID.
                string jsonContent = $@"{{
                    ""input"": {{
                        ""prompt"": ""寝室公约内容"",
                        ""biz_params"": {{
                            ""user_defined_params"": {{
                                ""{pluginCode}"": {{
                                    ""article_index"": 2
                                }}
                            }}
                        }}
                    }},
                    ""parameters"": {{}},
                    ""debug"": {{}}
                }}";
    
                HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
    
                try
                {
                    HttpResponseMessage response = await client.PostAsync(url, content);
    
                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine("Request successful:");
                        Console.WriteLine(responseBody);
                    }
                    else
                    {
                        Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine(responseBody);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error calling DashScope: {ex.Message}");
                }
            }
        }
    }
    
    応答サンプル
    {
        "output": {
            "finish_reason": "stop",
            "session_id": "237ca6187c814f3b9e7461090a5f8b74",
            "text": "寝室公约的第二条规定如下:
    
    "寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。"
    
    这表示在寝室内,成员之间需要建立起一种积极正面的关系,通过帮助、关心和支持彼此来营造一个和谐的生活和学习环境。同时也要学会理解和接受室友之间的差异,以真诚的态度去交流沟通。如果还有其他条款或具体内容想要了解,请告诉我!"
        },
        "usage": {
            "models": [
                {
                    "output_tokens": 133,
                    "model_id": "qwen-max",
                    "input_tokens": 829
                }
            ]
        },
        "request_id": "64e8c359-d071-9d2e-bb94-187e86cc3a79"
    }
    

    Go

    リクエストサンプル
    package main
    
    import (
      "bytes"
      "encoding/json"
      "fmt"
      "io"
      "net/http"
      "os"
    )
    
    func main() {
      // If you have not configured an environment variable, replace the following line with apiKey := "sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
      apiKey := os.Getenv("DASHSCOPE_API_KEY")
      appId := "YOUR_APP_ID"           // Replace with the actual application ID
      pluginCode := "YOUR_PLUGIN_CODE" // Replace with the actual plug-in ID
    
      if apiKey == "" {
          fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
          return
      }
    
      url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
    
      // Create request body
      requestBody := map[string]interface{}{
          "input": map[string]interface{}{
              "prompt": "寝室公约内容",
              "biz_params": map[string]interface{}{
                  "user_defined_params": map[string]interface{}{
                      pluginCode: map[string]interface{}{
                          "article_index": 2,
                      },
                  },
              },
          },
          "parameters": map[string]interface{}{},
          "debug":      map[string]interface{}{},
      }
    
      jsonData, err := json.Marshal(requestBody)
      if err != nil {
          fmt.Printf("Failed to marshal JSON: %v\n", err)
          return
      }
    
      // Create HTTP POST request
      req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
      if err != nil {
          fmt.Printf("Failed to create request: %v\n", err)
          return
      }
    
      // Set request headers
      req.Header.Set("Authorization", "Bearer "+apiKey)
      req.Header.Set("Content-Type", "application/json")
    
      // Send request
      client := &http.Client{}
      resp, err := client.Do(req)
      if err != nil {
          fmt.Printf("Failed to send request: %v\n", err)
          return
      }
      defer resp.Body.Close()
    
      // Read response
      body, err := io.ReadAll(resp.Body)
      if err != nil {
          fmt.Printf("Failed to read response: %v\n", err)
          return
      }
    
      // Handle response
      if resp.StatusCode == http.StatusOK {
          fmt.Println("Request successful:")
          fmt.Println(string(body))
      } else {
          fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
          fmt.Println(string(body))
      }
    }
    
    応答サンプル
    {
        "output": {
            "finish_reason": "stop",
            "session_id": "860d2a4c1f3649ac880298537993cb51",
            "text": "寝室公约的第二条规定如下:
    
    寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。
    
    这强调了在宿舍生活中,室友之间应该保持良好的互助关系,同时也要互相尊重对方。您想要了解其他条款的内容吗?"
        },
        "usage": {
            "models": [
                {
                    "output_tokens": 84,
                    "model_id": "qwen-max",
                    "input_tokens": 876
                }
            ]
        },
        "request_id": "0a250055-90a4-992d-9276-e268ad35d1ab"
    }
    
  • 認証が必要な場合:このシナリオでは、認証 が有効化され、ユーザレベル認証 が設定されたカスタムプラグインを呼び出す方法を説明します。

    プラグイン ID はプラグインカード上で確認できます。

    • biz_params フィールドの user_defined_params を使用してカスタムプラグイン情報を渡します。your_plugin_code はご利用のプラグイン ID に置き換え、入力パラメーターをキーと値のペアで指定します。
    • biz_params フィールドの user_defined_tokens を使用して認証情報を渡します。your_plugin_code はご利用のプラグイン ID に置き換え、user_token の値を認証トークン(例:DashScope API キー)に設定します。
    • 認証が成功すると、サービスは提供されたインデックスパラメーターに基づいて指定された項目を照会し、正しい結果を返します。

    この例では、article_index パラメーターに 2 を設定し、user_token の値である YOUR_TOKEN を実際の DASHSCOPE_API_KEY に置き換えます。認証が成功すると、2 番目の寮規則の内容が照会され、正しい結果が返されます。

    Python

    リクエストサンプル
    import os
    import dashscope
    # dashscope 2.0.1 or later is required.
    from dashscope import DashScopeError
    
    # The following is the configuration for the Singapore (ap-southeast-1) region. The region value varies by region.
    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". We recommend using an environment variable in production to avoid leaking your API key.
            api_key=os.getenv("DASHSCOPE_API_KEY"),
            region="ap-southeast-1")
    biz_params = {
        # Pass the authentication information for the agent application's custom plugin. Replace `your_plugin_code` with your plugin ID and replace `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='寝室公约内容',
                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'See the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
    
    応答サンプル
    寝室公约的第二条规定如下:
    
    寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。
    
    如果您需要了解更多的规定内容,请告诉我。
    

    Java

    リクエストサンプル
    import com.alibaba.dashscope.app.*;
    import com.alibaba.dashscope.exception.ApiException;
    import com.alibaba.dashscope.exception.InputRequiredException;
    import com.alibaba.dashscope.exception.NoApiKeyException;
    import com.alibaba.dashscope.utils.JsonUtils;
    import com.alibaba.dashscope.utils.Constants;
    
    public class Main {
      static {
            Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
        }
        public static void appCall() throws NoApiKeyException, InputRequiredException {
            String bizParams =
                    // Replace {your_plugin_code} with your plugin ID, and YOUR_TOKEN with your 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 you have not configured an environment variable, replace the following line with .apiKey("sk-xxx") using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .appId("YOUR_APP_ID")
                    .prompt("寝室公约内容")
                    .bizParams(JsonUtils.parse(bizParams))
                    .build();
    
            Application application = new Application();
            ApplicationResult result = application.call(param);
            System.out.printf("%s\n",
                    result.getOutput().getText());
        }
        public static void main(String[] args) {
            try {
                appCall();
            } catch (ApiException | NoApiKeyException | InputRequiredException e) {
                System.out.printf("Exception: %s", e.getMessage());
                System.out.println("请参考文档:https://www.alibabacloud.com/help/model-studio/developer-reference/error-code");
            }
            System.exit(0);
        }
    }
    
    応答サンプル
    寝室公约的第二条规定如下:
    
    寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。
    
    如果您需要查询更多的规定内容,请告诉我。
    

    YOUR_APP_ID はご利用のアプリケーション ID に、your_plugin_code はカスタムプラグイン ID に、YOUR_TOKEN は認証トークンに置き換えてください。

    HTTP

    curl

    リクエストサンプル
    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": "寝室公约内容",
            "biz_params":
            {
                "user_defined_params":
                {
                    "{your_plugin_code}":
                        {
                        "article_index": 2
                        }
                },
                "user_defined_tokens":
                {
                    "{your_plugin_code}":
                        {
                        "user_token": "YOUR_TOKEN"
                        }
                }
            }
        },
        "parameters":  {},
        "debug":{}
    }'
    

    YOUR_APP_ID はご利用のアプリケーション ID に、{your_plugin_code} はカスタムプラグイン ID に、YOUR_TOKEN は認証トークンに置き換えてください。

    応答サンプル
    {"output":{"finish_reason":"stop",
    "session_id":"d3b5c3e269dc40479255a7a02df5c630",
    "text":"寝室公约的第二条内容为:“寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。”这强调了寝室生活中成员之间和谐相处与共同进步的重要性。"},
    "usage":{"models":[{"output_tokens":80,"model_id":"qwen-max","input_tokens":432}]},
    "request_id":"1f77154c-edc3-9003-b622-816fa2f849cf"}%
    

    PHP

    リクエストサンプル
    <?php
    
    # 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
    $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' => '寝室公约内容',
            'biz_params' => [
            'user_defined_params' => [
                '{your_plugin_code}' => [//Replace {your_plugin_code} with your plugin ID.
                    'article_index' => 2
                    ]
                ],
            'user_defined_tokens' => [
                '{your_plugin_code}' => [//Replace {your_plugin_code} with your plugin ID.
                    'user_token' => 'YOUR_TOKEN'//Replace with the actual Token, such as API key
                ]
            ]
            ]
        ],
    ];
    // Encode data as JSON
    $dataString = json_encode($data);
    
    // Check if json_encode was successful
    if (json_last_error() !== JSON_ERROR_NONE) {
        die("JSON encoding failed with error: " . json_last_error_msg());
    }
    
    // Initialize the cURL session
    $ch = curl_init($url);
    
    // Set cURL options
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $api_key
    ]);
    
    // Execute the request
    $response = curl_exec($ch);
    
    // Check whether cURL succeeded
    if ($response === false) {
        die("cURL Error: " . curl_error($ch));
    }
    
    // Get HTTP status code
    $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    // Close the cURL session
    curl_close($ch);
    // Decode response data
    $response_data = json_decode($response, true);
    // Handle response
    if ($status_code == 200) {
        if (isset($response_data['output']['text'])) {
            echo "{$response_data['output']['text']}\n";
        } else {
            echo "No text in response.\n";
        }
    }else {
        if (isset($response_data['request_id'])) {
            echo "request_id={$response_data['request_id']}\n";}
        echo "code={$status_code}\n";
        if (isset($response_data['message'])) {
            echo "message={$response_data['message']}\n";}
        else {
            echo "message=Unknown error\n";}
    }
    ?>
    
    応答サンプル
    寝室公约的第二条规定如下:
    
    > 寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。
    
    如果需要了解更多的公约内容或其他信息,请随时告诉我!
    

    Node.js

    必要な依存関係のインストール:
    npm install axios
    
    リクエストサンプル
    const axios = require('axios');
    async function callDashScope() {
        // If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
        const apiKey = process.env.DASHSCOPE_API_KEY;
        const appId = '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: "寝室公约内容",
                biz_params: {
                    user_defined_params: {
                        [pluginCode]: {
                            // article_index is a variable for the custom plug-in, replace with the actual plug-in variable
                            'article_index': 6
                        }
                    },
                    user_defined_tokens: {
                        [pluginCode]: {
                            // Replace YOUR_TOKEN with the actual authentication information, such as 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();
    
    応答サンプル
    寝室公约的第六条规定:养成良好的作息习惯,每一位寝室成员都享有休息的权利和承担保证他人休息权利和义务。如果你需要了解更多的规定内容,请进一步说明。
    

    C#

    リクエストサンプル
    using System.Text;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            // If you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
            string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
            string appId = "YOUR_APP_ID";// Replace with the actual application ID
    
            if (string.IsNullOrEmpty(apiKey))
            {
                Console.WriteLine("请确保设置了 DASHSCOPE_API_KEY。");
                return;
            }
    
            string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
    
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
                string pluginCode = "your_plugin_code"; // Replace your_plugin_code with your plugin ID.
                // Replace YOUR_TOKEN with the actual Token, such as API key
                string jsonContent = $@"{{
                    ""input"": {{
                        ""prompt"": ""寝室公约内容"",
                        ""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}");
                }
            }
        }
    }
    
    応答サンプル
    {
        "output": {
            "finish_reason": "stop",
            "session_id": "1a1913a9922a401f8eba36df8ea1a062",
            "text": "寝室公约的第二条规定如下:
    
    寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。
    
    如需了解更详细的公约内容,请进一步指明。"
        },
        "usage": {
            "models": [
                {
                    "output_tokens": 66,
                    "model_id": "qwen-max",
                    "input_tokens": 802
                }
            ]
        },
        "request_id": "04bac806-c5e6-9fab-a846-a66641862be9"
    }
    

    Go

    リクエストサンプル
    package main
    
    import (
      "bytes"
      "encoding/json"
      "fmt"
      "io"
      "net/http"
      "os"
    )
    
    func main() {
      // If you have not configured an environment variable, replace the following line with apiKey := "sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
      apiKey := os.Getenv("DASHSCOPE_API_KEY")
      appId := "YOUR_APP_ID"           // Replace with the actual application ID
      pluginCode := "YOUR_PLUGIN_CODE" // Replace with the actual plug-in ID
    
      if apiKey == "" {
          fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
          return
      }
    
      url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
    
      // Create request body
      requestBody := map[string]interface{}{
          "input": map[string]interface{}{
              "prompt": "寝室公约内容",
              "biz_params": map[string]interface{}{
                  "user_defined_params": map[string]interface{}{
                      pluginCode: map[string]interface{}{
                          "article_index": 10,
                      },
                  },
                  "user_defined_tokens": map[string]interface{}{
                      pluginCode: map[string]interface{}{
                          "user_token": "YOUR_USER_TOKEN", // Replace with the actual authentication token, such as 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 HTTP POST request
      req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
      if err != nil {
          fmt.Printf("Failed to create request: %v\n", err)
          return
      }
    
      // Set request headers
      req.Header.Set("Authorization", "Bearer "+apiKey)
      req.Header.Set("Content-Type", "application/json")
    
      // Send request
      client := &http.Client{}
      resp, err := client.Do(req)
      if err != nil {
          fmt.Printf("Failed to send request: %v\n", err)
          return
      }
      defer resp.Body.Close()
    
      // Read response
      body, err := io.ReadAll(resp.Body)
      if err != nil {
          fmt.Printf("Failed to read response: %v\n", err)
          return
      }
    
      // Handle response
      if resp.StatusCode == http.StatusOK {
          fmt.Println("Request successful:")
          fmt.Println(string(body))
      } else {
          fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
          fmt.Println(string(body))
      }
    }
    
    応答サンプル
    {
        "output": {
            "finish_reason": "stop",
            "session_id": "b8e051ba7e954ff8919208e7b84430fa",
            "text": "寝室公约的第十条规定,寝室成员应共同努力,营造和维护内务整洁干净、美观、高文化品味的寝室环境。如果需要了解完整的寝室公约内容,可能还需要查看其他条款或直接咨询宿舍管理部门。对于更多具体内容,您还有想要了解的部分吗?"
        },
        "usage": {
            "models": [
                {
                    "output_tokens": 70,
                    "model_id": "qwen-max",
                    "input_tokens": 855
                }
            ]
        },
        "request_id": "0921ee34-2754-9616-a826-cea33a0e0a14"
    }
    

カスタムノードパラメーターの渡し方

このトピックでは、都市名による行政区画の照会の例を用いて、API 呼び出しを通じてアプリケーションにカスタムノードパラメーターを渡す方法を説明します。

注記アプリケーションのカスタムノードパラメーターは、ワークフロー の開始ノードを通じて渡されます。

以下の例では、ワークフロー の開始ノードにカスタムパラメーターを渡す方法を示します。

使用方法

ステップ 1:カスタムノードパラメーターの設定

Workflows で対象アプリを開きます。Start ノードで String 型の変数 city を追加します。プロンプトに city と query を挿入し、アプリを公開します。

ステップ 2:API 呼び出し

呼び出し時には、biz_paramsフィールドでcityを渡し、promptフィールドでqueryを渡します。

Python

リクエストサンプル
import os
import dashscope
from dashscope import DashScopeError

# The following is the configuration for the Singapore (ap-southeast-1) region. The region value varies by region.
client = dashscope.Client(
    # If you have not configured an environment variable, you can use your Model Studio API key by replacing the following line with: api_key="sk-xxx".
    # We recommend that you do not hardcode the API key in your code in a production environment to reduce the risk of API key leaks.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    region="ap-southeast-1")
# Pass custom parameters for a workflow application.
biz_params = {"city": "杭州"}
try:
    response = client.apps.completions.create(
        app_id='YOUR_APP_ID',  # Replace with your actual application ID.
        prompt='查询这个城市的行政区域划分',
        biz_params=biz_params  # Pass 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'See the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
応答サンプル
杭州市,作为浙江省的省会城市,其行政区域划分包括10个市辖区:上城区、拱墅区、西湖区、滨江区、萧山区、余杭区、临平区、钱塘区、富阳区、临安区。每个区都有其独特的特色和发展重点。

- 上城区:位于杭州市中心地带,是杭州的政治、经济、文化中心之一。
- 拱墅区:以运河文化为特色,拥有众多历史文化遗产。
- 西湖区:著名的西湖风景区就位于此区,是旅游观光的重要目的地。
- 滨江区:高新技术产业聚集地,阿里巴巴等知名企业坐落于此。
- 萧山区:东南部的一个行政区,经济发展迅速,特别是制造业方面。
- 余杭区:近年来发展快速,尤其是互联网经济领域,阿里巴巴总部也设在这里(注:阿里巴巴总部实际位于滨江区)。
- 临平区:新成立的行政区,旨在促进该地区经济社会全面发展。
- 钱塘区:同样是一个较新的行政区划调整结果,强调创新发展和生态保护相结合。
- 富阳区:位于杭州西南方向,以其丰富的自然景观和悠久的历史文化著称。
- 临安区:地处杭州西部,以生态优美闻名,并且有着深厚的文化底蕴。

请注意,随着时间推移,具体的城市规划可能会有所变化,请参考最新的官方信息。

Java

リクエストサンプル
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 Main {
  static {
        Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
    }
    public static void appCall() throws NoApiKeyException, InputRequiredException {

        String bizParams =
                "{\"city\":\"杭州\"}";
        ApplicationParam param = ApplicationParam.builder()
                // If you have not configured an environment variable, replace the following line with .apiKey("sk-xxx") using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("YOUR_APP_ID")
                .prompt("查询这个城市的行政区域划分")
                .bizParams(JsonUtils.parse(bizParams))
                .build();

        Application application = new Application();
        ApplicationResult result = application.call(param);
        System.out.printf("%s\n",
                result.getOutput().getText());
    }

    public static void main(String[] args) {
        try {
            appCall();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.printf("Exception: %s", e.getMessage());
            System.out.println("请参考文档:https://www.alibabacloud.com/help/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}
応答サンプル
杭州市是浙江省的省会城市,其行政区域划分主要包括10个市辖区:上城区、拱墅区、西湖区、滨江区、萧山区、余杭区、临平区、钱塘区、富阳区、临安区。每个区都有自己的特色和发展重点。

- 上城区:位于杭州市中心,拥有许多历史文化遗产。
- 拱墅区:以大运河文化而闻名,同时也是一个重要的商业和居住区。
- 西湖区:以其美丽的自然风光著称,包括著名的西湖风景区。
- 滨江区:高新技术产业集聚地,杭州国家高新技术产业开发区就设在这里。
- 萧山区:经济发展迅速,尤其在制造业方面表现突出。
- 余杭区:近年来随着阿里巴巴等高科技企业的发展而快速崛起。
- 临平区:2021年由原余杭区部分区域调整而来,注重生态建设和科技创新。
- 钱塘区:同样是在2021年成立的新区,定位为杭州东部交通枢纽及产业发展新高地。
- 富阳区:历史悠久的文化名城,也是造纸业的重要基地之一。
- 临安区:位于杭州西部,森林覆盖率高,生态环境良好。

这些区域共同构成了杭州市独特的地理格局和社会经济结构。如果你对某个特定区域感兴趣或需要更详细的信息,请告诉我!

HTTP

curl

リクエストサンプル
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": "查询这个城市的行政区域划分",
        "biz_params": {
        "city": "杭州"}
    },
    "parameters":  {}
}'

YOUR_APP_ID は実際のアプリケーション ID に置き換えてください。

応答サンプル
{"output":{"finish_reason":"stop","session_id":"c211219896004b50a1f6f66f2ec5413e",
"text":"杭州市下辖10个区、1个县,代管2个县级市,分别为:
上城区、拱墅区、西湖区、滨江区、萧山区、余杭区、临平区、钱塘区、富阳区、临安区、桐庐县、淳安县、建德市、诸暨市。
注意,诸暨市由浙江省直辖、杭州市与绍兴市共同管理。"},"usage":{},
"request_id":"02c3c9e1-7912-9505-91aa-248d04fb1f5d"}

PHP

リクエストサンプル
<?php

# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$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' => '查询这个城市的行政区域划分',
        'biz_params' => [
            'city' => '杭州'
        ]
    ],
];
// Encode data as JSON
$dataString = json_encode($data);

// Check if json_encode was successful
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// Initialize the cURL session
$ch = curl_init($url);

// Set cURL options
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $api_key
]);

// Execute the request
$response = curl_exec($ch);

// Check whether cURL succeeded
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}

// Get HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL session
curl_close($ch);
// Decode response data
$response_data = json_decode($response, true);
// Handle response
if ($status_code == 200) {
    if (isset($response_data['output']['text'])) {
        echo "{$response_data['output']['text']}\n";
    } else {
        echo "No text in response.\n";
    }
} else {
    if (isset($response_data['request_id'])) {
        echo "request_id={$response_data['request_id']}\n";
    }
    echo "code={$status_code}\n";
    if (isset($response_data['message'])) {
        echo "message={$response_data['message']}\n";
    } else {
        echo "message=Unknown error\n";
    }
}
応答サンプル
杭州市是浙江省的省会城市,其行政区域划分主要包括10个市辖区:上城区、拱墅区、西湖区、滨江区、萧山区、余杭区、临平区、钱塘区、富阳区、临安区。

每个区都有自己的特色和发展重点,比如:
- **上城区**和**拱墅区**位于杭州市中心,商业繁华,历史悠久。
- **西湖区**以美丽的西湖而闻名,同时也是一个重要的科教文化区。
- **滨江区**则以其高新技术产业发展著称。
- **萧山区**、**余杭区**等则是近年来随着城市发展迅速崛起的新城区或经济开发区。
- **临安区**、**富阳区**等地则更多保留了自然风光与乡村风貌。

请注意,中国的行政区划可能会根据国家政策调整有所变化,请通过官方渠道获取最新信息。

Node.js

必要な依存関係のインストール:
npm install axios
リクエストサンプル
const axios = require('axios');

async function callDashScope() {
    // If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = '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: "查询这个城市的行政区域划分",
            biz_params: {
                'city': '杭州',
            },
        },
        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();
応答サンプル
杭州市是浙江省的省会,其行政区域划分包括10个市辖区。具体如下:

1. 上城区(Shàngchéng Qū):位于杭州市中心偏南,是杭州历史最悠久、文化底蕴最深厚的区域之一。
2. 拱墅区(Gǒngshù Qū):原为下城区和拱墅区合并而成的新区,位于杭州市北部。
3. 西湖区(Xīhú Qū):以世界文化遗产西湖而闻名,拥有丰富的自然与人文景观。
4. 滨江区(Bīnjiāng Qū):地处钱塘江南岸,是一个高新技术产业集聚地。
5. 萧山区(Xiāoshān Qū):位于杭州市东部,是中国重要的制造业基地之一。
6. 余杭区(Yúháng Qū):曾经是中国四大名镇之一的临平所在地,现已成为杭州重要的经济发展区。
7. 富阳区(Fùyáng Qū):位于杭州市西南部,因富春江穿流其间而得名。
8. 临安区(Lín'ān Qū):位于杭州市西部山区,以其美丽的自然风光著称。
9. 钱塘区(Qiántáng Qū):成立于2021年,由原大江东产业集聚区及部分萧山区组成,旨在促进杭州东部地区的发展。
10. 临平区(Lín Píng Qū):从余杭区分设出来的一个新行政区划,主要涵盖原余杭区内的临平街道等地。

以上信息反映了截至我最后更新时的情况,请注意行政区划可能会有所调整,请以官方发布的最新消息为准。

C#

リクエストサンプル
using System.Text;

class Program
{
    static async Task Main(string[] args)
    {
        //If you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "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"": ""查询这个城市的行政区域划分"",
                    ""biz_params"":{
                        ""city"":""杭州""
                    }
                },
                ""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}");
            }
        }
    }
}
応答サンプル
{
    "output": {
        "finish_reason": "stop",
        "session_id": "7a9ff57eec7d475fa5d487de5f5178d2",
        "text": "杭州市是浙江省的省会,它下辖有10个市辖区:上城区、拱墅区、西湖区、滨江区、萧山区、余杭区、临平区、钱塘区、富阳区和临安区。每个区都有其独特的地理位置和发展特色。例如,西湖区以美丽的自然风光著称,尤其是著名的杭州西湖就位于此;而滨江区则更多地以其高新技术产业发展闻名。此外,随着城市的发展,行政区划也可能会有所调整,请关注官方发布的最新信息。"
    },
    "usage": {

    },
    "request_id": "d2c2fcc9-f821-98c9-9430-8704a2a41225"
}

Go

リクエストサンプル
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	// If you have not configured an environment variable, replace the following line with apiKey := "sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "YOUR_APP_ID" // Replace with the actual application ID

	if apiKey == "" {
		fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
		return
	}

	url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)

	// Create request body
	requestBody := map[string]interface{}{
		"input": map[string]interface{}{
			"prompt": "查询这个城市的行政区域划分",
			"biz_params": map[string]interface{}{
				"city": "杭州",
			},
		},
		"parameters": map[string]interface{}{},
		"debug":      map[string]interface{}{},
	}

	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		fmt.Printf("Failed to marshal JSON: %v\n", err)
		return
	}

	// Create HTTP POST request
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("Failed to create request: %v\n", err)
		return
	}

	// Set request headers
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// Send request
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Printf("Failed to send request: %v\n", err)
		return
	}
	defer resp.Body.Close()

	// Read response
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Failed to read response: %v\n", err)
		return
	}

	// Handle response
	if resp.StatusCode == http.StatusOK {
		fmt.Println("Request successful:")
		fmt.Println(string(body))
	} else {
		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
		fmt.Println(string(body))
	}
}
応答サンプル
{
    "output": {
        "finish_reason": "stop",
        "session_id": "2dc3e1a9dcd248c6bb9ca92bffc3e745",
        "text": "杭州市,简称“杭”,是浙江省的省会城市。根据最新的行政区划调整,杭州市现辖10个市辖区、2个县级市和1个县,具体如下:

- 市辖区(10个):上城区、拱墅区、西湖区、滨江区、萧山区、余杭区、临平区、钱塘区、富阳区、临安区。
- 县级市(2个):建德市、桐庐县(注意这里的桐庐实际上被列为县级市处理,但准确地说它是一个县)。
- 县(1个):淳安县。

请注意,随着时间的变化,行政区域可能会有所调整,请以官方最新发布的消息为准。上述信息基于较新的资料整理而来,对于最新的变动情况,建议访问政府官方网站获取最准确的信息。"
    },
    "usage": {

    },
    "request_id": "d3c8f368-b645-9446-bfe4-20ca51821a02"
}

関連ドキュメント

カスタムプラグイン:カスタムプラグインの作成方法について学習します。

アプリケーションの呼び出し:アプリケーションの呼び出し方法とその他のユースケースについて学習します。

アプリケーション呼び出し API:完全なパラメーターリストと呼び出し例を参照します。