請求體 app_idstring(必選) 應用標識。 可在應用管理頁面的應用卡片上擷取應用 ID。
Java SDK中為 appId。通過 HTTP 調用時,請將實際的應用 ID 放入 URL中,替換APP_ID。
promptstring(必選) 使用者的輸入指令,用於指導應用產生回複。
通過 HTTP 調用時,請將 prompt放入 input對象中。
session_idstring (可選) 歷史對話標識。 傳入session_id時,請求將自動攜帶雲端儲存的對話歷史。此時必須傳遞prompt。 該 ID 在連續 1 小時內無任何請求後將自動失效。
Java SDK 中為 setSessionId。通過 HTTP 調用時,請將 session_id放入 input對象中。
messagesarray(可選) 傳遞給大模型的上下文,按對話順序排列。 當使用messages參數實現多輪對話時,無需傳遞prompt和 session_id。 若同時傳入session_id和messages,則大模型優先使用messages中的內容,忽略session_id和prompt。
通過HTTP調用時,請將 messages 放入 input 對象中。
使用該參數,Python Dashscope SDK的版本至少應為1.20.14,Java Dashscope SDK的版本至少應為2.17.0。
訊息類型 System Messageobject(可選) 系統訊息,用於設定大模型的角色、語氣、任務目標或約束條件等。一般放在messages數組的第一位。 屬性 contentstring(必選) 系統指令,用於明確模型的角色、行為規範、回答風格和任務約束等。 rolestring(必選) 系統訊息的角色,固定為system。 User Messageobject(必選) 使用者訊息,用於向模型傳遞問題、指令或上下文等。 屬性 contentstring(必選) 訊息內容。 rolestring(必選) 使用者訊息的角色,固定為user。 Assistant Messageobject(可選) 模型的回複。通常用於在多輪對話中作為上下文回傳給模型。 屬性 contentstring(必選) 模型回複的常值內容。 rolestring(必選) 助手訊息的角色,固定為assistant。 workspace string (可選) 業務空間標識。相關文檔:擷取Workspace ID。 僅調用子業務空間的應用時需傳遞workspace ID。
通過 HTTP 調用時,請指定Header中的 X-DashScope-WorkSpace。
stream boolean(可選) 預設值為 False 是否以流式輸出方式回複。 推薦設定為True,可提升閱讀體驗並降低逾時風險。 參數值:
False(預設):模型產生全部內容後一次性返回;
True(推薦):邊產生邊輸出,每產生一部分內容即返回一個資料區塊(chunk)。需即時逐個讀取這些塊以拼接完整回複。
通過Java SDK實現流式輸出請通過streamCall介面調用;通過HTTP實現流式輸出請在Header中指定X-DashScope-SSE為enable。
incremental_output boolean(可選)預設值為 False 在流式輸出模式下是否開啟增量輸出。 推薦設定為True,可提升閱讀體驗。 參數值:
False(預設):每次輸出當前已經產生的整個序列,最後一次輸出為產生的完整結果。
I
I like
I like apple
I like apple.
True(推薦):增量輸出,即後續輸出內容不包含已輸出的內容。需要即時地逐個讀取這些片段以獲得完整的結果。
I
like
apple
.
Java SDK中為incrementalOutput*。*通過HTTP調用時,請將incremental_output放入parameters對象中。
flow_stream_mode string(可選)預設值為full_thoughts 工作流应用的流式輸出模式。 參數值:
-
message_format(推薦):
在message欄位輸出指定節點(流程输出節點或结束節點)的結果。
重要在控制台應用中開啟目標節點的流式输出開關,即可流式返回結果;未開啟時,一次性返回該節點的最終結果。
Java SDK 中為FlowStreamMode.MESSAGE_FORMAT。
-
full_thoughts(預設):
在thoughts欄位輸出所有節點的結果。
重要使用此模式時,必須同時將 has_thoughts 參數設定為 True。
Java SDK 中為FlowStreamMode.FULL_THOUGHTS。
-
agent_format:
在 text欄位輸出指定節點(大模型節點或結束節點)的結果。
在控制台應用中開啟目標節點的结果返回開關,即可流式返回結果。
重要請勿在並行節點上使用此模式,可能導致內容混雜。請確保開啟開關的節點有明確的執行順序。
Java SDK 中為FlowStreamMode.AGENT_FORMAT。
Python SDK 版本至少為1.24.0,Java SDK 版本至少為2.21.0。通過HTTP調用時,請將flow_stream_mode放入parameters對象中。
biz_paramsobject (可選) 應用通過自訂變數、節點或外掛程式傳遞參數時,使用該欄位進行傳遞。
Java SDK 中為 bizParams。通過HTTP調用時,請將 biz_params放入 input對象中。
工作流应用開始節點的自訂變數直接傳遞,樣本: biz_params = {"city": "杭州"}
智能体应用通過以下欄位傳遞提示詞變數或外掛程式變數參數: 屬性 user_defined_params object (可選) 表示自訂外掛程式參數資訊。 一個應用內添加的外掛程式不可重複,且上限 10 個。 屬性 tool_idstring (可選) 外掛程式 ID,可在外掛程式卡片上擷取。 ${plugin_params}string(可選) 對象最內側包含的多個索引值對。每個索引值對錶示使用者自訂的待傳遞參數名及其指定值。如: "article_index": 2
使用步驟:
- 在應用內關聯指定外掛程式,並发布應用。
- API調用通過此參數傳遞外掛程式資訊。
可提供多個索引值對,其中每個鍵為外掛程式的 TOOL_ID,值為該外掛程式所需的參數對象。樣本: "user_defined_params": {
"<TOOL_ID>": {
"article_index": 2},
"<TOOL_ID>": {
"article_index": 8}
}
user_defined_tokens object(可選) 表示自訂外掛程式的使用者級鑒權資訊。 一個應用內添加的外掛程式不可重複,且上限 10 個。 屬性 tool_idstring (可選) 外掛程式 ID,可在外掛程式卡片中擷取。通過<TOOL_ID>欄位傳遞。 user_token string (可選) 傳遞該外掛程式需要的使用者鑒權資訊,如實際DASHSCOPE_API_KEY的值。 使用步驟:
- 在應用內關聯指定外掛程式,並发布應用。
- API調用通過此參數傳遞外掛程式使用者級鑒權資訊。
可提供多個索引值對,其中每個鍵為外掛程式的 TOOL_ID,值為user_token 對象。 has_thoughts boolean (可選)預設值為 False 是否輸出外掛程式調用、知識檢索的過程,在thoughts欄位中查看。 參數值:
Java SDK 中為 hasThoughts。通過 HTTP 調用時,請將 has_thoughts放入 parameters對象中。
rag_options object (可選) 用於配置與檢索相關的參數。包括但不限於對指定的知識庫或文檔進行檢索。
Java SDK 中為 ragOptions。通過HTTP調用時,請將 rag_options放入 parameters對象中。
屬性 pipeline_ids array(必選) 包含一個或多個知識庫 ID 的列表。上限5個。 檢索指定知識庫內的所有文檔。 擷取方式:
Java SDK 中為pipelineIds。
file_idsarray(可選) 包含一個或多個非結構化文檔 ID 的列表。上限5個。 檢索指定知識庫內的非結構化文檔。 傳入文檔 ID 時,必須同時在 pipeline_ids 欄位中傳入這些文檔所屬的知識庫 ID。 擷取方式:
Java SDK 中為 fileIds。
metadata_filterobject (可選) 用於篩選非結構化文檔的中繼資料。通過指定一個或多個索引值對,檢索指定知識庫內具備該中繼資料的非結構化文檔。 使用前提: 傳入中繼資料時,必須同時在 pipeline_ids 欄位中傳入這些中繼資料所屬的知識庫 ID。 查看方式: 該對象由一個或多個索引值對組成: 組合邏輯: 不同鍵之間為“與”(AND) 邏輯。例如,"author": "John.Doe", "source": ["internal_wiki", "public_docs"] 表示篩選出作者是 "John.Doe" 並且來源是 "internal_wiki" 或 "public_docs" 的文檔。
Java SDK 中為 metadataFilter。
tags array (可選) 包含一個或多個非結構化文檔標籤的列表。 檢索具備該標籤的非結構化文檔。 查看方式: | 單輪對話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='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')
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("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);
}
}
HTTPcurl請求樣本curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "你是誰?"
},
"parameters": {},
"debug": {}
}'
APP_ID替換為實際的應用 ID。
PHP請求樣本<?php
# 若沒有配置環境變數,可用百鍊API Key將下行替換為:$api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // 替換為實際的應用 ID
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// 構造請求資料
$data = [
"input" => [
'prompt' => '你是誰?'
]
];
// 將資料編碼為 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 = '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 = "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}");
}
}
}
}
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 := "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))
}
}
多輪對話通過session_id或messages啟用多輪對話。 Python請求樣本import os
from http import HTTPStatus
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
def call_with_session():
response = Application.call(
# 若沒有配置環境變數,可用百鍊API Key將下行替換為:api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='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='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()
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("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);
}
}
HTTPcurl請求樣本(上一輪對話)curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "你是誰?"
},
"parameters": {},
"debug": {}
}'
請求樣本(下一輪對話)curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "你有什麼技能?",
"session_id":"4f8ef7233dc641aba496cb201fa59f8c"
},
"parameters": {},
"debug": {}
}'
PHP請求樣本(上一輪對話)<?php
# 若沒有配置環境變數,可用百鍊API Key將下行替換為:$api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // 替換為實際的應用 ID
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// 構造請求資料
$data = [
"input" => [
'prompt' => '你是誰?'
]
];
// 將資料編碼為 JSON
$dataString = json_encode($data);
// 檢查 json_encode 是否成功
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// 初始化 cURL 對話
$ch = curl_init($url);
// 設定 cURL 選項
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// 執行請求
$response = curl_exec($ch);
// 檢查 cURL 執行是否成功
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// 擷取 HTTP 狀態代碼
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 關閉 cURL 對話
curl_close($ch);
// 解碼響應資料
$response_data = json_decode($response, true);
// 處理響應
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
};
if (isset($response_data['output']['session_id'])) {
echo "session_id={$response_data['output']['session_id']}\n";
}
}else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";}
else {
echo "message=Unknown error\n";}
}
?>
請求樣本(下一輪對話)<?php
# 若沒有配置環境變數,可用百鍊API Key將下行替換為:$api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // 替換為實際的應用 ID
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// 構造請求資料
$data = [
"input" => [
'prompt' => '你有什麼技能?',
// 替換為實際上一輪對話返回的session_id
'session_id' => '2e658bcb514f4d30ab7500b4766a8d43'
]
];
// 將資料編碼為 JSON
$dataString = json_encode($data);
// 檢查 json_encode 是否成功
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// 初始化 cURL 對話
$ch = curl_init($url);
// 設定 cURL 選項
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// 執行請求
$response = curl_exec($ch);
// 檢查 cURL 執行是否成功
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// 擷取 HTTP 狀態代碼
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 關閉 cURL 對話
curl_close($ch);
// 解碼響應資料
$response_data = json_decode($response, true);
// 處理響應
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
};
if (isset($response_data['output']['session_id'])) {
echo "session_id={$response_data['output']['session_id']}\n";
}
}else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";}
else {
echo "message=Unknown error\n";}
}
?>
Node.js需安裝相關依賴:npm install axios
請求樣本(上一輪對話)const axios = require('axios');
async function callDashScope() {
// 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey='sk-xxx'。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';// 替換為實際的應用 ID
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "你是誰?"
},
parameters: {},
debug: {}
};
try {
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
console.log(`${response.data.output.text}`);
console.log(`session_id=${response.data.output.session_id}`);
} else {
console.log(`request_id=${response.headers['request_id']}`);
console.log(`code=${response.status}`);
console.log(`message=${response.data.message}`);
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
請求樣本(下一輪對話)const axios = require('axios');
async function callDashScope() {
// 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey='sk-xxx'。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';// 替換為實際的應用 ID
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
// session_id替換為實際上一輪對話的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();
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 = "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}");
}
}
}
}
請求樣本(下一輪對話)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 = "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}");
}
}
}
}
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 := "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))
}
}
請求樣本(下一輪對話)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 := "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))
}
}
APP_ID替換為實際的應用 ID。下一輪對話的輸入參數session_id欄位值替換為實際上一輪對話返回的session_id值。
傳遞 參數通過biz_params傳遞自訂參數。 Python請求樣本import os
from http import HTTPStatus
# 建議dashscope SDK 的版本 >= 1.14.0
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
biz_params = {
# 智能體應用的自訂外掛程式輸入參數傳遞,自訂的外掛程式ID替換<TOOL_ID>
"user_defined_params": {
"<TOOL_ID>": {
"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='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替換<TOOL_ID>
"{\"user_defined_params\":{\"<TOOL_ID>\":{\"article_index\":2}}}";
ApplicationParam param = ApplicationParam.builder()
// 若沒有配置環境變數,可用百鍊API Key將下行替換為:.apiKey("sk-xxx")。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("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);
}
}
HTTPcurl請求樣本curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "寢室公約內容",
"biz_params":
{
"user_defined_params":
{
"<TOOL_ID>":
{
"article_index": 2
}
}
}
},
"parameters": {},
"debug":{}
}'
APP_ID替換為實際的應用 ID。<TOOL_ID>替換為外掛程式ID。
PHP請求樣本<?php
# 若沒有配置環境變數,可用百鍊API Key將下行替換為:$api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // 替換為實際的應用 ID
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
//<TOOL_ID>替換為實際的外掛程式ID
// 構造請求資料
$data = [
"input" => [
'prompt' => '寢室公約內容',
'biz_params' => [
'user_defined_params' => [
'<TOOL_ID>' => [
'article_index' => 2
]
]
]
],
];
// 將資料編碼為 JSON
$dataString = json_encode($data);
// 檢查 json_encode 是否成功
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// 初始化 cURL 對話
$ch = curl_init($url);
// 設定 cURL 選項
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// 執行請求
$response = curl_exec($ch);
// 檢查 cURL 執行是否成功
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// 擷取 HTTP 狀態代碼
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 關閉 cURL 對話
curl_close($ch);
// 解碼響應資料
$response_data = json_decode($response, true);
// 處理響應
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
}
}else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";}
else {
echo "message=Unknown error\n";}
}
?>
Node.js需安裝相關依賴:npm install axios
請求樣本const axios = require('axios');
async function callDashScope() {
// 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey='sk-xxx'。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';// 替換為實際的應用 ID
const pluginCode = 'TOOL_ID';// 替換為實際的外掛程式ID
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "寢室公約內容",
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 = "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 = "TOOL_ID"; // TOOL_ID替換為實際的外掛程式 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}");
}
}
}
}
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 := "APP_ID" // 替換為實際的應用 ID
pluginCode := "TOOL_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{}{
"user_defined_params": map[string]interface{}{
pluginCode: map[string]interface{}{
"article_index": 2,
},
},
},
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// 建立 HTTP POST 請求
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// 佈建要求頭
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// 發送請求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
// 讀取響應
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// 處理響應
if resp.StatusCode == http.StatusOK {
fmt.Println("Request successful:")
fmt.Println(string(body))
} else {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
流式輸出通過stream實現流式輸出。 Python請求樣本import os
from http import HTTPStatus
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
responses = Application.call(
# 若沒有配置環境變數,可用百鍊API Key將下行替換為:api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='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("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);
}
}
HTTPcurl請求樣本curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--header 'X-DashScope-SSE: enable' \
--data '{
"input": {
"prompt": "你是誰?"
},
"parameters": {
"incremental_output":true
},
"debug": {}
}'
APP_ID替換為實際的應用 ID。
PHP請求樣本<?php
// 若沒有配置環境變數,可用百鍊API Key將下行替換為:$api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // 替換為實際的應用 ID
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// 構造請求資料
$data = [
"input" => [
'prompt' => '你是誰?'],
"parameters" => [
'incremental_output' => true]];// 增量輸出
// 將資料編碼為 JSON
$dataString = json_encode($data);
// 檢查 json_encode 是否成功
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// 初始化 cURL 對話
$ch = curl_init($url);
// 設定 cURL 選項
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); // 不返回傳輸的資料
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $string) {
echo $string; // 處理流式資料
return strlen($string);
});
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key,
'X-DashScope-SSE: enable' // 流式輸出
]);
// 執行請求
$response = curl_exec($ch);
// 檢查 cURL 執行是否成功
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// 擷取 HTTP 狀態代碼
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 關閉 cURL 對話
curl_close($ch);
if ($status_code != 200) {
echo "HTTP Status Code: $status_code\n";
echo "Request Failed.\n";
}
?>
Node.js需安裝相關依賴:npm install axios
請求樣本1.輸出完整響應 const axios = require('axios');
async function callDashScope() {
//若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey='sk-xxx'。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';// 替換為實際的應用 ID
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "你是誰?"
},
parameters: {
'incremental_output' : 'true' // 增量輸出
},
debug: {}
};
try {
console.log("Sending request to DashScope API...");
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
'X-DashScope-SSE': 'enable' // 流式輸出
},
responseType: 'stream' // 用於處理流式響應
});
if (response.status === 200) {
// 處理流式響應
response.data.on('data', (chunk) => {
console.log(`Received chunk: ${chunk.toString()}`);
});
} else {
console.log("Request failed:");
if (response.data.request_id) {
console.log(`request_id=${response.data.request_id}`);
}
console.log(`code=${response.status}`);
if (response.data.message) {
console.log(`message=${response.data.message}`);
} else {
console.log('message=Unknown error');
}
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
可展開摺疊面板查看具體內容: 2.只輸出text欄位內容 const axios = require('axios');
const { Transform } = require('stream');
async function callDashScope() {
//若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey='sk-xxx'。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID'; // 替換為實際的應用 ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: { prompt: "你是誰?" },
parameters: { incremental_output: true }, // 增量輸出
debug: {}
};
try {
console.log("Sending request to DashScope API...");
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
'X-DashScope-SSE': 'enable' // 流式輸出
},
responseType: 'stream' // 用於處理流式響應
});
if (response.status === 200) {
// // 處理流式響應 SSE協議解析轉換流
const sseTransformer = new Transform({
transform(chunk, encoding, callback) {
this.buffer += chunk.toString();
// 按SSE事件分割(兩個分行符號)
const events = this.buffer.split(/\n\n/);
this.buffer = events.pop() || ''; // 保留未完成部分
events.forEach(eventData => {
const lines = eventData.split('\n');
let textContent = '';
// 解析事件內容
lines.forEach(line => {
if (line.startsWith('data:')) {
try {
const jsonData = JSON.parse(line.slice(5).trim());
if (jsonData.output?.text) {
textContent = jsonData.output.text;
}
} catch(e) {
console.error('JSON解析錯誤:', e.message);
}
}
});
if (textContent) {
// 添加分行符號並推送
this.push(textContent + '\n');
}
});
callback();
},
flush(callback) {
if (this.buffer) {
this.push(this.buffer + '\n');
}
callback();
}
});
sseTransformer.buffer = '';
// 管道處理
response.data
.pipe(sseTransformer)
.on('data', (textWithNewline) => {
process.stdout.write(textWithNewline); // 自動換行輸出
})
.on('end', () => console.log(""))
.on('error', err => console.error("管道錯誤:", err));
} else {
console.log("請求失敗,狀態代碼:", response.status);
response.data.on('data', chunk => console.log(chunk.toString()));
}
} catch (error) {
console.error(`API調用失敗: ${error.message}`);
if (error.response) {
console.error(`狀態代碼: ${error.response.status}`);
error.response.data.on('data', chunk => console.log(chunk.toString()));
}
}
}
callDashScope();
C#請求樣本using System.Net;
using System.Text;
class Program
{
static async Task Main(string[] args)
{
//若沒有配置環境變數,可用百鍊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 = "APP_ID"; // 替換為實際的應用ID
string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
client.DefaultRequestHeaders.Add("X-DashScope-SSE", "enable");
string jsonContent = @"{
""input"": {
""prompt"": ""你是誰""
},
""parameters"": {""incremental_output"": true},
""debug"": {}
}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
try
{
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Content = content;
HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Request successful:");
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
using (var stream = await response.Content.ReadAsStreamAsync())
using (var reader = new StreamReader(stream))
{
string? line; // 聲明為可Null 字元串
while ((line = await reader.ReadLineAsync()) != null)
{
if (line.StartsWith("data:"))
{
string data = line.Substring(5).Trim();
Console.WriteLine(data);
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
}
}
}
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}
Go請求樣本package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
)
func main() {
// 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey := "sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // 替換為實際的應用 ID
if apiKey == "" {
fmt.Println("請確保設定了DASHSCOPE_API_KEY。")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// 建立請求體,其中incremental_output為是否開啟流式響應
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "你是誰?",
},
"parameters": map[string]interface{}{
"incremental_output": true,
},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// 建立 HTTP POST 請求
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// 佈建要求頭,其中X-DashScope-SSE設定為enable,表示開啟流式響應
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-DashScope-SSE", "enable")
// 發送請求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
return
}
// 處理流式響應
reader := io.Reader(resp.Body)
buf := make([]byte, 1024)
for {
n, err := reader.Read(buf)
if n > 0 {
data := string(buf[:n])
lines := strings.Split(data, "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if len(line) >= 5 && line[:5] == "data:" {
timestamp := time.Now().Format("2006-01-02 15:04:05.000")
fmt.Printf("%s: %s\n", timestamp, line[5:])
} else if len(line) > 0 {
fmt.Println(line)
}
}
}
if err != nil {
if err == io.EOF {
break
}
fmt.Printf("Error reading response: %v\n", err)
break
}
}
}
檢索知識庫調用智能体应用時,通過rag_options實現知識庫檢索。 Python請求樣本import os
from http import HTTPStatus
# 建議dashscope SDK 的版本 >= 1.20.11
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
response = Application.call(
# 若沒有配置環境變數,可用百鍊API Key將下行替換為:api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='APP_ID', # 應用ID替換APP_ID
prompt='請幫我推薦一款3000元以下的手機',
rag_options={
"pipeline_ids": ["PIPELINE_ID1","PIPELINE_ID2"], # 替換為實際的知識庫ID,逗號隔開多個
}
)
if response.status_code != HTTPStatus.OK:
print(f'request_id={response.request_id}')
print(f'code={response.status_code}')
print(f'message={response.message}')
print(f'請參考文檔: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請求樣本// 建議dashscope SDK 的版本 >= 2.16.8;
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import java.util.Arrays;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void streamCall() throws NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// 若沒有配置環境變數,可用百鍊API Key將下行替換為:.apiKey("sk-xxx")。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("APP_ID") // 替換為實際的應用ID
.prompt("請幫我推薦一款3000元左右的手機")
.ragOptions(RagOptions.builder()
// 替換為實際指定的知識庫ID,逗號隔開多個
.pipelineIds(Arrays.asList("PIPELINES_ID1", "PIPELINES_ID2"))
.build())
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("%s\n",
result.getOutput().getText());// 處理只輸出文本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);
}
}
HTTPcurl請求樣本curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/{APP_ID}/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "請幫我推薦一款3000元以下的手機"
},
"parameters": {
"rag_options" : {
"pipeline_ids":["PIPELINE_ID1"]}
},
"debug": {}
}'
APP_ID替換為實際的應用 ID,PIPELINE_ID1替換為指定的知識庫ID。
PHP請求樣本<?php
# 若沒有配置環境變數,可用百鍊API Key將下行替換為:$api_key="sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // 替換為實際的應用 ID
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// 構造請求資料
$data = [
"input" => [
'prompt' => '請幫我推薦一款3000元以下的手機'
],
"parameters" => [
'rag_options' => [
'pipeline_ids' => ['PIPELINE_ID1','PIPELINE_ID2']//替換為指定的知識庫ID,逗號隔開多個
]
]
];
// 將資料編碼為 JSON
$dataString = json_encode($data);
// 檢查 json_encode 是否成功
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// 初始化 cURL 對話
$ch = curl_init($url);
// 設定 cURL 選項
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// 執行請求
$response = curl_exec($ch);
// 檢查 cURL 執行是否成功
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// 擷取 HTTP 狀態代碼
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 關閉 cURL 對話
curl_close($ch);
// 解碼響應資料
$response_data = json_decode($response, true);
// 處理響應
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
}
}else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";}
else {
echo "message=Unknown error\n";}
}
?>
Node.js需安裝相關依賴:npm install axios
請求樣本const axios = require('axios');
async function callDashScope() {
// 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey='sk-xxx'。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';//替換為實際的應用 ID
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "請幫我推薦一款3000元以下的手機"
},
parameters: {
rag_options:{
pipeline_ids:['PIPELINE_ID1','PIPELINE_ID2'] // 替換為指定的知識庫ID,多個請用逗號隔開
}
},
debug: {}
};
try {
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
console.log(`${response.data.output.text}`);
} else {
console.log(`request_id=${response.headers['request_id']}`);
console.log(`code=${response.status}`);
console.log(`message=${response.data.message}`);
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
C#請求樣本using System.Text;
class Program
{
static async Task Main(string[] args)
{
// 若沒有配置環境變數,可用百鍊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 = "APP_ID";// 替換為實際的應用ID
// 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"":[""PIPELINE_ID1""]
}}
}},
""debug"": {{}}
}}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}
Go請求樣本package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// 若沒有配置環境變數,可用百鍊API Key將下行替換為:apiKey := "sk-xxx"。但不建議在生產環境中直接將API Key寫入程式碼到代碼中,以減少API Key泄露風險。
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "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{"PIPELINE_ID1"}, // 替換為指定的知識庫ID
},
},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// 建立 HTTP POST 請求
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// 佈建要求頭
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// 發送請求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
// 讀取響應
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// 處理響應
if resp.StatusCode == http.StatusOK {
fmt.Println("Request successful:")
fmt.Println(string(body))
} else {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
查看檢索過程資訊:調用時在代碼中添加has_thoughts並設定為True,則檢索的過程資訊會在output的thoughts欄位中返回。 |