全部產品
Search
文件中心

Alibaba Cloud Model Studio:應用調用

更新時間:Dec 17, 2024

您可以通過DashScope SDK或HTTP的方式來整合百鍊應用(智能體、工作流程或智能體編排)到您的業務系統中。

前提條件

您可以使用DashScope SDK或HTTP介面調用百鍊的應用,請您根據您的需求,參考以下方式準備您的計算環境。

調用方式

準備條件

通過DashScope SDK調用

DashScope SDK提供了Python和Java兩個版本,請參考DashScope SDK,安裝最新版SDK。

如果您需要通過代理server或者pvl進行訪問,可以自訂endpoint:

Python

可以添加到環境變數,需要配置的自訂endpoint:

DASHSCOPE_HTTP_BASE_URL=https://Your_Custom_DashScope.aliyuncs.com/api/v1/

或者添加到代碼中,位置在調用 Application.call之前:

os.environ['DASHSCOPE_HTTP_BASE_URL'] = 'https://Your_Custom_DashScope.aliyuncs.com/api/v1/'

Java

直接在代碼中添加,位置如下:

Application application = new Application("https://Your_Custom_DashScope.aliyuncs.com/api/v1/");
ApplicationResult result = application.call(param);
請將Your_Custom_DashScope替換為您自訂的部分,如:dashscope。

通過HTTP調用

如果您通過HTTP方式進行調用,需要配置的endpoint:

POST https://dashscope-intl.aliyuncs.com/api/v1/apps/{YOUR_APP_ID}/completion
無論使用哪種調用方式,建議您配置API Key到環境變數

如何使用

單輪對話

您可以參考以下範例程式碼,通過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將下行替換為:api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    app_id='YOUR_APP_ID',
    prompt='你是誰?')

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/zh/model-studio/developer-reference/error-code')
else:
    print(response.output.text)

響應樣本

我是阿里雲開發的一款超大規模語言模型,我叫通義千問。我被設計用來協助使用者產生各種類型的文本,如文章、故事、詩歌、故事等,並能根據不同的情境和需求進行調整和最佳化。此外,我還能夠回答各種問題,提供資訊和解釋,輔助學習和研究。如果您有任何需要,歡迎隨時向我提問!

Java

請求樣本

// 建議dashscope SDK的版本 >= 2.12.0
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
    static {
      Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
    }
    public static void appCall()
            throws ApiException, NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                // 若沒有配置環境變數,可用百鍊API Key將下行替換為:.apiKey("sk-xxx")。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("YOUR_APP_ID")
                .prompt("你是誰?")
                .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("請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

響應樣本

text: 我是阿里雲開發的一款超大規模語言模型,我叫通義千問。

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": "你是誰?"
    },
    "parameters":  {},
    "debug": {}
}' 
YOUR_APP_ID替換為實際的應用 ID。

響應樣本

{"output":{"finish_reason":"stop",
"session_id":"232ea2e9e6ef448db6b14465c06a9a56",
"text":"我是來自阿里雲的超大規模語言模型,我叫通義千問。我是一個能夠回答問題、創作文字,還能表達觀點、撰寫代碼的AI助手。如果您有任何問題或需要協助,請隨時告訴我,我會儘力為您提供協助。"},
"usage":{"models":[{"output_tokens":51,"model_id":"qwen-max","input_tokens":121}]},
"request_id":"661c9cad-e59c-9f78-a262-78eff243f151"}% 

PHP

請求樣本

<?php

# 若沒有配置環境變數,可用百鍊API Key將下行替換為:$api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
$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' => '你是誰?'
    ]
];

// 將資料編碼為 JSON
$dataString = json_encode($data);

// 檢查 json_encode 是否成功
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// 初始化 cURL 對話
$ch = curl_init($url);

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

// 執行請求
$response = curl_exec($ch);

// 檢查 cURL 執行是否成功
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}

// 擷取 HTTP 狀態代碼
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 關閉 cURL 對話
curl_close($ch);
// 解碼響應資料
$response_data = json_decode($response, true);
// 處理響應
if ($status_code == 200) {
    if (isset($response_data['output']['text'])) {
        echo "{$response_data['output']['text']}\n";
    } else {
        echo "No text in response.\n";
    }}
else {
    if (isset($response_data['request_id'])) {
        echo "request_id={$response_data['request_id']}\n";}
    echo "code={$status_code}\n";
    if (isset($response_data['message'])) {
        echo "message={$response_data['message']}\n";} 
    else {
        echo "message=Unknown error\n";}
}
?>

響應樣本

我是來自阿里雲的超大規模語言模型,我叫通義千問。

Node.js

需安裝相關依賴:

npm install axios

請求樣本

const axios = require('axios');

async function callDashScope() {
    // 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey='sk-xxx'。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
    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: "你是誰?"
        },
        parameters: {},
        debug: {}
    };

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

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

callDashScope();

響應樣本

我是來自阿里雲的大規模語言模型,我叫通義千問。

C#

請求樣本

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

class Program
{
    static async Task Main(string[] args)
    {
        //若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。 
        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"": ""你是誰?""
                },
                ""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": "我是阿里雲開發的一款超大規模語言模型,我叫通義千問。我被設計用來協助使用者產生各種類型的文本,如文章、故事、詩歌、故事等,並能根據不同的情境和需求進行變換和創新。此外,我還能夠回答各種問題,提供資訊和解釋,協助使用者解決問題和擷取知識。如果你有任何問題或需要協助,請隨時告訴我!"
    },
    "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() {
	// 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey := "sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "YOUR_APP_ID" // 替換為實際的應用 ID

	if apiKey == "" {
		fmt.Println("請確保設定了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]string{
			"prompt": "你是誰?",
		},
		"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": "我是通義千問,由阿里雲開發的AI助手。我被設計用來回答各種問題、提供資訊和與使用者進行對話。有什麼我可以協助你的嗎?"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 36,
                "model_id": "qwen-plus",
                "input_tokens": 74
            }
        ]
    },
    "request_id": "f97ee37d-0f9c-9b93-b6bf-bd263a232bf9"
}

調用智能體應用實現Prompt範例庫功能時,還需要在上述代碼的parameters對象中添加並設定has_thoughts參數為True,檢索的過程資訊在thoughts欄位中返回。

多輪對話

相比於單輪對話,多輪對話可以讓大模型參考歷史對話資訊,更符合日常交流的情境。阿里雲百鍊應用提供雲端託管多輪對話功能,通過session_id進行多輪對話,阿里雲百鍊雲端將自動裝載多輪對話

上一次調用後返回的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將下行替換為:api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        app_id='YOUR_APP_ID',  # 替換為實際的應用 ID
        prompt='你是誰?')

    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/zh/model-studio/developer-reference/error-code')
        return response

    responseNext = Application.call(
                # 若沒有配置環境變數,可用百鍊API Key將下行替換為:api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
                api_key=os.getenv("DASHSCOPE_API_KEY"),
                app_id='YOUR_APP_ID',  # 替換為實際的應用 ID
                prompt='你有什麼技能?',
                session_id=response.output.session_id)  # 上一輪response的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'請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code')
    else:
        print('%s\n session_id=%s\n' % (responseNext.output.text, responseNext.output.session_id))
        # print('%s\n' % (response.usage))

if __name__ == '__main__':
    call_with_session()

響應樣本

我具備多種技能,可以協助你完成各種任務。以下是一些主要的技能:

1. **資訊查詢**:提供天氣、新聞、歷史事實、科學知識等各種資訊。
2. **語言處理**:翻譯文本、糾正語法錯誤、產生文章和故事。
3. **技術問題解答**:解答編程、軟體使用、技術故障排除等問題。
4. **學習輔導**:協助解答數學、物理、化學等學科的問題。
5. **生活建議**:提供健康、飲食、旅行、購物等方面的建議。
6. **娛樂互動**:講笑話、玩文字遊戲、進行簡單的聊天互動。
7. **議程管理**:提醒重要日期、安排議程、設定提醒。
8. **資料分析**:解釋資料圖表、提供資料分析建議。
9. **情感支援**:傾聽你的感受、提供安慰和支援。

如果你有具體的需求或問題,可以直接告訴我,我會儘力協助你!
 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()
                // 若沒有配置環境變數,可用百鍊API Key將下行替換為:.apiKey("sk-xxx")。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // 替換為實際的應用 ID
                .appId("YOUR_APP_ID")
                .prompt("你是誰?")
                .build();

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

        param.setSessionId(result.getOutput().getSessionId());
        param.setPrompt("你有什麼技能?");
        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("請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

響應樣本

我具備多項技能,可以為您提供多種協助。以下是一些主要的技能:

1. **多語言理解與產生**:我能理解和產生包括中文、英文在內的多種語言文本。
2. **資訊檢索與綜合**:我可以根據您的問題尋找相關資訊並進行整理和總結。
3. **寫作輔助**:無論是撰寫文章、報告還是創意寫作,我都能提供支援。
4. **編程助手**:對於程式員來說,我可以協助解答編程相關的問題,提供程式碼範例等。
5. **教育輔導**:在學習過程中遇到困難時,我可以作為助手提供協助,涵蓋從數學到歷史等多個學科領域。
6. **生活建議**:關於健康飲食、旅行規劃等方面的問題我也能給出一些建議。
7. **情感交流**:雖然我是AI,但我努力以一種溫暖和支援的方式與您交流。

如果您有任何具體需求或想要進一步瞭解某個方面的內容,請隨時告訴我!
, session_id: f2e94a980a34424fa25be45a7048d77c

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": "你是誰?"
    },
    "parameters":  {},
    "debug": {}
}' 

響應樣本

{
    "output": {
        "finish_reason": "stop",
        "session_id": "4f8ef7233dc641aba496cb201fa59f8c",
        "text": "我是通義千問,由阿里雲開發的AI助手。我被設計用來回答各種問題、提供資訊和與使用者進行對話。有什麼我可以協助你的嗎?"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 36,
                "model_id": "qwen-plus",
                "input_tokens": 75
            }
        ]
    },
    "request_id": "e571b14a-423f-9278-8d1e-d86c418801e0"
}

請求樣本(下一輪對話)

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": "你有什麼技能?",
        "session_id":"4f8ef7233dc641aba496cb201fa59f8c"
    },
    "parameters":  {},
    "debug": {}
}' 

響應樣本

{
    "output": {
        "finish_reason": "stop",
        "session_id": "4f8ef7233dc641aba496cb201fa59f8c",
        "text": "作為AI助手,我具備多種技能,可以協助你完成各種任務,包括但不限於:

1. **知識查詢**:我可以協助你尋找各種領域的資訊,比如科學、歷史、文化、技術等。
2. **語言翻譯**:我可以幫你翻譯不同語言的文字,支援多種語言之間的互譯。
3. **文本產生**:我可以產生文章、故事、詩歌、新聞稿等各種類型的文本。
4. **問題解答**:無論是學術問題、生活常識還是技術難題,我都可以嘗試為你提供答案。
5. **對話交流**:我可以與你進行自然流暢的對話,提供情感支援或娛樂。
6. **代碼編寫與調試**:我可以協助你編寫代碼、解決編程中的問題。
7. **資料分析**:我可以協助你分析資料,提供統計結果和可視化建議。
8. **創意啟發**:如果你需要創意靈感,比如設計、廣告詞、營銷策略等,我也可以提供協助。

如果你有任何具體的需求或問題,歡迎隨時告訴我!"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 208,
                "model_id": "qwen-plus",
                "input_tokens": 125
            }
        ]
    },
    "request_id": "9de2c3ed-e1f0-9963-85f4-8f289203418b"
}

PHP

請求樣本(上一輪對話)

<?php
# 若沒有配置環境變數,可用百鍊API Key將下行替換為:$api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
$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' => '你是誰?'
    ]
];

// 將資料編碼為 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";}
}
?>

響應樣本

我是來自阿里雲的超大規模語言模型,我叫通義千問。
session_id=2e658bcb514f4d30ab7500b4766a8d43

請求樣本(下一輪對話)

<?php
# 若沒有配置環境變數,可用百鍊API Key將下行替換為:$api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
$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' => '你有什麼技能?',
        // 替換為實際上一輪對話返回的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";}
}
?>

響應樣本

我具備多項技能,包括但不限於:

1. **多語言能力**:我可以理解和產生多種語言的文字內容。
2. **寫作與創作**:協助撰寫文章、故事、詩歌等創意內容。
3. **知識問答**:回答來自各個領域的常識性和專業性問題。
4. **代碼編寫與理解**:能夠編寫簡單的程式碼,並協助解釋或調試代碼。
5. **邏輯推理**:解決需要邏輯思考的問題和謎題。
6. **情感支援**:提供正面的心理支援和鼓勵。
7. **遊戲娛樂**:參與文字遊戲或其他形式的互動娛樂活動。

我的目標是成為您的得力助手,在您需要的時候提供協助和支援。如果您有任何具體需求或想要嘗試的功能,請隨時告訴我!
session_id=2e658bcb514f4d30ab7500b4766a8d43

Node.js

需安裝相關依賴:

npm install axios

請求樣本(上一輪對話)

const axios = require('axios');

async function callDashScope() {
    // 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey='sk-xxx'。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
    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: "你是誰?"
        },
        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();

響應樣本

我是通義千問,由阿里雲開發的人工智慧助手。我可以回答各種問題、提供資訊和與使用者進行對話。有什麼我可以協助你的嗎?
session_id=fe4ce8b093bf46159ea9927a7b22f0d3

請求樣本(下一輪對話)

const axios = require('axios');

async function callDashScope() {
    // 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey='sk-xxx'。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
    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: "你有什麼技能?",
            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();

響應樣本

我具備多種技能,可以協助你處理不同的任務和問題。以下是一些主要的技能領域:

1. **資訊查詢與檢索**:我可以協助尋找特定的資訊、資料或新聞。
2. **寫作與創作**:包括撰寫文章、故事、詩歌、報告等。
3. **語言翻譯**:能夠提供不同語言之間的翻譯服務。
4. **教育輔導**:解答學術問題,協助理解複雜的概念。
5. **支援人員**:解決電腦使用中遇到的技術難題。
6. **生活建議**:提供建議關於健康、飲食、旅行等方面。
7. **娛樂互動**:講笑話、玩文字遊戲等輕鬆活動。

如果你有具體的需求或想瞭解更詳細的某一方面,請告訴我!
session_id=fe4ce8b093bf46159ea9927a7b22f0d3

C#

請求樣本(上一輪對話)

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

class Program
{
    static async Task Main(string[] args)
    {
        //若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。 
        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"": ""你是誰?""
                },
                ""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": "我是通義千問,由阿里雲開發的AI助手。我被設計用來回答各種問題、提供資訊和與使用者進行對話。有什麼我可以協助你的嗎?"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 36,
                "model_id": "qwen-plus",
                "input_tokens": 75
            }
        ]
    },
    "request_id": "53691ae5-be17-96c6-a830-8f0f92329028"
}

請求樣本(下一輪對話)

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

class Program
{
    static async Task Main(string[] args)
    {
        //若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。 
        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"": ""你有什麼技能?"",
                    ""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": "我具備多種技能,可以:

- 回答廣泛領域的知識性問題
- 提供學習資源和建議
- 協助解決技術問題
- 進行多語言交流
- 協助規划行程和活動
- 提供日常生活中的實用建議

如果你有任何具體需求或問題,歡迎隨時告訴我!"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 70,
                "model_id": "qwen-plus",
                "input_tokens": 123
            }
        ]
    },
    "request_id": "da5044ed-461e-9e91-8ca5-38a3c72a8306"
}

Go

請求樣本(上一輪對話)

package main

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

func main() {
	// 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey := "sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "YOUR_APP_ID" // 替換為實際的應用 ID

	if apiKey == "" {
		fmt.Println("請確保設定了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]string{
			"prompt": "你是誰?",
		},
		"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": "我是通義千問,由阿里雲開發的AI助手。我被設計用來回答各種問題、提供資訊和與使用者進行對話。有什麼我可以協助你的嗎?"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 36,
                "model_id": "qwen-plus",
                "input_tokens": 75
            }
        ]
    },
    "request_id": "fa65e14a-ab63-95b2-aa43-035bf5c51835"
}

請求樣本(下一輪對話)

package main

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

func main() {
	// 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey := "sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "YOUR_APP_ID" // 替換為實際的應用 ID

	if apiKey == "" {
		fmt.Println("請確保設定了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]string{
			"prompt":     "你有什麼技能?",
			"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": "我具備多種技能,可以:

- 回答各種知識性問題,如科學、歷史、文化等領域的疑問。
- 提供實用建議,比如旅行攻略、健康小貼士、學習方法等。
- 協助處理文字工作,例如撰寫文章、編輯文檔、創作故事或詩歌。
- 進行多語言翻譯,支援多種語言之間的互譯。
- 與使用者進行自然流暢的對話,陪伴聊天、解答疑惑。

如果你有任何具體需求,歡迎告訴我!"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 104,
                "model_id": "qwen-plus",
                "input_tokens": 125
            }
        ]
    },
    "request_id": "badccade-9f54-986b-8d8c-75ef15e9616c"
}
YOUR_APP_ID替換為實際的應用 ID。下一輪對話的輸入參數session_id欄位值替換為實際上一輪對話返回的session_id值。

自訂參數透傳

當您需要通過改變參數讓同一個智能體或工作流程適應不同的業務情境時,可以利用自訂參數來傳遞配置資訊。在應用的調用過程中透傳自訂參數,有以下兩種方式:1.智能體應用自訂外掛程式的參數和鑒權透傳;2.工作流程應用和智能體編排應用的自訂輸入參數透傳。需要透傳的參數都需要使用biz_params傳遞。

更多關於透傳功能的調用細節請參考:應用的參數透傳

  • 工作流程應用和智能體編排應用中,支援自訂開始節點的參數。

    1. 參考下面在工作流程應用中透傳城市名參數的例子,在應用的開始節點設定String類型變數city,同時在Prompt中插入變數city和變數query,發布應用。

      image

    2. 調用時通過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": "杭州"}
      response = Application.call(
          # 若沒有配置環境變數,可用百鍊API Key將下行替換為:api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
          api_key=os.getenv("DASHSCOPE_API_KEY"),
          app_id='YOUR_APP_ID',  # 替換為實際的應用 ID
          prompt='查詢這個城市的行政地區劃分',
          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'請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code')
      else:
          print(f'{response.output.text}')  # 處理只輸出文本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\":\"杭州\"}";
              ApplicationParam param = ApplicationParam.builder()
                      // 若沒有配置環境變數,可用百鍊API Key將下行替換為:.apiKey("sk-xxx")。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
                      .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                      .appId("YOUR_APP_ID")
                      .prompt("查詢這個城市的行政地區劃分")
                      .bizParams(JsonUtils.parse(bizParams))
                      .build();
      
              Application application = new Application();
              ApplicationResult result = application.call(param);
              System.out.printf("%s\n",
                      result.getOutput().getText());
          }
      
          public static void main(String[] args) {
              try {
                  appCall();
              } catch (ApiException | NoApiKeyException | InputRequiredException e) {
                  System.out.printf("Exception: %s", e.getMessage());
                  System.out.println("請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code");
              }
              System.exit(0);
          }
      }

      響應樣本

      杭州市是浙江省的省會城市,其行政地區劃分主要包括10個市轄區:上城區、拱墅區、西湖區、濱江區、蕭山區、餘杭區、臨平區、錢塘區、富陽區、臨安區。每個區都有自己的特色和發展重點。
      
      - 上城區:位於杭州市中心,擁有許多歷史文化遺產。
      - 拱墅區:以大運河文化而聞名,同時也是一個重要的商業和居住區。
      - 西湖區:以其美麗的自然風光著稱,包括著名的西湖風景區。
      - 濱江區:高新技術產業集聚地,杭州國家高新技術產業開發區就設在這裡。
      - 蕭山區:經濟發展迅速,尤其在製造業方面表現突出。
      - 餘杭區:近年來隨著阿里巴巴等高科技企業的發展而快速崛起。
      - 臨平區:2021年由原餘杭區部分地區調整而來,注重生態建設和科技創新。
      - 錢塘區:同樣是在2021年成立的新區,定位為杭州東部交通樞紐及產業發展新高地。
      - 富陽區:歷史悠久的文化名城,也是造紙業的重要基地之一。
      - 臨安區:位於杭州西部,森林覆蓋率高,生態環境良好。
      
      這些地區共同構成了杭州市獨特的地理格局和社會經濟結構。如果你對某個特定地區感興趣或需要更詳細的資訊,請告訴我!

      HTTP

      curl

      請求樣本

      curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
      --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
      --header 'Content-Type: application/json' \
      --data '{
          "input": {
              "prompt": "查詢這個城市的行政地區劃分",
              "biz_params": {
              "city": "杭州"}
          },
          "parameters":  {}
      }'
      
      YOUR_APP_ID替換為實際的應用 ID。

      響應樣本

      {"output":{"finish_reason":"stop","session_id":"c211219896004b50a1f6f66f2ec5413e",
      "text":"杭州市下轄10個區、1個縣,代管2個縣級市,分別為:
      上城區、拱墅區、西湖區、濱江區、蕭山區、餘杭區、臨平區、錢塘區、富陽區、臨安區、桐廬縣、淳安縣、建德市、諸暨市。
      注意,諸暨市由浙江省直轄、杭州市與紹興市共同管理。"},"usage":{},
      "request_id":"02c3c9e1-7912-9505-91aa-248d04fb1f5d"}

      PHP

      請求樣本

      <?php
      
      # 若沒有配置環境變數,可用百鍊API Key將下行替換為:$api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
      $api_key = getenv("DASHSCOPE_API_KEY");
      $application_id = 'YOUR_APP_ID'; // 替換為實際的應用 ID
      $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
      
      // 構造請求資料
      $data = [
          "input" => [
              'prompt' => '查詢這個城市的行政地區劃分',
              'biz_params' => [
                  'city' => '杭州'
              ]
          ],
      ];
      // 將資料編碼為 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() {
          // 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey='sk-xxx'。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
          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: "查詢這個城市的行政地區劃分",
                  biz_params: {
                      'city': '杭州',
                  },
              },
              parameters: {},
              debug: {},
          };
      
          try {
              console.log("Sending request to DashScope API...");
      
              const response = await axios.post(url, data, {
                  headers: {
                      'Authorization': `Bearer ${apiKey}`,
                      'Content-Type': 'application/json'
                  }
              });
      
              if (response.status === 200) {
                  if (response.data.output && response.data.output.text) {
                      console.log(`${response.data.output.text}`);
                  }
              } else {
                  console.log("Request failed:");
                  if (response.data.request_id) {
                      console.log(`request_id=${response.data.request_id}`);
                  }
                  console.log(`code=${response.status}`);
                  if (response.data.message) {
                      console.log(`message=${response.data.message}`);
                  } else {
                      console.log('message=Unknown error');
                  }
              }
          } catch (error) {
              console.error(`Error calling DashScope: ${error.message}`);
              if (error.response) {
                  console.error(`Response status: ${error.response.status}`);
                  console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
              }
          }
      }
      
      callDashScope();
      

      響應樣本

      杭州市是浙江省的省會,其行政地區劃分包括10個市轄區。具體如下:
      
      1. 上城區(Shàngchéng Qū):位於杭州市中心偏南,是杭州歷史最悠久、文化底蘊最深厚的地區之一。
      2. 拱墅區(Gǒngshù Qū):原為下城區和拱墅區合并而成的新區,位於杭州市北部。
      3. 西湖區(Xīhú Qū):以世界文化遺產西湖而聞名,擁有豐富的自然與人文景觀。
      4. 濱江區(Bīnjiāng Qū):地處錢塘江南岸,是一個高新技術產業集聚地。
      5. 蕭山區(Xiāoshān Qū):位於杭州市東部,是中國重要的製造業基地之一。
      6. 餘杭區(Yúháng Qū):曾經是中國四大名鎮之一的臨平所在地,現已成為杭州重要的經濟發展區。
      7. 富陽區(Fùyáng Qū):位於杭州市西南部,因富春江穿流其間而得名。
      8. 臨安區(Lín'ān Qū):位於杭州市西部山區,以其美麗的自然風光著稱。
      9. 錢塘區(Qiántáng Qū):成立於2021年,由原大江東產業集聚區及部分蕭山區組成,旨在促進杭州東部地區的發展。
      10. 臨平區(Lín Píng Qū):從餘杭區分設出來的一個新行政區劃,主要涵蓋原餘杭區內的臨平街道等地。
      
      以上資訊反映了截至我最後更新時的情況,請注意行政區劃可能會有所調整,請以官方發布的最新訊息為準。

      C#

      請求樣本

      using System.Text;
      
      class Program
      {
          static async Task Main(string[] args)
          {
              //若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。 
              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"": ""查詢這個城市的行政地區劃分"",
                          ""biz_params"":{
                              ""city"":""杭州""
                          }
                      },
                      ""parameters"": {},
                      ""debug"": {}
                  }";
      
                  HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
      
                  try
                  {
                      HttpResponseMessage response = await client.PostAsync(url, content);
      
                      if (response.IsSuccessStatusCode)
                      {
                          string responseBody = await response.Content.ReadAsStringAsync();
                          Console.WriteLine("Request successful:");
                          Console.WriteLine(responseBody);
                      }
                      else
                      {
                          Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                          string responseBody = await response.Content.ReadAsStringAsync();
                          Console.WriteLine(responseBody);
                      }
                  }
                  catch (Exception ex)
                  {
                      Console.WriteLine($"Error calling DashScope: {ex.Message}");
                  }
              }
          }
      }

      響應樣本

      {
          "output": {
              "finish_reason": "stop",
              "session_id": "7a9ff57eec7d475fa5d487de5f5178d2",
              "text": "杭州市是浙江省的省會,它下轄有10個市轄區:上城區、拱墅區、西湖區、濱江區、蕭山區、餘杭區、臨平區、錢塘區、富陽區和臨安區。每個區都有其獨特的地理位置和發展特色。例如,西湖區以美麗的自然風光著稱,尤其是著名的杭州西湖就位於此;而濱江區則更多地以其高新技術產業發展聞名。此外,隨著城市的發展,行政區劃也可能會有所調整,請關注官方發布的最新資訊。"
          },
          "usage": {
      
          },
          "request_id": "d2c2fcc9-f821-98c9-9430-8704a2a41225"
      }

      Go

      請求樣本

      package main
      
      import (
      	"bytes"
      	"encoding/json"
      	"fmt"
      	"io"
      	"net/http"
      	"os"
      )
      
      func main() {
      	// 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey := "sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
      	apiKey := os.Getenv("DASHSCOPE_API_KEY")
      	appId := "YOUR_APP_ID" // 替換為實際的應用 ID
      
      	if apiKey == "" {
      		fmt.Println("請確保設定了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": "查詢這個城市的行政地區劃分",
      			"biz_params": map[string]interface{}{
      				"city": "杭州",
      			},
      		},
      		"parameters": map[string]interface{}{},
      		"debug":      map[string]interface{}{},
      	}
      
      	jsonData, err := json.Marshal(requestBody)
      	if err != nil {
      		fmt.Printf("Failed to marshal JSON: %v\n", err)
      		return
      	}
      
      	// 建立 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"
      }
  • 智能體應用中,自訂外掛程式的參數透傳功能使用user_defined_params傳遞參數資訊。自訂外掛程式的使用者級鑒權功能使用user_defined_tokens傳遞鑒權資訊,其中user_token傳遞的值為該外掛程式需要的鑒權資訊,如API_KEY。

    外掛程式中傳入帶有x-source屬性的參數才會產生效果,同時,目標外掛程式的描述請使用自然語言描述外掛程式的功能,協助大模型判斷當前任務是否需要調用當前外掛程式。

    image

    參考下面查詢寢室公約內容的例子,在應用中單擊選擇外掛程式添加需要使用的自訂外掛程式後,單擊發布應用。

    自訂外掛程式參數透傳

    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 = {
        # 智能體應用的自訂外掛程式輸入參數透傳,自訂的外掛程式ID替換{your_plugin_code}
        "user_defined_params": {
            "{your_plugin_code}": {
                "article_index": 2}}}
    response = Application.call(
            # 若沒有配置環境變數,可用百鍊API Key將下行替換為:api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
            api_key=os.getenv("DASHSCOPE_API_KEY"),
            app_id='YOUR_APP_ID',
            prompt='寢室公約內容',
            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'請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code')
    else:
        print('%s\n' % (response.output.text))  # 處理只輸出文本text
        # print('%s\n' % (response.usage))

    響應樣本

    寢室公約的第二條規定如下:
    
    "寢室成員應當互幫互助、互相關心、互相學習、共同提高;寬容謙讓、相互尊重、以誠相待。"
    
    這表明在寢室內,成員之間應該培養一種積極正面的生活和學習氛圍,彼此協助和支援,同時也要學會理解和尊重他人。如果您需要瞭解公約的其他條款,請告訴我!

    Java

    請求樣本

    import com.alibaba.dashscope.app.*;
    import com.alibaba.dashscope.exception.ApiException;
    import com.alibaba.dashscope.exception.InputRequiredException;
    import com.alibaba.dashscope.exception.NoApiKeyException;
    import com.alibaba.dashscope.utils.JsonUtils;
    
    import com.alibaba.dashscope.utils.Constants;
    
    public class Main {
        static {
            Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
        }
        public static void appCall() throws NoApiKeyException, InputRequiredException {
            String bizParams =
                    // 智能體應用的自訂外掛程式輸入參數透傳,自訂的外掛程式ID替換{your_plugin_code}
                    "{\"user_defined_params\":{\"{your_plugin_code}\":{\"article_index\":2}}}";
            ApplicationParam param = ApplicationParam.builder()
                    // 若沒有配置環境變數,可用百鍊API Key將下行替換為:.apiKey("sk-xxx")。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .appId("YOUR_APP_ID")
                    .prompt("寢室公約內容")
                    .bizParams(JsonUtils.parse(bizParams))
                    .build();
    
            Application application = new Application();
            ApplicationResult result = application.call(param);
            System.out.printf("%s\n",
                    result.getOutput().getText());
        }
    
        public static void main(String[] args) {
            try {
                appCall();
            } catch (ApiException | NoApiKeyException | InputRequiredException e) {
                System.out.printf("Exception: %s", e.getMessage());
                System.out.println("請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code");
            }
            System.exit(0);
        }
    }      

    響應樣本

    寢室公約的第二條規定如下:
    
    第二條 寢室成員應當互幫互助、互相關心、互相學習、共同提高;寬容謙讓、相互尊重、以誠相待。
    
    這強調了在共同生活環境中,室友之間應該保持積極正面的關係,通過相互協助和支援來營造一個和諧的生活和學習氛圍。如果有更多具體的條款需要瞭解,請告知我。

    HTTP

    curl

    請求樣本

    curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
    --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
    --header 'Content-Type: application/json' \
    --data '{
        "input": {
            "prompt": "寢室公約內容",
            "biz_params": 
            {
                "user_defined_params":
                {
                    "{your_plugin_code}":
                        {
                        "article_index": 2
                        }
                }
            } 
        },
        "parameters":  {},
        "debug":{}
    }'
    YOUR_APP_ID替換為實際的應用 ID。

    響應樣本

    {"output":
    {"finish_reason":"stop",
    "session_id":"e151267ffded4fbdb13d91439011d31e",
    "text":"寢室公約的第二條內容是:“寢室成員應當互幫互助、互相關心、互相學習、共同提高;寬容謙讓、相互尊重、以誠相待。”這意呀著在寢室生活中,大家要彼此支援,共同創造一個和諧、積極向上的生活環境。"},
    "usage":{"models":[{"output_tokens":94,"model_id":"qwen-max","input_tokens":453}]},
    "request_id":"a39fd2b5-7e2c-983e-84a1-1039f726f18a"}%

    PHP

    請求樣本

    <?php
    
    # 若沒有配置環境變數,可用百鍊API Key將下行替換為:$api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
    $api_key = getenv("DASHSCOPE_API_KEY");
    $application_id = 'YOUR_APP_ID'; // 替換為實際的應用 ID
    $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
    //{your_plugin_code}替換為實際的外掛程式ID
    // 構造請求資料
    $data = [
        "input" => [
            'prompt' => '寢室公約內容',
            '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";}
    }
    ?>

    響應樣本

    寢室公約的第二條規定:寢室成員應當互幫互助、互相關心、互相學習、共同提高;寬容謙讓、相互尊重、以誠相待。這是為了保證大家能在一個和諧友愛的環境中生活和學習。如果有更多具體的條款需要瞭解,或者有其他問題,隨時可以問我!

    Node.js

    需安裝相關依賴:

    npm install axios

    請求樣本

    const axios = require('axios');
    
    async function callDashScope() {
        // 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey='sk-xxx'。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
        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: "寢室公約內容",
                biz_params: {
                    user_defined_params: {
                        [pluginCode]: {
                            // article_index為自訂外掛程式的變數,替換為實際的外掛程式變數
                            'article_index': 3
                        }
                    }
                }
            },
            parameters: {},
            debug: {}
        };
    
        try {
            console.log("Sending request to DashScope API...");
    
            const response = await axios.post(url, data, {
                headers: {
                    'Authorization': `Bearer ${apiKey}`,
                    'Content-Type': 'application/json'
                }
            });
    
            if (response.status === 200) {
                if (response.data.output && response.data.output.text) {
                    console.log(`${response.data.output.text}`);
                }
            } else {
                console.log("Request failed:");
                if (response.data.request_id) {
                    console.log(`request_id=${response.data.request_id}`);
                }
                console.log(`code=${response.status}`);
                if (response.data.message) {
                    console.log(`message=${response.data.message}`);
                } else {
                    console.log('message=Unknown error');
                }
            }
        } catch (error) {
            console.error(`Error calling DashScope: ${error.message}`);
            if (error.response) {
                console.error(`Response status: ${error.response.status}`);
                console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
            }
        }
    }
    callDashScope();
    

    響應樣本

    寢室公約的第三條規定如下:
    
    注意安全用電,杜絕火災隱患。寢室內嚴禁使用明火、違規電器、各種灶具以及其他違規物品,不得存放易爆、易燃物品,私接電源。
    
    如果您需要瞭解更多的規定,請告訴我。

    C#

    請求樣本

    using System.Text;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            // 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
            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("請確保設定了 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"": ""寢室公約內容"",
                        ""biz_params"": {{
                            ""user_defined_params"": {{
                                ""{pluginCode}"": {{
                                    ""article_index"": 2
                                }}
                            }}
                        }}
                    }},
                    ""parameters"": {{}},
                    ""debug"": {{}}
                }}";
    
                HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
    
                try
                {
                    HttpResponseMessage response = await client.PostAsync(url, content);
    
                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine("Request successful:");
                        Console.WriteLine(responseBody);
                    }
                    else
                    {
                        Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine(responseBody);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error calling DashScope: {ex.Message}");
                }
            }
        }
    }

    響應樣本

    {
        "output": {
            "finish_reason": "stop",
            "session_id": "237ca6187c814f3b9e7461090a5f8b74",
            "text": "寢室公約的第二條規定如下:
    
    "寢室成員應當互幫互助、互相關心、互相學習、共同提高;寬容謙讓、相互尊重、以誠相待。"
    
    這表示在寢室內,成員之間需要建立起一種積極正面的關係,通過協助、關心和支援彼此來營造一個和諧的生活和學習環境。同時也要學會理解和接受室友之間的差異,以真誠的態度去交流溝通。如果還有其他條款或具體內容想要瞭解,請告訴我!"
        },
        "usage": {
            "models": [
                {
                    "output_tokens": 133,
                    "model_id": "qwen-max",
                    "input_tokens": 829
                }
            ]
        },
        "request_id": "64e8c359-d071-9d2e-bb94-187e86cc3a79"
    }

    Go

    請求樣本

    package main
    
    import (
    	"bytes"
    	"encoding/json"
    	"fmt"
    	"io"
    	"net/http"
    	"os"
    )
    
    func main() {
    	// 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey := "sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
    	apiKey := os.Getenv("DASHSCOPE_API_KEY")
    	appId := "YOUR_APP_ID"           // 替換為實際的應用 ID
    	pluginCode := "YOUR_PLUGIN_CODE" // 替換為實際的外掛程式 ID
    
    	if apiKey == "" {
    		fmt.Println("請確保設定了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": "寢室公約內容",
    			"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": "寢室公約的第二條規定如下:
    
    寢室成員應當互幫互助、互相關心、互相學習、共同提高;寬容謙讓、相互尊重、以誠相待。
    
    這強調了在宿捨生活中,室友之間應該保持良好的互助關係,同時也要互相尊重對方。您想要瞭解其他條款的內容嗎?"
        },
        "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 = {
        # 智能體應用的自訂外掛程式鑒權透傳,自訂的外掛程式ID替換{your_plugin_code},鑒權資訊替換YOUR_TOKEN,如API key
        "user_defined_params": {
            "{your_plugin_code}": {
                "article_index": 2}},
        "user_defined_tokens": {
            "{your_plugin_code}": {
                "user_token": "YOUR_TOKEN"}}}
    response = Application.call(
                # 若沒有配置環境變數,可用百鍊API Key將下行替換為:api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
                api_key=os.getenv("DASHSCOPE_API_KEY"), 
                app_id='YOUR_APP_ID',
                prompt='寢室公約內容',
                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'請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code')
    else:
        print('%s\n' % (response.output.text))  # 處理只輸出文本text
        # print('%s\n' % (response.usage))

    響應樣本

    寢室公約的第二條規定如下:
    
    寢室成員應當互幫互助、互相關心、互相學習、共同提高;寬容謙讓、相互尊重、以誠相待。
    
    如果您需要瞭解更多的規定內容,請告訴我。

    Java

    請求樣本

    import com.alibaba.dashscope.app.*;
    import com.alibaba.dashscope.exception.ApiException;
    import com.alibaba.dashscope.exception.InputRequiredException;
    import com.alibaba.dashscope.exception.NoApiKeyException;
    import com.alibaba.dashscope.utils.JsonUtils;
    import com.alibaba.dashscope.utils.Constants;
    
    public class Main {
        static {
            Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
        }
        public static void appCall() throws NoApiKeyException, InputRequiredException {
            String bizParams =
                    // {your_plugin_code}替換為實際的外掛程式ID,YOUR_TOKEN替換為實際的Token,如API key
                    "{\"user_defined_params\":{\"{your_plugin_code}\":{\"article_index\":2}}," +
                            "\"user_defined_tokens\":{\"{your_plugin_code}\":{\"user_token\":\"YOUR_TOKEN\"}}}";
            ApplicationParam param = ApplicationParam.builder()
                    // 若沒有配置環境變數,可用百鍊API Key將下行替換為:.apiKey("sk-xxx")。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .appId("YOUR_APP_ID")
                    .prompt("寢室公約內容")
                    .bizParams(JsonUtils.parse(bizParams))
                    .build();
    
            Application application = new Application();
            ApplicationResult result = application.call(param);
            System.out.printf("%s\n",
                    result.getOutput().getText());
        }
        public static void main(String[] args) {
            try {
                appCall();
            } catch (ApiException | NoApiKeyException | InputRequiredException e) {
                System.out.printf("Exception: %s", e.getMessage());
                System.out.println("請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code");
            }
            System.exit(0);
        }
    }

    響應樣本

    寢室公約的第二條規定如下:
    
    寢室成員應當互幫互助、互相關心、互相學習、共同提高;寬容謙讓、相互尊重、以誠相待。
    
    如果您需要查詢更多的規定內容,請告訴我。

    HTTP

    curl

    請求樣本

    curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
    --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
    --header 'Content-Type: application/json' \
    --data '{
        "input": {
            "prompt": "寢室公約內容",
            "biz_params": 
            {
                "user_defined_params":
                {
                    "{your_plugin_code}":
                        {
                        "article_index": 2
                        }
                },
                "user_defined_tokens":
                {
                    "{your_plugin_code}":
                        {
                        "user_token": "YOUR_TOKEN"
                        }
                }
            } 
        },
        "parameters":  {},
        "debug":{}
    }'
    
    
    
    YOUR_APP_ID替換為實際的應用 ID。

    響應樣本

    {"output":{"finish_reason":"stop",
    "session_id":"d3b5c3e269dc40479255a7a02df5c630",
    "text":"寢室公約的第二條內容為:“寢室成員應當互幫互助、互相關心、互相學習、共同提高;寬容謙讓、相互尊重、以誠相待。”這強調了寢室生活中成員之間和諧相處與共同進步的重要性。"},
    "usage":{"models":[{"output_tokens":80,"model_id":"qwen-max","input_tokens":432}]},
    "request_id":"1f77154c-edc3-9003-b622-816fa2f849cf"}%

    PHP

    請求樣本

    <?php
    
    # 若沒有配置環境變數,可用百鍊API Key將下行替換為:$api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
    $api_key = getenv("DASHSCOPE_API_KEY");
    $application_id = 'YOUR_APP_ID'; // 替換為實際的應用 ID
    $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
    
    // 構造請求資料
    $data = [
        "input" => [
            'prompt' => '寢室公約內容',
            'biz_params' => [
            'user_defined_params' => [
                '{your_plugin_code}' => [//{your_plugin_code}替換為實際的外掛程式ID
                    'article_index' => 2            
                    ]
                ],
            'user_defined_tokens' => [
                '{your_plugin_code}' => [//{your_plugin_code}替換為實際的外掛程式ID
                    'user_token' => 'YOUR_TOKEN'//替換為實際的Token,如API key
                ]
            ]
            ]
        ],
    ];
    // 將資料編碼為 JSON
    $dataString = json_encode($data);
    
    // 檢查 json_encode 是否成功
    if (json_last_error() !== JSON_ERROR_NONE) {
        die("JSON encoding failed with error: " . json_last_error_msg());
    }
    
    // 初始化 cURL 對話
    $ch = curl_init($url);
    
    // 設定 cURL 選項
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $api_key
    ]);
    
    // 執行請求
    $response = curl_exec($ch);
    
    // 檢查 cURL 執行是否成功
    if ($response === false) {
        die("cURL Error: " . curl_error($ch));
    }
    
    // 擷取 HTTP 狀態代碼
    $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    // 關閉 cURL 對話
    curl_close($ch);
    // 解碼響應資料
    $response_data = json_decode($response, true);
    // 處理響應
    if ($status_code == 200) {
        if (isset($response_data['output']['text'])) {
            echo "{$response_data['output']['text']}\n";
        } else {
            echo "No text in response.\n";
        }
    }else {
        if (isset($response_data['request_id'])) {
            echo "request_id={$response_data['request_id']}\n";}
        echo "code={$status_code}\n";
        if (isset($response_data['message'])) {
            echo "message={$response_data['message']}\n";} 
        else {
            echo "message=Unknown error\n";}
    }
    ?>

    響應樣本

    寢室公約的第二條規定如下:
    
    > 寢室成員應當互幫互助、互相關心、互相學習、共同提高;寬容謙讓、相互尊重、以誠相待。
    
    如果需要瞭解更多的公約內容或其他資訊,請隨時告訴我!

    Node.js

    需安裝相關依賴:

    npm install axios

    請求樣本

    const axios = require('axios');
    async function callDashScope() {
        // 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey='sk-xxx'。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
        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: "寢室公約內容",
                biz_params: {
                    user_defined_params: {
                        [pluginCode]: {
                            // article_index為自訂外掛程式的變數,替換為實際的外掛程式變數
                            'article_index': 6
                        }
                    },
                    user_defined_tokens: {
                        [pluginCode]: {
                            // YOUR_TOKEN替換為實際的鑒權資訊,如API key
                            user_token: 'YOUR_TOKEN'
                        }
                    }
                }
            },
            parameters: {},
            debug: {}
        };
    
        try {
            console.log("Sending request to DashScope API...");
    
            const response = await axios.post(url, data, {
                headers: {
                    'Authorization': `Bearer ${apiKey}`,
                    'Content-Type': 'application/json'
                }
            });
    
            if (response.status === 200) {
                if (response.data.output && response.data.output.text) {
                    console.log(`${response.data.output.text}`);
                }
            } else {
                console.log("Request failed:");
                if (response.data.request_id) {
                    console.log(`request_id=${response.data.request_id}`);
                }
                console.log(`code=${response.status}`);
                if (response.data.message) {
                    console.log(`message=${response.data.message}`);
                } else {
                    console.log('message=Unknown error');
                }
            }
        } catch (error) {
            console.error(`Error calling DashScope: ${error.message}`);
            if (error.response) {
                console.error(`Response status: ${error.response.status}`);
                console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
            }
        }
    }
    callDashScope();

    響應樣本

    寢室公約的第六條規定:養成良好的作息習慣,每一位寢室成員都享有休息的權利和承擔保證他人休息權利和義務。如果你需要瞭解更多的規定內容,請進一步說明。

    C#

    請求樣本

    using System.Text;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            // 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
            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("請確保設定了 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替換為實際的Token,如API key
                string jsonContent = $@"{{
                    ""input"": {{
                        ""prompt"": ""寢室公約內容"",
                        ""biz_params"": {{
                            ""user_defined_params"": {{
                                ""{pluginCode}"": {{
                                    ""article_index"": 2
                                }}
                            }},
                            ""user_defined_tokens"": {{
                                ""{pluginCode}"": {{
                                    ""user_token"": ""YOUR_TOKEN"" 
                                }}
                            }}
                        }}
                    }},
                    ""parameters"": {{}},
                    ""debug"": {{}}
                }}";
    
                HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
    
                try
                {
                    HttpResponseMessage response = await client.PostAsync(url, content);
    
                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine("Request successful:");
                        Console.WriteLine(responseBody);
                    }
                    else
                    {
                        Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine(responseBody);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error calling DashScope: {ex.Message}");
                }
            }
        }
    }

    響應樣本

    {
        "output": {
            "finish_reason": "stop",
            "session_id": "1a1913a9922a401f8eba36df8ea1a062",
            "text": "寢室公約的第二條規定如下:
    
    寢室成員應當互幫互助、互相關心、互相學習、共同提高;寬容謙讓、相互尊重、以誠相待。
    
    如需瞭解更詳細的公約內容,請進一步指明。"
        },
        "usage": {
            "models": [
                {
                    "output_tokens": 66,
                    "model_id": "qwen-max",
                    "input_tokens": 802
                }
            ]
        },
        "request_id": "04bac806-c5e6-9fab-a846-a66641862be9"
    }

    Go

    請求樣本

    package main
    
    import (
    	"bytes"
    	"encoding/json"
    	"fmt"
    	"io"
    	"net/http"
    	"os"
    )
    
    func main() {
    	// 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey := "sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
    	apiKey := os.Getenv("DASHSCOPE_API_KEY")
    	appId := "YOUR_APP_ID"           // 替換為實際的應用 ID
    	pluginCode := "YOUR_PLUGIN_CODE" // 替換為實際的外掛程式 ID
    
    	if apiKey == "" {
    		fmt.Println("請確保設定了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": "寢室公約內容",
    			"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", // 替換實際的鑒權 token,如API key
    					},
    				},
    			},
    		},
    		"parameters": map[string]interface{}{},
    		"debug":      map[string]interface{}{},
    	}
    
    	jsonData, err := json.Marshal(requestBody)
    	if err != nil {
    		fmt.Printf("Failed to marshal JSON: %v\n", err)
    		return
    	}
    
    	// 建立 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": "寢室公約的第十條規定,寢室成員應共同努力,營造和維護內務整潔乾淨、美觀、高文化品味的寢室環境。如果需要瞭解完整的寢室公約內容,可能還需要查看其他條款或直接諮詢宿舍管理部門。對於更多具體內容,您還有想要瞭解的部分嗎?"
        },
        "usage": {
            "models": [
                {
                    "output_tokens": 70,
                    "model_id": "qwen-max",
                    "input_tokens": 855
                }
            ]
        },
        "request_id": "0921ee34-2754-9616-a826-cea33a0e0a14"
    }

流式輸出

大模型並不是一次性產生最終結果,而是逐步產生中間結果,最終結果由中間結果拼接而成。使用非流式輸出方式需要等待模型產生結束後再將產生的中間結果拼接後返回,而流式輸出可以即時地將中間結果返回,您可以在模型進行輸出的同時進行閱讀,減少等待模型回複的時間。

流式輸出的實現在Python SDK中需要設定stream為True,Java SDK中流式介面為streamCall,HTTP調用時需要設定Header中的 X-DashScope-SSE 為 enable。

工作流程應用和智能體編排應用的流式輸出實現還需要設定has_thoughts為True,結果在thoughts欄位中返回。

如果您想要增量輸出回複則設定incremental_output為True。

參考下方樣本:

  • 智能體應用流式輸出調用樣本如下:

    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將下行替換為:api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
                api_key=os.getenv("DASHSCOPE_API_KEY"), 
                app_id='YOUR_APP_ID',
                prompt='你是誰?',
                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/zh/model-studio/developer-reference/error-code')
        else:
            print(f'{response.output.text}\n')  # 處理只輸出文本text

    響應樣本

    我是來自
    
    阿里
    
    雲
    
    的大規模語言模型
    
    ,我叫通
    
    義千問。

    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()
                    // 若沒有配置環境變數,可用百鍊API Key將下行替換為:.apiKey("sk-xxx")。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    // 替換為實際的應用 ID
                    .appId("YOUR_APP_ID")
                    .prompt("你是誰?")
                    // 增量輸出
                    .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/zh/model-studio/developer-reference/error-code");
            }
            System.exit(0);
        }
    }

    響應樣本

    我是阿里
    雲
    開發的一款超大規模語言
    模型,我叫
    通義千問
    。

    HTTP

    curl

    請求樣本

    curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
    --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
    --header 'Content-Type: application/json' \
    --header 'X-DashScope-SSE: enable' \
    --data '{
        "input": {
            "prompt": "你是誰?"
    
        },
        "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":"我是"},"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":"來自"},"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":"阿里"},"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":"雲"},"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":"的超大規模語言"},"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":"模型,我叫"},"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":"通義千問"},"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將下行替換為:$api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
    $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' => '你是誰?'],
        "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":"我是阿里"},"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":"雲"},"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":"開發"},"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":"的一款超大規模語言"},"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":"模型,我叫"},"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":"通義千問"},"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

    請求樣本

    const axios = require('axios');
    
    async function callDashScope() {
        //若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey='sk-xxx'。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
        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: "你是誰?"
            },
            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();

    響應樣本

    id:1
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"null","text":"你好!"},"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":"有什麼"},"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":"可以協助"},"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":"你的嗎?"},"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"}

    C#

    請求樣本

    using System.Text;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            //若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。 
            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"": ""你是誰?""
                    },
                    ""parameters"": {""incremental_output"": true},
                    ""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}");
                }
            }
        }
    }

    響應樣本

    id:1
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"0c60c5cc649f431193dbabfd00973bda","finish_reason":"null","text":"我是"},"usage":{"models":[{"input_tokens":74,"output_tokens":1,"model_id":"qwen-plus"}]},"request_id":"6b83b0a8-0c82-935b-809a-12bbde366add"}
    
    id:2
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"0c60c5cc649f431193dbabfd00973bda","finish_reason":"null","text":"通"},"usage":{"models":[{"input_tokens":74,"output_tokens":2,"model_id":"qwen-plus"}]},"request_id":"6b83b0a8-0c82-935b-809a-12bbde366add"}
    
    id:3
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"0c60c5cc649f431193dbabfd00973bda","finish_reason":"null","text":"義"},"usage":{"models":[{"input_tokens":74,"output_tokens":3,"model_id":"qwen-plus"}]},"request_id":"6b83b0a8-0c82-935b-809a-12bbde366add"}
    
    id:4
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"0c60c5cc649f431193dbabfd00973bda","finish_reason":"null","text":"千"},"usage":{"models":[{"input_tokens":74,"output_tokens":4,"model_id":"qwen-plus"}]},"request_id":"6b83b0a8-0c82-935b-809a-12bbde366add"}
    
    id:5
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"0c60c5cc649f431193dbabfd00973bda","finish_reason":"null","text":"問,由阿里"},"usage":{"models":[{"input_tokens":74,"output_tokens":8,"model_id":"qwen-plus"}]},"request_id":"6b83b0a8-0c82-935b-809a-12bbde366add"}
    
    id:6
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"0c60c5cc649f431193dbabfd00973bda","finish_reason":"null","text":"雲開發的AI"},"usage":{"models":[{"input_tokens":74,"output_tokens":12,"model_id":"qwen-plus"}]},"request_id":"6b83b0a8-0c82-935b-809a-12bbde366add"}
    
    id:7
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"0c60c5cc649f431193dbabfd00973bda","finish_reason":"null","text":"助手。我被"},"usage":{"models":[{"input_tokens":74,"output_tokens":16,"model_id":"qwen-plus"}]},"request_id":"6b83b0a8-0c82-935b-809a-12bbde366add"}
    
    id:8
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"0c60c5cc649f431193dbabfd00973bda","finish_reason":"null","text":"設計用來協助使用者"},"usage":{"models":[{"input_tokens":74,"output_tokens":20,"model_id":"qwen-plus"}]},"request_id":"6b83b0a8-0c82-935b-809a-12bbde366add"}
    
    id:9
    

    Go

    請求樣本

    package main
    
    import (
    	"bytes"
    	"encoding/json"
    	"fmt"
    	"io"
    	"net/http"
    	"os"
    )
    
    func main() {
    	// 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey := "sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
    	apiKey := os.Getenv("DASHSCOPE_API_KEY")
    	appId := "YOUR_APP_ID" // 替換為實際的應用 ID
    
    	if apiKey == "" {
    		fmt.Println("請確保設定了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]string{
    			"prompt": "你是誰?",
    		},
    		"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
    	}
    
    	// 佈建要求頭
    	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()
    
    	// 讀取響應
    	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))
    	}
    }
    

    響應樣本

    Request successful:
    id:1
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"我是"},"usage":{"models":[{"input_tokens":74,"output_tokens":1,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"}
    
    id:2
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"阿里"},"usage":{"models":[{"input_tokens":74,"output_tokens":2,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"}
    
    id:3
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"雲"},"usage":{"models":[{"input_tokens":74,"output_tokens":3,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"}
    
    id:4
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"開發"},"usage":{"models":[{"input_tokens":74,"output_tokens":4,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"}
    
    id:5
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"的一款超大規模語言"},"usage":{"models":[{"input_tokens":74,"output_tokens":8,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"}
    
    id:6
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"模型,我叫"},"usage":{"models":[{"input_tokens":74,"output_tokens":12,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"}
    
    id:7
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"通義千問"},"usage":{"models":[{"input_tokens":74,"output_tokens":16,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"}
    
    id:8
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"。我被設計"},"usage":{"models":[{"input_tokens":74,"output_tokens":20,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"}
    
    id:9
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"用來協助使用者產生"},"usage":{"models":[{"input_tokens":74,"output_tokens":24,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"}
    
    id:10
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"各種文本,如"},"usage":{"models":[{"input_tokens":74,"output_tokens":28,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"}
    
    id:11
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"文章、故事、"},"usage":{"models":[{"input_tokens":74,"output_tokens":32,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"}
    
    id:12
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"詩歌、故事等"},"usage":{"models":[{"input_tokens":74,"output_tokens":36,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"}
    
    id:13
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":",並能根據不同的"},"usage":{"models":[{"input_tokens":74,"output_tokens":40,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"}
    
    id:14
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"情境和需求進行"},"usage":{"models":[{"input_tokens":74,"output_tokens":44,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"}
    
    id:15
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"調整和最佳化。"},"usage":{"models":[{"input_tokens":74,"output_tokens":48,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"}
    
    id:16
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"此外,我還能夠"},"usage":{"models":[{"input_tokens":74,"output_tokens":52,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"}
    
    id:17
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"回答各種問題,"},"usage":{"models":[{"input_tokens":74,"output_tokens":56,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"}
    
    id:18
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"提供資訊查詢、"},"usage":{"models":[{"input_tokens":74,"output_tokens":60,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"}
    
    id:19
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"知識解答、解決問題"},"usage":{"models":[{"input_tokens":74,"output_tokens":64,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"}
    
    id:20
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"等服務。如果您"},"usage":{"models":[{"input_tokens":74,"output_tokens":68,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"}
    
    id:21
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"有任何問題或需要"},"usage":{"models":[{"input_tokens":74,"output_tokens":72,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"}
    
    id:22
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"任何協助,請隨時"},"usage":{"models":[{"input_tokens":74,"output_tokens":76,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"}
    
    id:23
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"告訴我,我會儘力"},"usage":{"models":[{"input_tokens":74,"output_tokens":80,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"}
    
    id:24
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"提供支援。"},"usage":{"models":[{"input_tokens":74,"output_tokens":83,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"}
    
    id:25
    event:result
    :HTTP_STATUS/200
    data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":74,"output_tokens":83,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"}
  • 工作流程應用和智能體編排應用的流式輸出實現還需要設定has_thoughts為True。所有節點的流式輸出(能流式的會流式輸出比如LLM節點,非流式的會同步輸出比如文本轉換節點)在應用API中的thoughts欄位返回。這樣既不會破壞結束節點最終的結果,也能滿足使用者多變的流式需求。參考下面多節點樣本。

    1. 如圖所示發行的工作流程應用配置,對杭州的美食和景點進行流式輸出。

      image

    2. 通過API調用。

      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": "杭州"}
      responses = Application.call(
          # 若沒有配置環境變數,可用百鍊API Key將下行替換為:api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
          api_key=os.getenv("DASHSCOPE_API_KEY"),
          # 替換為實際的應用 ID
          app_id='YOUR_APP_ID',
          prompt='你好',
          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/zh/model-studio/developer-reference/error-code')
          else:
              print(f'{response.output.thoughts}\n')  # 處理輸出只返回thoughts;在output的thoughts欄位中返回過程資訊

      響應樣本

      [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"開始","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_Ilo9","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_Ilo9"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
      
      [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"開始","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":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"西湖醋魚,\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_Ilo9"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
      
      [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"開始","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":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"東坡肉,\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_Ilo9"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
      
      [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"開始","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":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"知味觀小\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_Ilo9"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
      
      [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"開始","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":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"籠包,龍井蝦仁,\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_Ilo9"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
      
      [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"開始","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":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"叫化雞\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_Ilo9","nodeExecTime":"1332ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
      
      [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"開始","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":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_Ilo9","nodeExecTime":"1332ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_vQDv","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_vQDv"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
      
      [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"開始","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":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_Ilo9","nodeExecTime":"1332ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_kBgf","nodeResult":"{\\"result\\":\\"西湖,靈隱\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_vQDv"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
      
      [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"開始","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":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_Ilo9","nodeExecTime":"1332ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_kBgf","nodeResult":"{\\"result\\":\\"寺,宋城\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_vQDv"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
      
      [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"開始","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":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_Ilo9","nodeExecTime":"1332ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_kBgf","nodeResult":"{\\"result\\":\\",西溪濕地\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_vQDv"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
      
      [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"開始","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":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_Ilo9","nodeExecTime":"1332ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_kBgf","nodeResult":"{\\"result\\":\\",千島湖\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_vQDv"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
      
      [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"開始","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":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_Ilo9","nodeExecTime":"1332ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_kBgf","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_vQDv","nodeExecTime":"948ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"結束","nodeResult":"{\\"result\\":\\"西湖,靈隱寺,宋城,西溪濕地,千島湖\\"}","nodeType":"End","nodeStatus":"success","nodeId":"End_DrQn7F","nodeExecTime":"1ms"}', 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\":\"杭州\"}";
              ApplicationParam param = ApplicationParam.builder()
                      // 若沒有配置環境變數,可用百鍊API Key將下行替換為:.apiKey("sk-xxx")。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
                      .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                      .appId("YOUR_APP_ID") //替換為實際的應用 ID
                      .prompt("你好")
                      .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/zh/model-studio/developer-reference/error-code");
              }
              System.exit(0);
          }
      }

      響應樣本

      [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"開始","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":"開始","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":"大模型_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":"開始","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":"大模型_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":"開始","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":"大模型_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":"開始","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":"大模型_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":"開始","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":"大模型_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":"開始","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":"大模型_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":"大模型_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":"開始","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":"大模型_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":"大模型_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":"開始","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":"大模型_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":"大模型_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":"開始","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":"大模型_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":"大模型_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":"開始","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":"大模型_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":"大模型_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":"結束","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": "你好",
              "biz_params": {
              "city": "杭州"}
          },
          "parameters":  {
              "has_thoughts": true,
              "incremental_output": true
          },
          "debug": {}
      }'
      YOUR_APP_ID替換為實際的應用 ID。

      響應樣本

      id:1
      event:result
      :HTTP_STATUS/200
      data:{"output":{"session_id":"2d55b40211054ac3b5f05478aea677b5","finish_reason":"null"},"usage":{},"request_id":"a8db9989-8fae-9698-a407-ab362bbb88d8"}
      
      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_Ilo9\"}"}],"session_id":"2d55b40211054ac3b5f05478aea677b5","finish_reason":"null"},"usage":{},"request_id":"a8db9989-8fae-9698-a407-ab362bbb88d8"}
      
      id:3
      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_Ilo9\"}"}],"session_id":"2d55b40211054ac3b5f05478aea677b5","finish_reason":"null"},"usage":{},"request_id":"a8db9989-8fae-9698-a407-ab362bbb88d8"}
      
      id:4
      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_Ilo9\"}"}],"session_id":"2d55b40211054ac3b5f05478aea677b5","finish_reason":"null"},"usage":{},"request_id":"a8db9989-8fae-9698-a407-ab362bbb88d8"}
      
      id:5
      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_Ilo9\"}"}],"session_id":"2d55b40211054ac3b5f05478aea677b5","finish_reason":"null"},"usage":{},"request_id":"a8db9989-8fae-9698-a407-ab362bbb88d8"}
      
      id:6
      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_Ilo9\"}"}],"session_id":"2d55b40211054ac3b5f05478aea677b5","finish_reason":"null"},"usage":{},"request_id":"a8db9989-8fae-9698-a407-ab362bbb88d8"}
      
      id:7
      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_Ilo9\",\"nodeExecTime\":\"1996ms\"}"},
      {"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"2d55b40211054ac3b5f05478aea677b5","finish_reason":"null"},"usage":{},"request_id":"a8db9989-8fae-9698-a407-ab362bbb88d8"}
      
      id:8
      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_Ilo9\",\"nodeExecTime\":\"1996ms\"}"},
      {"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"西湖,宋\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"2d55b40211054ac3b5f05478aea677b5","finish_reason":"null"},"usage":{},"request_id":"a8db9989-8fae-9698-a407-ab362bbb88d8"}
      
      id:9
      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_Ilo9\",\"nodeExecTime\":\"1996ms\"}"},
      {"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"城,靈隱寺\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"2d55b40211054ac3b5f05478aea677b5","finish_reason":"null"},"usage":{},"request_id":"a8db9989-8fae-9698-a407-ab362bbb88d8"}
      
      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_Ilo9\",\"nodeExecTime\":\"1996ms\"}"},
      {"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",西溪國家濕地公園,雷\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"2d55b40211054ac3b5f05478aea677b5","finish_reason":"null"},"usage":{},"request_id":"a8db9989-8fae-9698-a407-ab362bbb88d8"}
      
      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_Ilo9\",\"nodeExecTime\":\"1996ms\"}"},
      {"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"峰塔\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_vQDv\",\"nodeExecTime\":\"1383ms\"}"},
      {"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"西湖,宋城,靈隱寺,西溪國家濕地公園,雷峰塔\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"1ms\"}"}],"session_id":"2d55b40211054ac3b5f05478aea677b5","finish_reason":"stop","text":"西湖,宋城,靈隱寺,西溪國家濕地公園,雷峰塔"},"usage":{},"request_id":"a8db9989-8fae-9698-a407-ab362bbb88d8"}

      PHP

      請求樣本

      <?php
      
      # 若沒有配置環境變數,可用百鍊API Key將下行替換為:$api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
      $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' => '你好',
              'biz_params' => [
                  'city' => '杭州'
              ]
          ],
          "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\":\"開始\",\"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\":\"開始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_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:4
      event:result
      :HTTP_STATUS/200
      data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"開始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_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\":\"開始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_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:6
      event:result
      :HTTP_STATUS/200
      data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"開始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_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:7
      event:result
      :HTTP_STATUS/200
      data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"開始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"仁,叫化雞\\\"}\",\"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\":\"開始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_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\":\"開始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"大模型_kBgf\",\"nodeResult\":\"{\\\"result\\\":\\\"西湖,靈隱\\\"}\",\"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\":\"開始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"大模型_kBgf\",\"nodeResult\":\"{\\\"result\\\":\\\"寺,宋城\\\"}\",\"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\":\"開始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"大模型_kBgf\",\"nodeResult\":\"{\\\"result\\\":\\\",西溪濕地\\\"}\",\"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\":\"開始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"大模型_kBgf\",\"nodeResult\":\"{\\\"result\\\":\\\",杭州塔\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_vQDv\",\"nodeExecTime\":\"899ms\"}"},{"response":"{\"nodeName\":\"結束\",\"nodeResult\":\"{\\\"result\\\":\\\"西湖,靈隱寺,宋城,西溪濕地,杭州塔\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"0ms\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"stop","text":"西湖,靈隱寺,宋城,西溪濕地,杭州塔"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"}
      

      Node.js

      需安裝相關依賴:

      npm install axios

      請求樣本

      const axios = require('axios');
      
      async function callDashScope() {
          // 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey='sk-xxx'。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
          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: "你好",
                  biz_params:{
                      'city':'杭州'
                  }
              },
              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\\\":\\\"西湖醋\\\"}\",\"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\\\":\\\"魚,\\\"}\",\"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\\\":\\\"龍井蝦仁\\\"}\",\"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\\\":\\\",東坡肉\\\"}\",\"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\\\":\\\",知味觀\\\"}\",\"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\\\":\\\"小籠包,\\\"}\",\"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\\\":\\\"叫花雞\\\"}\",\"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\\\":\\\"西湖,\\\"}\",\"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\\\":\\\"靈隱\\\"}\",\"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\\\":\\\"寺,宋城,西溪濕地\\\"}\",\"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\\\":\\\",千島湖\\\"}\",\"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\\\":\\\"西湖,靈隱寺,宋城,西溪濕地,千島湖\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"1ms\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"stop","text":"西湖,靈隱寺,宋城,西溪濕地,千島湖"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"}
      Stream ended.
      

      C#

      請求樣本

      using System.Text;
      
      class Program
      {
          static async Task Main(string[] args)
          {
              //若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。 
              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";
              // 工作流程應用和智能體編排應用實現流式輸出需要設定has_thoughts為true
              using (HttpClient client = new HttpClient())
              {
                  client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
                  client.DefaultRequestHeaders.Add("X-DashScope-SSE", "enable");
      
                  string jsonContent = @"{
                      ""input"": {
                          ""prompt"": ""你好"",
                          ""biz_params"":{
                              ""city"":""杭州""
                          }
                      },
                      ""parameters"": {
                          ""incremental_output"": true,
                          ""has_thoughts"": true 
                          },
                      ""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}");
                  }
              }
          }
      }

      響應樣本

      id:1
      event:result
      :HTTP_STATUS/200
      data:{"output":{"session_id":"ed976b73d9be46f7aff888b9440fe5d6","finish_reason":"null"},"usage":{},"request_id":"32c86a8c-dbd1-9c12-a175-8837224a13e0"}
      
      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_Ilo9\"}"}],"session_id":"ed976b73d9be46f7aff888b9440fe5d6","finish_reason":"null"},"usage":{},"request_id":"32c86a8c-dbd1-9c12-a175-8837224a13e0"}
      
      id:3
      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_Ilo9\"}"}],"session_id":"ed976b73d9be46f7aff888b9440fe5d6","finish_reason":"null"},"usage":{},"request_id":"32c86a8c-dbd1-9c12-a175-8837224a13e0"}
      
      id:4
      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_Ilo9\"}"}],"session_id":"ed976b73d9be46f7aff888b9440fe5d6","finish_reason":"null"},"usage":{},"request_id":"32c86a8c-dbd1-9c12-a175-8837224a13e0"}
      
      id:5
      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_Ilo9\"}"}],"session_id":"ed976b73d9be46f7aff888b9440fe5d6","finish_reason":"null"},"usage":{},"request_id":"32c86a8c-dbd1-9c12-a175-8837224a13e0"}
      
      id:6
      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_Ilo9\"}"}],"session_id":"ed976b73d9be46f7aff888b9440fe5d6","finish_reason":"null"},"usage":{},"request_id":"32c86a8c-dbd1-9c12-a175-8837224a13e0"}
      
      id:7
      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_Ilo9\"}"}],"session_id":"ed976b73d9be46f7aff888b9440fe5d6","finish_reason":"null"},"usage":{},"request_id":"32c86a8c-dbd1-9c12-a175-8837224a13e0"}
      
      id:8
      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_Ilo9\"}"}],"session_id":"ed976b73d9be46f7aff888b9440fe5d6","finish_reason":"null"},"usage":{},"request_id":"32c86a8c-dbd1-9c12-a175-8837224a13e0"}
      
      id:9
      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_Ilo9\",\"nodeExecTime\":\"2199ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"ed976b73d9be46f7aff888b9440fe5d6","finish_reason":"null"},"usage":{},"request_id":"32c86a8c-dbd1-9c12-a175-8837224a13e0"}
      
      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_Ilo9\",\"nodeExecTime\":\"2199ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"西湖,靈隱\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"ed976b73d9be46f7aff888b9440fe5d6","finish_reason":"null"},"usage":{},"request_id":"32c86a8c-dbd1-9c12-a175-8837224a13e0"}
      
      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_Ilo9\",\"nodeExecTime\":\"2199ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"寺,宋城\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"ed976b73d9be46f7aff888b9440fe5d6","finish_reason":"null"},"usage":{},"request_id":"32c86a8c-dbd1-9c12-a175-8837224a13e0"}
      
      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_Ilo9\",\"nodeExecTime\":\"2199ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",西溪濕地\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"ed976b73d9be46f7aff888b9440fe5d6","finish_reason":"null"},"usage":{},"request_id":"32c86a8c-dbd1-9c12-a175-8837224a13e0"}
      
      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_Ilo9\",\"nodeExecTime\":\"2199ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",雷峰塔\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"ed976b73d9be46f7aff888b9440fe5d6","finish_reason":"null"},"usage":{},"request_id":"32c86a8c-dbd1-9c12-a175-8837224a13e0"}
      
      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_Ilo9\",\"nodeExecTime\":\"2199ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_vQDv\",\"nodeExecTime\":\"1145ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"西湖,靈隱寺,宋城,西溪濕地,雷峰塔\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"0ms\"}"}],"session_id":"ed976b73d9be46f7aff888b9440fe5d6","finish_reason":"stop","text":"西湖,靈隱寺,宋城,西溪濕地,雷峰塔"},"usage":{},"request_id":"32c86a8c-dbd1-9c12-a175-8837224a13e0"}

      Go

      請求樣本

      package main
      
      import (
      	"bytes"
      	"encoding/json"
      	"fmt"
      	"io"
      	"net/http"
      	"os"
      )
      
      func main() {
      	// 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey := "sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
      	apiKey := os.Getenv("DASHSCOPE_API_KEY")
      	appId := "YOUR_APP_ID" // 替換為實際的應用 ID
      
      	if apiKey == "" {
      		fmt.Println("請確保設定了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": "你好",
      			"biz_params": map[string]interface{}{
      				"city": "杭州", // 參數透傳
      			},
      		},
      		"parameters": map[string]interface{}{
      			"incremental_output": true, // 設定此參數為true可以增量輸出結果
      			"has_thoughts":       true, // 工作流程應用和智能體編排應用實現流式輸出需要設定此參數為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
      	}
      
      	// 佈建要求頭
      	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()
      
      	// 讀取響應
      	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))
      	}
      }
      

      響應樣本

      Request successful:
      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\\\":\\\"西湖醋\\\"}\",\"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\\\":\\\"魚,\\\"}\",\"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\\\":\\\"龍井蝦仁\\\"}\",\"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\\\":\\\",東坡肉\\\"}\",\"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\\\":\\\",知味小\\\"}\",\"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\\\":\\\"籠,叫花\\\"}\",\"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\\\":\\\"雞\\\"}\",\"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\\\":\\\"西湖,靈隱\\\"}\",\"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\\\":\\\"寺,宋城\\\"}\",\"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\\\":\\\",西溪濕地\\\"}\",\"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\\\":\\\",千島湖\\\"}\",\"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\\\":\\\"西湖,靈隱寺,宋城,西溪濕地,千島湖\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"1ms\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"stop","text":"西湖,靈隱寺,宋城,西溪濕地,千島湖"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
      • thoughts內每一項都是一個節點的執行詳情,如下以一個LLM節點結果為例。

      data:
      {
          "output": {
              "thoughts": [
                  {
                      "response": "{"nodeName":"開始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}"
                  },
                  {
                      "response": "{"nodeName":"大模型_Bsvj","nodeResult":"{\"result\":\"仁,叫化雞\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_Ilo9","nodeExecTime":"1486ms"}"
                  }
              ],
              "session_id": "a3b73a6db84d444d8efdab2b2e754f52",
              "finish_reason": "null"
          },
          "usage": {
      
          },
          "request_id": "795e98eb-5de3-969f-a9b5-5983d1b6d955"
      }
      如果使用者關注一個LLM節點(以上方LLM_Ilo9為例)的流式結果,可以關注每次推送的thoughts中nodeId為LLM_Ilo9的節點輸出。
      • 如果節點發生失敗,則整個任務也會失敗。

知識庫過濾

知識庫功能作為百鍊的RAG能力,能有效為大模型補充私人知識和提供最新資訊。智能體應用開啟知識檢索增強功能或工作流程應用建立知識庫節點後,您在調用應用時可以指定要檢索的範圍,提高大模型的回答準確性。更多知識庫功能請參考:知識庫

調用時知識庫ID是必傳參數,但如果在應用中配置了知識庫,則調用時可不傳入。

  • 檢索指定的知識庫:在rag_options中傳入知識庫ID。

    • 知識庫ID可以在知識索引頁面擷取,也可以使用調用CreateIndex介面返回的Data.Id

      目前僅非結構化資料的知識庫支援通過API進行建立。
    • 可以是智能體應用已經關聯的知識庫,也可以是沒有關聯的知識庫。

    • 只會在指定的知識庫裡檢索。例如,網頁端的智能體應用裡引用了知識庫A,而API調用時只指定了知識庫B,那麼不會檢索知識庫A,只會檢索知識庫B。

    此處選擇了百鍊系列手機產品介紹.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將下行替換為:api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
        api_key=os.getenv("DASHSCOPE_API_KEY"), 
        app_id='YOUR_APP_ID',  # 應用ID替換YOUR_APP_ID
        prompt='請幫我推薦一款3000元以下的手機',
        rag_options={
            "pipeline_ids": ["YOUR_PIPELINE_ID1,YOUR_PIPELINE_ID2"],  # 替換為實際的知識庫 ID,逗號隔開多個
        }
    )
    
    if response.status_code != HTTPStatus.OK:
        print(f'request_id={response.request_id}')
        print(f'code={response.status_code}')
        print(f'message={response.message}')
        print(f'請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code')
    else:
        print('%s\n' % (response.output.text))  # 處理只輸出文本text
        # print('%s\n' % (response.usage))

    響應樣本

    根據您的預算,我推薦您選擇**百鍊 Zephyr Z9**。這款手機的參考售價在2499-2799元之間,符合您的預算需求。它擁有輕巧的6.4英寸1080 x 2340像素螢幕設計,搭配128GB儲存與6GB RAM,適合日常使用。此外,它還配備了4000mAh電池以及支援30倍數字變焦的鏡頭,能夠很好地滿足拍照及續航的需求。如果您追求的是輕薄便攜且功能全面的手機,那麼百鍊 Zephyr Z9會是一個不錯的選擇。

    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()
                    // 若沒有配置環境變數,可用百鍊API Key將下行替換為:.apiKey("sk-xxx")。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .appId("YOUR_APP_ID") // 替換為實際的應用ID
                    .prompt("請幫我推薦一款3000元左右的手機")
                    .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());// 處理只輸出文本text
        }
    
        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/zh/model-studio/developer-reference/error-code");
            }
            System.exit(0);
        }
    }

    響應樣本

    在3000元預算範圍內,我推薦您考慮**百鍊 Zephyr Z9**。這款手機定價在2499至2799之間,非常符合您的預算要求。它具有以下特點:
    
    - **輕巧設計**:6.4英寸螢幕大小適中,便於單手操作。
    - **效能均衡**:搭載128GB儲存與6GB RAM,對於日常使用來說足夠了。
    - **續航能力**:配備4000mAh電池,可以滿足一天的正常使用需求。
    - **拍照功能**:具備30倍數字變焦鏡頭,適合捕捉遠處景物。
    
    如果您更注重遊戲體驗或對其他方面有特別的需求,請告訴我,以便我能提供更加個人化的建議!

    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": "請幫我推薦一款3000元以下的手機"
        },
        "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":"在3000元以下的價格範圍內,我向您推薦百鍊 Zephyr Z9。
    這款手機定價在2499至2799元之間,完美符合您的預算要求。
    它擁有輕巧的6.4英寸1080 x 2340像素顯示屏,搭配了128GB的儲存空間和6GB的RAM,足以應對日常使用中的各種應用程式和多任務處理。
    此外,它配備了一塊4000mAh的電池,能夠確保您一整天的使用無虞,還搭載了30倍數字變焦鏡頭,方便您捕捉生活中的細節。
    綜上所述,百鍊 Zephyr Z9在性價比、設計與功能上都是一個不錯的選擇。"},
    "usage":{"models":[{"output_tokens":158,"model_id":"qwen-max","input_tokens":1025}]},
    "request_id":"eb2d40f7-bede-9d48-88dc-08abdcdd0351"}% 

    PHP

    請求樣本

    <?php
    # 若沒有配置環境變數,可用百鍊API Key將下行替換為:$api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
    $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' => '請幫我推薦一款3000元以下的手機'
        ],
        "parameters" => [
            'rag_options' => [
                'pipeline_ids' => ['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2']//替換為指定的知識庫 ID,逗號隔開多個
            ]
        ]
    ];
    // 將資料編碼為 JSON
    $dataString = json_encode($data);
    
    // 檢查 json_encode 是否成功
    if (json_last_error() !== JSON_ERROR_NONE) {
        die("JSON encoding failed with error: " . json_last_error_msg());
    }
    
    // 初始化 cURL 對話
    $ch = curl_init($url);
    
    // 設定 cURL 選項
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $api_key
    ]);
    
    // 執行請求
    $response = curl_exec($ch);
    
    // 檢查 cURL 執行是否成功
    if ($response === false) {
        die("cURL Error: " . curl_error($ch));
    }
    
    // 擷取 HTTP 狀態代碼
    $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    // 關閉 cURL 對話
    curl_close($ch);
    // 解碼響應資料
    $response_data = json_decode($response, true);
    // 處理響應
    if ($status_code == 200) {
        if (isset($response_data['output']['text'])) {
            echo "{$response_data['output']['text']}\n";
        } else {
            echo "No text in response.\n";
        }
    }else {
        if (isset($response_data['request_id'])) {
            echo "request_id={$response_data['request_id']}\n";}
        echo "code={$status_code}\n";
        if (isset($response_data['message'])) {
            echo "message={$response_data['message']}\n";} 
        else {
            echo "message=Unknown error\n";}
    }
    ?>

    響應樣本

    在3000元以下的預算範圍內,我推薦您考慮**百鍊 Zephyr Z9**。這款手機定價在2499-2799元之間,非常適合您的預算。它具有輕巧的設計,配備6.4英寸1080 x 2340像素螢幕、128GB儲存與6GB RAM,能夠很好地滿足日常使用需求。此外,其4000mAh電池可以保證一天的正常使用,並且配備了30倍數字變焦鏡頭來捕捉遠處細節,既輕薄又不失強大功能。

    Node.js

    需安裝相關依賴:

    npm install axios

    請求樣本

    const axios = require('axios');
    async function callDashScope() {
        // 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey='sk-xxx'。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
        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: "請幫我推薦一款3000元以下的手機"
            },
            parameters: {
                rag_options:{
                    pipeline_ids:['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2']  // 替換為指定的知識庫 ID,多個請用逗號隔開
                }
            },
            debug: {}
        };
    
        try {
            const response = await axios.post(url, data, {
                headers: {
                    'Authorization': `Bearer ${apiKey}`,
                    'Content-Type': 'application/json'
                }
            });
    
            if (response.status === 200) {
                console.log(`${response.data.output.text}`);
            } else {
                console.log(`request_id=${response.headers['request_id']}`);
                console.log(`code=${response.status}`);
                console.log(`message=${response.data.message}`);
            }
        } catch (error) {
            console.error(`Error calling DashScope: ${error.message}`);
            if (error.response) {
                console.error(`Response status: ${error.response.status}`);
                console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
            }
        }
    }
    
    callDashScope();

    響應樣本

    在3000元以下的預算內,我推薦您考慮**百鍊 Zephyr Z9**。這款手機參考售價為3999-4299元,但如果能趕上促銷活動或折扣,可能會降到您的預算範圍內。
    
    ### 百鍊 Zephyr Z9 ——輕薄便攜的藝術
    - **螢幕**: 6.4英寸 1080 x 2340像素
    - **儲存與RAM**: 128GB儲存 / 6GB RAM
    - **電池**: 4000mAh
    - **相機**: 30倍數字變焦鏡頭
    
    這款手機的特點是輕薄便攜,日常使用非常方便,而且具有不錯的續航能力。如果您更關注性價比和日常使用體驗,百鍊 Zephyr Z9 是一個不錯的選擇。
    
    如果您的預算非常嚴格,建議關注電商平台的促銷活動,或者考慮其他品牌的同價位手機。希望這些建議對您有所協助!

    C#

    請求樣本

    using System.Text;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            // 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
            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("請確保設定了 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 jsonContent = $@"{{
                    ""input"": {{
                        ""prompt"": ""請幫我推薦一款3000元以下的手機""
                    }},
                    ""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": "根據您的預算,我推薦您考慮**百鍊 Zephyr Z9**。這款手機的參考售價在2499-2799元之間,符合您的預算需求。它擁有6.4英寸1080 x 2340像素螢幕、128GB儲存空間和6GB RAM,對於日常使用來說已經足夠了。此外,4000mAh電池可以保證一天內的正常使用,而30倍數字變焦鏡頭則能滿足您拍攝遠處景物的需求。這是一款輕薄便攜且功能全面的選擇。"
        },
        "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() {
    	// 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey := "sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
    	apiKey := os.Getenv("DASHSCOPE_API_KEY")
    	appId := "YOUR_APP_ID" // 替換為實際的應用 ID
    
    	if apiKey == "" {
    		fmt.Println("請確保設定了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]string{
    			"prompt": "請幫我推薦一款3000元以下的手機",
    		},
    		"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": "根據您的預算,我為您推薦**百鍊 Zephyr Z9**。這款手機的價格在2499-2799元之間,非常適合3000元以下的預算需求。它擁有輕巧的6.4英寸1080 x 2340像素螢幕設計,搭配128GB儲存與6GB RAM,能夠滿足日常使用的需求。同時,4000mAh電池確保了一天的使用無憂,而30倍數字變焦鏡頭則可以捕捉遠處的細節,是一款性價比很高的選擇。"
        },
        "usage": {
            "models": [
                {
                    "output_tokens": 119,
                    "model_id": "qwen-max",
                    "input_tokens": 1055
                }
            ]
        },
        "request_id": "3a755dd7-58a0-9a5e-8a07-b85b1db838a6"
    }
  • 檢索指定的非結構化資料文檔:在rag_options中傳入知識庫ID、文檔ID、文檔標籤tags或文檔中繼資料metadata(索引值對)。

    檢索指定的文檔ID:傳入文檔ID。

    • 文檔ID可以在資料管理頁面擷取。

    • 可以傳入多個文檔ID,僅支援已建知識索引的文檔。

    • 傳入文檔ID時,傳入文檔所屬的知識庫ID才會生效

    • 只會在指定的文檔裡檢索。例如:網頁端的智能體應用裡引用了知識庫A,而API調用時指定了文檔ID和其所屬的知識庫B的ID,那麼不會檢索知識庫A的文檔,只會檢索知識庫B的文檔

      此處樣本選擇百鍊系列手機產品介紹.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將下行替換為:api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
          api_key=os.getenv("DASHSCOPE_API_KEY"),
          app_id='YOUR_APP_ID',  # 應用ID替換YOUR_APP_ID
          prompt='請幫我推薦一款3000元以下的手機',
          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'請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code')
      else:
          print('%s\n' % (response.output))

      響應樣本

      {
          "text": "在3000元以下的預算範圍內,我推薦您考慮**百鍊 Zephyr Z9**。這款手機的特點如下:
      
      - **螢幕**:6.4英寸 1080 x 2340像素,適合日常使用和娛樂。
      - **記憶體與儲存**:6GB RAM + 128GB 儲存空間,能夠滿足大部分使用者對於流暢度以及儲存的需求。
      - **電池容量**:4000mAh,提供了一整天的使用保障。
      - **網路攝影機功能**:配備了一個支援30倍數字變焦的鏡頭,可以捕捉到更遠距離的細節。
      - **其他特性**:設計輕薄便攜,易於攜帶。
      
      參考售價為2499至2799元之間,正好符合您的預算要求,並且提供了不錯的性價比。希望這些建議對您有所協助!",
          "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()
                      // 若沒有配置環境變數,可用百鍊API Key將下行替換為:.apiKey("sk-xxx")。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
                      .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                      .appId("a1930cf4ad2a4153b8887f7b17969ba3") // 替換為實際的應用ID
                      .prompt("請幫我推薦一款3000元左右的手機")
                      .ragOptions(RagOptions.builder()
                              .pipelineIds(List.of("PIPELINES_ID1","PIPELINES_ID2"))  // 替換為實際指定的知識庫 ID,逗號隔開多個
                              .fileIds(List.of("FILE_ID1", "FILE_ID2"))  // 替換為實際指定的非結構化文檔 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());// 處理只輸出文本text
          }
      
          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/zh/model-studio/developer-reference/error-code");
              }
              System.exit(0);
          }
      }

      響應樣本

      根據您的預算,我為您推薦**百鍊 Zephyr Z9**。這款手機的價格在2499-2799元之間,非常適合您3000元左右的預算範圍。
      
      ### 百鍊 Zephyr Z9 產品亮點:
      - **螢幕**:6.4英寸、1080 x 2340像素,提供清晰細膩的視覺體驗。
      - **儲存與運行記憶體**:128GB儲存空間和6GB RAM,足以應對日常使用需求。
      - **電池**:4000mAh容量電池可以確保一整天的正常使用。
      - **網路攝影機**:支援30倍數字變焦鏡頭,能夠捕捉遠處細節。
      - **設計**:輕薄便攜,適合追求時尚與便捷的使用者。
      
      這款手機不僅價格適中,而且配置均衡,在外觀設計上也非常出色,是這個價位段非常不錯的選擇。希望這些建議對您有所協助!如果還有其他需求或疑問,請隨時告訴我。

      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": "請幫我推薦一款3000元左右的手機"
          },
          "parameters":  {
                          "rag_options" : {
                          "pipeline_ids":["YOUR_PIPELINE_ID1"],
                          "file_ids":["YOUR_FILE_ID1"],
                          "metadata_filter":{
                          "name":"張三"},
                          "tags":"手機"
                          }
          },
          "debug": {}
      }'
      YOUR_APP_ID替換為實際的應用 ID,YOUR_PIPELINE_ID1替換為指定的知識庫ID,YOUR_FILE_ID1替換為指定的非結構化文檔ID,metadata_filter內的索引值對替換為實際的中繼資料。

      響應樣本

      {"output":{"finish_reason":"stop","session_id":"f2f114864dd24a458f923aab0ec99a1d",
      "text":"根據您的預算,我推薦您考慮“通義 Vivid 7”。它擁有 6.5 英寸 1080 x 2400 像素的全面屏,具備 AI 智能攝影功能,能夠讓您拍攝出具有專業級色彩與細節的照片。
      其硬體設定包括 8GB RAM 和 128GB 儲存空間,確保了流暢的操作體驗;4500mAh 的電池容量也能較好地滿足日常使用需求。
      此外,側面指紋解鎖的設計既便捷又安全。參考售價為 2999 至 3299 元之間,符合您的預算範圍。"},
      "usage":{"models":[{"output_tokens":141,"model_id":"qwen-plus","input_tokens":1610}]},
      "request_id":"d815d3d1-8cef-95e2-b895-89fc8d0e0f84"}%      

      PHP

      請求樣本

      <?php
      # 若沒有配置環境變數,可用百鍊API Key將下行替換為:$api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
      $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' => '請幫我推薦一款3000元以下的手機'
          ],
          "parameters" => [
              '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" => ["標籤1", "標籤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";}
      }
      ?>

      響應樣本

      根據您的預算,我為您推薦**百鍊 Zephyr Z9**。這款手機的參考售價在2499-2799元之間,非常適合3000元以下的需求。它擁有輕巧的6.4英寸1080 x 2340像素設計,搭配128GB儲存與6GB RAM,可以滿足日常使用需求。此外,其配備4000mAh電池確保一天無憂,並且還有30倍數字變焦鏡頭捕捉遠處細節,是一款既輕薄又不失強大的選擇。

      Node.js

      需安裝相關依賴:

      npm install axios

      請求樣本

      const axios = require('axios');
      async function callDashScope() {
          // 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey='sk-xxx'。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
          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: "請幫我推薦一款3000元以下的手機"
              },
              parameters: {
                  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: ['標籤1', '標籤2'] // 文檔標籤,多個請用逗號隔開
                  }
              },
              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();

      響應樣本

      在3000元以下的預算範圍內,我推薦您考慮**百鍊 Zephyr Z9**。這款手機的價格區間是2499-2799元,它擁有輕薄便攜的設計,配備6.4英寸1080 x 2340像素螢幕、128GB儲存與6GB RAM,能夠滿足日常使用需求。其4000mAh電池保證了一天的使用時間,而30倍數字變焦鏡頭則可以協助捕捉到更遠距離的細節。總體來說,這是一款性價比較高的選擇。

      C#

      請求樣本

      using System.Text;
      
      class Program
      {
          static async Task Main(string[] args)
          {
              // 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
              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("請確保設定了 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 jsonContent = $@"{{
                      ""input"": {{
                          ""prompt"": ""請幫我推薦一款3000元以下的手機""
                      }},
                      ""parameters"": {{
                          ""rag_options"" : {{
                              ""pipeline_ids"":[""YOUR_PIPELINE_ID1""],
                              ""file_ids"":[""YOUR_FILE_ID1""],
                              ""metadata_filter"":{{
                                  ""name"":""張三""
                              }},
                      ""tags"":""手機""
                          }}
                      }},
                      ""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": "根據您的預算,我為您推薦**百鍊 Zephyr Z9**。這款手機售價在2499-2799元之間,非常適合3000元以下的預算要求。
      
      ### 產品亮點
      - **輕薄設計**:採用6.4英寸螢幕,解析度1080 x 2340像素,外觀精緻且便於攜帶。
      - **效能均衡**:配備6GB RAM和128GB儲存空間,能夠滿足日常使用需求。
      - **長效續航**:內建4000mAh電池,確保您一整天的正常使用不受影響。
      - **出色攝影**:支援30倍數字變焦功能,輕鬆捕捉遠方美景或細節。
      
      如果您追求的是性價比高、能滿足基本需求同時又具備一定特色的智能手機,那麼百鍊 Zephyr Z9將是一個不錯的選擇。"
          },
          "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() {
      	// 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey := "sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
      	apiKey := os.Getenv("DASHSCOPE_API_KEY")
      	appId := "YOUR_APP_ID" // 替換為實際的應用 ID
      
      	if apiKey == "" {
      		fmt.Println("請確保設定了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]string{
      			"prompt": "請幫我推薦一款3000元以下的手機",
      		},
      		"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": "張三", // 中繼資料索引值對
      				},
      				"tags": "手機", // 非結構化資料文檔標籤
      			},
      		},
      		"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": "根據您的預算,我推薦您考慮**百鍊 Zephyr Z9**。這款手機的參考售價為2499-2799元,非常適合3000元以下的需求。它具有以下特點:
      
      - 輕巧的6.4英寸1080 x 2340像素螢幕設計。
      - 搭配128GB儲存與6GB RAM,能夠滿足日常使用需求。
      - 配備了4000mAh電池,保證了一天的正常使用。
      - 後置網路攝影機支援30倍數字變焦鏡頭,可以捕捉到遠處的細節。
      
      如果您對攝影或者遊戲沒有特別高的要求,那麼百鍊 Zephyr Z9應該是一個不錯的選擇。"
          },
          "usage": {
              "models": [
                  {
                      "output_tokens": 156,
                      "model_id": "qwen-max",
                      "input_tokens": 1055
                  }
              ]
          },
          "request_id": "8940b597-92e1-9471-b4eb-896e563c479d"
      }
  • 檢索結構化資料文檔裡的指定資料:在rag_options中傳入知識庫ID、結構化資料文檔的“結構化資料表頭+值”的索引值對。

    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將下行替換為:api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        app_id='YOUR_APP_ID',  # 應用ID替換YOUR_APP_ID
        prompt='請幫我推薦一款3000元以下的手機',
        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'請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code')
    else:
        print('%s\n' % (response.output))

    響應樣本

    {
        "text": "我為您推薦"百鍊"這款手機,它的價格是2999元,符合您的預算要求。如果您需要瞭解更多資訊,比如效能、外觀等,請告訴我。",
        "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()
                    // 若沒有配置環境變數,可用百鍊API Key將下行替換為:.apiKey("sk-xxx")。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .appId("YOUR_APP_ID") // 替換為實際的應用ID
                    .prompt("請幫我推薦一款3000元左右的手機")
                    .ragOptions(RagOptions.builder()
                            .pipelineIds(List.of("PIPELINE_ID1","PIPELINE_ID2"))  // 替換為實際指定的知識庫 ID,逗號隔開多個
                            .structuredFilter(structureFilter)
                            .build())
                    .build();
    
            Application application = new Application();
            ApplicationResult result = application.call(param);
            System.out.printf("%s\n",
                    result.getOutput().getText());// 處理只輸出文本text
        }
    
        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/zh/model-studio/developer-reference/error-code");
            }
            System.exit(0);
        }
    }

    響應樣本

    我為您推薦"百鍊"這款手機,它的價格是2999.0元,符合您的預算要求。如果您需要瞭解更多關於這款手機的資訊,比如配置、效能等,請告訴我,我會為您提供更詳細的資料。

    HTTP

    curl

    請求樣本

    curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
    --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
    --header 'Content-Type: application/json' \
    --data '{
        "input": {
            "prompt": "請幫我推薦一款3000元左右的手機"
        },
        "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":"我為您推薦一款價格接近3000元的手機:\n\n- **百鍊手機**,價格為2999元。
    \n\n這款手機性價比高,能滿足您的預算需求。
    如果您需要更多關於這款手機的詳細資料或者有其他特定需求(比如網路攝影機效能、處理器型號等),請告訴我,我會儘力提供更詳盡的資訊。"},
    "usage":{"models":[{"output_tokens":73,"model_id":"qwen-max","input_tokens":235}]},"request_id":"934e1258-219c-9ef1-8982-fc1bcefb8f11"}%  

    PHP

    請求樣本

    <?php
    # 若沒有配置環境變數,可用百鍊API Key將下行替換為:$api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
    $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' => '請幫我推薦一款3000元以下的手機'
        ],
        "parameters" => [
            'rag_options' => [
                'pipeline_ids' => ['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'],// 替換為指定的知識庫 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";}
    }
    ?>

    響應樣本

    我為您推薦"百鍊"這款手機,它的價格是2999元,符合您的預算要求。如果您需要瞭解更多關於這款手機的資訊,請告訴我。

    Node.js

    需安裝相關依賴:

    npm install axios

    請求樣本

    const axios = require('axios');
    async function callDashScope() {
        // 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey='sk-xxx'。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
        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: "請幫我推薦一款3000元以下的手機"
            },
            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();

    響應樣本

    我為您推薦"百鍊"這款手機,它的價格是2999元,符合您的預算要求。如果您需要瞭解更多詳情或有其他特定需求,請告訴我!

    C#

    請求樣本

    using System.Text;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            // 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
            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("請確保設定了 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 jsonContent = $@"{{
                    ""input"": {{
                        ""prompt"": ""請幫我推薦一款3000元以下的手機""
                    }},
                    ""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": "我為您推薦"百鍊"這款手機,它的價格是2999.0元,符合您的預算要求。如果您需要更多關於這款手機的資訊或者其他建議,請告訴我。"
        },
        "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() {
    	// 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey := "sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
    	apiKey := os.Getenv("DASHSCOPE_API_KEY")
    	appId := "YOUR_APP_ID" // 替換為實際的應用 ID
    
    	if apiKey == "" {
    		fmt.Println("請確保設定了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]string{
    			"prompt": "請幫我推薦一款3000元以下的手機",
    		},
    		"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": "我推薦您考慮"百鍊"這款手機,它的價格是2999.0元,符合您的預算要求。如果您需要更多關於這款手機的資訊或者其他推薦,請告訴我。"
        },
        "usage": {
            "models": [
                {
                    "output_tokens": 39,
                    "model_id": "qwen-max",
                    "input_tokens": 104
                }
            ]
        },
        "request_id": "036abd4f-10c8-9709-881d-8cc9f8095d54"
    }

調用時可以在上述代碼中設定has_thoughts參數為True,處理代碼輸出完整響應結果,參與檢索的知識庫資訊會在output中的thoughts欄位中返回。

在智能體應用的檢索配置中開啟展示回答來源開關並發布應用,可在調用的返回結果中查看回答來源。image

API參考

您可以通過應用調用API參考查看完整的參數列表。

常見問題

運行Java程式碼範例時,如果出現類似“java: 程式包com.alibaba.dashscope.app不存在”的異常資訊,應該怎麼處理?

  1. 檢查匯入語句中的類名和包名是否正確。

  2. 添加依賴庫:如果使用Maven或Gradle進行專案管理,確保DashScope Java SDK依賴庫已經添加到pom.xmlbuild.gradle檔案中,且為最新版本。您可以訪問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可能不包含您嘗試使用的功能或類。如果您已經添加過依賴庫DashScope Java SDK,請確認您所使用的DashScope Java SDK是否為最新版。如果目前的版本較低,請將其升級至最新版本。您可以在pom.xmlbuild.gradle檔案中修改DashScope Java SDK的版本為最新版本。

    <!-- 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. 重新運行程式碼範例。

    如果仍然存在問題,建議查閱開發人員論壇瞭解是否有其他使用者遇到相同的問題及其解決方案,或提交工單以擷取進一步的協助。