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

Alibaba Cloud Model Studio:アプリケーションの呼び出し

最終更新日:May 09, 2026

Model Studio アプリケーション(エージェント、ワークフロー、エージェントオーケストレーションなど)を、DashScope SDK または HTTP を使用して業務システムに統合できます。

前提条件

Model Studio アプリケーションの呼び出しには、DashScope SDK または HTTP インターフェイスを使用できます。

呼び出し方法に関係なく、API キーを環境変数として設定する必要があります。DashScope SDK を使用する場合は、DashScope SDK のインストールも必要です。

使用方法

単一ラウンドの会話

DashScope SDK または HTTP メソッドを使用して単一ラウンドの会話を実装するためのサンプルコードです

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" に置き換えることができます。ただし、API キー漏洩のリスクを低減するため、本番環境では API キーをコード内にハードコードしないことを推奨します。
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    app_id='YOUR_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'Refer to: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
else:
    print(response.output.text)

応答のサンプル

I am a large language model developed by Alibaba Cloud, named Qwen. I am designed to help users generate various types of text, such as articles, stories, poems, stories, etc., and can be adjusted and optimized according to different scenarios and needs. In addition, I can also answer various questions, provide information and explanations, and assist in learning and research. If you have any needs, please feel free to ask me questions at any time!

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") に置き換えることができます。ただし、API キー漏洩のリスクを低減するため、本番環境では API キーをコード内にハードコードしないことを推奨します。
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("YOUR_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("Refer to: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

応答のサンプル

text: I am a large language model developed by Alibaba Cloud, named Qwen.

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": "Who are you?"
    },
    "parameters":  {},
    "debug": {}
}' 
YOUR_APP_ID を実際のアプリケーション ID に置き換えてください。

応答のサンプル

{"output":{"finish_reason":"stop",
"session_id":"232ea2e9e6ef448db6b14465c06a9a56",
"text":"I am a super-large-scale language model developed by Alibaba Cloud, and my name is Qwen. I am an AI assistant who can answer questions, create text, express opinions, and even write code. If you have any questions or need assistance, please don't hesitate to let me know, and I will do my best to provide you with the help you need."},
"usage":{"models":[{"output_tokens":51,"model_id":"qwen-max","input_tokens":121}]},
"request_id":"661c9cad-e59c-9f78-a262-78eff243f151"}% 
PHP

リクエストのサンプル

<?php

# 環境変数が設定されていない場合は、次の行を API キーに置き換えることができます:$api_key="sk-xxx"。ただし、API キー漏洩のリスクを低減するため、本番環境では API キーをコード内にハードコードしないことを推奨します。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_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";}
}
?>

応答のサンプル

I am a super-large-scale language model developed by Alibaba Cloud, and my name is Qwen.
Node.js

依存関係:

npm install axios

リクエストのサンプル

const axios = require('axios');

async function callDashScope() {
    // 環境変数が設定されていない場合は、次の行を apiKey='sk-xxx' に置き換えることができます。ただし、API キー漏洩のリスクを低減するため、本番環境では API キーをコード内にハードコードしないことを推奨します。
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'YOUR_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();

応答のサンプル

I am a large-scale language model developed by Alibaba Cloud, and my name is Qwen.
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" に置き換えることができます。ただし、API キー漏洩のリスクを低減するため、本番環境では API キーをコード内にハードコードしないことを推奨します。 
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "YOUR_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}");
            }
        }
    }
}

応答のサンプル

{
    "output": {
        "finish_reason": "stop",
        "session_id": "c274e14a58d9492f9baeffdc003a97c5",
        "text": "I am a super-large-scale language model developed by Alibaba Cloud, and my name is Qwen. I am designed to assist users in generating various types of text, such as articles, stories, poems, etc., and can adapt and innovate according to different scenarios and needs. Additionally, I am capable of answering a wide range of questions, providing information and explanations, and helping users solve problems and acquire knowledge. If you have any questions or need assistance, please feel free to let me know anytime!"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 79,
                "model_id": "qwen-plus",
                "input_tokens": 74
            }
        ]
    },
    "request_id": "5c4b86b1-cd2d-9847-8d00-3fba8f187bc6"
}
Go

リクエストのサンプル

package main

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

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

	if apiKey == "" {
		fmt.Println("Please ensure 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))
	}
}

応答のサンプル

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

マルチラウンド会話

マルチラウンド会話では、LLM が会話履歴を参照できるため、日常的なコミュニケーションシナリオにより近い形になります。

現在、エージェントアプリケーションおよびワークフローアプリケーションのみがマルチラウンド会話をサポートしています。
  • session_id を渡すと、リクエストにクラウドに保存された会話履歴が自動的に含まれます。

    session_id を渡す場合、prompt は必須です。
  • messages 配列を自分で管理することもできます。各ラウンドの会話履歴と新しい命令を messages 配列に追加し、その履歴を messages で渡します。

    messages を渡す場合、prompt は任意です。両方を渡した場合、prompt は補足情報として messages の末尾に追加されます。
session_idmessages の両方を渡した場合、messages が優先的に使用されます。

クラウドストレージ(session_id)

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" に置き換えてください。ただし、API キーの漏洩リスクを低減するため、本番環境ではコード内に API キーを直接ハードコードしないことを推奨します。
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        app_id='YOUR_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'Refer to: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
        return response

    responseNext = Application.call(
                # 環境変数が設定されていない場合は、次の行を api_key="sk-xxx" に置き換えてください。ただし、API キーの漏洩リスクを低減するため、本番環境ではコード内に API キーを直接ハードコードしないことを推奨します。
                api_key=os.getenv("DASHSCOPE_API_KEY"),
                app_id='YOUR_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'Refer to: https://www.alibabacloud.com/help/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()

応答例

I have multiple skills and can assist you with various tasks. Here are some of my main skills:

1. **Information retrieval**: Providing weather, news, historical facts, scientific knowledge, and various other information.
2. **Language processing**: Translating text, correcting grammar errors, generating articles and stories.
3. **Technical problem solving**: Answering programming questions, software usage, technical troubleshooting, etc.
4. **Educational assistance**: Helping with questions in subjects like mathematics, physics, chemistry, etc.
5. **Life advice**: Providing advice on health, diet, travel, shopping, etc.
6. **Entertainment interaction**: Telling jokes, playing word games, engaging in simple chat interactions.
7. **Schedule management**: Reminding important dates, arranging schedules, setting reminders.
8. **Data analysis**: Explaining data charts, providing data analysis suggestions.
9. **Emotional support**: Listening to your feelings, providing comfort and support.

If you have specific needs or questions, you can tell me directly, and I'll do my best to help you!
 session_id=98ceb3ca0c4e4b05a20a00f913050b42
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") に置き換えてください。ただし、API キーの漏洩リスクを低減するため、本番環境ではコード内に API キーを直接ハードコードしないことを推奨します。
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // 実際のアプリケーション ID に置き換えてください
                .appId("YOUR_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("Refer to: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

応答例

I possess multiple skills and can provide various types of assistance. Here are some of my main skills:

1. **Multilingual understanding and generation**: I can understand and generate text in multiple languages including Chinese and English.
2. **Information retrieval and synthesis**: I can search for relevant information based on your questions and organize and summarize it.
3. **Writing assistance**: Whether it's writing articles, reports, or creative writing, I can provide support.
4. **Programming assistant**: For programmers, I can help answer programming-related questions, provide code examples, etc.
5. **Educational guidance**: When encountering difficulties in the learning process, I can serve as an assistant to provide help, covering multiple subject areas from mathematics to history.
6. **Life advice**: I can also give some advice on issues related to healthy eating, travel planning, etc.
7. **Emotional communication**: Although I am an AI, I strive to communicate with you in a warm and supportive way.

If you have any specific needs or want to learn more about a particular aspect, please feel free to tell me!
, session_id: f2e94a980a34424fa25be45a7048d77c
HTTP
curl

リクエスト例(ラウンド 1)

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": "Who are you?"
    },
    "parameters":  {},
    "debug": {}
}' 

応答例

{
    "output": {
        "finish_reason": "stop",
        "session_id": "4f8ef7233dc641aba496cb201fa59f8c",
        "text": "I am Qwen, an AI assistant developed by Alibaba Cloud. I am designed to answer various questions, provide information, and engage in conversations with users. Is there anything I can help you with?"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 36,
                "model_id": "qwen-plus",
                "input_tokens": 75
            }
        ]
    },
    "request_id": "e571b14a-423f-9278-8d1e-d86c418801e0"
}

リクエスト例(ラウンド 2)

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": "What skills do you have?",
        "session_id":"4f8ef7233dc641aba496cb201fa59f8c"
    },
    "parameters":  {},
    "debug": {}
}' 

応答例

{
    "output": {
        "finish_reason": "stop",
        "session_id": "4f8ef7233dc641aba496cb201fa59f8c",
        "text": "As an AI assistant, I have multiple skills that can help you complete various tasks, including but not limited to:

1. **Knowledge queries**: I can help you find information in various fields such as science, history, culture, technology, etc.
2. **Language translation**: I can help you translate text in different languages, supporting translation between multiple languages.
3. **Text generation**: I can generate articles, stories, poems, press releases, and various other types of text.
4. **Question answering**: Whether it's academic questions, common knowledge, or technical problems, I can try to provide answers for you.
5. **Conversational exchange**: I can have natural and smooth conversations with you, providing emotional support or entertainment.
6. **Code writing and debugging**: I can help you write code and solve problems in programming.
7. **Data analysis**: I can help you analyze data, provide statistical results and visualization suggestions.
8. **Creative inspiration**: If you need creative inspiration, such as design, advertising copy, marketing strategies, etc., I can also provide help.

If you have any specific needs or questions, feel free to tell me anytime!"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 208,
                "model_id": "qwen-plus",
                "input_tokens": 125
            }
        ]
    },
    "request_id": "9de2c3ed-e1f0-9963-85f4-8f289203418b"
}
PHP

リクエスト例(ラウンド 1)

<?php
# 環境変数が設定されていない場合は、次の行を API キーに置き換えてください:$api_key="sk-xxx"。ただし、API キーの漏洩リスクを低減するため、本番環境ではコード内に API キーを直接ハードコードしないことを推奨します。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_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";
    }
}
?>

応答例

I am a large-scale language model from Alibaba Cloud, my name is Qwen.
session_id=2e658bcb514f4d30ab7500b4766a8d43

リクエスト例(ラウンド 2)

<?php
# 環境変数が設定されていない場合は、次の行を API キーに置き換えてください:$api_key="sk-xxx"。ただし、API キーの漏洩リスクを低減するため、本番環境ではコード内に API キーを直接ハードコードしないことを推奨します。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_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";
    }
}
?>

応答例

I have multiple skills, including but not limited to:

1. **Multilingual capability**: I can understand and generate text content in multiple languages.
2. **Writing and creation**: Help with writing articles, stories, poems, and other creative content.
3. **Knowledge Q&A**: Answer common and professional questions from various fields.
4. **Code writing and understanding**: Able to write simple program code, and help explain or debug code.
5. **Logical reasoning**: Solve problems and puzzles that require logical thinking.
6. **Emotional support**: Provide positive psychological support and encouragement.
7. **Games and entertainment**: Participate in word games or other forms of interactive entertainment activities.

My goal is to be your capable assistant, providing help and support when you need it. If you have any specific needs or features you'd like to try, please feel free to tell me!
session_id=2e658bcb514f4d30ab7500b4766a8d43
Node.js

依存関係:

npm install axios

リクエスト例(ラウンド 1)

const axios = require('axios');

async function callDashScope() {
    // 環境変数が設定されていない場合は、次の行を apiKey='sk-xxx' に置き換えてください。ただし、API キーの漏洩リスクを低減するため、本番環境ではコード内に API キーを直接ハードコードしないことを推奨します。
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'YOUR_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();

応答例

I am Qwen, an artificial intelligence assistant developed by Alibaba Cloud. I can answer various questions, provide information, and engage in conversations with users. Is there anything I can help you with?
session_id=fe4ce8b093bf46159ea9927a7b22f0d3

リクエスト例(ラウンド 2)

const axios = require('axios');

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

    const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
    // session_id を前回の会話で取得した実際の 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();

応答例

I have various skills that can help you handle different tasks and questions. Here are some of my main skill areas:

1. **Information query and retrieval**: I can help find specific information, data, or news.
2. **Writing and creation**: Including writing articles, stories, poems, reports, etc.
3. **Language translation**: Can provide translation services between different languages.
4. **Educational tutoring**: Answer academic questions, help understand complex concepts.
5. **Technical support**: Solve technical problems encountered in computer use.
6. **Life advice**: Provide advice on health, diet, travel, and other aspects.
7. **Entertainment interaction**: Tell jokes, play word games, and other relaxing activities.

If you have specific needs or want to learn more about a particular aspect, please let me know!
session_id=fe4ce8b093bf46159ea9927a7b22f0d3
C#

リクエスト例(ラウンド 1)

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

class Program
{
    static async Task Main(string[] args)
    {
        //環境変数が設定されていない場合は、次の行を apiKey="sk-xxx" に置き換えてください。ただし、API キーの漏洩リスクを低減するため、本番環境ではコード内に API キーを直接ハードコードしないことを推奨します。 
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "YOUR_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}");
            }
        }
    }
}

応答例

{
    "output": {
        "finish_reason": "stop",
        "session_id": "7b830e4cc8fe44faad0e648f9b71435f",
        "text": "I am Qwen, an AI assistant developed by Alibaba Cloud. I am designed to answer various questions, provide information, and engage in conversations with users. Is there anything I can help you with?"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 36,
                "model_id": "qwen-plus",
                "input_tokens": 75
            }
        ]
    },
    "request_id": "53691ae5-be17-96c6-a830-8f0f92329028"
}

リクエスト例(ラウンド 2)

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

class Program
{
    static async Task Main(string[] args)
    {
        //環境変数が設定されていない場合は、次の行を apiKey="sk-xxx" に置き換えてください。ただし、API キーの漏洩リスクを低減するため、本番環境ではコード内に API キーを直接ハードコードしないことを推奨します。 
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "YOUR_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}");
            }
        }
    }
}

応答例

{
    "output": {
        "finish_reason": "stop",
        "session_id": "7b830e4cc8fe44faad0e648f9b71435f",
        "text": "I have multiple skills and can:

- Answer knowledge questions from a wide range of fields
- Provide learning resources and suggestions
- Assist with technical problems
- Communicate in multiple languages
- Help plan trips and activities
- Provide practical advice for daily life

If you have any specific needs or questions, feel free to let me know!"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 70,
                "model_id": "qwen-plus",
                "input_tokens": 123
            }
        ]
    },
    "request_id": "da5044ed-461e-9e91-8ca5-38a3c72a8306"
}
Go

リクエスト例(ラウンド 1)

package main

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

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

	if apiKey == "" {
		fmt.Println("Please 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))
	}
}

応答例

{
    "output": {
        "finish_reason": "stop",
        "session_id": "f7eea37f0c734c20998a021b688d6de2",
        "text": "I am Qwen, an AI assistant developed by Alibaba Cloud. I am designed to answer various questions, provide information, and engage in conversations with users. Is there anything I can help you with?"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 36,
                "model_id": "qwen-plus",
                "input_tokens": 75
            }
        ]
    },
    "request_id": "fa65e14a-ab63-95b2-aa43-035bf5c51835"
}

リクエスト例(ラウンド 2)

package main

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

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

	if apiKey == "" {
		fmt.Println("Please 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))
	}
}

応答例

{
    "output": {
        "finish_reason": "stop",
        "session_id": "f7eea37f0c734c20998a021b688d6de2",
        "text": "I have multiple skills and can:

- Answer various knowledge questions in fields such as science, history, culture, etc.
- Provide practical advice, such as travel tips, health tips, study methods, etc.
- Assist with text work, such as writing articles, editing documents, creating stories or poems.
- Perform multilingual translation, supporting translation between multiple languages.
- Have natural and smooth conversations with users, keeping them company, answering questions.

If you have any specific needs, feel free to let me know!"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 104,
                "model_id": "qwen-plus",
                "input_tokens": 125
            }
        ]
    },
    "request_id": "badccade-9f54-986b-8d8c-75ef15e9616c"
}
YOUR_APP_ID は実際のアプリケーション ID に置き換えてください。ラウンド 2 では、session_id をラウンド 1 で返された実際の session_id に置き換えてください。

自己管理(messages)

Python

リクエスト例

# dashscope SDK のバージョンは >= 1.20.14 である必要があります
import os
from http import HTTPStatus
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

messages = [
    {'role': 'system', 'content': 'You are a helpful assistant.'},
    {'role': 'user', 'content': 'Who are you?'},
    {"role": "assistant","content": "I am a large-scale language model developed by Alibaba Cloud, my name is Qwen."},
    {"role": "user","content": "What can you do?"}
]
response = Application.call(
    # 環境変数が設定されていない場合は、次の行を api_key="sk-xxx" に置き換えてください。ただし、API キーの漏洩リスクを低減するため、本番環境ではコード内に API キーを直接ハードコードしないことを推奨します。
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    app_id='YOUR_APP_ID',  # 実際のアプリケーション ID に置き換えてください
    messages=messages)

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'Refer to: https://www.alibabacloud.com/help/model-studio/error-code')
else:
    print('%s\n' % (response.output.text))

応答例

As Qwen, I can help you complete various tasks, including but not limited to:

1. Answering questions: Whether it's scientific knowledge, technical problems, or common sense, I can provide accurate information and answers.
2. Creating text: Such as writing stories, poems, articles, etc., generating creative content based on given conditions.
3. Programming assistant: Can assist with programming learning, explain code logic, help debug program errors, etc.
4. Language translation: Support translation services between multiple languages.
5. Providing suggestions: Offering advice or solutions when facing decisions.
6. Emotional communication: Engaging in conversations with users, listening and giving positive responses and support.

In short, my goal is to be your capable assistant in work and life. If you have any specific needs, please feel free to tell me!
Java

リクエスト例

// dashscope SDK のバージョンは >= 2.17.0 である必要があります
import java.util.ArrayList;
import java.util.List;

import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;

public class Main {
      static {
        Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
      }
      public static void appCall()
            throws ApiException, NoApiKeyException, InputRequiredException {
        List messages = new ArrayList<>();
        messages.add(Message.builder().role("system").content("You are a helpful assistant.").build());
        messages.add(Message.builder().role("user").content("Who are you?").build());
        messages.add(Message.builder().role("assistant").content("I am a large-scale language model developed by Alibaba Cloud, my name is Qwen.").build());
        messages.add(Message.builder().role("user").content("What can you do?").build());

        ApplicationParam param = ApplicationParam.builder()
                // 環境変数が設定されていない場合は、次の行を .apiKey("sk-xxx") に置き換えてください。ただし、API キーの漏洩リスクを低減するため、本番環境ではコード内に API キーを直接ハードコードしないことを推奨します。
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("YOUR_APP_ID")
                .messages(messages)
                .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("Refer to: https://www.alibabacloud.com/help/model-studio/error-code");
        }
        System.exit(0);
    }
}

応答例

text: I can help you complete various tasks, including but not limited to:

1. Answering questions: Whether academic questions, common knowledge, or questions in professional fields, I will do my best to provide accurate answers.
2. Creating text: Such as writing stories, official documents, emails, scripts, etc., just give me some basic information and requirements.
3. Table processing: Can help you organize data, generate or modify tables.
4. Code writing: Support code writing and explanation in multiple programming languages.
5. Multilingual translation: Can translate between different languages.
6. Simulated dialogue: Can play different roles to engage in simulated conversations with users.

If you have any specific needs, please feel free to tell me!
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": {
        "messages":[      
            {
                "role": "system",
                "content": "You are a helpful assistant."
            },
            {
                "role": "user",
                "content": "Who are you?"
            },
            {
                "role": "assistant",
                "content": "I am a large-scale language model developed by Alibaba Cloud, my name is Qwen."
            },
            {
                "role": "user",
                "content": "What can you do?"
            }
        ]
    },
    "parameters":  {},
    "debug": {}
}' 

応答例

{"output":
{"finish_reason":"stop","session_id":"990ca89d89794826976d7499ad10cddb",
"text":"I can help you complete various tasks, including but not limited to:\n\n1. Answering questions: Whether academic knowledge, practical tips, or common sense questions, I will do my best to provide accurate answers.\n2. Creating text: Such as writing stories, official documents, emails, scripts, etc., as long as you tell me your specific needs, I can help you write them.\n3. Expressing opinions: For some subjective questions, I can also give my own views and discuss them with you.\n4. Games and entertainment: We can play word games together, or I can tell you a joke to help you relax.\n\nIn short, anything related to language, you can ask me for help!"},
"usage":{"models":[{"output_tokens":126,"model_id":"qwen-max","input_tokens":86}]},"request_id":"3908c4a3-8d7a-9e51-81a5-0fc366582990"}%  
PHP

リクエスト例

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

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

// リクエストデータを構築
$data = [
    "input" => [
        "messages" => [
            [
                "role" => "system",
                "content" => "You are a helpful assistant."
            ],
            [
                "role" => "user",
                "content" => "Who are you?"
            ],
            [
                "role" => "assistant",
                "content" => "I am a large-scale language model developed by Alibaba Cloud, and my name is Qwen."
            ],
            [
                "role" => "user",
                "content" => "What can you do?"
            ]
        ]
    ]
];

// データを 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";
    }
}
?>

応答例

I can help you complete various tasks, such as:

1. Answering questions: Whether academic questions, practical knowledge, or entertainment gossip, I will do my best to provide accurate answers.
2. Creating text: Including but not limited to writing stories, official documents, emails, etc.
3. Providing advice: Such as travel suggestions, learning methods, career planning, and other guidance and advice.
4. Engaging in conversation: We can chat, share feelings, and even have some interesting discussions.

If you need help with anything, just let me know!
Node.js

依存関係:

npm install axios

リクエスト例

const axios = require('axios');
async function callDashScope() {
    // 環境変数が設定されていない場合は、次の行を apiKey='sk-xxx' に置き換えてください。ただし、API キーの漏洩リスクを低減するため、本番環境ではコード内に API キーを直接ハードコードしないことを推奨します。
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'YOUR_APP_ID';//実際のアプリケーション ID に置き換えてください

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

    const data = {
        "input": {
        "messages":[      
            {
                "role": "system",
                "content": "You are a helpful assistant."
            },
            {
                "role": "user",
                "content": "Who are you?"
            },
            {
                "role": "assistant",
                "content": "I am a large-scale language model developed by Alibaba Cloud, my name is Qwen."
            },
            {
                "role": "user",
                "content": "What can you do?"
            }
        ]
    },
        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();

応答例

I can help you complete various tasks, including but not limited to:

1. Answering questions: Whether academic knowledge, practical information, or common sense questions, I will do my best to provide accurate answers.
2. Creating text: Such as writing stories, official documents, emails, scripts, etc., as long as you provide enough background information and requirements, I can help you write them.
3. Providing suggestions: If you need advice on certain decisions, such as travel destination selection, gift selection, study methods, etc., I can also provide suggestions based on your description.
4. Language translation: Support text translation between multiple languages.
5. Code writing and explanation: For programming-related questions, I can help write simple programs or explain complex concepts.
6. Engaging in conversation: In addition to the above functions, I can also have daily communication with users, sharing ideas.

If you have any specific needs, please feel free to tell me!
C#

リクエスト例

using System.Text;

class Program
{
    static async Task Main(string[] args)
    {
        // 環境変数が設定されていない場合は、次の行を apiKey="sk-xxx" に置き換えてください。ただし、API キーの漏洩リスクを低減するため、本番環境ではコード内に API キーを直接ハードコードしないことを推奨します。
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
        string appId = "YOUR_APP_ID";// 実際のアプリケーション ID に置き換えてください
        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("Please 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"": {{
                    ""messages"": [
                        {{
                            ""role"": ""system"",
                            ""content"": ""You are a helpful assistant.""
                        }},
                        {{
                            ""role"": ""user"",
                            ""content"": ""Who are you?""
                        }},
                        {{
                            ""role"": ""assistant"",
                            ""content"": ""I am a large-scale language model developed by Alibaba Cloud, my name is Qwen.""
                        }},
                        {{
                            ""role"": ""user"",
                            ""content"": ""What can you do?""
                        }}
                    ]
                }},
                ""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(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": "a6d041ca3d084a7ca9eff1c456afad70",
        "text": "As Qwen, I can help you complete various tasks, including but not limited to:\n\n1. Answering questions: Providing answers to various knowledge-based questions.\n2. Text generation: Writing articles, stories, poems, and other text content.\n3. Language translation: Performing translation work between different languages.\n4. Conversational exchange: Having natural and smooth conversations with users.\n5. Providing suggestions: Offering suggestions or solutions based on user needs.\n\nIf you have any specific needs, please tell me, and I will do my best to help you."
    },
    "usage": {
        "models": [
            {
                "output_tokens": 102,
                "model_id": "qwen-max",
                "input_tokens": 87
            }
        ]
    },
    "request_id": "27fb8a01-70d5-974f-bb0a-e9408a9c1772"
}
Go

リクエスト例

package main

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

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

	if apiKey == "" {
		fmt.Println("Please 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{}{
			"messages": []interface{}{
				map[string]string{
					"role":    "system",
					"content": "You are a helpful assistant.",
				},
				map[string]string{
					"role":    "user",
					"content": "Who are you?",
				},
				map[string]string{
					"role":    "assistant",
					"content": "I am a large-scale language model developed by Alibaba Cloud, my name is Qwen.",
				},
				map[string]string{
					"role":    "user",
					"content": "What can you do?",
				},
			},
		},
		"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))
	}
}

応答例

{
    "output": {
        "finish_reason": "stop",
        "session_id": "2ae51a5eac3b4b269834cf0695330a05",
        "text": "I can help you complete various tasks, including but not limited to:\n\n1. Answering questions: Providing answers to knowledge-based questions in various fields.\n2. Text creation: Writing stories, articles, poems, etc.\n3. Programming assistant: Providing guidance and code examples for programming.\n4. Conversational chat: Engaging in daily conversations, keeping you company.\n5. Translation services: Providing translation support between multiple languages.\n6. Information queries: Finding news, weather forecasts, historical data, and other information.\n7. Learning guidance: Helping answer questions in learning, providing learning suggestions.\n\nIf you have any specific needs or questions, you can tell me, and I will do my best to help you!"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 132,
                "model_id": "qwen-max",
                "input_tokens": 87
            }
        ]
    },
    "request_id": "1289eb09-e4ed-9f9e-98ca-805c83b333a1"
}

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

同じエージェントまたはワークフローを異なるビジネスシナリオに適応させるには、プラグインまたはノードに対してカスタムパラメーターを設定し、アプリケーション呼び出し時に biz_params を通じてパラメーターを渡すことができます。パラメーターの設定方法については、「アプリケーションパラメーターパススルー」をご参照ください。サンプルコードは以下のとおりです。

  1. カスタムプラグイン パラメーター: 関連付けられた エージェントアプリケーション または関連付けられた ワークフローアプリケーションプラグインノード を通じて渡します。

    カスタムプラグインに対して、パラメーターおよびユーザーレベルの認証情報を渡すことができます。

    • パラメーター: user_defined_params

    • ユーザーレベルの認証: user_defined_tokensuser_token は、プラグインに必要な認証情報(例:DASHSCOPE_API_KEY)です。

    次のサンプルは、関連付けられたプラグインの index パラメーターおよびユーザーレベルの認証情報を必要とする エージェントアプリケーション です。

    プラグインツールは、同一ワークスペース内の エージェントアプリケーション のみに関連付けることができます。
    your_plugin_code は、プラグインカードに表示される関連付けられたプラグインツール ID に置き換え、入力パラメーターのキーと値のペアを渡してください。この例では、値が 2 の article_index を使用しています。

    パラメーターの渡し方

    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 = {
        # エージェントアプリケーション向けのカスタムプラグイン入力パラメーターの渡し方。your_plugin_code はご利用のカスタムプラグイン ID に置き換えてください。
        "user_defined_params": {
            "your_plugin_code": {
                "article_index": 2}}}
    response = Application.call(
            # 環境変数が設定されていない場合は、次の行を api_key="sk-xxx" に置き換えることもできます。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
            api_key=os.getenv("DASHSCOPE_API_KEY"),
            app_id='YOUR_APP_ID',
            prompt='Dormitory convention content',
            biz_params=biz_params)
    
    if response.status_code != HTTPStatus.OK:
        print(f'request_id={response.request_id}')
        print(f'code={response.status_code}')
        print(f'message={response.message}')
        print(f'Refer to: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
    else:
        print('%s\n' % (response.output.text))  # テキスト出力のみを処理
        # print('%s\n' % (response.usage))

    応答サンプル

    寄宿舎規則の第 2 条は次のとおりです。
    
    「寄宿舎のメンバーは互いに助け合い、思いやりを持ち、学び合い、共に成長すること。寛容で謙虚であり、互いを尊重し、誠意を持って接すること。」
    
    これは、寄宿舎内でメンバーが前向きな生活・学習環境を築き、相互支援を行うとともに、互いの違いを理解し尊重することが求められることを示しています。規則の他の条項について知りたい場合は、お知らせください!
    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 =
                    // エージェントアプリケーション向けのカスタムプラグイン入力パラメーターの渡し方。{your_plugin_code} はご利用のカスタムプラグイン ID に置き換えてください。
                    "{\"user_defined_params\":{\"{your_plugin_code}\":{\"article_index\":2}}}";
            ApplicationParam param = ApplicationParam.builder()
                    // 環境変数が設定されていない場合は、次の行を .apiKey("sk-xxx") に置き換えることもできます。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .appId("YOUR_APP_ID")
                    .prompt("Dormitory convention content")
                    .bizParams(JsonUtils.parse(bizParams))
                    .build();
    
            Application application = new Application();
            ApplicationResult result = application.call(param);
            System.out.printf("%s\n",
                    result.getOutput().getText());
        }
    
        public static void main(String[] args) {
            try {
                appCall();
            } catch (ApiException | NoApiKeyException | InputRequiredException e) {
                System.out.printf("Exception: %s", e.getMessage());
                System.out.println("Refer to: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code");
            }
            System.exit(0);
        }
    }      

    応答サンプル

    寄宿舎規則第 2 条は次のように定めています。
    
    寄宿舎のメンバーは互いに助け合い、思いやりを持ち、学び合い、共に成長すること。寛容で謙虚であり、互いを尊重し、誠意を持って接すること。
    
    これは、共同生活環境において、ルームメートが前向きな関係を維持し、相互支援を通じて調和のとれた生活・学習環境を育むことが重要であることを強調しています。より具体的な条項について知りたい場合は、お知らせください。
    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": "Dormitory convention content",
            "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":"寄宿舎規則の第 2 条は次のとおりです。「寄宿舎のメンバーは互いに助け合い、思いやりを持ち、学び合い、共に成長すること。寛容で謙虚であり、互いを尊重し、誠意を持って接すること。」これは、寄宿舎生活において、全員が互いに支え合い、調和的で前向きな生活環境を共同で創り出すべきであることを意味しています。"},
    "usage":{"models":[{"output_tokens":94,"model_id":"qwen-max","input_tokens":453}]},
    "request_id":"a39fd2b5-7e2c-983e-84a1-1039f726f18a"}%
    PHP

    リクエストサンプル

    <?php
    
    # 環境変数が設定されていない場合は、Dashscope API キーに置き換えてください:$api_key="sk-xxx"。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
    $api_key = getenv("DASHSCOPE_API_KEY");
    $application_id = 'YOUR_APP_ID'; // 実際のアプリケーション ID に置き換えてください
    $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
    // {your_plugin_code} は実際のプラグイン ID に置き換えてください
    // リクエストデータを構築
    $data = [
        "input" => [
            'prompt' => 'Dormitory convention content',
            'biz_params' => [
            'user_defined_params' => [
                '{your_plugin_code}' => [
                    '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";}
    }
    ?>
    

    応答サンプル

    寄宿舎規則第 2 条は次のように定めています。寄宿舎のメンバーは互いに助け合い、思いやりを持ち、学び合い、共に成長すること。寛容で謙虚であり、互いを尊重し、誠意を持って接すること。これは、共同生活環境において、ルームメートが前向きな関係を維持し、相互支援を通じて調和のとれた生活・学習環境を育むことが重要であることを強調しています。より具体的な条項について知りたい場合は、お知らせください。
    Node.js

    依存関係:

    npm install axios

    リクエストサンプル

    const axios = require('axios');
    
    async function callDashScope() {
        // 環境変数が設定されていない場合は、次の行を apiKey='sk-xxx' に置き換えることもできます。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
        const apiKey = process.env.DASHSCOPE_API_KEY;
        const appId = 'YOUR_APP_ID';// 実際のアプリケーション ID に置き換えてください
        const pluginCode = 'YOUR_PLUGIN_CODE';// 実際のプラグイン ID に置き換えてください
        const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
    
        const data = {
            input: {
                prompt: "Dormitory convention content",
                biz_params: {
                    user_defined_params: {
                        [pluginCode]: {
                            // article_index はカスタムプラグインの変数です。実際のプラグイン変数に置き換えてください。
                            '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();
    

    応答サンプル

    寄宿舎規則の第 3 条は次のとおりです。
    
    電気の安全に注意し、火災の危険を排除すること。寄宿舎内での明火、無許可の電気機器、各種コンロ、その他の禁止品の使用は厳禁です。爆発物や可燃物の保管、および電源への無断接続も禁止されています。
    
    さらに詳しい規則を知りたい場合は、お知らせください。
    C#

    リクエストサンプル

    using System.Text;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            // 環境変数が設定されていない場合は、次の行を apiKey="sk-xxx" に置き換えることもできます。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
            string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
            string appId = "YOUR_APP_ID";// 実際のアプリケーション ID に置き換えてください
    
            if (string.IsNullOrEmpty(apiKey))
            {
                Console.WriteLine("Make sure you have set DASHSCOPE_API_KEY.");
                return;
            }
    
            string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
    
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
                string pluginCode = "{your_plugin_code}"; // {your_plugin_code} は実際のプラグイン ID に置き換えてください
                string jsonContent = $@"{{
                    ""input"": {{
                        ""prompt"": ""Dormitory convention content"",
                        ""biz_params"": {{
                            ""user_defined_params"": {{
                                ""{pluginCode}"": {{
                                    ""article_index"": 2
                                }}
                            }}
                        }}
                    }},
                    ""parameters"": {{}},
                    ""debug"": {{}}
                }}";
    
                HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
    
                try
                {
                    HttpResponseMessage response = await client.PostAsync(url, content);
    
                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine("Request successful:");
                        Console.WriteLine(responseBody);
                    }
                    else
                    {
                        Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine(responseBody);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error calling DashScope: {ex.Message}");
                }
            }
        }
    }

    応答サンプル

    {
        "output": {
            "finish_reason": "stop",
            "session_id": "237ca6187c814f3b9e7461090a5f8b74",
            "text": "寄宿舎規則の第 2 条は次のとおりです。
            
    \"寄宿舎のメンバーは互いに助け合い、思いやりを持ち、学び合い、共に成長すること。寛容で謙虚であり、互いを尊重し、誠意を持って接すること。\"
    
    これは、寄宿舎内でメンバーが前向きな関係を築き、相互支援・思いやりを通じて調和のとれた生活・学習環境を創ることが求められることを示しています。また、ルームメート間の違いを理解・受容し、誠意あるコミュニケーションを取ることが重要です。他の条項や特定の内容について知りたい場合は、お知らせください!"
        },
        "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() {
    	// 環境変数が設定されていない場合は、次の行を apiKey := "sk-xxx" に置き換えることもできます。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
    	apiKey := os.Getenv("DASHSCOPE_API_KEY")
    	appId := "YOUR_APP_ID"           // 実際のアプリケーション ID に置き換えてください
    	pluginCode := "YOUR_PLUGIN_CODE" // 実際のプラグイン ID に置き換えてください
    
    	if apiKey == "" {
    		fmt.Println("Make sure you have set DASHSCOPE_API_KEY.")
    		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 convention content",
    			"biz_params": map[string]interface{}{
    				"user_defined_params": map[string]interface{}{
    					pluginCode: map[string]interface{}{
    						"article_index": 2,
    					},
    				},
    			},
    		},
    		"parameters": map[string]interface{}{},
    		"debug":      map[string]interface{}{},
    	}
    
    	jsonData, err := json.Marshal(requestBody)
    	if err != nil {
    		fmt.Printf("Failed to marshal JSON: %v\n", err)
    		return
    	}
    
    	// 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))
    	}
    }
    

    応答サンプル

    {
        "output": {
            "finish_reason": "stop",
            "session_id": "860d2a4c1f3649ac880298537993cb51",
            "text": "寄宿舎規則の第 2 条は次のとおりです。
    寄宿舎のメンバーは互いに助け合い、思いやりを持ち、学び合い、共に成長すること。寛容で謙虚であり、互いを尊重し、誠意を持って接すること。
    
    これは、寄宿舎生活において、ルームメートが良好な相互支援を維持しつつ、互いを尊重することが重要であることを強調しています。他の条項について知りたいですか?"
        },
        "usage": {
            "models": [
                {
                    "output_tokens": 84,
                    "model_id": "qwen-max",
                    "input_tokens": 876
                }
            ]
        },
        "request_id": "0a250055-90a4-992d-9276-e268ad35d1ab"
    }
    

    ユーザーレベルの認証

    Python

    リクエストサンプル

    from http import HTTPStatus
    import os
    # 推奨される 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 = {
        # エージェントアプリケーション向けのカスタムプラグイン認証情報の渡し方。your_plugin_code はご利用のカスタムプラグイン ID に、YOUR_TOKEN は認証情報(例:API キー)に置き換えてください。
        "user_defined_params": {
            "your_plugin_code": {
                "article_index": 2}},
        "user_defined_tokens": {
            "your_plugin_code": {
                "user_token": "YOUR_TOKEN"}}}
    response = Application.call(
                # 環境変数が設定されていない場合は、次の行を api_key="sk-xxx" に置き換えることもできます。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
                api_key=os.getenv("DASHSCOPE_API_KEY"), 
                app_id='YOUR_APP_ID',
                prompt='Dormitory convention content',
                biz_params=biz_params)
    
    if response.status_code != HTTPStatus.OK:
        print(f'request_id={response.request_id}')
        print(f'code={response.status_code}')
        print(f'message={response.message}')
        print(f'Refer to: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
    else:
        print('%s\n' % (response.output.text))  # テキスト出力のみを処理
        # print('%s\n' % (response.usage))

    応答サンプル

    寄宿舎規則の第 2 条は次のとおりです。
    
    寄宿舎のメンバーは互いに助け合い、思いやりを持ち、学び合い、共に成長すること。寛容で謙虚であり、互いを尊重し、誠意を持って接すること。
    
    追加の規則についてさらに詳しい情報を必要とされる場合は、お知らせください。
    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 =
                    // {your_plugin_code} は実際のプラグイン ID に、YOUR_TOKEN は実際のトークン(例:API キー)に置き換えてください。
                    "{\"user_defined_params\":{\"{your_plugin_code}\":{\"article_index\":2}}," +
                            "\"user_defined_tokens\":{\"{your_plugin_code}\":{\"user_token\":\"YOUR_TOKEN\"}}}";
            ApplicationParam param = ApplicationParam.builder()
                    // 環境変数が設定されていない場合は、次の行を .apiKey("sk-xxx") に置き換えることもできます。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .appId("YOUR_APP_ID")
                    .prompt("Dormitory convention content")
                    .bizParams(JsonUtils.parse(bizParams))
                    .build();
    
            Application application = new Application();
            ApplicationResult result = application.call(param);
            System.out.printf("%s\n",
                    result.getOutput().getText());
        }
        public static void main(String[] args) {
            try {
                appCall();
            } catch (ApiException | NoApiKeyException | InputRequiredException e) {
                System.out.printf("Exception: %s", e.getMessage());
                System.out.println("Refer to: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code");
            }
            System.exit(0);
        }
    }

    応答サンプル

    寄宿舎規則の第 2 条は次のとおりです。
    
    寄宿舎のメンバーは互いに助け合い、思いやりを持ち、学び合い、共に成長すること。寛容で謙虚であり、互いを尊重し、誠意を持って接すること。
    
    追加の規則についてさらに詳しい情報を必要とされる場合は、お知らせください。
    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": "Dormitory convention content",
            "biz_params": 
            {
                "user_defined_params":
                {
                    "{your_plugin_code}":
                        {
                        "article_index": 2
                        }
                },
                "user_defined_tokens":
                {
                    "{your_plugin_code}":
                        {
                        "user_token": "YOUR_TOKEN"
                        }
                }
            } 
        },
        "parameters":  {},
        "debug":{}
    }'
    
    
    
    YOUR_APP_ID は実際のアプリケーション ID に置き換えてください。

    応答サンプル

    {"output":{"finish_reason":"stop",
    "session_id":"d3b5c3e269dc40479255a7a02df5c630",
    "text":"寄宿舎規則の第 2 条は次のとおりです。「寄宿舎のメンバーは互いに助け合い、思いやりを持ち、学び合い、共に成長すること。寛容で謙虚であり、互いを尊重し、誠意を持って接すること。」これは、寄宿舎生活において、全員が互いに支え合い、調和的で前向きな生活環境を共同で創り出すべきであることを意味しています。"},
    "usage":{"models":[{"output_tokens":80,"model_id":"qwen-max","input_tokens":432}]},
    "request_id":"1f77154c-edc3-9003-b622-816fa2f849cf"}%
    PHP

    リクエストサンプル

    <?php
    
    # 環境変数が設定されていない場合は、Dashscope API キーに置き換えてください:$api_key="sk-xxx"。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
    $api_key = getenv("DASHSCOPE_API_KEY");
    $application_id = 'YOUR_APP_ID'; // 実際のアプリケーション ID に置き換えてください
    $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
    
    // リクエストデータを構築
    $data = [
        "input" => [
            'prompt' => 'Dormitory convention content',
            'biz_params' => [
            'user_defined_params' => [
                '{your_plugin_code}' => [// 実際のプラグイン ID に置き換えてください
                    'article_index' => 2            
                    ]
                ],
            'user_defined_tokens' => [
                '{your_plugin_code}' => [// 実際のプラグイン ID に置き換えてください
                    'user_token' => 'YOUR_TOKEN'// 実際のトークン(例:API キー)に置き換えてください
                ]
            ]
            ]
        ],
    ];
    // データを 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";}
    }
    ?>
    

    応答サンプル

    寄宿舎規則の第 2 条は次のとおりです。
    
    > 寄宿舎のメンバーは互いに助け合い、思いやりを持ち、学び合い、共に成長すること。寛容で謙虚であり、互いを尊重し、誠意を持って接すること。
    
    規則やその他の詳細についてさらに情報を必要とされる場合は、遠慮なくお知らせください!
    Node.js

    依存関係:

    npm install axios

    リクエストサンプル

    const axios = require('axios');
    async function callDashScope() {
        // 環境変数が設定されていない場合は、次の行を apiKey='sk-xxx' に置き換えることもできます。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
        const apiKey = process.env.DASHSCOPE_API_KEY;
        const appId = 'YOUR_APP_ID';// 実際のアプリケーション ID に置き換えてください
        const pluginCode = 'YOUR_PLUGIN_CODE';// 実際のプラグイン ID に置き換えてください
        const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
    
        const data = {
            input: {
                prompt: "Dormitory convention content",
                biz_params: {
                    user_defined_params: {
                        [pluginCode]: {
                            // article_index はカスタムプラグインの変数です。実際のプラグイン変数に置き換えてください。
                            'article_index': 6
                        }
                    },
                    user_defined_tokens: {
                        [pluginCode]: {
                            // YOUR_TOKEN は実際の認証情報(例:API キー)に置き換えてください。
                            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();

    応答サンプル

    寄宿舎規則の第 6 条は次のように定めています。日常生活における良好な習慣を身につけること。すべての寄宿舎メンバーは休息する権利を持ち、他者の休息権を確保する責任があります。規則についてさらに詳しい情報を必要とされる場合は、お知らせください。
    C#

    リクエストサンプル

    using System.Text;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            // 環境変数が設定されていない場合は、次の行を apiKey="sk-xxx" に置き換えることもできます。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
            string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
            string appId = "YOUR_APP_ID";// 実際のアプリケーション ID に置き換えてください
    
            if (string.IsNullOrEmpty(apiKey))
            {
                Console.WriteLine("Make sure you have set DASHSCOPE_API_KEY.");
                return;
            }
    
            string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
    
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
                string pluginCode = "your_plugin_code"; // your_plugin_code は実際のプラグイン ID に置き換えてください
                // YOUR_TOKEN は実際のトークン(例:API キー)に置き換えてください
                string jsonContent = $@"{{
                    ""input"": {{
                        ""prompt"": ""Dormitory convention content"",
                        ""biz_params"": {{
                            ""user_defined_params"": {{
                                ""{pluginCode}"": {{
                                    ""article_index"": 2
                                }}
                            }},
                            ""user_defined_tokens"": {{
                                ""{pluginCode}"": {{
                                    ""user_token"": ""YOUR_TOKEN"" 
                                }}
                            }}
                        }}
                    }},
                    ""parameters"": {{}},
                    ""debug"": {{}}
                }}";
    
                HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
    
                try
                {
                    HttpResponseMessage response = await client.PostAsync(url, content);
    
                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine("Request successful:");
                        Console.WriteLine(responseBody);
                    }
                    else
                    {
                        Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine(responseBody);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error calling DashScope: {ex.Message}");
                }
            }
        }
    }

    応答サンプル

    {
        "output": {
            "finish_reason": "stop",
            "session_id": "1a1913a9922a401f8eba36df8ea1a062",
            "text": "寄宿舎規則の第 2 条は次のとおりです。
            
    寄宿舎のメンバーは互いに助け合い、思いやりを持ち、学び合い、共に成長すること。寛容で謙虚であり、互いを尊重し、誠意を持って接すること。
    
    他の条項や特定の内容について知りたい場合は、お知らせください!"
        },
        "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() {
    	// 環境変数が設定されていない場合は、次の行を apiKey := "sk-xxx" に置き換えることもできます。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
    	apiKey := os.Getenv("DASHSCOPE_API_KEY")
    	appId := "YOUR_APP_ID"           // 実際のアプリケーション ID に置き換えてください
    	pluginCode := "YOUR_PLUGIN_CODE" // 実際のプラグイン ID に置き換えてください
    
    	if apiKey == "" {
    		fmt.Println("Make sure you have set DASHSCOPE_API_KEY.")
    		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 convention content",
    			"biz_params": map[string]interface{}{
    				"user_defined_params": map[string]interface{}{
    					pluginCode: map[string]interface{}{
    						"article_index": 10,
    					},
    				},
    				"user_defined_tokens": map[string]interface{}{
    					pluginCode: map[string]interface{}{
    						"user_token": "YOUR_USER_TOKEN", // 実際の認証トークン(例:API キー)に置き換えてください
    					},
    				},
    			},
    		},
    		"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))
    	}
    }
    

    応答サンプル

    {
        "output": {
            "finish_reason": "stop",
            "session_id": "b8e051ba7e954ff8919208e7b84430fa",
            "text": "寄宿舎規則の第 10 条は、寄宿舎のメンバーが協力して清潔で整然とした、美しく文化的な寄宿舎環境を創造・維持すべきであると定めています。寄宿舎規則の全文を理解するには、他の条項を確認するか、直接寄宿舎管理部門に問い合わせる必要があります。さらに具体的な内容を知りたいことはありますか?"
        },
        "usage": {
            "models": [
                {
                    "output_tokens": 70,
                    "model_id": "qwen-max",
                    "input_tokens": 855
                }
            ]
        },
        "request_id": "0921ee34-2754-9616-a826-cea33a0e0a14"
    }
    
  2. カスタムノードパラメーター: ワークフローアプリケーションスタートノード、または エージェントオーケストレーションアプリケーションアプリケーションノード を通じて渡します。

    次のサンプルでは、[ワークフローアプリケーション][開始ノード] でパラメーター city を定義します。[プロンプト] に変数 cityquery を挿入してから、アプリケーションを [公開] します。

    image

    呼び出し時 は、biz_params を通じて city を渡し、prompt を通じて query を渡します。

    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'
    # ワークフローおよびエージェントオーケストレーションアプリケーション向けのカスタムパラメーターの渡し方
    biz_params = {"city": "Hangzhou"}
    response = Application.call(
        # 環境変数が設定されていない場合は、次の行を api_key="sk-xxx" に置き換えることもできます。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        app_id='YOUR_APP_ID',  # 実際のアプリケーション ID に置き換えてください
        prompt='Query the administrative divisions of this city',
        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'Refer to: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
    else:
        print(f'{response.output.text}')  # テキスト出力のみを処理

    応答サンプル

    杭州市は浙江省の省都であり、行政区分は上城区、拱墅区、西湖区、浜江区、蕭山区、余杭区、臨平区、銭塘区、富陽区、臨安区の 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\":\"Hangzhou\"}";
            ApplicationParam param = ApplicationParam.builder()
                    // 環境変数が設定されていない場合は、次の行を .apiKey("sk-xxx") に置き換えることもできます。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .appId("YOUR_APP_ID")
                    .prompt("Query the administrative divisions of this city")
                    .bizParams(JsonUtils.parse(bizParams))
                    .build();
    
            Application application = new Application();
            ApplicationResult result = application.call(param);
            System.out.printf("%s\n",
                    result.getOutput().getText());
        }
    
        public static void main(String[] args) {
            try {
                appCall();
            } catch (ApiException | NoApiKeyException | InputRequiredException e) {
                System.out.printf("Exception: %s", e.getMessage());
                System.out.println("Refer to: 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": "Query the administrative divisions of this city",
            "biz_params": {
            "city": "Hangzhou"}
        },
        "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="sk-xxx"。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
    $api_key = getenv("DASHSCOPE_API_KEY");
    $application_id = 'YOUR_APP_ID'; // 実際のアプリケーション ID に置き換えてください
    $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
    
    // リクエストデータを構築
    $data = [
        "input" => [
            'prompt' => 'Query the administrative divisions of this city',
            'biz_params' => [
                'city' => 'Hangzhou'
            ]
        ],
    ];
    // データを 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";
        }
    }
    

    応答サンプル

    杭州市は浙江省の省都であり、行政区分は主に上城区、拱墅区、西湖区、浜江区、蕭山区、余杭区、臨平区、銭塘区、富陽区、臨安区の 10 区で構成されています。
    
    各区にはそれぞれ独自の特徴と開発重点があり、例えば:
    - **上城区**および**拱墅区**は杭州市の中心部に位置し、活気ある商業と豊かな歴史で知られています。
    - **西湖区**は美しい西湖で有名で、科学・教育・文化の重要なエリアでもあります。
    - **浜江区**はハイテク産業の発展で知られています。
    - **蕭山区**や**余杭区**などは、近年の都市成長により、新しい都市地区または経済開発区として急速に台頭しています。
    - **臨安区**および**富陽区**は、より多くの自然景観と田園的な魅力を保っています。
    
    中国の行政区分は国の政策に基づいて変更される可能性があるため、最新の情報を公式チャネルでご確認ください。
    Node.js

    依存関係:

    npm install axios

    リクエストサンプル

    const axios = require('axios');
    
    async function callDashScope() {
        // 環境変数が設定されていない場合は、次の行を apiKey='sk-xxx' に置き換えることもできます。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
        const apiKey = process.env.DASHSCOPE_API_KEY;
        const appId = 'YOUR_APP_ID'; // 実際のアプリケーション ID に置き換えてください
    
        const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
    
        const data = {
            input: {
                prompt: "Query the administrative divisions of this city",
                biz_params: {
                    'city': 'Hangzhou',
                },
            },
            parameters: {},
            debug: {},
        };
    
        try {
            console.log("Sending request to DashScope API...");
    
            const response = await axios.post(url, data, {
                headers: {
                    'Authorization': `Bearer ${apiKey}`,
                    'Content-Type': 'application/json'
                }
            });
    
            if (response.status === 200) {
                if (response.data.output && response.data.output.text) {
                    console.log(`${response.data.output.text}`);
                }
            } else {
                console.log("Request failed:");
                if (response.data.request_id) {
                    console.log(`request_id=${response.data.request_id}`);
                }
                console.log(`code=${response.status}`);
                if (response.data.message) {
                    console.log(`message=${response.data.message}`);
                } else {
                    console.log('message=Unknown error');
                }
            }
        } catch (error) {
            console.error(`Error calling DashScope: ${error.message}`);
            if (error.response) {
                console.error(`Response status: ${error.response.status}`);
                console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
            }
        }
    }
    
    callDashScope();
    

    応答サンプル

    杭州市は浙江省の省都であり、行政区分は 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)
        {
            //環境変数が設定されていない場合は、次の行を apiKey="sk-xxx" に置き換えることもできます。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。 
            string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
            string appId = "YOUR_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"": ""Query the administrative divisions of this city"",
                        ""biz_params"":{
                            ""city"":""Hangzhou""
                        }
                    },
                    ""parameters"": {},
                    ""debug"": {}
                }";
    
                HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
    
                try
                {
                    HttpResponseMessage response = await client.PostAsync(url, content);
    
                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine("Request successful:");
                        Console.WriteLine(responseBody);
                    }
                    else
                    {
                        Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine(responseBody);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error calling DashScope: {ex.Message}");
                }
            }
        }
    }

    応答サンプル

    {
        "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() {
    	// 環境変数が設定されていない場合は、次の行を apiKey := "sk-xxx" に置き換えることもできます。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
    	apiKey := os.Getenv("DASHSCOPE_API_KEY")
    	appId := "YOUR_APP_ID" // 実際のアプリケーション ID に置き換えてください
    
    	if apiKey == "" {
    		fmt.Println("Make sure you have set DASHSCOPE_API_KEY.")
    		return
    	}
    
    	url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
    
    	// リクエストボディを作成
    	requestBody := map[string]interface{}{
    		"input": map[string]interface{}{
    			"prompt": "Query the administrative divisions of this city",
    			"biz_params": map[string]interface{}{
    				"city": "Hangzhou",
    			},
    		},
    		"parameters": map[string]interface{}{},
    		"debug":      map[string]interface{}{},
    	}
    
    	jsonData, err := json.Marshal(requestBody)
    	if err != nil {
    		fmt.Printf("Failed to marshal JSON: %v\n", err)
    		return
    	}
    
    	// 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))
    	}
    }
    

    応答サンプル

    {
        "output": {
            "finish_reason": "stop",
            "session_id": "2dc3e1a9dcd248c6bb9ca92bffc3e745",
            "text": "杭州市(略称「杭」)は浙江省の省都です。最新の行政区分調整によると、杭州市は現在 10 区、2 県級市、1 県を管轄しています。具体的には以下のとおりです。
    
    - 区(10):上城区、拱墅区、西湖区、浜江区、蕭山区、余杭区、臨平区、銭塘区、富陽区、臨安区。
    - 県級市(2):建徳市、桐廬県(注:桐廬はここでは県級市として扱われていますが、より正確には県です)。
    - 県(1):淳安県。
    
    行政区域は時間とともに変更される可能性があるため、最新の公式発表をご確認ください。上記の情報は比較的新しいデータに基づいて編集されていますが、最新の変更については政府の公式ウェブサイトを訪問し、最も正確な情報を入手することをお勧めします。"
        },
        "usage": {
    
        },
        "request_id": "d3c8f368-b645-9446-bfe4-20ca51821a02"
    }

ストリーミング出力

ストリーミング出力モードでは、モデルが中間結果を生成し、最終結果はこれらのすべての中間結果を連結して形成されます。モデルの出力を読み取りながら処理できるため、モデルの応答を待つ時間を短縮できます。呼び出し方法に応じて、以下のパラメーターを設定することでストリーミング出力を実現できます。

  • Python SDK: stream を True に設定します。

  • Java SDK: streamCall インターフェイス経由で呼び出します。

  • HTTP: リクエストヘッダーで X-DashScope-SSEenable に指定します。

デフォルトでは、ストリーミング出力は非増分(non-incremental)であり、各レスポンスにはそれまでに生成されたすべてのコンテンツが含まれます。 増分ストリーミング出力を使用するには、incremental_output(Java の場合は incrementalOutput)パラメーターを true に設定してください。HTTP の場合、incremental_output を true に設定し、parameters オブジェクト内に配置します。

例:

  • エージェントアプリケーションの場合:

    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" に置き換えてください。ただし、本番環境では API キーをコード内にハードコードすると漏洩リスクが高まるため、推奨されません。
                api_key=os.getenv("DASHSCOPE_API_KEY"), 
                app_id='YOUR_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'詳細については、「https://www.alibabacloud.com/help/ja/model-studio/developer-reference/error-code」をご参照ください。')
        else:
            print(f'{response.output.text}\n')  # テキストのみを出力する処理

    レスポンス例

    I am
    
    Alibaba
    
    Cloud
    
    's large-scale language model
    
    , my name is
    
    Qwen.

    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") に置き換えてください。ただし、本番環境では API キーをコード内にハードコードすると漏洩リスクが高まるため、推奨されません。
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    // 実際のアプリケーション ID に置き換えてください
                    .appId("YOUR_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("詳細については、「https://www.alibabacloud.com/help/ja/model-studio/developer-reference/error-code」をご参照ください。");
            }
            System.exit(0);
        }
    }

    レスポンス例

    I am Alibaba
    Cloud
    's large-scale language
    model, my name is
    Qwen
    .

    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' \
    --header 'X-DashScope-SSE: enable' \
    --data '{
        "input": {
            "prompt": "Who are you?"
    
        },
        "parameters":  {
            "incremental_output":true
        },
        "debug": {}
    }'
    YOUR_APP_ID は実際のアプリケーション ID に置き換えてください。

    レスポンス例

    id:1
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"I"},"usage":{"models":[{"input_tokens":203,"output_tokens":1,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}
    
    id:2
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"am"},"usage":{"models":[{"input_tokens":203,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}
    
    id:3
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":" Alibaba"},"usage":{"models":[{"input_tokens":203,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}
    
    id:4
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":" Cloud"},"usage":{"models":[{"input_tokens":203,"output_tokens":4,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}
    
    id:5
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"'s large-scale language"},"usage":{"models":[{"input_tokens":203,"output_tokens":8,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}
    
    id:6
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":" model, my name is"},"usage":{"models":[{"input_tokens":203,"output_tokens":12,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}
    
    id:7
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":" Qwen"},"usage":{"models":[{"input_tokens":203,"output_tokens":16,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}
    
    id:8
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"."},"usage":{"models":[{"input_tokens":203,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}
    
    id:9
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":203,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}
    PHP

    リクエスト例

    <?php
    
    // 環境変数が設定されていない場合は、次の行を $api_key="sk-xxx" に置き換えてください。ただし、本番環境では API キーをコード内にハードコードすると漏洩リスクが高まるため、推奨されません。
    $api_key = getenv("DASHSCOPE_API_KEY");
    $application_id = 'YOUR_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";
    }
    ?>

    レスポンス例

    id:1
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":"I am Alibaba"},"usage":{"models":[{"input_tokens":58,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"}
    id:2
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":" Cloud"},"usage":{"models":[{"input_tokens":58,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"}
    id:3
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":"'s"},"usage":{"models":[{"input_tokens":58,"output_tokens":4,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"}
    id:4
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":" a large-scale language"},"usage":{"models":[{"input_tokens":58,"output_tokens":8,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"}
    id:5
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":" model, my name is"},"usage":{"models":[{"input_tokens":58,"output_tokens":12,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"}
    id:6
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":" Qwen"},"usage":{"models":[{"input_tokens":58,"output_tokens":16,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"}
    id:7
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":"."},"usage":{"models":[{"input_tokens":58,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"}
    id:8
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":58,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"}
    
    Node.js

    依存関係:

    npm install axios

    リクエスト例

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

    const axios = require('axios');
    
    async function callDashScope() {
        // 環境変数が設定されていない場合は、次の行を apiKey='sk-xxx' に置き換えてください。ただし、本番環境では API キーをコード内にハードコードすると漏洩リスクが高まるため、推奨されません。
        const apiKey = process.env.DASHSCOPE_API_KEY;
        const appId = 'YOUR_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' に置き換えてください。ただし、本番環境では API キーをコード内にハードコードすると漏洩リスクが高まるため、推奨されません。
        const apiKey = process.env.DASHSCOPE_API_KEY;
        const appId = 'YOUR_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) {
                // // ストリーミングレスポンス 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("Pipeline 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();

    レスポンス例

    1. 完全なレスポンスを出力
    id:1
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"null","text":"Hello!"},"usage":{"models":[{"input_tokens":56,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"}
    id:2
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"null","text":" Is there"},"usage":{"models":[{"input_tokens":56,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"}
    id:3
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"null","text":" anything I can"},"usage":{"models":[{"input_tokens":56,"output_tokens":4,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"}
    id:4
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"null","text":" help you with?"},"usage":{"models":[{"input_tokens":56,"output_tokens":7,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"}
    id:5
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":56,"output_tokens":7,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"}
    2. テキストフィールドのみを出力
    I am
    Alibaba
    Cloud
    's large-scale
    language model, I
    am called 
    Qwen.
    C#

    リクエスト例

    using System.Net;
    using System.Text;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            // 環境変数が設定されていない場合は、次の行を apiKey="sk-xxx" に置き換えてください。ただし、本番環境では API キーをコード内にハードコードすると漏洩リスクが高まるため、推奨されません。
            string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
            string appId = "YOUR_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}");
                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}");
                }
            }
        }
    }

    レスポンス例

    2025-02-14 16:22:08:482
    Request successful:
    2025-02-14 16:22:09:098
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"I"},"usage":{"models":[{"input_tokens":51,"output_tokens":1,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:09:099
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" am"},"usage":{"models":[{"input_tokens":51,"output_tokens":2,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:09:172
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" Alibaba"},"usage":{"models":[{"input_tokens":51,"output_tokens":3,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:09:172
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" Cloud's large-scale language"},"usage":{"models":[{"input_tokens":51,"output_tokens":7,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:09:463
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" model, my name is"},"usage":{"models":[{"input_tokens":51,"output_tokens":11,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:09:618
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" Qwen"},"usage":{"models":[{"input_tokens":51,"output_tokens":15,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:09:777
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":". I am your AI"},"usage":{"models":[{"input_tokens":51,"output_tokens":19,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:09:932
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" assistant,"},"usage":{"models":[{"input_tokens":51,"output_tokens":23,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:10:091
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" I can answer questions,"},"usage":{"models":[{"input_tokens":51,"output_tokens":27,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:10:244
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" create text, such as"},"usage":{"models":[{"input_tokens":51,"output_tokens":31,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:10:389
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" writing stories, writing"},"usage":{"models":[{"input_tokens":51,"output_tokens":35,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:10:525
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" documents, writing"},"usage":{"models":[{"input_tokens":51,"output_tokens":39,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:10:662
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" emails, writing scripts"},"usage":{"models":[{"input_tokens":51,"output_tokens":43,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:10:902
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":", and I can also express"},"usage":{"models":[{"input_tokens":51,"output_tokens":47,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:11:062
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" opinions, play games, etc"},"usage":{"models":[{"input_tokens":51,"output_tokens":51,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:11:233
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"."},"usage":{"models":[{"input_tokens":51,"output_tokens":52,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:11:309
    {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":51,"output_tokens":52,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"}
    2025-02-14 16:22:11:388
    Go

    リクエスト例

    package main
    
    import (
    	"bytes"
    	"encoding/json"
    	"fmt"
    	"io"
    	"net/http"
    	"os"
    	"strings"
    	"time"
    )
    
    func main() {
    	// 環境変数が設定されていない場合は、次の行を apiKey := "sk-xxx" に置き換えてください。ただし、本番環境では API キーをコード内にハードコードすると漏洩リスクが高まるため、推奨されません。
    	apiKey := os.Getenv("DASHSCOPE_API_KEY")
    	appId := "YOUR_APP_ID" // 実際のアプリケーション ID に置き換えてください
    
    	if apiKey == "" {
    		fmt.Println("Please ensure DASHSCOPE_API_KEY is set.")
    		return
    	}
    
    	url := fmt.Sprintf("https://dashscope-intl.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
    		}
    	}
    }
    

    レスポンス例

    id:1
    event:result
    :HTTP_STATUS/200
    2025-02-13 18:21:09.050: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":"I am"},"usage":{"models":[{"input_tokens":262,"output_tokens":1,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
    id:2
    event:result
    :HTTP_STATUS/200
    2025-02-13 18:21:10.016: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" Tong"},"usage":{"models":[{"input_tokens":262,"output_tokens":2,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
    id:3
    event:result
    :HTTP_STATUS/200
    2025-02-13 18:21:10.016: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":"yi"},"usage":{"models":[{"input_tokens":262,"output_tokens":3,"model_id":"qwen-plus"}]},"request_id:4
    event:result
    :HTTP_STATUS/200
    2025-02-13 18:21:10.016: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" Qianwen, developed by"},"usage":{"models":[{"input_tokens":262,"output_tokens":7,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
    id:5
    event:result
    :HTTP_STATUS/200
    2025-02-13 18:21:10.017: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" Alibaba Cloud"},"usage":{"models":[{"input_tokens":262,"output_tokens":11,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
    id:6
    event:result
    :HTTP_STATUS/200
    2025-02-13 18:21:10.017: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":", an AI assistant. I"},"usage":{"models":[{"input_tokens":262,"output_tokens":15,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
    id:7
    event:result
    :HTTP_STATUS/200
    2025-02-13 18:21:10.017: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" am designed to answer"},"usage":{"models":[{"input_tokens":262,"output_tokens":19,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
    id:8
    event:result
    :HTTP_STATUS/200
    2025-02-13 18:21:10.018: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" various questions, provide"},"usage":{"models":[{"input_tokens":262,"output_tokens":23,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
    id:9
    event:result
    :HTTP_STATUS/200
    2025-02-13 18:21:10.102: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" information and engage"},"usage":{"models":[{"input_tokens":262,"output_tokens":27,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
    id:10
    event:result
    :HTTP_STATUS/200
    2025-02-13 18:21:10.257: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" in conversations. Need"},"usage":{"models":[{"input_tokens":262,"output_tokens":31,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
    id:11
    event:result
    :HTTP_STATUS/200
    2025-02-13 18:21:10.414: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" any help?"},"usage":{"models":[{"input_tokens":262,"output_tokens":34,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
    id:12
    event:result
    :HTTP_STATUS/200
    2025-02-13 18:21:10.481: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":262,"output_tokens":34,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}
  • ワークフローアプリケーションには、flow_stream_mode の値によって決定される 2 つのストリーミング出力モードがあります。

    パラメーター値と使用方法:

    • full_thoughts(デフォルト値):

      • 説明:すべてのノードの中間結果が thoughts フィールドに出力されます。

      • 要件:has_thoughts を True に設定する必要があります。

    • agent_format

      • 説明:エージェントアプリケーションと同じ出力モードです。

      • 効果:コンソールで特定のノードの 応答 スイッチをオンにすると、そのノードのストリーミング結果が outputtext フィールドに含まれます。

      • シナリオ:特定の中間ノードの出力のみに関心があるシナリオに適しています。

      応答 スイッチは、テキスト変換ノード、LLM ノード、および終了ノードでのみ利用可能です(終了ノードではデフォルトでオンになっています)。ストリーミング出力をサポートしないノードは、一度にすべてのコンテンツを出力します。

    例:

    full_thoughts

    これは公開済みの ワークフローアプリケーションで、ストリーミング出力が有効になっています。

    image

    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'
    biz_params = {
        "city": "Hangzhou"}
    responses = Application.call(
        # 環境変数が設定されていない場合は、次の行を api_key="sk-xxx" に置き換えてください。ただし、本番環境では API キーをコード内にハードコードすると漏洩リスクが高まるため、推奨されません。
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        # 実際のアプリケーション ID に置き換えてください
        app_id='YOUR_APP_ID',
        prompt='Hello',
        biz_params=biz_params,
        # ストリーミング出力を有効化
        stream=True,
        # incremental_output=true で増分出力が有効になり、false で無効になります。指定しない場合のデフォルトは false です
        incremental_output=True,
        # has_thoughts を True に設定する必要があります
        has_thoughts=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'詳細については、「https://www.alibabacloud.com/help/ja/model-studio/developer-reference/error-code」をご参照ください。')
        else:
            print(f'{response.output.thoughts}\n')  # thoughts のみを返すように出力を処理します。プロセス情報は output の thoughts フィールドに返されます

    レスポンス例

    [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_99FA","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_99FA"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
    
    [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\"Dongpo\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_99FA"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
    
    [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\" Pork, West Lake Vinegar Fish,\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_99FA"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
    
    [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\" Longjing Shrimp, Hangzhou Pa\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_99FA"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
    
    [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\"stry, Beggar\'s Chicken\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_99FA","nodeExecTime":"1027ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_qkYJ","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_qkYJ"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
    
    [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_99FA","nodeExecTime":"1027ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_2","nodeResult":"{\\"result\\":\\"West Lake,\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_qkYJ"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
    
    [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_99FA","nodeExecTime":"1027ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_2","nodeResult":"{\\"result\\":\\" Lingyin Temple, Xixi\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_qkYJ"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
    
    [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_99FA","nodeExecTime":"1027ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_2","nodeResult":"{\\"result\\":\\" National Wetland Park, Hefang\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_qkYJ"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
    
    [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_99FA","nodeExecTime":"1027ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_2","nodeResult":"{\\"result\\":\\" Street, Hangzhou Botanical Garden\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_qkYJ"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
    
    [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_99FA","nodeExecTime":"1027ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_2","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_qkYJ","nodeExecTime":"1048ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"End","nodeResult":"{\\"result\\":\\"What do you think about our recommendation?\\"}","nodeType":"End","nodeStatus":"success","nodeId":"End_DrQn7F","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
    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 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 streamCall() throws NoApiKeyException, InputRequiredException {
            String bizParams =
                    "{\"city\":\"Hangzhou\"}";
            ApplicationParam param = ApplicationParam.builder()
                    // 環境変数が設定されていない場合は、次の行を .apiKey("sk-xxx") に置き換えてください。ただし、本番環境では API キーをコード内にハードコードすると漏洩リスクが高まるため、推奨されません。
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .appId("YOUR_APP_ID") //実際のアプリケーション ID に置き換えてください
                    .prompt("Hello")
                    .bizParams(JsonUtils.parse(bizParams))
                    .incrementalOutput(true) // 増分出力
                    .hasThoughts(true) // ワークフローアプリケーションでストリーミング出力を実現するには、このパラメーターを true に設定する必要があります。出力結果は thoughts フィールドで確認できます
                    .build();
    
            Application application = new Application();
            Flowable<ApplicationResult> result = application.streamCall(param); // ストリーミング出力を実現
            result.blockingForEach(data -> {
                System.out.printf("%s\n",data.getOutput().getThoughts());// thoughts フィールドのみを表示するように出力を処理
            });
        }
    
        public static void main(String[] args) {
            try {
                streamCall();
            } catch (ApiException | NoApiKeyException | InputRequiredException e) {
                System.out.printf("Exception: %s", e.getMessage());
                System.out.println("詳細については、「https://www.alibabacloud.com/help/ja/model-studio/developer-reference/error-code」をご参照ください。");
            }
            System.exit(0);
        }
    }

    レスポンス例

    [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_S78u","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_S78u"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)]
    [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"西湖醋魚,\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_S78u"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)]
    [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"龍井蝦仁\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_S78u"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)]
    [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\",東坡肉,知味小\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_S78u"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)]
    [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"蒸し饅頭,叫化鶏\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_S78u"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)]
    [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_5ZzA","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_5ZzA"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)]
    [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_jjc0","nodeResult":"{\"result\":\"西湖,\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_5ZzA"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)]
    [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_jjc0","nodeResult":"{\"result\":\"霊隠\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_5ZzA"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)]
    [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_jjc0","nodeResult":"{\"result\":\"寺,宋城\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_5ZzA"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)]
    [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_jjc0","nodeResult":"{\"result\":\",西渓湿地,千島湖\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_5ZzA"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)]
    [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_jjc0","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_5ZzA","nodeExecTime":"938ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"End","nodeResult":"{\"result\":\"西湖,霊隠寺,宋城,西渓湿地,千島湖\"}","nodeType":"End","nodeStatus":"success","nodeId":"End_DrQn7F","nodeExecTime":"5ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)]
    HTTP
    curl

    リクエスト例

    curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
    --header 'X-DashScope-SSE: enable' \
    --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
    --header 'Content-Type: application/json' \
    --data '{
        "input": {
            "prompt": "Hello",
            "biz_params": {
            "city": "Hangzhou"}
        },
        "parameters":  {
            "has_thoughts": true,
            "incremental_output": true
        },
        "debug": {}
    }'
    YOUR_APP_ID は実際のアプリケーション ID に置き換えてください。

    レスポンス例

    id:1
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
    
    id:2
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
    
    id:3
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_j45e\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
    
    id:4
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"West Lake Fish in Vinegar Sauce,Long\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":5,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
    
    id:5
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"jing Shrimp,Dongpo Pork,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":13,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
    
    id:6
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"Beggar's Chicken,Song\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":18,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
    
    id:7
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"cheng Fish Soup\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"LLM_2Km9\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
    
    id:8
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
    
    id:9
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"Ling\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
    
    id:10
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"yin Temple,Songcheng,Xixi\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":11,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
    
    id:11
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\" National Wetland Park,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
    
    id:12
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"Hangzhou Zoo\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_2Km9\",\"nodeExecTime\":\"1137ms\"}"},{"response":"{\"nodeName\":\"End\",\"nodeResult\":\"{\\\"result\\\":\\\"Dear, are you satisfied with my introduction\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"1ms\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"stop","text":"Dear, are you satisfied with my introduction"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
    PHP

    リクエスト例

    <?php
    
    # 環境変数が設定されていない場合は、次の行を $api_key="sk-xxx" に置き換えてください。ただし、本番環境では API キーをコード内にハードコードすると漏洩リスクが高まるため、推奨されません。
    $api_key = getenv("DASHSCOPE_API_KEY");
    $application_id = 'YOUR_APP_ID'; // 実際のアプリケーション ID に置き換えてください
    
    $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
    
    // リクエストデータを構築
    $data = [
        "input" => [
            'prompt' => 'Hello',
            'biz_params' => [
                'city' => 'Hangzhou'
            ]
        ],
        "parameters" => [
            'has_thoughts' => true, // ワークフローアプリケーションおよびオーケストレーションアプリケーションの場合、このパラメーターを true に設定する必要があります。プロセス情報は thoughts に返されます
            '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";
    }
    ?>

    レスポンス例

    id:1
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"}
    id:2
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Ilo9\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"}
    id:3
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"West Lake Fish in Vinegar Sauce\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"}
    id:4
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\",\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"}
    id:5
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"Dongpo Pork,Zhiwei Steamed\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"}
    id:6
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\",Longjing Shrimp\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"requestid:7
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\",Beggar's Chicken\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"}
    id:8
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"LLM_vQDv\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"}
    id:9
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"LLM_kBgf\",\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,Lingyin\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"}
    id:10
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"LLM_kBgf\",\"nodeResult\":\"{\\\"result\\\":\\\" Temple,Songcheng\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"}
    id:11
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"LLM_kBgf\",\"nodeResult\":\"{\\\"result\\\":\\\",Xixi Wetland\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"}
    id:12
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"LLM_kBgf\",\"nodeResult\":\"{\\\"result\\\":\\\",Hangzhou Tower\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_vQDv\",\"nodeExecTime\":\"899ms\"}"},{"response":"{\"nodeName\":\"End\",\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,Lingyin Temple,Songcheng,Xixi Wetland,Hangzhou Tower\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"0ms\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"stop","text":"West Lake,Lingyin Temple,Songcheng,Xixi Wetland,Hangzhou Tower"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"}
    
    Node.js

    依存関係

    npm install axios

    リクエスト例

    const axios = require('axios');
    
    async function callDashScope() {
        // 環境変数が設定されていない場合は、次の行を apiKey='sk-xxx' に置き換えてください。ただし、本番環境では API キーをコード内にハードコードすると漏洩リスクが高まるため、推奨されません。
        const apiKey = process.env.DASHSCOPE_API_KEY;
        const appId = 'YOUR_APP_ID';// 実際のアプリケーション ID に置き換えてください
    
        const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
    
        const data = {
            input: {
                prompt: "hello",
                biz_params:{
                    'city':'Hangzhou'
                }
            },
            parameters: {
                'incremental_output' : 'true',
                'has_thoughts':'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) {
                console.log("Request successful:");
    
                // ストリーミングレスポンスを処理
                response.data.on('data', (chunk) => {
                    console.log(`Received chunk: ${chunk.toString()}`);
                });
    
                response.data.on('end', () => {
                    console.log("Stream ended.");
                });
    
                response.data.on('error', (error) => {
                    console.error(`Stream error: ${error.message}`);
                });
            } 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();

    レスポンス例

    /opt/homebrew/bin/node ./index.js
    Sending request to DashScope API...
    Request successful:
    Received chunk: id:1
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
    Received chunk: id:2
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
    Received chunk: id:3
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"West Lake Fish\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
    Received chunk: id:4
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\" in Vinegar Sauce,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
    Received chunk: id:5
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Longjing Shrimp\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
    Received chunk: id:6
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",Dongpo Pork\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
    Received chunk: id:7
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",Zhiwei\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
    Received chunk: id:8
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\" Steamed Buns,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
    Received chunk: id:9
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Beggar's Chicken\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
    Received chunk: id:10
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
    Received chunk: id:11
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Lingyin\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
    Received chunk: id:12
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\" Temple,Songcheng,Xixi Wetland\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
    Received chunk: id:13
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",Thousand Island Lake\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
    Received chunk: id:14
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_5ZzA\",\"nodeExecTime\":\"855ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,Lingyin Temple,Songcheng,Xixi Wetland,Thousand Island Lake\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"1ms\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"stop","text":"West Lake,Lingyin Temple,Songcheng,Xixi Wetland,Thousand Island Lake"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
    Stream ended.
    C#

    リクエスト例

    using System.Net;
    using System.Text;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            // 環境変数が設定されていない場合は、次の行を apiKey="sk-xxx" に置き換えてください。ただし、本番環境では API キーをコード内にハードコードすると漏洩リスクが高まるため、推奨されません。
            string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
            string appId = "YOUR_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}");
                client.DefaultRequestHeaders.Add("X-DashScope-SSE", "enable");
    
                string jsonContent = @"{
                    ""input"": {
                        ""prompt"": ""Hello"",
                        ""biz_params"":{
                            ""city"":""Hangzhou""
                        }
                    },
                    ""parameters"": {
                        ""incremental_output"": true,
                        ""has_thoughts"": 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}");
                }
            }
        }
    }

    レスポンス例

    2025-02-14 16:55:28:670
    Request successful:
    2025-02-14 16:55:28:980
    {"output":{"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
    2025-02-14 16:55:28:980
    {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
    2025-02-14 16:55:28:980
    {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_j45e\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
    2025-02-14 16:55:29:178
    {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"West Lake Fish in Vinegar Sauce,Long\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":5,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
    2025-02-14 16:55:29:780
    {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"jing Shrimp,Dongpo Pork,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":13,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
    2025-02-14 16:55:29:979
    {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"Zhiwei Steamed Buns,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":18,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
    2025-02-14 16:55:30:179
    {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"Beggar's Chicken\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1315ms\"}"},{"response":"{\"nodeName\":\"LLM_2Km9\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
    2025-02-14 16:55:30:379
    {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1315ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
    2025-02-14 16:55:30:986
    {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1315ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"Lingyin Temple,Song\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":7,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
    2025-02-14 16:55:31:180
    {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1315ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"cheng,Xixi Wetland,Thousand Island Lake\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_2Km9\",\"nodeExecTime\":\"1008ms\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":16,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
    2025-02-14 16:55:31:382
    {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1315ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_2Km9\",\"nodeExecTime\":\"1008ms\"}"},{"response":"{\"nodeName\":\"End\",\"nodeResult\":\"{\\\"result\\\":\\\"Dear, are you satisfied with my introduction\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"0ms\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"stop","text":"Dear, are you satisfied with my introduction"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":16,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
    2025-02-14 16:55:31:751
    Go

    リクエスト例

    package main
    
    import (
    	"bufio"
    	"bytes"
    	"encoding/json"
    	"fmt"
    	"net/http"
    	"os"
    )
    
    func main() {
    	apiKey := os.Getenv("DASHSCOPE_API_KEY")
    	appId := "YOUR_APP_ID" // 実際のアプリケーション ID に置き換えてください
    
    	if apiKey == "" {
    		fmt.Println("Please ensure that 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": "hello",
    			"biz_params": map[string]interface{}{
    				"city": "Hangzhou",
    			},
    		},
    		"parameters": map[string]interface{}{
    			"incremental_output": true,
    			"has_thoughts":       true,
    		},
    		"debug": map[string]interface{}{},
    	}
    
    	jsonData, err := json.Marshal(requestBody)
    	if err != nil {
    		fmt.Printf("Failed to marshal JSON: %v\n", err)
    		return
    	}
    
    	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")
    	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()
    
    	scanner := bufio.NewScanner(resp.Body)
    	for scanner.Scan() {
    		line := scanner.Text()
    		fmt.Println(line)
    	}
    
    	if err := scanner.Err(); err != nil {
    		fmt.Printf("Error reading response: %v\n", err)
    	}
    
    	if resp.StatusCode != http.StatusOK {
    		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
    	}
    }
    

    レスポンス例

    リクエスト成功:
    id:1
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    
    id:2
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    
    id:3
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"West Lake Vinegar\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    
    id:4
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Fish,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    
    id:5
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Longjing Shrimp\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    
    id:6
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",Dongpo Pork\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    
    id:7
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",Zhiwei Small\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    
    id:8
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Basket,Beggar's\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    
    id:9
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Chicken\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    
    id:10
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,Lingyin\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    
    id:11
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Temple,Songcheng\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    
    id:12
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",Xixi Wetland\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    
    id:13
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",Qiandao Lake\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    
    id:14
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_5ZzA\",\"nodeExecTime\":\"1760ms\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    
    id:15
    event:result
    :HTTP_STATUS/200
    data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_5ZzA\",\"nodeExecTime\":\"1760ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,Lingyin Temple,Songcheng,Xixi Wetland,Qiandao Lake\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"1ms\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"stop","text":"West Lake,Lingyin Temple,Songcheng,Xixi Wetland,Qiandao Lake"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
    • thoughts の各アイテムはノードの実行詳細です。以下は LLM ノードの結果の例です。

      id:7
      event:result
      :HTTP_STATUS/200
      data:
      {
          "output": {
              "thoughts": [
                  {
                      "response": "{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"
                  },
                  {
                      "response": "{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"Songcheng Fish Soup\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"
                  },
                  {
                      "response": "{\"nodeName\":\"LLM_2Km9\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"
                  }
              ],
              "session_id": "6035ee0814b64a9fb88346ecaf8b44bf",
              "finish_reason": "null"
          },
          "usage": {
              "models": [
                  {
                      "input_tokens": 25,
                      "output_tokens": 21,
                      "model_id": "qwen-max"
                  }
              ]
          },
          "request_id": "64825069-b3aa-93a7-bcf1-c66fe57111fd"
      }
      LLM ノード(上記の例では LLM_j45e)のストリーミング結果に関心がある場合は、thoughts の各プッシュにおける nodeId LLM_j45e のノードの出力に注目してください。
    • ノードが失敗した場合、タスク全体も失敗します。

    agent_format

    これは公開済みの ワークフローアプリケーションです。応答 スイッチは最初の LLM ノードに対してのみオンになっており、このノードの結果のみに注目しています。

    image

    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'
    biz_params = {
        "city": "Hangzhou"}
    responses = Application.call(
        # 環境変数が設定されていない場合は、次の行を api_key="sk-xxx" に置き換えてください。ただし、本番環境では API キーをコード内にハードコードすると漏洩リスクが高まるため、推奨されません。
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        # 実際のアプリケーション ID に置き換えてください
        app_id='YOUR_APP_ID',
        prompt='Hello',
        biz_params=biz_params,
        # ストリーミング出力を有効化
        stream=True,
        # 互換モードを有効にして、指定されたノードのストリーミング結果を出力
        flow_stream_mode="agent_format",
        # incremental_output=true で増分出力が有効になり、false で無効になります。指定しない場合のデフォルトは false です
        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'詳細については、「https://www.alibabacloud.com/help/ja/model-studio/developer-reference/error-code」をご参照ください。')
        else:
            print(f'{response.output.text}\n')  # 出力テキストを処理します。結果は text に返されます

    レスポンス例

    West Lake
    
    Fish in Vinegar Sauce,
    
    Longjing Shrimp
    
    ,Dongpo Pork
    
    ,Zhiwei Small
    
    Steamed Buns,Beggar's Chicken
    HTTP
    curl

    リクエスト例

    curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
    --header 'X-DashScope-SSE: enable' \
    --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
    --header 'Content-Type: application/json' \
    --data '{
        "input": {
            "prompt": "Hello",
            "biz_params": {
            "city": "Hangzhou"}
        },
        "parameters":  {
            "incremental_output": true,
            "flow_stream_mode": "agent_format"
        },
        "debug": {}
    }'

    レスポンス例

    id:1
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"null","text":"West Lake"},"usage":{"models":[{"input_tokens":25,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"}
    
    id:2
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"null","text":" Fish in Vinegar"},"usage":{"models":[{"input_tokens":25,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"}
    
    id:3
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"null","text":" Sauce"},"usage":{"models":[{"input_tokens":25,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"}
    
    id:4
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"null","text":",Longjing Shrimp,Dongpo"},"usage":{"models":[{"input_tokens":25,"output_tokens":11,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"}
    
    id:5
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"null","text":" Pork,Zhiwei"},"usage":{"models":[{"input_tokens":25,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"}
    
    id:6
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"null","text":" Steamed Buns,Beggar's"},"usage":{"models":[{"input_tokens":25,"output_tokens":19,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"}
    
    id:7
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"null","text":" Chicken"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"}
    
    id:8
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"stop","text":"Dear, are you satisfied with my introduction"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"}
    PHP

    リクエスト例

    <?php
    
    # 環境変数が設定されていない場合は、次の行を $api_key="sk-xxx" に置き換えてください。ただし、本番環境では API キーをコード内にハードコードすると漏洩リスクが高まるため、推奨されません。
    $api_key = getenv("DASHSCOPE_API_KEY");
    $application_id = 'YOUR_APP_ID'; // 実際のアプリケーション ID に置き換えてください
    
    $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
    
    // リクエストデータを構築
    $data = [
        "input" => [
            'prompt' => 'Hello',
            'biz_params' => [
                'city' => 'Hangzhou'
            ]
        ],
        "parameters" => [
            'flow_stream_mode' => 'agent_format', // ワークフローアプリケーションのストリーミング出力互換モードの場合、このパラメーターを agent_format に設定します
            '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";
    }
    ?>

    レスポンス例

    id:1
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"8ef1ff3df37646ef9c7b8522e8cba912","finish_reason":"null","text":"West Lake"},"usage":{"models":[{"input_tokens":25,"output_tokens":1,"model_id":"qwen-max"}]},"request_id":"9cf6539f-32id:2
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"8ef1ff3df37646ef9c7b8522e8cba912","finish_reason":"null","text":" Fish in Vinegar Sauce,Longjing Shrimp,Dongpo Pork,"},"usage":{"models":[{"input_tokens":25,"output_tokens":13,"model_id":"qwen-max"}]},"request_id":"9cf6539f-32a0-960b-bdfb-1823545edb5f"}
    id:3
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"8ef1ff3df37646ef9c7b8522e8cba912","finish_reason":"null","text":"Zhiwei Steamed Buns,"},"usage":{"models":[{"input_tokens":25,"output_tokens":18,"model_id":"qwen-max"}]},"request_id":"9cf6539f-32a0-960b-bdfb-1823545edb5f"}
    id:4
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"8ef1ff3df37646ef9c7b8522e8cba912","finish_reason":"null","text":"Beggar's Chicken"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"9cf6539f-32a0-960b-bdfb-1823545edb5f"}
    id:5
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"8ef1ff3df37646ef9c7b8522e8cba912","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"9cf6539f-32a0-960b-bdfb-1823545edb5f"}
    
    Node.js

    依存関係

    npm install axios

    リクエスト例

    const axios = require('axios');
    
    async function callDashScope() {
        // 環境変数が設定されていない場合は、次の行を apiKey='sk-xxx' に置き換えてください。ただし、本番環境では API キーをコード内にハードコードすると漏洩リスクが高まるため、推奨されません。
        const apiKey = process.env.DASHSCOPE_API_KEY;
        const appId = 'YOUR_APP_ID';// 実際のアプリケーション ID に置き換えてください
    
        const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
    
        const data = {
            input: {
                prompt: "Hello",
                biz_params:{
                    'city':'Hangzhou'
                }
            },
            parameters: {
                'incremental_output' : 'true',
                "flow_stream_mode" : "agent_format"
            },
            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) {
                console.log("Request successful:");
    
                // ストリーミングレスポンスを処理
                response.data.on('data', (chunk) => {
                    console.log(`Received chunk: ${chunk.toString()}`);
                });
    
                response.data.on('end', () => {
                    console.log("Stream ended.");
                });
    
                response.data.on('error', (error) => {
                    console.error(`Stream error: ${error.message}`);
                });
            } 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();

    レスポンス例

    Sending request to DashScope API...
    Request successful:
    Received chunk: id:1
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"null","text":"West Lake"},"usage":{"models":[{"input_tokens":25,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"}
    
    
    Received chunk: id:2
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"null","text":" Fish in Vinegar Sauce"},"usage":{"models":[{"input_tokens":25,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"}
    
    
    Received chunk: id:3
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"null","text":",Longjing Shrimp"},"usage":{"models":[{"input_tokens":25,"output_tokens":7,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"}
    
    
    Received chunk: id:4
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"null","text":",Dongpo Pork"},"usage":{"models":[{"input_tokens":25,"output_tokens":11,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"}
    
    
    Received chunk: id:5
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"null","text":",Beggar's Chicken"},"usage":{"models":[{"input_tokens":25,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"}
    
    
    Received chunk: id:6
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"null","text":",Zhiwei Steamed"},"usage":{"models":[{"input_tokens":25,"output_tokens":19,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"}
    
    
    Received chunk: id:7
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"null","text":" Buns"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"}
    
    
    Received chunk: id:8
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"}
    
    
    Stream ended.
    C#

    リクエスト例

    using System.Net;
    using System.Text;
    class Program
    {
        static async Task Main(string[] args)
        {
            // 環境変数が設定されていない場合は、次の行を apiKey="sk-xxx" に置き換えてください。ただし、本番環境では API キーをコード内にハードコードすると漏洩リスクが高まるため、推奨されません。
            string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
            string appId = "YOUR_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}");
                client.DefaultRequestHeaders.Add("X-DashScope-SSE", "enable");
    
                string jsonContent = @"{
                    ""input"": {
                        ""prompt"": ""Hello"",
                        ""biz_params"":{
                            ""city"":""Hangzhou""
                        }
                    },
                    ""parameters"": {
                        ""incremental_output"": true,
                        ""flow_stream_mode"": ""agent_format"" 
                        },
                    ""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}");
                }
            }
        }
    }

    レスポンス例

    2025-02-14 17:17:09:408
    Request successful:
    2025-02-14 17:17:10:256
    {"output":{"session_id":"37b12773b63944a5b18e352a9c2cef7d","finish_reason":"null","text":"West Lake"},"usage":{"models":[{"input_tokens":25,"output_tokens":1,"model_id":"qwen-max"}]},"request_id":"aee133b1-9b5e-9658-a91f-380938c4162c"}
    2025-02-14 17:17:10:257
    {"output":{"session_id":"37b12773b63944a5b18e352a9c2cef7d","finish_reason":"null","text":" Fish in Vinegar Sauce,Longjing Shrimp,"},"usage":{"models":[{"input_tokens":25,"output_tokens":9,"model_id":"qwen-max"}]},"request_id":"aee133b1-9b5e-9658-a91f-380938c4162c"}
    2025-02-14 17:17:10:449
    {"output":{"session_id":"37b12773b63944a5b18e352a9c2cef7d","finish_reason":"null","text":"Beggar's Chicken,Dongpo"},"usage":{"models":[{"input_tokens":25,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"aee133b1-9b5e-9658-a91f-380938c4162c"}
    2025-02-14 17:17:10:650
    {"output":{"session_id":"37b12773b63944a5b18e352a9c2cef7d","finish_reason":"null","text":" Pork,Zhiwei Steamed Buns"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"aee133b1-9b5e-9658-a91f-380938c4162c"}
    2025-02-14 17:17:10:850
    {"output":{"session_id":"37b12773b63944a5b18e352a9c2cef7d","finish_reason":"stop","text":"Dear, are you satisfied with my introduction"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"aee133b1-9b5e-9658-a91f-380938c4162c"}
    Go

    リクエスト例

    package main
    
    import (
    	"bufio"
    	"bytes"
    	"encoding/json"
    	"fmt"
    	"net/http"
    	"os"
    )
    
    func main() {
    	// 環境変数が設定されていない場合は、次の行を apiKey := "sk-xxx" に置き換えてください。ただし、本番環境では API キーをコード内にハードコードすると漏洩リスクが高まるため、推奨されません。
    	apiKey := os.Getenv("DASHSCOPE_API_KEY")
    	appId := "YOUR_APP_ID" // 実際のアプリケーション ID に置き換えてください
    
    	if apiKey == "" {
    		fmt.Println("Please ensure 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": "Hello",
    			"biz_params": map[string]interface{}{
    				"city": "Hangzhou", // パラメーターの受け渡し
    			},
    		},
    		"parameters": map[string]interface{}{
    			"incremental_output": true,           // このパラメーターを true に設定すると、結果の増分出力が有効になります
    			"flow_stream_mode":   "agent_format", // ワークフローアプリケーションで互換モードのストリーミング出力を実現するには、このパラメーターを agent_format に設定する必要があります
    		},
    		"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")
    	req.Header.Set("X-DashScope-SSE", "enable") // ストリーミング出力リクエストでは、このパラメーターを 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()
    
    	// レスポンスを読み取り
    	scanner := bufio.NewScanner(resp.Body)
    	for scanner.Scan() {
    		line := scanner.Text()
    		fmt.Println(line)
    	}
    
    	if err := scanner.Err(); err != nil {
    		fmt.Printf("Error reading response: %v\n", err)
    		return
    	}
    
    	// レスポンスを処理
    	if resp.StatusCode == http.StatusOK {
    		fmt.Println("Request successful:")
    	} else {
    		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
    	}
    }
    

    レスポンス例

    Request successful:
    id:1
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"null","text":"West Lake"},"usage":{"models":[{"input_tokens":25,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"}
    
    id:2
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"null","text":" Fish in Vinegar Sauce"},"usage":{"models":[{"input_tokens":25,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"}
    
    id:3
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"null","text":",Longjing Shrimp"},"usage":{"models":[{"input_tokens":25,"output_tokens":7,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"}
    
    id:4
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"null","text":",Dongpo Pork"},"usage":{"models":[{"input_tokens":25,"output_tokens":11,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"}
    
    id:5
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"null","text":",Zhiwei"},"usage":{"models":[{"input_tokens":25,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"}
    
    id:6
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"null","text":" Steamed Buns,Beggar's"},"usage":{"models":[{"input_tokens":25,"output_tokens":19,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"}
    
    id:7
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"null","text":" Chicken"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"}
    
    id:8
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":16,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"}

ナレッジベースの取得

ナレッジベースは、Model Studio の RAG 機能です。モデルに対して非公開かつ最新の知識を効果的に補完できます。Agent Applications を呼び出す際に取得範囲を指定することで、回答の精度を向上させることができます。

事前準備

Model Studio コンソールで、ご利用のAgent Application に対して Knowledge Base Retrieval Augmentation を有効化し、その後、Publish してください。

RAG Applications の場合は、この前提条件をスキップしてください。

取得範囲の指定

  1. 特定のナレッジベースを取得するには、以下のいずれかの方法を選択します。

    • コンソールで、アプリケーション内の Configure Knowledge Base をクリックし、目的のナレッジベースを選択します。その後、Publish してください。

    • コンソールで目的のナレッジベースを関連付けず、API 呼び出し時に rag_options を通じてナレッジベース ID を渡します。

    • コンソールで目的のナレッジベースを関連付け、さらに API 呼び出し時に rag_options を通じてナレッジベース ID を渡します。

      この場合、呼び出し時に渡されたナレッジベースのみが取得されます。たとえば、Agent Application がナレッジベース A に関連付けられているにもかかわらず、API 呼び出し時にナレッジベース B を指定した場合、ナレッジベース A は取得されず、ナレッジベース B のみが取得されます。

    ナレッジベース ID(pipeline_ids)の取得方法: Knowledge Base ページで確認するか、CreateIndex API が返す Data.Id を使用します。CreateIndex は構造化されていないナレッジベースのみをサポートします。

    以下のサンプルでは、構造化されていないナレッジベースとして Bailian Phones Specifications.docx を使用しています。

    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" に置き換えてください。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
        api_key=os.getenv("DASHSCOPE_API_KEY"), 
        app_id='YOUR_APP_ID',  # YOUR_APP_ID をアプリケーション ID に置き換えます
        prompt='Please recommend a mobile phone under 3000 yuan',
        rag_options={
            "pipeline_ids": ["YOUR_PIPELINE_ID1,YOUR_PIPELINE_ID2"],  # 実際のナレッジベース ID に置き換えます。複数の 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'Refer to: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
    else:
        print('%s\n' % (response.output.text))  # テキスト出力のみを処理します
        # print('%s\n' % (response.usage))

    応答例

    Based on your budget, I recommend the **Bailian Zephyr Z9**. This phone is priced between 2499-2799 yuan, which fits your budget. It features a lightweight 6.4-inch 1080 x 2340 pixel screen design, paired with 128GB storage and 6GB RAM, suitable for daily use. Additionally, it has a 4000mAh battery and a lens that supports 30× digital zoom, which can meet your photography and battery life needs. If you're looking for a slim, portable phone with comprehensive features, the Bailian Zephyr Z9 would be a good choice.
    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.Collections;
    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 streamCall() throws NoApiKeyException, InputRequiredException {
            ApplicationParam param = ApplicationParam.builder()
                    // 環境変数が設定されていない場合は、次の行を .apiKey("sk-xxx") に置き換えてください。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .appId("YOUR_APP_ID") // 実際のアプリケーション ID に置き換えます
                    .prompt("Please recommend a mobile phone around 3000 yuan")
                    .ragOptions(RagOptions.builder()
                            // 実際の指定ナレッジベース ID に置き換えます。複数の場合はカンマで区切ります
                            .pipelineIds(List.of("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("Refer to: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code");
            }
            System.exit(0);
        }
    }

    応答例

    Within your 3000 yuan budget, I recommend the **Bailian Zephyr Z9**. This phone is priced between 2499 and 2799, which fits your budget perfectly. It has the following features:
    
    - **Lightweight design**: The 6.4-inch screen is moderately sized, convenient for one-handed operation.
    - **Balanced performance**: Equipped with 128GB storage and 6GB RAM, which is sufficient for daily use.
    - **Battery life**: Features a 4000mAh battery that can meet your normal usage needs throughout the day.
    - **Photography capabilities**: Has a lens with 30× digital zoom, suitable for capturing distant scenery.
    
    If you're more focused on gaming experience or have other specific requirements, please let me know so I can provide more personalized recommendations!
    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": "Please recommend a mobile phone under 3000 yuan"
        },
        "parameters":  {
                        "rag_options" : {
                        "pipeline_ids":["YOUR_PIPELINE_ID1"]}
        },
        "debug": {}
    }'
    YOUR_APP_ID を実際のアプリケーション ID に、YOUR_PIPELINE_ID1 を指定のナレッジベース ID に置き換えてください。

    応答例

    {"output":{"finish_reason":"stop","session_id":"d1208af96f9a4d8390e9b29e86f0623c",
    "text":"For a budget under 3000 yuan, I recommend the Bailian Zephyr Z9.
    This phone is priced between 2499 and 2799 yuan, perfectly fitting your budget requirement.
    It features a lightweight 6.4-inch 1080 x 2340 pixel display, paired with 128GB storage and 6GB RAM, sufficient for handling various applications and multitasking in daily use.
    Additionally, it comes with a 4000mAh battery, ensuring your usage throughout the day, and is equipped with a 30× digital zoom lens, allowing you to capture details in your life.
    In summary, the Bailian Zephyr Z9 is a good choice in terms of cost-effectiveness, design, and functionality."},
    "usage":{"models":[{"output_tokens":158,"model_id":"qwen-max","input_tokens":1025}]},
    "request_id":"eb2d40f7-bede-9d48-88dc-08abdcdd0351"}% 
    PHP

    リクエスト例

    <?php
    # 環境変数が設定されていない場合は、次の行を API キーに置き換えてください: $api_key="sk-xxx"。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
    $api_key = getenv("DASHSCOPE_API_KEY");
    $application_id = 'YOUR_APP_ID'; // 実際のアプリケーション ID に置き換えます
    
    $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
    
    // リクエストデータを構築します
    $data = [
        "input" => [
            'prompt' => 'Please recommend a smartphone under 3000 yuan.'
        ],
        "parameters" => [
            'rag_options' => [
                'pipeline_ids' => ['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'] // 指定のナレッジベース ID に置き換えます。複数の 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";
        }
    }
    ?>
    

    応答例

    For a budget under 3000 yuan, I recommend the **Bailian Zephyr Z9**. This phone is priced between 2499-2799 yuan, which is perfect for your budget. It features a lightweight design with a 6.4-inch 1080 x 2340 pixel screen, 128GB storage and 6GB RAM, which can meet your daily usage needs well. Additionally, its 4000mAh battery ensures a full day of normal use, and it's equipped with a 30× digital zoom lens to capture distant details, making it both slim and powerful.
    Node.js

    依存関係:

    npm install axios

    リクエスト例

    const axios = require('axios');
    async function callDashScope() {
        // 環境変数が設定されていない場合は、次の行を apiKey='sk-xxx' に置き換えてください。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
        const apiKey = process.env.DASHSCOPE_API_KEY;
        const appId = 'YOUR_APP_ID';//実際のアプリケーション ID に置き換えます
    
        const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
    
        const data = {
            input: {
                prompt: "Please recommend a mobile phone under 3000 yuan"
            },
            parameters: {
                rag_options:{
                    pipeline_ids:['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2']  // 指定のナレッジベース ID に置き換えます。複数の 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();

    応答例

    For a budget under 3000 yuan, I recommend you consider the **Bailian Zephyr Z9**. This phone has a reference price of 3999-4299 yuan, but if you can catch promotional activities or discounts, it might fall within your budget range.
    
    ### Bailian Zephyr Z9 - The Art of Lightweight Portability
    - **Screen**: 6.4-inch 1080 x 2340 pixels
    - **Storage and RAM**: 128GB storage / 6GB RAM
    - **Battery**: 4000mAh
    - **Camera**: 30× digital zoom lens
    
    This phone features a slim and portable design, very convenient for daily use, and has good battery life. If you're more concerned about value for money and daily user experience, the Bailian Zephyr Z9 is a good choice.
    
    If your budget is very strict, I suggest watching for promotional activities on e-commerce platforms, or considering other brands' phones in the same price range. Hope these suggestions are helpful!
    C#

    リクエスト例

    using System.Text;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            // 環境変数が設定されていない場合は、次の行を apiKey="sk-xxx" に置き換えてください。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
            string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
            string appId = "YOUR_APP_ID";// 実際のアプリケーション ID に置き換えます
            // YOUR_PIPELINE_ID1 を指定のナレッジベース ID に置き換えます
            if (string.IsNullOrEmpty(apiKey))
            {
                Console.WriteLine("Please 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 mobile phone under 3000 yuan""
                    }},
                    ""parameters"": {{
                        ""rag_options"" : {{
                            ""pipeline_ids"":[""YOUR_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}");
                }
            }
        }
    }

    応答例

    {
        "output": {
            "finish_reason": "stop",
            "session_id": "2344ddc540ec4c5fa110b92d813d3807",
            "text": "Based on your budget, I recommend the **Bailian Zephyr Z9**. This phone has a reference price between 2499-2799 yuan, which fits your budget requirements. It features a 6.4-inch 1080 x 2340 pixel screen, 128GB storage and 6GB RAM, which is sufficient for daily use. Additionally, the 4000mAh battery ensures normal use throughout the day, while the 30× digital zoom lens can meet your needs for capturing distant scenery. This is a slim, portable, and feature-rich choice."
        },
        "usage": {
            "models": [
                {
                    "output_tokens": 121,
                    "model_id": "qwen-max",
                    "input_tokens": 1841
                }
            ]
        },
        "request_id": "99fceedf-2034-9fb0-aaad-9c837136801f"
    }
    Go

    リクエスト例

    package main
    
    import (
    	"bytes"
    	"encoding/json"
    	"fmt"
    	"io"
    	"net/http"
    	"os"
    )
    
    func main() {
    	// 環境変数が設定されていない場合は、次の行を apiKey := "sk-xxx" に置き換えてください。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
    	apiKey := os.Getenv("DASHSCOPE_API_KEY")
    	appId := "YOUR_APP_ID" // 実際のアプリケーション ID に置き換えます
    
    	if apiKey == "" {
    		fmt.Println("Please 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 mobile phone under 3000 yuan",
    		},
    		"parameters": map[string]interface{}{
    			"rag_options": map[string]interface{}{
    				"pipeline_ids": []string{"YOUR_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))
    	}
    }
    

    応答例

    {
        "output": {
            "finish_reason": "stop",
            "session_id": "fadbb4d1fe094ade88985620363506e6",
            "text": "Based on your budget, I recommend the **Bailian Zephyr Z9**. This phone is priced between 2499-2799 yuan, which is very suitable for budgets under 3000 yuan. It features a lightweight 6.4-inch 1080 x 2340 pixel screen design, paired with 128GB storage and 6GB RAM, which can meet daily usage needs. At the same time, the 4000mAh battery ensures worry-free use throughout the day, while the 30× digital zoom lens can capture details from a distance, making it a very cost-effective choice."
        },
        "usage": {
            "models": [
                {
                    "output_tokens": 119,
                    "model_id": "qwen-max",
                    "input_tokens": 1055
                }
            ]
        },
        "request_id": "3a755dd7-58a0-9a5e-8a07-b85b1db838a6"
    }
  2. 指定された非構造化ドキュメントを取得するには、rag_options にナレッジベース ID、ドキュメント ID、タグ、またはメタデータ(キーと値のペア)を渡します。

    ドキュメント ID、タグ、およびメタデータは、非構造化ドキュメントに対してのみ有効です。
    • 取得方法:

      • ドキュメント ID(file_ids): Application Data ページで確認するか、ドキュメントをインポートする際に AddFile API が返す ID を使用します

      • ドキュメントタグ: Application Data ページでタグを確認するか、DescribeFile API から取得します。

      • ドキュメントメタデータ: Knowledge Base ページで View をクリックしてナレッジベースに入り、その後 Metadata Information をクリックします。

    • 複数のドキュメント ID を指定できますが、それらのドキュメントはナレッジインデックスに含まれている必要があります。

    • ドキュメント ID を指定する場合は、そのドキュメントが属するナレッジベース ID も必ず指定する必要があります

    • 指定されたドキュメントのみが取得されます。たとえば、Agent Application がナレッジベース A に関連付けられているにもかかわらず、API 呼び出し時にナレッジベース B のドキュメントを指定した場合、ナレッジベース A のドキュメントは取得されず、ナレッジベース B のドキュメントのみが取得されます

      以下のサンプルでは、構造化されていないナレッジベースとして Bailian Phones Specifications.docx を使用しています。

      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" に置き換えることができます。ただし、API キーの漏洩リスクを低減するため、本番環境ではコード内に API キーを直接ハードコードしないことを推奨します。
          api_key=os.getenv("DASHSCOPE_API_KEY"),
          app_id='YOUR_APP_ID',  # YOUR_APP_ID をアプリケーション ID に置き換えます
          prompt='Please recommend a mobile phone under 3000 yuan',
          rag_options={
              "pipeline_ids": ["YOUR_PIPELINE_ID1", "YOUR_PIPELINE_ID2"],  # 実際のナレッジベース ID に置き換えます。複数の場合はカンマで区切ります
              "file_ids": ["YOUR_FILE_ID1", "YOUR_FILE_ID2"],  # 実際の非構造化ドキュメント ID に置き換えます。複数の場合はカンマで区切ります
              "metadata_filter": {  # ドキュメントメタデータのキーと値のペアです。複数の場合はカンマで区切ります
                  "key1": "value1",
                  "key2": "value2"
              },
              "tags": ["tag1", "tag2"]  # ドキュメントタグです。複数の場合はカンマで区切ります
          }
      )
      
      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'Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
      else:
          print('%s\n' % (response.output))

      応答例

      {
          "text": "Within a budget of under 3000 yuan, I recommend you consider the **Bailian Zephyr Z9**. This phone has the following features:
      
      - **Screen**: 6.4-inch 1080 x 2340 pixels, suitable for daily use and entertainment.
      - **Memory and storage**: 6GB RAM + 128GB storage space, which can meet most users' needs for smoothness and storage.
      - **Battery capacity**: 4000mAh, providing all-day usage guarantee.
      - **Camera function**: Equipped with a lens supporting 30× digital zoom, capable of capturing details from greater distances.
      - **Other features**: Lightweight and portable design, easy to carry.
      
      The reference price is between 2499 and 2799 yuan, which perfectly fits your budget requirements and offers good value for money. Hope these suggestions are helpful!",
          "finish_reason": "stop",
          "session_id": "10bdea3d1435406aad8750538b701bee",
          "thoughts": null,
          "doc_references": null
      }
      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 com.google.gson.JsonObject;
      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 streamCall() throws NoApiKeyException, InputRequiredException {
              JsonObject metadataFilter = new JsonObject();
              metadataFilter.addProperty("key1", "value1"); // メタデータのキーと値のペア
              metadataFilter.addProperty("key2", "value2"); // 複数の場合は addProperty を繰り返し呼び出します
              ApplicationParam param = ApplicationParam.builder()
                      // 環境変数が設定されていない場合は、次の行を .apiKey("sk-xxx") に置き換えてください。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
                      .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                      .appId("YOUR_APP_ID") // 実際のアプリケーション ID に置き換えます
                      .prompt("Please recommend a mobile phone around 3000 yuan")
                      .ragOptions(RagOptions.builder()
                              .pipelineIds(List.of("PIPELINES_ID1","PIPELINES_ID2"))  // 実際の指定ナレッジベース ID に置き換えます。複数の ID はカンマで区切ります
                              .fileIds(List.of("FILE_ID1", "FILE_ID2"))  // 実際の指定非構造化ドキュメント ID に置き換えます。複数の ID はカンマで区切ります
                              .tags(List.of("tags1", "tags2")) // 指定のドキュメントタグ ID に置き換えます。複数のタグはカンマで区切ります
                              .metadataFilter(metadataFilter)
                              .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("Refer to: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code");
              }
              System.exit(0);
          }
      }

      応答例

      Based on your budget, I recommend the **Bailian Zephyr Z9**. This phone is priced between 2499-2799 yuan, which fits perfectly within your budget range of around 3000 yuan.
      
      ### Bailian Zephyr Z9 Product Highlights:
      - **Screen**: 6.4-inch, 1080 x 2340 pixels, providing a clear and detailed visual experience.
      - **Storage and RAM**: 128GB storage space and 6GB RAM, sufficient to meet daily usage needs.
      - **Battery**: 4000mAh capacity battery can ensure normal use throughout the day.
      - **Camera**: Supports 30× digital zoom lens, capable of capturing distant details.
      - **Design**: Lightweight and portable, suitable for users who pursue fashion and convenience.
      
      This phone is not only moderately priced but also has balanced configurations and excellent appearance design, making it a very good choice in this price range. Hope these suggestions are helpful! If you have other requirements or questions, please feel free to let me know.
      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": "Please recommend a mobile phone around 3000 yuan"
          },
          "parameters":  {
                          "rag_options" : {
                          "pipeline_ids":["YOUR_PIPELINE_ID1"],
                          "file_ids":["YOUR_FILE_ID1"],
                          "metadata_filter":{
                          "name":"Zhang San"},
                          "tags":"mobile phone"
                          }
          },
          "debug": {}
      }'
      YOUR_APP_ID を実際のアプリケーション ID に、YOUR_PIPELINE_ID1 を指定のナレッジベース ID に、YOUR_FILE_ID1 を指定の非構造化ドキュメント ID に置き換え、metadata_filter 内のキーと値のペアを実際のメタデータに置き換えてください。

      応答例

      {"output":{"finish_reason":"stop","session_id":"f2f114864dd24a458f923aab0ec99a1d",
      "text":"Based on your budget, I recommend you consider the \"Tongyi Vivid 7\".
      It has a 6.5-inch 1080 x 2400 pixel full screen, with AI intelligent photography capabilities that allow you to take photos with professional-level color and detail.
      Its hardware configuration includes 8GB RAM and 128GB storage space, ensuring a smooth operating experience; the 4500mAh battery capacity also meets daily usage needs well.
      Additionally, the side fingerprint unlock design is both convenient and secure. The reference price is between 2999 and 3299 yuan, which fits your budget range."},
      "usage":{"models":[{"output_tokens":141,"model_id":"qwen-plus","input_tokens":1610}]},
      "request_id":"d815d3d1-8cef-95e2-b895-89fc8d0e0f84"}%      
      PHP

      リクエスト例

      <?php
      # 環境変数が設定されていない場合は、次の行を API キーに置き換えてください: $api_key="sk-xxx"。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
      $api_key = getenv("DASHSCOPE_API_KEY");
      $application_id = 'YOUR_APP_ID'; // 実際のアプリケーション ID に置き換えます
      
      $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
      
      // リクエストデータを構築します
      $data = [
          "input" => [
              'prompt' => 'Please help me recommend a smartphone under 3000 yuan.'
          ],
          "parameters" => [
              'rag_options' => [
                  'pipeline_ids' => ['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'], // 指定のナレッジベース ID に置き換えます。複数の ID はカンマで区切ります
                  'file_ids' => ['YOUR_FILE_ID1','YOUR_FILE_ID2'], // 実際のドキュメント ID に置き換えます。複数の ID はカンマで区切ります
                  "metadata_filter" => [ // メタデータのキーと値のペア
                      "key1" => "value1",
                      "key2" => "value2"
                  ],
                  "tags" => ["Tag1", "Tag2"] // ドキュメントタグ
              ]
          ]
      ];
      
      // データを 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";
          }
      }
      ?>
      

      応答例

      Based on your budget, I recommend the **Bailian Zephyr Z9**. This phone has a reference price between 2499-2799 yuan, which is perfect for requirements under 3000 yuan. It features a lightweight 6.4-inch 1080 x 2340 pixel design, paired with 128GB storage and 6GB RAM, which can meet your daily usage needs. Additionally, it is equipped with a 4000mAh battery to ensure worry-free use throughout the day, and has a 30× digital zoom lens to capture distant details, making it a thin yet powerful choice.
      Node.js

      依存関係:

      npm install axios

      リクエスト例

      const axios = require('axios');
      async function callDashScope() {
          // 環境変数が設定されていない場合は、次の行を Model Studio API キーを使用して apiKey='sk-xxx' に置き換えてください。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
          const apiKey = process.env.DASHSCOPE_API_KEY;
          const appId = 'YOUR_APP_ID';//実際のアプリケーション ID に置き換えます
      
          const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
      
          const data = {
              input: {
                  prompt: "Please recommend a mobile phone under 3000 yuan"
              },
              parameters: {
                  rag_options:{
                      pipeline_ids:['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'], // 指定のナレッジベース ID に置き換えます。複数の ID はカンマで区切ります
                      file_ids:['YOUR_FILE_ID1','YOUR_FILE_ID2'], // 指定のファイル ID に置き換えます。複数の ID はカンマで区切ります
                      metadata_filter:{ // メタデータのキーと値のペア。複数のペアはカンマで区切ります
                          'key1':'value1',
                          'key2':'value2'
                      },
                      tags: ['tag1', 'tag2'] // ドキュメントタグ。複数のタグはカンマで区切ります
                  }
              },
              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();

      応答例

      Within a budget of under 3000 yuan, I recommend you consider the **Bailian Zephyr Z9**. This phone is priced between 2499-2799 yuan and features a slim, portable design with a 6.4-inch 1080 × 2340 pixel screen, 128GB storage, and 6GB RAM, which can meet your daily usage needs. Its 4000mAh battery ensures all-day usage, while the 30× digital zoom lens helps capture details from greater distances. Overall, this is a high-value option.
      C#

      リクエスト例

      using System.Text;
      
      class Program
      {
          static async Task Main(string[] args)
          {
              // 環境変数が設定されていない場合は、次の行を apiKey="sk-xxx" に置き換えてください。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
              string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
              string appId = "YOUR_APP_ID";// 実際のアプリケーション ID に置き換えます
              // YOUR_PIPELINE_ID1 を指定のナレッジベース ID に、YOUR_FILE_ID1 を指定の非構造化ドキュメント ID に置き換えます
              if (string.IsNullOrEmpty(apiKey))
              {
                  Console.WriteLine("Please 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 mobile phone under 3000 yuan""
                      }},
                      ""parameters"": {{
                          ""rag_options"" : {{
                              ""pipeline_ids"":[""YOUR_PIPELINE_ID1""],
                              ""file_ids"":[""YOUR_FILE_ID1""],
                              ""metadata_filter"":{{
                                  ""name"":""Zhang San""
                              }},
                      ""tags"":""mobile phone""
                          }}
                      }},
                      ""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}");
                  }
              }
          }
      }

      応答例

      {
          "output": {
              "finish_reason": "stop",
              "session_id": "be9b5a1964fe41c9bbfd8674226bd238",
              "text": "Based on your budget, I recommend the **Bailian Zephyr Z9**. This phone is priced between 2499-2799 yuan, which is very suitable for budgets under 3000 yuan.
      
      ### Product highlights
      - **Slim design**: Features a 6.4-inch screen with 1080 x 2340 pixel resolution, with an exquisite appearance that's easy to carry.
      - **Balanced performance**: Equipped with 6GB RAM and 128GB storage space, capable of meeting daily usage needs.
      - **Long-lasting battery**: Built-in 4000mAh battery ensures your normal usage throughout the day is not affected.
      - **Excellent photography**: Supports 30× digital zoom function, easily capturing distant scenery or details.
      
      If you're looking for a smartphone with good value for money that can meet basic needs while also having certain features, then the Bailian Zephyr Z9 would be a good choice."
          },
          "usage": {
              "models": [
                  {
                      "output_tokens": 180,
                      "model_id": "qwen-max",
                      "input_tokens": 1055
                  }
              ]
          },
          "request_id": "d0811195-0b3f-931e-90b8-323a65053d9c"
      }
      Go

      リクエスト例

      package main
      
      import (
      	"bytes"
      	"encoding/json"
      	"fmt"
      	"io"
      	"net/http"
      	"os"
      )
      
      func main() {
      	// 環境変数が設定されていない場合は、次の行を apiKey := "sk-xxx" に置き換えてください。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
      	apiKey := os.Getenv("DASHSCOPE_API_KEY")
      	appId := "YOUR_APP_ID" // 実際のアプリケーション ID に置き換えます
      
      	if apiKey == "" {
      		fmt.Println("Please 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 mobile phone under 3000 yuan",
      		},
      		"parameters": map[string]interface{}{
      			"rag_options": map[string]interface{}{
      				"pipeline_ids": []string{"YOUR_PIPELINE_ID1"}, // 指定の非構造化ナレッジベース ID に置き換えます
      				"file_ids":     []string{"YOUR_FILE_ID1"},     // 指定の非構造化ドキュメント ID に置き換えます
      				"metadata_filter": map[string]string{
      					"name": "Zhang San", // メタデータのキーと値のペア
      				},
      				"tags": "mobile phone", // 非構造化データのドキュメントタグ
      			},
      		},
      		"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))
      	}
      }
      

      応答例

      {
          "output": {
              "finish_reason": "stop",
              "session_id": "9de268b3d84748b5ac6321aba72b6ecd",
              "text": "Based on your budget, I recommend you consider the **Bailian Zephyr Z9**. This phone has a reference price of 2499-2799 yuan, which is very suitable for needs under 3000 yuan. It has the following features:
      
      - Lightweight 6.4-inch 1080 x 2340 pixel screen design.
      - Paired with 128GB storage and 6GB RAM, capable of meeting daily usage needs.
      - Equipped with a 4000mAh battery, ensuring normal use throughout the day.
      - The rear camera supports 30× digital zoom lens, capable of capturing distant details.
      
      If you don't have particularly high requirements for photography or gaming, then the Bailian Zephyr Z9 should be a good choice."
          },
          "usage": {
              "models": [
                  {
                      "output_tokens": 156,
                      "model_id": "qwen-max",
                      "input_tokens": 1055
                  }
              ]
          },
          "request_id": "8940b597-92e1-9471-b4eb-896e563c479d"
      }
  3. 構造化ドキュメントから指定されたデータを取得するには、rag_options にナレッジベース ID および「構造化データのヘッダー + 値」のキーと値のペアを渡します。

    構造化データのキーと値のペア(structured_filter)の取得方法: Knowledge Base ページで View をクリックしてナレッジベースに入り、その後 View Index をクリックします。

    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" に置き換えることができます。ただし、API キーの漏洩リスクを低減するため、本番環境ではコード内に直接 API キーをハードコードしないことを推奨します。
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        app_id='YOUR_APP_ID',  # YOUR_APP_ID をアプリケーション ID に置き換えます
        prompt='Please recommend a mobile phone under 3000 yuan',
        rag_options={
            "pipeline_ids": ["YOUR_PIPELINE_ID1", "YOUR_PIPELINE_ID2"],  # 実際のナレッジベース ID に置き換えます。複数ある場合はコンマで区切ります
             "structured_filter": {  # 構造化データのキーと値のペアです。構造化データに対応しており、複数ある場合はコンマで区切ります
                "key1": "value1",
                "key2": "value2"  
             }
        }
    )
    
    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'Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
    else:
        print('%s\n' % (response.output))

    応答例

    {
        "text": "I recommend the \"Bailian\" phone, which is priced at 2999 yuan, fitting your budget requirement. If you need to know more information, such as performance, appearance, etc., please let me know.",
        "finish_reason": "stop",
        "session_id": "80a3b868b5ce42c8a12f01dccf8651e2",
        "thoughts": null,
        "doc_references": null
    }
    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 com.google.gson.JsonObject;
    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 streamCall() throws NoApiKeyException, InputRequiredException {
            JsonObject structureFilter = new JsonObject();
            structureFilter.addProperty("key1", "value1"); // 構造化データのキーと値のペア
            structureFilter.addProperty("key2", "value2"); // 複数の場合は addProperty を繰り返し呼び出します
            ApplicationParam param = ApplicationParam.builder()
                    // 環境変数が設定されていない場合は、次の行を .apiKey("sk-xxx") に置き換えてください。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .appId("YOUR_APP_ID") // 実際のアプリケーション ID に置き換えます
                    .prompt("Please recommend a mobile phone around 3000 yuan")
                    .ragOptions(RagOptions.builder()
                            .pipelineIds(List.of("PIPELINE_ID1","PIPELINE_ID2"))  // 実際の指定ナレッジベース ID に置き換えます。複数の ID はカンマで区切ります
                            .structuredFilter(structureFilter)
                            .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("Refer to: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code");
            }
            System.exit(0);
        }
    }

    応答例

    I recommend the "Bailian" phone, which is priced at 2999.0 yuan, fitting your budget requirement. If you need to know more information about this phone, such as configuration, performance, etc., please let me know, and I will provide you with more detailed information.
    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": "Please recommend a mobile phone around 3000 yuan"
        },
        "parameters":  {
                        "rag_options" : {
                        "pipeline_ids":["YOUR_PIPELINE_ID1"],
                        "structured_filter":{
                        "price":"2999"}
                        }
        },
        "debug": {}
    }'
    YOUR_APP_ID を実際のアプリケーション ID に、YOUR_PIPELINE_ID1 を指定のナレッジベース ID に置き換えてください。

    応答例

    {"output":{"finish_reason":"stop","session_id":"d6bc4206f9cc4d368d534f8aa4e502bc",
    "text":"I recommend a mobile phone priced close to 3000 yuan:\n\n- **Bailian phone**, priced at 2999 yuan.
    \n\nThis phone offers good value for money and meets your budget requirements.
    If you need more detailed information about this phone or have other specific requirements (such as camera performance, processor model, etc.), please let me know, and I will try to provide more comprehensive information."},
    "usage":{"models":[{"output_tokens":73,"model_id":"qwen-max","input_tokens":235}]},"request_id":"934e1258-219c-9ef1-8982-fc1bcefb8f11"}%  
    PHP

    リクエスト例

    <?php
    # 環境変数が設定されていない場合は、次の行を API キーに置き換えてください: $api_key="sk-xxx"。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
    $api_key = getenv("DASHSCOPE_API_KEY");
    $application_id = 'YOUR_APP_ID'; // 実際のアプリケーション ID に置き換えます
    
    $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
    
    // リクエストデータを構築します
    $data = [
        "input" => [
            'prompt' => 'Please help me recommend a smartphone under 3000 yuan.'
        ],
        "parameters" => [
            'rag_options' => [
                'pipeline_ids' => ['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'], // 指定のナレッジベース ID に置き換えます。複数の ID はカンマで区切ります
                "structured_filter" => [ // 構造化データのキーと値のペア。複数のエントリはカンマで区切ります
                    "key1" => "value1",
                    "key2" => "value2"
                ]
            ]
        ]
    ];
    
    // データを 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";
        }
    }
    ?>
    

    応答例

    I recommend the "Bailian" phone, which is priced at 2999 yuan, fitting your budget requirement. If you need to know more information about this phone, please let me know.
    Node.js

    依存関係:

    npm install axios

    リクエスト例

    const axios = require('axios');
    async function callDashScope() {
        // 環境変数が設定されていない場合は、次の行を apiKey='sk-xxx' に置き換えてください。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
        const apiKey = process.env.DASHSCOPE_API_KEY;
        const appId = 'YOUR_APP_ID';  // 実際のアプリケーション ID に置き換えます
        // YOUR_PIPELINE_ID1 を指定のナレッジベース ID に置き換え、複数のナレッジベース ID はカンマで区切ります
        const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
    
        const data = {
            input: {
                prompt: "Please recommend a mobile phone under 3000 yuan"
            },
            parameters: {
                rag_options:{
                    pipeline_ids:['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'],
                    structured_filter:{
                        'key1':'value1',
                        'key2':'value2'
                    }
                }
            },
            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();

    応答例

    I recommend the "Bailian" phone, which is priced at 2999 yuan, fitting your budget requirement. If you need to know more details or have other specific requirements, please let me know!
    C#

    リクエスト例

    using System.Text;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            // 環境変数が設定されていない場合は、次の行を apiKey="sk-xxx" に置き換えてください。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
            string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
            string appId = "YOUR_APP_ID";// 実際のアプリケーション ID に置き換えます
            // YOUR_PIPELINE_ID1 を指定のナレッジベース ID に置き換えます
            if (string.IsNullOrEmpty(apiKey))
            {
                Console.WriteLine("Please 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 mobile phone under 3000 yuan""
                    }},
                    ""parameters"": {{
                        ""rag_options"" : {{
                            ""pipeline_ids"":[""YOUR_PIPELINE_ID1""],
                            ""structured_filter"":{{
                                ""price"":""2999""
                            }}
                        }}
                    }},
                    ""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}");
                }
            }
        }
    }

    応答例

    {
        "output": {
            "finish_reason": "stop",
            "session_id": "108e9104568e44f1915fb3d3d44fdc92",
            "text": "I recommend the \"Bailian\" phone, which is priced at 2999.0 yuan, fitting your budget requirement. If you need more information about this phone or other suggestions, please let me know."
        },
        "usage": {
            "models": [
                {
                    "output_tokens": 38,
                    "model_id": "qwen-max",
                    "input_tokens": 104
                }
            ]
        },
        "request_id": "d6d103f4-5c22-9782-9682-45d51a5607f9"
    }
    Go

    リクエスト例

    package main
    
    import (
    	"bytes"
    	"encoding/json"
    	"fmt"
    	"io"
    	"net/http"
    	"os"
    )
    
    func main() {
    	// 環境変数が設定されていない場合は、次の行を apiKey := "sk-xxx" に置き換えてください。ただし、本番環境では API キーをコード内にハードコードしないことを推奨します。これにより、API キー漏洩のリスクを低減できます。
    	apiKey := os.Getenv("DASHSCOPE_API_KEY")
    	appId := "YOUR_APP_ID" // 実際のアプリケーション ID に置き換えます
    
    	if apiKey == "" {
    		fmt.Println("Please 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 mobile phone under 3000 yuan",
    		},
    		"parameters": map[string]interface{}{
    			"rag_options": map[string]interface{}{
    				"pipeline_ids": []string{"YOUR_PIPELINE_ID1"}, // 指定の構造化ナレッジベース ID に置き換えます
    				"structured_filter": map[string]string{
    					"price": "2999", // 構造化データのキーと値のペア
    				},
    			},
    		},
    		"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))
    	}
    }
    

    応答例

    {
        "output": {
            "finish_reason": "stop",
            "session_id": "9e0a031b51d1492e8b613ca391b445b0",
            "text": "I recommend you consider the \"Bailian\" phone, which is priced at 2999.0 yuan, fitting your budget requirement. If you need more information about this phone or other recommendations, please let me know."
        },
        "usage": {
            "models": [
                {
                    "output_tokens": 39,
                    "model_id": "qwen-max",
                    "input_tokens": 104
                }
            ]
        },
        "request_id": "036abd4f-10c8-9709-881d-8cc9f8095d54"
    }
情報の表示
  • 取得プロセスの表示: 呼び出し時にコードに has_thoughts を追加し、True に設定します。取得プロセスは outputthoughts フィールドに返されます。

  • 回答ソースの表示: Agent ApplicationRetrieval ConfigurationShow Source を有効化し、アプリケーションを公開してください。image

API リファレンス

パラメーターの完全なリストについては、「DashScope のワークフローおよびレガシ エージェントアプリケーション API リファレンス」をご参照ください。

エラーコード

呼び出しが失敗した場合は、トラブルシューティングのため「エラーメッセージ」をご参照ください。

参照

よくある質問

Java コードサンプルを実行中に「java: package com.alibaba.dashscope.app does not exist」という例外が発生した場合、どのように対処すればよいですか?

  1. インポート文内のクラス名およびパッケージ名が正しいことを確認します。

  2. 依存関係を追加します。Maven または Gradle を使用している場合は、pom.xml または build.gradle ファイルに DashScope Java SDK の依存関係が含まれており、かつ最新バージョンであることを確認してください。Maven で DashScope Java SDK の最新バージョン番号を確認できます。

    <!-- https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>dashscope-sdk-java</artifactId>
        <version>最新のバージョンを入力してください(例:2.16.4)</version>
    </dependency>
    // https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java
    implementation group: 'com.alibaba', name: 'dashscope-sdk-java', version: '最新のバージョンを入力してください(例:2.16.4)'
  3. SDK をアップグレードします。DashScope Java SDK の古いバージョンには必要な機能やクラスが含まれていない可能性があります。バージョンが古くなっている場合は、pom.xml または build.gradle ファイル内のバージョン番号を変更してアップグレードしてください。

    <!-- https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>dashscope-sdk-java</artifactId>
        <version>最新のバージョン番号に置き換えてください</version>
    </dependency>
    // https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java
    implementation group: 'com.alibaba', name: 'dashscope-sdk-java', version: '最新のバージョン番号に置き換えてください'
  4. 変更を適用するためにプロジェクトを再読み込みします。

  5. コードサンプルを再度実行します。

    問題が解決しない場合は、開発者フォーラムで同様の問題とそのソリューションを確認するか、チケットを送信してください。