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

Alibaba Cloud Model Studio:アプリケーション向け DashScope API リファレンス

最終更新日:Apr 29, 2026

本トピックでは、DashScope API を使用して Alibaba Cloud Model Studio アプリケーション(エージェントワークフロー)を呼び出す際の入力パラメーターおよび出力パラメーターについて説明し、一般的なシナリオにおける呼び出しの例を提供します。

重要

このトピックは国際エディション(シンガポールリージョン)にのみ適用されます。

関連ガイド

詳細については、「アプリケーションの呼び出し」をご参照ください。

前提条件

作業を開始する前に、以下のタスクを完了してください。

  1. アプリケーションの作成: アプリケーション管理 にアクセスして Alibaba Cloud Model Studio アプリケーション を作成し、アプリケーション ID を取得します。

  2. API キーの取得: キー管理 から API キーを取得し、API キーを環境変数として設定します。

  3. SDK のインストール (任意): SDK を使用して呼び出しを行う場合は、お使いのプログラミング言語用の DashScope SDK をインストールします。

呼び出し方法

  • HTTP API 呼び出し

    リクエスト URL: POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion

    APP_ID は実際のアプリケーション ID に置き換えてください。
  • SDK 呼び出し

    Python/Java SDK: 正しいエンドポイントがデフォルトで設定されています。

    カスタムエンドポイント: base_url パラメーターを使用して設定します。

リクエストボディ

シングルターン対話

Python

リクエスト例

import os
from http import HTTPStatus
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
response = Application.call(
    # 環境変数を設定していない場合、次の行を api_key="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    app_id='APP_ID',# 実際のアプリケーション ID に置き換えてください
    prompt='Who are you?')

if response.status_code != HTTPStatus.OK:
    print(f'request_id={response.request_id}')
    print(f'code={response.status_code}')
    print(f'message={response.message}')
    print(f'See documentation: https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code')
else:
    print(response.output.text)

Java

リクエスト例

// DashScope SDK バージョン >= 2.12.0 を推奨します
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
    static {
      Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
    }
    public static void appCall()
            throws ApiException, NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                // 環境変数を設定していない場合、次の行を .apiKey("sk-xxx") に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("APP_ID")
                .prompt("Who are you?")
                .build();

        Application application = new Application();
        ApplicationResult result = application.call(param);

        System.out.printf("text: %s\n",
                result.getOutput().getText());
    }

    public static void main(String[] args) {
        try {
            appCall();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.err.println("message: "+e.getMessage());
            System.out.println("See documentation: https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

HTTP

curl

リクエスト例

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "Who are you?"
    },
    "parameters":  {},
    "debug": {}
}' 
APP_ID は実際のアプリケーション ID に置き換えてください。

PHP

リクエスト例

<?php

# 環境変数を設定していない場合、次の行を $api_key="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // 実際のアプリケーション ID に置き換えてください

$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";

// リクエストデータを構築
$data = [
    "input" => [
        'prompt' => 'Who are you?'
    ]
];

// データを JSON としてエンコード
$dataString = json_encode($data);

// json_encode が成功したか確認
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// cURL セッションを初期化
$ch = curl_init($url);

// cURL オプションを設定
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
]);

// リクエストを実行
$response = curl_exec($ch);

// cURL 実行が成功したか確認
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}

// HTTP ステータスコードを取得
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// cURL セッションを閉じる
curl_close($ch);
// レスポンスデータをデコード
$response_data = json_decode($response, true);
// レスポンスを処理
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() {
    // 環境変数を設定していない場合、次の行を apiKey='sk-xxx' に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// 実際のアプリケーション ID に置き換えてください

    const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;

    const data = {
        input: {
            prompt: "Who are you?"
        },
        parameters: {},
        debug: {}
    };

    try {
        const response = await axios.post(url, data, {
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        });

        if (response.status === 200) {
            console.log(`${response.data.output.text}`);
        } else {
            console.log(`request_id=${response.headers['request_id']}`);
            console.log(`code=${response.status}`);
            console.log(`message=${response.data.message}`);
        }
    } catch (error) {
        console.error(`Error calling DashScope: ${error.message}`);
        if (error.response) {
            console.error(`Response status: ${error.response.status}`);
            console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
        }
    }
}

callDashScope();

C#

リクエスト例

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        //環境変数を設定していない場合、次の行を apiKey="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。 
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "APP_ID"; // 実際のアプリケーション ID に置き換えてください

        string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

            string jsonContent = @"{
                ""input"": {
                    ""prompt"": ""Who are you?""
                },
                ""parameters"": {},
                ""debug"": {}
            }";

            HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            try
            {
                HttpResponseMessage response = await client.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("Request successful:");
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error calling DashScope: {ex.Message}");
            }
        }
    }
}

Go

リクエスト例

package main

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

func main() {
	// 環境変数を設定していない場合、次の行を apiKey := "sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // 実際のアプリケーション ID に置き換えてください

	if apiKey == "" {
		fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
		return
	}

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

	// リクエストボディを作成
	requestBody := map[string]interface{}{
		"input": map[string]string{
			"prompt": "Who are you?",
		},
		"parameters": map[string]interface{}{},
		"debug":      map[string]interface{}{},
	}

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

	// HTTP POST リクエストを作成
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("Failed to create request: %v\n", err)
		return
	}

	// リクエストヘッダーを設定
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// リクエストを送信
	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()

	// レスポンスを読み取り
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Failed to read response: %v\n", err)
		return
	}

	// レスポンスを処理
	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))
	}
}

マルチターン対話

session_id または messages を使用してマルチターン対話を有効にします。

Python

リクエスト例

import os
from http import HTTPStatus
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

def call_with_session():
    response = Application.call(
        # 環境変数を設定していない場合、次の行を api_key="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        app_id='APP_ID',  # 実際のアプリケーション ID に置き換えてください
        prompt='Who are you?')

    if response.status_code != HTTPStatus.OK:
        print(f'request_id={response.request_id}')
        print(f'code={response.status_code}')
        print(f'message={response.message}')
        print(f'See documentation: https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code')
        return response

    responseNext = Application.call(
                # 環境変数を設定していない場合、次の行を api_key="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
                api_key=os.getenv("DASHSCOPE_API_KEY"),
                app_id='APP_ID',  # 実際のアプリケーション ID に置き換えてください
                prompt='What skills do you have?',
                session_id=response.output.session_id)  # 前回のレスポンスからの session_id

    if responseNext.status_code != HTTPStatus.OK:
        print(f'request_id={responseNext.request_id}')
        print(f'code={responseNext.status_code}')
        print(f'message={responseNext.message}')
        print(f'See documentation: https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code')
    else:
        print('%s\n session_id=%s\n' % (responseNext.output.text, responseNext.output.session_id))
        # print('%s\n' % (response.usage))

if __name__ == '__main__':
    call_with_session()

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 java.util.Arrays;
import java.util.List;
import com.alibaba.dashscope.utils.Constants;
public class Main {
    static {
      Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
    }
    public static void callWithSession()
            throws ApiException, NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                // 環境変数を設定していない場合、次の行を .apiKey("sk-xxx") に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // 実際のアプリケーション ID に置き換えてください
                .appId("APP_ID")
                .prompt("Who are you?")
                .build();

        Application application = new Application();
        ApplicationResult result = application.call(param);

        param.setSessionId(result.getOutput().getSessionId());
        param.setPrompt("What skills do you have?");
        result = application.call(param);

        System.out.printf("%s\n session_id: %s\n",
                result.getOutput().getText(), result.getOutput().getSessionId());
    }

    public static void main(String[] args) {
        try {
            callWithSession();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.printf("Exception: %s", e.getMessage());
            System.out.println("See documentation: https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

HTTP

curl

リクエスト例 (前回の会話)

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "Who are you?"
    },
    "parameters":  {},
    "debug": {}
}' 

リクエスト例 (次のターン)

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "What skills do you have?",
        "session_id":"4f8ef7233dc641aba496cb201fa59f8c"
    },
    "parameters":  {},
    "debug": {}
}' 

PHP

リクエスト例 (前回の会話)

<?php
# 環境変数を設定していない場合、次の行を $api_key="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // 実際のアプリケーション ID に置き換えてください

$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";

// リクエストデータを構築
$data = [
    "input" => [
        'prompt' => 'Who are you?'
    ]
];

// データを JSON としてエンコード
$dataString = json_encode($data);

// json_encode が成功したか確認
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// cURL セッションを初期化
$ch = curl_init($url);

// cURL オプションを設定
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
]);

// リクエストを実行
$response = curl_exec($ch);

// cURL 実行が成功したか確認
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}

// HTTP ステータスコードを取得
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// cURL セッションを閉じる
curl_close($ch);
// レスポンスデータをデコード
$response_data = json_decode($response, true);
// レスポンスを処理
if ($status_code == 200) {
    if (isset($response_data['output']['text'])) {
        echo "{$response_data['output']['text']}\n";
    } else {
        echo "No text in response.\n";
    };
    if (isset($response_data['output']['session_id'])) {
        echo "session_id={$response_data['output']['session_id']}\n";
    }
}else {
    if (isset($response_data['request_id'])) {
        echo "request_id={$response_data['request_id']}\n";}
    echo "code={$status_code}\n";
    if (isset($response_data['message'])) {
        echo "message={$response_data['message']}\n";} 
    else {
        echo "message=Unknown error\n";}
}
?>

リクエスト例 (次のターン)

<?php
# 環境変数を設定していない場合、次の行を $api_key="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // 実際のアプリケーション ID に置き換えてください

$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";

// リクエストデータを構築
$data = [
    "input" => [
        'prompt' => 'What skills do you have?',
        // 前回の会話から返された実際の session_id に置き換えてください
        'session_id' => '2e658bcb514f4d30ab7500b4766a8d43'
    ]
];

// データを JSON としてエンコード
$dataString = json_encode($data);

// json_encode が成功したか確認
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// cURL セッションを初期化
$ch = curl_init($url);

// cURL オプションを設定
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
]);

// リクエストを実行
$response = curl_exec($ch);

// cURL 実行が成功したか確認
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}

// HTTP ステータスコードを取得
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// cURL セッションを閉じる
curl_close($ch);
// レスポンスデータをデコード
$response_data = json_decode($response, true);
// レスポンスを処理
if ($status_code == 200) {
    if (isset($response_data['output']['text'])) {
        echo "{$response_data['output']['text']}\n";
    } else {
        echo "No text in response.\n";
    };
    if (isset($response_data['output']['session_id'])) {
        echo "session_id={$response_data['output']['session_id']}\n";
    }
}else {
    if (isset($response_data['request_id'])) {
        echo "request_id={$response_data['request_id']}\n";}
    echo "code={$status_code}\n";
    if (isset($response_data['message'])) {
        echo "message={$response_data['message']}\n";} 
    else {
        echo "message=Unknown error\n";}
}
?>

Node.js

必要な依存関係をインストール:

npm install axios

サンプルリクエスト (前回の会話)

const axios = require('axios');

async function callDashScope() {
    // 環境変数を設定していない場合、次の行を apiKey='sk-xxx' に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// 実際のアプリケーション ID に置き換えてください

    const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;

    const data = {
        input: {
            prompt: "Who are you?"
        },
        parameters: {},
        debug: {}
    };

    try {
        const response = await axios.post(url, data, {
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        });

        if (response.status === 200) {
            console.log(`${response.data.output.text}`);
            console.log(`session_id=${response.data.output.session_id}`);
        } else {
            console.log(`request_id=${response.headers['request_id']}`);
            console.log(`code=${response.status}`);
            console.log(`message=${response.data.message}`);
        }
    } catch (error) {
        console.error(`Error calling DashScope: ${error.message}`);
        if (error.response) {
            console.error(`Response status: ${error.response.status}`);
            console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
        }
    }
}
callDashScope();

リクエスト例 (次のターン)

const axios = require('axios');

async function callDashScope() {
    // 環境変数を設定していない場合、次の行を apiKey='sk-xxx' に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// 実際のアプリケーション ID に置き換えてください

    const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
    // 前回の会話から返された実際の session_id に置き換えてください
    const data = {
        input: {
            prompt: "What skills do you have?",
            session_id: 'fe4ce8b093bf46159ea9927a7b22f0d3',
        },
        parameters: {},
        debug: {}
    };

    try {
        const response = await axios.post(url, data, {
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        });

        if (response.status === 200) {
            console.log(`${response.data.output.text}`);
            console.log(`session_id=${response.data.output.session_id}`);
        } else {
            console.log(`request_id=${response.headers['request_id']}`);
            console.log(`code=${response.status}`);
            console.log(`message=${response.data.message}`);
        }
    } catch (error) {
        console.error(`Error calling DashScope: ${error.message}`);
        if (error.response) {
            console.error(`Response status: ${error.response.status}`);
            console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
        }
    }
}
callDashScope();

C#

リクエスト例 (最初のターン)

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        //環境変数を設定していない場合、次の行を apiKey="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。 
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "APP_ID"; // 実際のアプリケーション ID に置き換えてください

        string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

            string jsonContent = @"{
                ""input"": {
                    ""prompt"": ""Who are you?""
                },
                ""parameters"": {},
                ""debug"": {}
            }";

            HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            try
            {
                HttpResponseMessage response = await client.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("Request successful:");
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error calling DashScope: {ex.Message}");
            }
        }
    }
}

リクエスト例 (次のターン)

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        //環境変数を設定していない場合、次の行を apiKey="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。 
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "APP_ID"; // 実際のアプリケーション ID に置き換えてください

        string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

            string jsonContent = @"{
                ""input"": {
                    ""prompt"": ""What skills do you have?"",
                    ""session_id"": ""7b830e4cc8fe44faad0e648f9b71435f""
                },
                ""parameters"": {},
                ""debug"": {}
            }";

            HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            try
            {
                HttpResponseMessage response = await client.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("Request successful:");
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error calling DashScope: {ex.Message}");
            }
        }
    }
}

Go

リクエスト例 (前回の会話)

package main

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

func main() {
	// 環境変数を設定していない場合、次の行を apiKey := "sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // 実際のアプリケーション ID に置き換えてください

	if apiKey == "" {
		fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
		return
	}

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

	// リクエストボディを作成
	requestBody := map[string]interface{}{
		"input": map[string]string{
			"prompt": "Who are you?",
		},
		"parameters": map[string]interface{}{},
		"debug":      map[string]interface{}{},
	}

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

	// HTTP POST リクエストを作成
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("Failed to create request: %v\n", err)
		return
	}

	// リクエストヘッダーを設定
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// リクエストを送信
	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()

	// レスポンスを読み取り
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Failed to read response: %v\n", err)
		return
	}

	// レスポンスを処理
	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))
	}
}

リクエスト例 (次のターン)

package main

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

func main() {
	// 環境変数を設定していない場合、次の行を apiKey := "sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // 実際のアプリケーション ID に置き換えてください

	if apiKey == "" {
		fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
		return
	}

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

	// リクエストボディを作成
	requestBody := map[string]interface{}{
		"input": map[string]string{
			"prompt":     "What skills do you have?",
			"session_id": "f7eea37f0c734c20998a021b688d6de2", // 前回の会話から返された実際の session_id に置き換えてください
		},
		"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
	}

	// HTTP POST リクエストを作成
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("Failed to create request: %v\n", err)
		return
	}

	// リクエストヘッダーを設定
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// リクエストを送信
	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()

	// レスポンスを読み取り
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Failed to read response: %v\n", err)
		return
	}

	// レスポンスを処理
	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))
	}
}
APP_ID は実際のアプリケーション ID に置き換えてください。次のターンの入力パラメーター内の session_id の値は、前回の会話から返された実際の session_id の値に置き換えてください。

パラメーターの渡し方

biz_params を使用してカスタムパラメーターを渡します。

Python

リクエスト例

import os
from http import HTTPStatus
# DashScope SDK バージョン >= 1.14.0 を推奨します
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
biz_params = {
    # エージェントアプリケーションのカスタムプラグイン入力パラメーターを渡します。<TOOL_ID> をカスタムプラグイン ID に置き換えてください。
    "user_defined_params": {
        "<TOOL_ID>": {
            "article_index": 2}}}
response = Application.call(
        # 環境変数を設定していない場合、次の行を api_key="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        app_id='APP_ID',
        prompt='Dormitory rules content',
        biz_params=biz_params)

if response.status_code != HTTPStatus.OK:
    print(f'request_id={response.request_id}')
    print(f'code={response.status_code}')
    print(f'message={response.message}')
    print(f'See documentation: https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code')
else:
    print('%s\n' % (response.output.text))  # テキストのみを出力するように処理
    # print('%s\n' % (response.usage))

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 =
                // エージェントアプリケーションのカスタムプラグイン入力パラメーターを渡します。<TOOL_ID> をカスタムプラグイン ID に置き換えてください。
                "{\"user_defined_params\":{\"<TOOL_ID>\":{\"article_index\":2}}}";
        ApplicationParam param = ApplicationParam.builder()
                // 環境変数を設定していない場合、次の行を .apiKey("sk-xxx") に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("APP_ID")
                .prompt("Dormitory rules content")
                .bizParams(JsonUtils.parse(bizParams))
                .build();

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

    public static void main(String[] args) {
        try {
            appCall();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.printf("Exception: %s", e.getMessage());
            System.out.println("See documentation: https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}      

HTTP

curl

リクエスト例

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "Dormitory rules content",
        "biz_params": 
        {
            "user_defined_params":
            {
                "<TOOL_ID>":
                    {
                    "article_index": 2
                    }
            }
        } 
    },
    "parameters":  {},
    "debug":{}
}'
APP_ID は実際のアプリケーション ID に置き換えてください。<TOOL_ID> はプラグイン ID に置き換えてください。

PHP

リクエスト例

<?php

# 環境変数を設定していない場合、次の行を $api_key="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // 実際のアプリケーション ID に置き換えてください
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
//<TOOL_ID> を実際のプラグイン ID に置き換えてください
// リクエストデータを構築
$data = [
    "input" => [
        'prompt' => 'Dormitory rules content',
        'biz_params' => [
        'user_defined_params' => [
            '<TOOL_ID>' => [
                'article_index' => 2            
                ]
            ]
        ]
    ],
];
// データを JSON としてエンコード
$dataString = json_encode($data);

// json_encode が成功したか確認
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// cURL セッションを初期化
$ch = curl_init($url);

// cURL オプションを設定
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
]);

// リクエストを実行
$response = curl_exec($ch);

// cURL 実行が成功したか確認
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}

// HTTP ステータスコードを取得
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// cURL セッションを閉じる
curl_close($ch);
// レスポンスデータをデコード
$response_data = json_decode($response, true);
// レスポンスを処理
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() {
    // 環境変数を設定していない場合、次の行を apiKey='sk-xxx' に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// 実際のアプリケーション ID に置き換えてください
    const pluginCode = 'TOOL_ID';// 実際のプラグイン ID に置き換えてください
    const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;

    const data = {
        input: {
            prompt: "Dormitory rules content",
            biz_params: {
                user_defined_params: {
                    [pluginCode]: {
                        // article_index はカスタムプラグインの変数です。実際のプラグイン変数に置き換えてください。
                        '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)
    {
        // 環境変数を設定していない場合、次の行を apiKey="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
        string appId = "APP_ID";// 実際のアプリケーション ID に置き換えてください

        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("Make sure DASHSCOPE_API_KEY is set.");
            return;
        }

        string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
            string pluginCode = "TOOL_ID"; // TOOL_ID を実際のプラグイン ID に置き換えてください
            string jsonContent = $@"{{
                ""input"": {{
                    ""prompt"": ""Dormitory rules content"",
                    ""biz_params"": {{
                        ""user_defined_params"": {{
                            ""{pluginCode}"": {{
                                ""article_index"": 2
                            }}
                        }}
                    }}
                }},
                ""parameters"": {{}},
                ""debug"": {{}}
            }}";

            HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            try
            {
                HttpResponseMessage response = await client.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("Request successful:");
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error calling DashScope: {ex.Message}");
            }
        }
    }
}

Go

リクエスト例

package main

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

func main() {
	// 環境変数を設定していない場合、次の行を apiKey := "sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID"           // 実際のアプリケーション ID に置き換えてください
	pluginCode := "TOOL_ID" // 実際のプラグイン ID に置き換えてください

	if apiKey == "" {
		fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
		return
	}

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

	// リクエストボディを作成
	requestBody := map[string]interface{}{
		"input": map[string]interface{}{
			"prompt": "Dormitory rules content",
			"biz_params": map[string]interface{}{
				"user_defined_params": map[string]interface{}{
					pluginCode: map[string]interface{}{
						"article_index": 2,
					},
				},
			},
		},
		"parameters": map[string]interface{}{},
		"debug":      map[string]interface{}{},
	}

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

	// HTTP POST リクエストを作成
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("Failed to create request: %v\n", err)
		return
	}

	// リクエストヘッダーを設定
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// リクエストを送信
	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()

	// レスポンスを読み取り
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Failed to read response: %v\n", err)
		return
	}

	// レスポンスを処理
	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))
	}
}

ストリーミング出力

stream を使用してストリーミング出力を有効にします。

Python

リクエスト例

import os
from http import HTTPStatus
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
responses = Application.call(
            # 環境変数を設定していない場合、次の行を api_key="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
            api_key=os.getenv("DASHSCOPE_API_KEY"), 
            app_id='APP_ID',
            prompt='Who are you?',
            stream=True,  # ストリーミング出力
            incremental_output=True)  # 増分出力

for response in responses:
    if response.status_code != HTTPStatus.OK:
        print(f'request_id={response.request_id}')
        print(f'code={response.status_code}')
        print(f'message={response.message}')
        print(f'See documentation: https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code')
    else:
        print(f'{response.output.text}\n')  # テキストのみを出力するように処理

Java

リクエスト例

// DashScope SDK バージョン >= 2.15.0 を推奨します
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.reactivex.Flowable;// ストリーミング出力
// エージェントアプリケーション呼び出しのストリーミング出力を実装

import com.alibaba.dashscope.utils.Constants;

public class Main {
    static {
      Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
    }
    public static void streamCall() throws NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                // 環境変数を設定していない場合、次の行を .apiKey("sk-xxx") に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // 実際のアプリケーション ID に置き換えてください
                .appId("APP_ID")
                .prompt("Who are you?")
                // 増分出力
                .incrementalOutput(true)
                .build();
        Application application = new Application();
        // .streamCall(): ストリーミング出力内容
        Flowable<ApplicationResult> result = application.streamCall(param);
        result.blockingForEach(data -> {
            System.out.printf("%s\n",
                    data.getOutput().getText());
        });
    }
    public static void main(String[] args) {
        try {
            streamCall();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.printf("Exception: %s", e.getMessage());
            System.out.println("See documentation: https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

HTTP

curl

リクエスト例

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--header 'X-DashScope-SSE: enable' \
--data '{
    "input": {
        "prompt": "Who are you?"

    },
    "parameters":  {
        "incremental_output":true
    },
    "debug": {}
}'
APP_ID は実際のアプリケーション ID に置き換えてください。

PHP

リクエスト例

<?php

// 環境変数を設定していない場合、次の行を $api_key="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // 実際のアプリケーション ID に置き換えてください

$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";

// リクエストデータを構築
$data = [
    "input" => [
        'prompt' => 'Who are you?'],
    "parameters" => [
        'incremental_output' => true]];// 増分出力
// データを JSON としてエンコード
$dataString = json_encode($data);

// json_encode が成功したか確認
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// cURL セッションを初期化
$ch = curl_init($url);

// cURL オプションを設定
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); // 転送データを返さない
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $string) {
    echo $string; // ストリーミングデータを処理
    return strlen($string);
});
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $api_key,
    'X-DashScope-SSE: enable' // ストリーミング出力
]);

// リクエストを実行
$response = curl_exec($ch);

// cURL 実行が成功したか確認
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}

// HTTP ステータスコードを取得
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// cURL セッションを閉じる
curl_close($ch);

if ($status_code != 200) {
    echo "HTTP Status Code: $status_code\n";
    echo "Request Failed.\n";
}
?>

Node.js

必要な依存関係をインストール:

npm install axios

リクエスト例

1. 完全なレスポンスを出力

const axios = require('axios');

async function callDashScope() {
    //環境変数を設定していない場合、次の行を apiKey='sk-xxx' に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// 実際のアプリケーション ID に置き換えてください

    const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;

    const data = {
        input: {
            prompt: "Who are you?"
        },
        parameters: {
            'incremental_output' : 'true' // 増分出力
        },
        debug: {}
    };

    try {
        console.log("Sending request to DashScope API...");

        const response = await axios.post(url, data, {
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json',
                'X-DashScope-SSE': 'enable' // ストリーミング出力
            },
            responseType: 'stream' // ストリーミングレスポンスを処理するため
        });

        if (response.status === 200) {
            // ストリーミングレスポンスを処理
            response.data.on('data', (chunk) => {
                console.log(`Received chunk: ${chunk.toString()}`);
            });
        } else {
            console.log("Request failed:");
            if (response.data.request_id) {
                console.log(`request_id=${response.data.request_id}`);
            }
            console.log(`code=${response.status}`);
            if (response.data.message) {
                console.log(`message=${response.data.message}`);
            } else {
                console.log('message=Unknown error');
            }
        }
    } catch (error) {
        console.error(`Error calling DashScope: ${error.message}`);
        if (error.response) {
            console.error(`Response status: ${error.response.status}`);
            console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
        }
    }
}

callDashScope();

折りたたみ可能なパネルを展開して特定のコンテンツを表示できます:

2. テキストフィールドの内容のみを出力

const axios = require('axios');
const { Transform } = require('stream');

async function callDashScope() {
    //環境変数を設定していない場合、次の行を apiKey='sk-xxx' に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID'; // 実際のアプリケーション ID に置き換えてください

    const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;

    const data = {
        input: { prompt: "Who are you?" },
        parameters: { incremental_output: true }, // 増分出力
        debug: {}
    };

    try {
        console.log("Sending request to DashScope API...");

        const response = await axios.post(url, data, {
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json',
                'X-DashScope-SSE': 'enable' // ストリーミング出力
            },
            responseType: 'stream' // ストリーミングレスポンスを処理するため
        });

        if (response.status === 200) {
            // // ストリーミングレスポンス SSE プロトコル解析変換ストリームを処理
            const sseTransformer = new Transform({
                transform(chunk, encoding, callback) {
                    this.buffer += chunk.toString();
                    
                    // SSE イベントで分割 (改行2つ)
                    const events = this.buffer.split(/\n\n/);
                    this.buffer = events.pop() || ''; // 不完全な部分を保持
                    
                    events.forEach(eventData => {
                        const lines = eventData.split('\n');
                        let textContent = '';
                        
                        // イベントコンテンツを解析
                        lines.forEach(line => {
                            if (line.startsWith('data:')) {
                                try {
                                    const jsonData = JSON.parse(line.slice(5).trim());
                                    if (jsonData.output?.text) {
                                        textContent = jsonData.output.text;
                                    }
                                } catch(e) {
                                    console.error('JSON parsing error:', e.message);
                                }
                            }
                        });

                        if (textContent) {
                            // 改行を追加してプッシュ
                            this.push(textContent + '\n');
                        }
                    });
                    
                    callback();
                },
                flush(callback) {
                    if (this.buffer) {
                        this.push(this.buffer + '\n');
                    }
                    callback();
                }
            });
            sseTransformer.buffer = '';

            // パイプ処理
            response.data
                .pipe(sseTransformer)
                .on('data', (textWithNewline) => {
                    process.stdout.write(textWithNewline); // 自動改行出力
                })
                .on('end', () => console.log(""))
                .on('error', err => console.error("Pipe error:", err));

        } else {
            console.log("Request failed, status code:", response.status);
            response.data.on('data', chunk => console.log(chunk.toString()));
        }
    } catch (error) {
        console.error(`API call failed: ${error.message}`);
        if (error.response) {
            console.error(`Status code: ${error.response.status}`);
            error.response.data.on('data', chunk => console.log(chunk.toString()));
        }
    }
}

callDashScope();

C#

リクエスト例

using System.Net;
using System.Text;

class Program
{
    static async Task Main(string[] args)
    {
        //環境変数を設定していない場合、次の行を apiKey="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "APP_ID"; // 実際のアプリケーション ID に置き換えてください
        string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
            client.DefaultRequestHeaders.Add("X-DashScope-SSE", "enable");

            string jsonContent = @"{
                ""input"": {
                    ""prompt"": ""Who are you""
                },
                ""parameters"": {""incremental_output"": true},
                ""debug"": {}
            }";

            HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
            try
            {
                var request = new HttpRequestMessage(HttpMethod.Post, url);
                request.Content = content;

                HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
                

                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine("Request successful:");
                    Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
                    using (var stream = await response.Content.ReadAsStreamAsync())
                    using (var reader = new StreamReader(stream))
                    {
                        string? line; // nullable string として宣言
                        while ((line = await reader.ReadLineAsync()) != null)
                        {
                            if (line.StartsWith("data:"))
                            {
                                string data = line.Substring(5).Trim();
                                Console.WriteLine(data);
                                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error calling DashScope: {ex.Message}");
            }
        }
    }
}

Go

リクエスト例

package main

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

func main() {
	// 環境変数を設定していない場合、次の行を apiKey := "sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // 実際のアプリケーション ID に置き換えてください

	if apiKey == "" {
		fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
		return
	}

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

	// リクエストボディを作成。ここで incremental_output はストリーミングレスポンスを有効にします
	requestBody := map[string]interface{}{
		"input": map[string]string{
			"prompt": "Who are you?",
		},
		"parameters": map[string]interface{}{
			"incremental_output": true,
		},
		"debug": map[string]interface{}{},
	}

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

	// HTTP POST リクエストを作成
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("Failed to create request: %v\n", err)
		return
	}

	// リクエストヘッダーを設定。ここで X-DashScope-SSE はストリーミングレスポンスを有効にするために enable に設定します
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("X-DashScope-SSE", "enable")

	// リクエストを送信
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Printf("Failed to send request: %v\n", err)
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
		body, _ := io.ReadAll(resp.Body)
		fmt.Println(string(body))
		return
	}

	// ストリーミングレスポンスを処理
	reader := io.Reader(resp.Body)
	buf := make([]byte, 1024)
	for {
		n, err := reader.Read(buf)
		if n > 0 {
			data := string(buf[:n])
			lines := strings.Split(data, "\n")
			for _, line := range lines {
				line = strings.TrimSpace(line)
				if len(line) >= 5 && line[:5] == "data:" {
					timestamp := time.Now().Format("2006-01-02 15:04:05.000")
					fmt.Printf("%s: %s\n", timestamp, line[5:])
				} else if len(line) > 0 {
					fmt.Println(line)
				}
			}
		}
		if err != nil {
			if err == io.EOF {
				break
			}
			fmt.Printf("Error reading response: %v\n", err)
			break
		}
	}
}

ナレッジベース取得

エージェントアプリケーション を呼び出す際、rag_options を使用してナレッジベース取得を有効にします。

Python

リクエスト例

import os
from http import HTTPStatus
# DashScope SDK バージョン >= 1.20.11 を推奨します
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

response = Application.call(
    # 環境変数を設定していない場合、次の行を api_key="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
    api_key=os.getenv("DASHSCOPE_API_KEY"), 
    app_id='APP_ID',  # APP_ID をアプリケーション ID に置き換えてください
    prompt='Please recommend a phone under 3000 yuan',
    rag_options={
        "pipeline_ids": ["PIPELINE_ID1","PIPELINE_ID2"],  # 実際のナレッジベース ID に置き換えてください。複数ある場合はカンマ区切りで指定します
    }
)

if response.status_code != HTTPStatus.OK:
    print(f'request_id={response.request_id}')
    print(f'code={response.status_code}')
    print(f'message={response.message}')
    print(f'See documentation: https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code')
else:
    print('%s\n' % (response.output.text))  # テキストのみを出力するように処理
    # print('%s\n' % (response.usage))

Java

リクエスト例

// DashScope SDK バージョン >= 2.16.8 を推奨します;
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import java.util.Arrays;

import com.alibaba.dashscope.utils.Constants;

public class Main {
    static {
        Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
    }
    public static void streamCall() throws NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                // 環境変数を設定していない場合、次の行を .apiKey("sk-xxx") に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("APP_ID") // 実際のアプリケーション ID に置き換えてください
                .prompt("Please recommend a phone around 3000 yuan")
                .ragOptions(RagOptions.builder()
                        // 実際の指定されたナレッジベース ID に置き換えてください。複数ある場合はカンマ区切りで指定します
                        .pipelineIds(Arrays.asList("PIPELINES_ID1", "PIPELINES_ID2"))
                        .build())
                .build();

        Application application = new Application();
        ApplicationResult result = application.call(param);
        System.out.printf("%s\n",
                result.getOutput().getText());// テキストのみを出力するように処理
    }

    public static void main(String[] args) {
        try {
            streamCall();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.printf("Exception: %s", e.getMessage());
            System.out.println("See documentation: https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

HTTP

curl

リクエスト例

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/{APP_ID}/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "Please recommend a phone under 3000 yuan"
    },
    "parameters":  {
                    "rag_options" : {
                    "pipeline_ids":["PIPELINE_ID1"]}
    },
    "debug": {}
}'
APP_ID は実際のアプリケーション ID に、PIPELINE_ID1 は指定されたナレッジベース ID に置き換えてください。

PHP

リクエスト例

<?php
# 環境変数を設定していない場合、次の行を $api_key="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // 実際のアプリケーション ID に置き換えてください

$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";

// リクエストデータを構築
$data = [
    "input" => [
        'prompt' => 'Please recommend a phone under 3000 yuan'
    ],
    "parameters" => [
        'rag_options' => [
            'pipeline_ids' => ['PIPELINE_ID1','PIPELINE_ID2']//指定されたナレッジベース ID に置き換えてください。複数ある場合はカンマ区切りで指定します
        ]
    ]
];
// データを JSON としてエンコード
$dataString = json_encode($data);

// json_encode が成功したか確認
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// cURL セッションを初期化
$ch = curl_init($url);

// cURL オプションを設定
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
]);

// リクエストを実行
$response = curl_exec($ch);

// cURL 実行が成功したか確認
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}

// HTTP ステータスコードを取得
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// cURL セッションを閉じる
curl_close($ch);
// レスポンスデータをデコード
$response_data = json_decode($response, true);
// レスポンスを処理
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() {
    // 環境変数を設定していない場合、次の行を apiKey='sk-xxx' に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';//実際のアプリケーション ID に置き換えてください

    const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;

    const data = {
        input: {
            prompt: "Please recommend a phone under 3000 yuan"
        },
        parameters: {
            rag_options:{
                pipeline_ids:['PIPELINE_ID1','PIPELINE_ID2']  // 指定されたナレッジベース ID に置き換えてください。複数ある場合はカンマ区切りで指定します
            }
        },
        debug: {}
    };

    try {
        const response = await axios.post(url, data, {
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        });

        if (response.status === 200) {
            console.log(`${response.data.output.text}`);
        } else {
            console.log(`request_id=${response.headers['request_id']}`);
            console.log(`code=${response.status}`);
            console.log(`message=${response.data.message}`);
        }
    } catch (error) {
        console.error(`Error calling DashScope: ${error.message}`);
        if (error.response) {
            console.error(`Response status: ${error.response.status}`);
            console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
        }
    }
}

callDashScope();

C#

リクエスト例

using System.Text;

class Program
{
    static async Task Main(string[] args)
    {
        // 環境変数を設定していない場合、次の行を apiKey="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
        string appId = "APP_ID";// 実際のアプリケーション ID に置き換えてください
        // PIPELINE_ID1 を指定されたナレッジベース ID に置き換えてください
        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("Make sure DASHSCOPE_API_KEY is set.");
            return;
        }

        string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
        
        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
            string jsonContent = $@"{{
                ""input"": {{
                    ""prompt"": ""Please recommend a phone under 3000 yuan""
                }},
                ""parameters"": {{
                    ""rag_options"" : {{
                        ""pipeline_ids"":[""PIPELINE_ID1""]
                    }}
                }},
                ""debug"": {{}}
            }}";

            HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            try
            {
                HttpResponseMessage response = await client.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error calling DashScope: {ex.Message}");
            }
        }
    }
}

Go

リクエスト例

package main

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

func main() {
	// 環境変数を設定していない場合、次の行を apiKey := "sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // 実際のアプリケーション ID に置き換えてください

	if apiKey == "" {
		fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
		return
	}

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

	// リクエストボディを作成
	requestBody := map[string]interface{}{
		"input": map[string]string{
			"prompt": "Please recommend a phone under 3000 yuan",
		},
		"parameters": map[string]interface{}{
			"rag_options": map[string]interface{}{
				"pipeline_ids": []string{"PIPELINE_ID1"}, // 指定されたナレッジベース ID に置き換えてください
			},
		},
		"debug": map[string]interface{}{},
	}

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

	// HTTP POST リクエストを作成
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("Failed to create request: %v\n", err)
		return
	}

	// リクエストヘッダーを設定
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// リクエストを送信
	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()

	// レスポンスを読み取り
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Failed to read response: %v\n", err)
		return
	}

	// レスポンスを処理
	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))
	}
}

取得プロセス情報を表示する: コードに has_thoughts を追加して True に設定します。取得プロセス情報は output フィールドの thoughts フィールドで返されます。

app_id string (必須)

アプリケーション識別子。

アプリケーション管理 ページのアプリケーションカードからアプリケーション ID を取得できます。

Java SDK ではこれは appId です。HTTP 経由で呼び出す場合、実際のアプリケーション ID を URL 内の APP_ID に置き換えてください。

prompt string (必須)

アプリケーションに応答を生成させるためのユーザー入力命令。

HTTP 経由で呼び出す場合、promptinput オブジェクト内に配置します。

session_id string (任意)

過去の会話識別子。

session_id を渡すと、リクエストは自動的にクラウドに保存されている会話履歴を引き継ぎます。この場合、prompt を渡す必要があります。

この ID は 1 時間の非アクティブ状態後に自動的に期限切れになります。

Java SDK ではこれは setSessionId です。HTTP 経由で呼び出す場合、session_idinput オブジェクト内に配置します。

messages array (任意)

大規模言語モデルに渡されるコンテキストで、会話順に並べられています。

messages パラメーターを使用してマルチターン対話を実行する場合、promptsession_id を渡す必要はありません。

session_idmessages の両方を渡す場合、大規模言語モデルは messages の内容を使用し、session_idprompt を無視します。

HTTP 経由で呼び出す場合、messagesinput オブジェクト内に配置します。
このパラメーターを使用するには、Python Dashscope SDK バージョンが少なくとも 1.20.14、Java Dashscope SDK バージョンが少なくとも 2.17.0 である必要があります。

メッセージタイプ

システムメッセージ object (任意)

モデルのロール、トーン、タスク目的、制約を設定するシステムメッセージ。通常、messages 配列の先頭に配置されます。

プロパティ

content string (必須)

モデルのロール、動作ガイドライン、応答スタイル、タスク制約を定義するシステム命令。

role string (必須)

システムメッセージのロールで、固定値は system です。

ユーザーメッセージ object(必須)

質問、命令、またはコンテキストをモデルに渡すユーザーメッセージ。

プロパティ

content string (必須)

メッセージ本文。

プロパティ

text string (必須)

入力テキスト。

role string (必須)

ユーザーメッセージのロールで、固定値は user です。

アシスタントメッセージ object (任意)

モデルの応答。通常、マルチターン対話でモデルにコンテキストとして渡すために使用されます。

プロパティ

content string (必須)

モデルの応答のテキスト本文。

role string (必須)

アシスタントメッセージのロールで、固定値は assistant です。

workspace string (任意)

ビジネススペース識別子。関連ドキュメント: 「ワークスペース ID の取得」。

サブワークスペース 内のアプリケーションを呼び出す場合にのみ、ワークスペース ID を渡す必要があります。

HTTP 経由で呼び出す場合、X-DashScope-WorkSpace ヘッダーを指定します。

stream boolean (任意) デフォルト値は False

ストリーミング出力で応答するかどうかを指定します。

読みやすさとタイムアウトリスクの低減のため、True に設定することを推奨します。

パラメーター値:

  • False (デフォルト): モデルが生成を完了した後にすべてのコンテンツを一度に返します。

  • True (推奨): モデルが生成するたびにコンテンツを出力し、新しいコンテンツが生成されるたびにデータチャンクを返します。完全な応答を組み立てるには、これらのチャンクをリアルタイムで読み取る必要があります。

Java SDK でストリーミング出力を実装するには、streamCall インターフェイスを使用します。HTTP 経由でストリーミング出力を実装するには、X-DashScope-SSE ヘッダーを enable に設定します。

incremental_output boolean (任意) デフォルト値は False

ストリーミングモードで増分出力を有効にするかどうかを指定します。

読みやすさの向上のため、True に設定することを推奨します。

パラメーター値:

  • False (デフォルト): 各出力には、それまでに生成されたシーケンス全体が含まれます。最終出力は完全な結果です。

    I
    I like
    I like apple
    I like apple.
  • True (推奨): 増分出力。後続の出力には、以前に出力されたコンテンツは含まれません。完全な結果を得るには、これらのセグメントをリアルタイムで読み取る必要があります。

    I
    like
    apple
    .
Java SDK ではこれは incrementalOutputparameters オブジェクト内の incremental_output です。

flow_stream_mode string (任意) デフォルト値は full_thoughts

ワークフローアプリケーション のストリーミング出力モード。

パラメーター値:

  • message_format (推奨):

    指定されたノード(OutputノードまたはEndノードのいずれか)からの結果を、message フィールドに出力します。

    重要

    コンソールアプリケーションで、対象ノードの Stream スイッチを有効にすると、ストリーミングモードで結果が返されます。無効の場合、ノードの最終結果が一度に返されます。

    Java SDK ではこれは FlowStreamMode.MESSAGE_FORMAT です。
  • full_thoughts (デフォルト):

    すべてのノードの結果を thoughts フィールドに出力します。

    重要

    このモードを使用する場合、has_thoughts パラメーターを True に設定する必要があります。

    Java SDK ではこれは FlowStreamMode.FULL_THOUGHTS です。
  • agent_format:

    指定されたノード (大規模言語モデルノードまたは終了ノード) の結果を text フィールドに出力します。

    コンソールアプリケーションで、対象ノードの Response スイッチを有効にすると、ストリーミングモードで結果が返されます。

    重要

    並列ノードではこのモードを使用しないでください。コンテンツが混在する可能性があります。有効化されたノードが明確な実行順序を持つことを確認してください。

    Java SDK ではこれは FlowStreamMode.AGENT_FORMAT です。
Python SDK バージョンは少なくとも 1.24.0、Java SDK バージョンは少なくとも 2.21.0 である必要があります。HTTP 経由で呼び出す場合、flow_stream_modeparameters オブジェクト内に配置します。

biz_params object (任意)

アプリケーションがカスタム変数、ノード、またはプラグインを使用している場合に、パラメーターを渡すためにこのフィールドを使用します。

Java SDK ではこれは bizParams です。HTTP 経由で呼び出す場合、biz_paramsinput オブジェクト内に配置します。

ワークフローアプリケーション の場合、開始ノードのカスタム変数を直接渡します。例:

biz_params = {"city": "Hangzhou"}

エージェントアプリケーション の場合、プロンプト変数またはプラグイン変数を以下のフィールドを使用して渡します:

プロパティ

user_defined_params object (任意)

カスタムプラグインパラメーター情報を表します。

アプリケーション内に追加されたプラグインは重複できません。最大 10 個のプラグインが使用可能です。

プロパティ

tool_id string (任意)

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

${plugin_params} string (任意)

最も内側のオブジェクトには複数のキーと値のペアが含まれます。各キーと値のペアは、ユーザー定義パラメーター名とその指定値を表します。例:

"article_index": 2

使用手順:

  1. 指定されたプラグインをアプリケーションに関連付け、公開 します。

  2. API 呼び出し時に、このパラメーターを通じてプラグイン情報を渡します。

複数のキーと値のペアを提供できます。各キーはプラグインの TOOL_ID で、値はそのプラグインに必要なパラメーターオブジェクトです。例:

"user_defined_params": {
        "<TOOL_ID>": {
            "article_index": 2},
        "<TOOL_ID>": {
            "article_index": 8}
        }

user_defined_tokens object (任意)

カスタムプラグインのユーザー認証情報を表します。

アプリケーション内に追加されたプラグインは重複できません。最大 10 個のプラグインが使用可能です。

プロパティ

tool_id string (任意)

プラグイン ID。プラグインカードから確認できます。<TOOL_ID> フィールドを通じて渡します。

user_token string (任意)

このプラグインに必要なユーザー認証情報を渡します。例: DASHSCOPE_API_KEY の実際の値。

使用手順:

  1. 指定されたプラグインをアプリケーションに関連付け、公開 します。

  2. API 呼び出し時に、このパラメーターを通じてプラグインのユーザー認証情報を渡します。

複数のキーと値のペアを提供できます。各キーはプラグインの TOOL_ID で、値は user_token オブジェクトです。

has_thoughts boolean (任意) デフォルト値は False

プラグイン呼び出しやナレッジ取得プロセスが thoughts フィールドに出力されるかどうかを確認できます。

パラメーター値:

  • True: 出力が含まれます。

  • False (デフォルト): 出力が含まれません。

Java SDK ではこれは hasThoughts です。HTTP 経由で呼び出す場合、has_thoughtsparameters オブジェクト内に配置します。

rag_options object (任意)

取得に関連するパラメーターを構成するために使用され、指定されたナレッジベースやドキュメントの取得などが含まれますが、これらに限定されません。

説明

エージェントアプリケーション のみがこのパラメーターをサポートします。

Java SDK ではこれは ragOptions です。HTTP 経由で呼び出す場合、rag_options parameters オブジェクト内に配置します。

プロパティ

pipeline_ids array 必須)

1 つ以上のナレッジベース ID を含むリスト。最大 5 つまで指定できます。

指定されたナレッジベース内のすべてのドキュメントを取得します。

取得方法:

  • ナレッジベース ページからナレッジベース ID を取得します。

  • または CreateIndex API (非構造化ナレッジベースのみをサポート) を使用し、Data.Id を取得します。

Java SDK ではこれは pipelineIds です。

file_ids array (任意)

1 つ以上の非構造化ドキュメント ID を含むリスト。最大 5 つまで指定できます。

指定されたナレッジベース内の非構造化ドキュメントを取得します。

ドキュメント ID を渡す場合、これらのドキュメントが属するナレッジベース ID を pipeline_ids フィールドにも渡す必要があります。

取得方法:

Java SDK ではこれは fileIds です。

metadata_filter object (任意)

メタデータによって非構造化ドキュメントをフィルタリングするために使用します。1 つ以上のキーと値のペアを指定することで、指定されたナレッジベース内にこのメタデータを持つ非構造化ドキュメントを取得します。

前提条件:

メタデータを渡す場合、このメタデータが属するナレッジベース ID を pipeline_ids フィールドにも渡す必要があります。

確認方法:

  • ナレッジベース ページで、ナレッジベースカードの 詳細を見る > メタ情報 をクリックして確認します。

  • または ListChunks API を使用して取得します。

このオブジェクトは 1 つ以上のキーと値のペアで構成されています:

  • キー: String 型で、メタデータ名を表します。

  • 値:

    • 完全一致: 値は String で、このフィールドの値がこの文字列と完全に一致するドキュメントのみを取得することを意味します。

      • 例: "author": "John.Doe"

    • 複数値の「OR」一致: 値は複数の String を含む Array (配列) または List (リスト) です。これは、このフィールドの値が配列内のいずれかの値に一致するドキュメントを取得することを意味します (論理的な OR)。

      • 例: "source": ["internal_wiki", "public_docs"]

組み合わせロジック:
異なるキーは「AND」ロジックを使用します。例: "author": "John.Doe", "source": ["internal_wiki", "public_docs"] は、「John.Doe」が作成した AND 「internal_wiki」または「public_docs」のいずれかから取得されたドキュメントをフィルタリングすることを意味します。

Java SDK ではこれは metadataFilter です。

tags array (任意)

非構造化ドキュメント用の 1 つ以上のタグを含むリスト。

これらのタグを持つ非構造化ドキュメントを取得します。

確認方法:

レスポンスオブジェクト

シングルターン対話のレスポンス例

{
    "output": {
        "finish_reason": "stop",
        "session_id": "6105c965c31b40958a43dc93c28c7a59",
        "text": "I am Qwen, an AI assistant developed by Alibaba Cloud. I'm designed to answer various questions, provide information, and converse with users. How can I help you?"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 36,
                "model_id": "qwen-plus",
                "input_tokens": 74
            }
        ]
    },
    "request_id": "f97ee37d-0f9c-9b93-b6bf-bd263a232bf9"
}

指定されたナレッジベースのレスポンス例

アプリケーションのナレッジベース機能を呼び出し、取得されたドキュメントから参照ドキュメント情報を出力したい場合、Model Studio コンソールの エージェントアプリケーション で、検索の構成 をクリックし、回答の出典を表示する スイッチを有効にして、公開 します。

{
    "text": "Based on your budget, I recommend considering the Bailian Zephyr Z9. This phone is lightweight and portable, featuring a 6.4-inch screen with 1080 x 2340 pixel resolution, paired with 128GB storage and 6GB RAM, making it perfect for daily use<ref>[1]</ref>. Additionally, it comes with a 4000mAh battery and a 30x digital zoom lens to capture distant details, priced between 2499-2799 yuan, fully meeting your budget requirements<ref>[1]</ref>.",
    "finish_reason": "stop",
    "session_id": "6c1d47fa5eca46b2ad0668c04ccfbf13",
    "thoughts": null,
    "doc_references": [
        {
            "index_id": "1",
            "title": "Bailian Phone Product Introduction",
            "doc_id": "file_7c0e9abee4f142f386e488c9baa9cf38_10317360",
            "doc_name": "Bailian Series Phone Product Introduction",
            "doc_url": null,
            "text": "【Document Name】:Bailian Series Phone Product Introduction\n【Title】:Bailian Phone Product Introduction\n【Content】:Reference Price: 5999- 6499. Bailian Ace Ultra ——For Gamers: Equipped with a 6.67-inch 1080 x 2400 pixel screen, built-in 10GB RAM and 256GB storage, ensuring smooth gaming. Bailian Ace Ultra ——For Gamers: Equipped with a 6.67-inch 1080 x 2400 pixel screen, built-in 10GB RAM and 256GB storage, ensuring smooth gaming. 5500mAh battery with liquid cooling system keeps your device cool during extended gaming sessions. High-dynamic dual speakers enhance immersive audio for gaming. Reference Price: 3999- 4299. Bailian Zephyr Z9 ——Art of Slim Design: Lightweight 6.4-inch 1080 x 2340 pixel design, paired with 128GB storage and 6GB RAM, handles daily tasks effortlessly. 4000mAh battery ensures all-day usage, while the 30x digital zoom lens captures distant details without compromising on power. Reference Price: 2499- 2799. Bailian Flex Fold+ ——New Era of Foldable Phones: Combines innovation and luxury with a 7.6-inch 1800 x 2400 pixel main screen and 4.7-inch 1080 x 2400 pixel outer screen, supporting multi-angle free-stop design for different scenarios. 512GB storage, 12GB RAM, plus a 4700mAh battery and UTG ultra-thin flexible glass, ushering in a new chapter for foldable phones. Additionally, this phone supports Dual SIM Dual Standby and satellite calls, keeping you connected worldwide. Reference Retail Price: 9999- 10999.\n",
            "biz_id": null,
            "images": [

            ],
            "page_number": [
                0]
        }]
}

エラーレスポンス例

リクエストが失敗した場合、レスポンスにはコードとメッセージを通じてエラーの詳細が含まれます。

この例は、無効な API-KEY によるエラーレスポンスを示しています。

request_id=1d14958f-0498-91a3-9e15-be477971967b, 
code=401, 
message=Invalid API-key provided.

status_code string

返されたステータスコード。

200 は成功を示し、それ以外はリクエストが失敗したことを示します。

失敗した場合、エラーコードは code から、エラーの詳細は message から取得します。

Java SDK はこのパラメーターを返しません。失敗した場合、status_codemessage の内容を含む例外をスローします。

request_id string

この呼び出しの一意な識別子。

Java SDK ではこれは requestId として返されます。

code string

エラーコード。呼び出しが成功した場合は空です。

Python SDK のみがこれを返します。

message string

エラーの詳細。成功時は無視されます。

Python SDK のみがこれを返します。

output object

呼び出し結果情報。

output プロパティ

text string

モデルが生成した応答コンテンツ。

finish_reason string

完了理由。

stop は自然な完了 (事前設定されたマーカーに到達) を意味し、null は強制中断 (例: 最大長制限に達した場合や手動で停止した場合) を意味します。

session_id string

現在の会話の一意な識別子。

これを後続のリクエストに渡すことで、過去の会話履歴を引き継ぎます。

thoughts array

呼び出し時に has_thoughts パラメーターを True に設定すると、thoughts でプラグイン呼び出し、ナレッジ取得プロセス、または ディープシンキングモデル の思考プロセスを確認できます。

thoughts プロパティ

thought string

モデルの思考プロセス。

コンソールの エージェントアプリケーションディープシンキングモデル を選択し、正常に公開した場合、API 呼び出し時に has_thoughts パラメーターを True に設定すると、モデルの思考プロセスがこのフィールドで返されます。

reasoningContent string

モデルの思考プロセス。

コンソールの ワークフローアプリケーションディープシンキングモデル を選択し、正常に公開した場合、API 呼び出し時に has_thoughts パラメーターを True に設定すると、モデルの思考プロセスがこのフィールドで返されます。

action_type string

大規模モデルが返す実行ステップのタイプ。例: API は API プラグインの実行を意味し、agentRag はナレッジ取得を意味し、reasoning は ディープシンキングモデル の思考プロセスを意味します。

action_name string

実行されたアクションの名前。例: ナレッジ取得、API プラグイン、または思考プロセス。

action string

実行ステップ。

action_input_stream string

入力パラメーターのストリーミング結果。

action_input string

プラグイン入力パラメーター。

observation string

取得またはプラグイン実行のプロセス。

doc_references array

モデルが引用した取得ドキュメントからの参照ドキュメント情報。

Model Studio コンソールの エージェントアプリケーション回答の出典を表示する スイッチを有効にし、公開 すると、doc_references に有効な情報が含まれる可能性があります。

doc_references プロパティ

index_id string

参照されたドキュメントのインデックス。例: [1]。

title string

参照されたテキストセグメントのタイトル。

doc_id string

参照されたドキュメントの ID。

doc_name string

参照されたドキュメントの名前。

text string

モデルが参照した具体的なテキストコンテンツ。

biz_id string

モデルが参照したビジネス関連識別子。

images array

モデルが参照した画像 URL のリスト。

usage object

このリクエストのデータ使用量情報を表します。

usage プロパティ

models array

この呼び出しのモデル情報。

models プロパティ

model_id string

このアプリケーションが呼び出したモデル ID。

input_tokens integer

ユーザー入力テキストをトークンに変換した後の長さ。

output_tokens integer

モデルが生成した応答をトークンに変換した後の長さ。

QPM 制限

単一アプリケーションのデフォルト QPM (1 分あたりのクエリ数) は 15,000 です。

エラーコード

呼び出しが失敗してエラーが返された場合、「エラー情報」を参照して解決策を確認してください。