Transmisikan parameter kustom—terutama ke plugin kustom dan node kustom—saat memanggil Agent Application dan Workflow Application Alibaba Cloud Model Studio (yang menggantikan aplikasi orkestrasi agen).
Buat Kunci API dan ekspor kunci API sebagai variabel lingkungan. Jika Anda menggunakan SDK untuk melakukan panggilan, instal DashScope SDK.
Parameter plugin kustom
Artikel ini menggunakan dormitory convention query tool untuk menunjukkan cara pass parameter ke plugin kustom melalui API.
Parameter untuk plugin kustom diteruskan melalui Agent Application atau Workflow Application yang terkait melalui node plugin-nya.
Contoh berikut menunjukkan cara meneruskan parameter plugin kustom untuk Agent Application.
Penggunaan
Langkah 1: Buat plugin kustom
Jika Anda telah membuat tool plugin atau mengimpor plugin, lewati langkah ini.
Buat plugin kustom: Buka halaman Plugins di Konsol Model Studio dan klik Add Custom Plug-in. Masukkan informasi plugin. Jika otentikasi diperlukan, aktifkan sakelar Enable Authentication dan konfigurasikan pengaturannya.
Deskripsi Plugin Contoh: Menanyakan konvensi asrama dan mencari entri tertentu berdasarkan indeks numerik.
URL Plugin Contoh: https://domitorgreement-plugin-example-icohrkdjxy.cn-beijing.fcapp.run

Catatan: Plug-in Description secara singkat merangkum tujuan plugin. Hal ini membantu model besar memutuskan apakah akan memanggil plugin untuk suatu tugas tertentu. Jelaskan dalam bahasa alami.
Buat tool: Isi informasi tool dan konfigurasikan parameter input dan output. Catatan:
Tool Description membantu model besar lebih memahami fungsi dan kasus penggunaan tool tersebut. Gunakan bahasa alami dan berikan contoh jika memungkinkan.
Parameter Name yang deskriptif membantu model besar memahami informasi yang diwakilinya.
Parameter Description menjelaskan fungsi parameter input. Harus ringkas dan akurat agar model besar dapat menentukan nilai yang tepat untuk digunakan.
Anda harus memilih Business Pass-through untuk Passing Method parameter input.
Dalam contoh ini, indeks konten konvensi asrama,
article_index, ditetapkan sebagai parameter transmisi langsung.
Klik Test Tool. Setelah pengujian berhasil, Publish plugin tersebut.
Langkah 2: Asosiasikan plugin dengan agen
Anda hanya dapat mengasosiasikan plugin dengan Agent Application yang berada dalam ruang kerja yang sama.
Pada kartu plugin yang telah dipublikasikan, klik Add to Agent dan pilih aplikasi agen.
Atau, klik + Plugin di dalam aplikasi untuk mengasosiasikan plugin kustom.
Akhirnya, Publish aplikasi tersebut.
Langkah 3: Panggilan API
Saat otentikasi tidak diperlukan: Untuk memanggil plugin kustom melalui API, gunakan parameter
user_defined_paramsdaribiz_paramsuntuk meneruskan informasi plugin kustom, gantiyour_plugin_codedengan ID plugin sebenarnya, dan teruskan pasangan kunci-nilai dari parameter input yang dikonfigurasi di plugin.Anda dapat menemukan ID plugin pada kartu plugin.
Dalam contoh ini, meneruskan nilai 2 ke parameter
article_indexmenanyakan konten konvensi asrama kedua dan mengembalikan hasil yang benar.Python
Contoh permintaan
import os from http import HTTPStatus # Kami merekomendasikan menggunakan DashScope SDK v1.14.0 atau yang lebih baru. import dashscope from dashscope import Application dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1' biz_params = { # Teruskan parameter input untuk plugin kustom aplikasi agen. Ganti `your_plugin_code` dengan ID plugin Anda. "user_defined_params": { "your_plugin_code": { "article_index": 2}}} response = Application.call( # Jika variabel lingkungan belum diatur, Anda dapat menggunakan Kunci API Model Studio Anda dengan mengganti baris berikut menjadi api_key="sk-xxx". Kami merekomendasikan penggunaan variabel lingkungan di lingkungan produksi untuk menghindari kebocoran kunci API Anda. api_key=os.getenv("DASHSCOPE_API_KEY"), app_id='YOUR_APP_ID', prompt='Dormitory convention content', biz_params=biz_params) if response.status_code != HTTPStatus.OK: print(f'request_id={response.request_id}') print(f'code={response.status_code}') print(f'message={response.message}') print(f'Untuk informasi lebih lanjut, lihat: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code') else: print('%s\n' % (response.output.text)) # Proses dan keluarkan hanya teksnya. # print('%s\n' % (response.usage))Contoh tanggapan
The second article of the dormitory convention is as follows: "Roommates must help, care for, and learn from each other to achieve mutual improvement. They must be tolerant, forgiving, respectful, and sincere." This suggests that roommates should foster a positive living and learning environment by supporting and helping each other, while also learning to understand and respect others. If you want to learn about other articles of the convention, just ask!Java
Contoh permintaan
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 = // Teruskan parameter input untuk plugin kustom aplikasi agen. Ganti `{your_plugin_code}` dengan ID plugin Anda. "{\"user_defined_params\":{\"{your_plugin_code}\":{\"article_index\":2}}}"; ApplicationParam param = ApplicationParam.builder() // Jika variabel lingkungan belum diatur, Anda dapat menggunakan Kunci API Model Studio Anda dengan mengganti baris berikut menjadi .apiKey("sk-xxx"). Kami merekomendasikan penggunaan variabel lingkungan di lingkungan produksi untuk menghindari kebocoran kunci API Anda. .apiKey(System.getenv("DASHSCOPE_API_KEY")) .appId("YOUR_APP_ID") .prompt("Dormitory convention content") .bizParams(JsonUtils.parse(bizParams)) .build(); Application application = new Application(); ApplicationResult result = application.call(param); System.out.printf("%s\n", result.getOutput().getText()); } public static void main(String[] args) { try { appCall(); } catch (ApiException | NoApiKeyException | InputRequiredException e) { System.out.printf("Exception: %s", e.getMessage()); System.out.println("Untuk informasi lebih lanjut, lihat: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code"); } System.exit(0); } }Contoh tanggapan
The second article of the dormitory convention is as follows: Article 2: Roommates must help, care for, and learn from each other to achieve mutual improvement. They must be tolerant, forgiving, respectful, and sincere. This emphasizes that in a shared living environment, roommates should maintain a positive and supportive relationship to create a harmonious atmosphere for living and learning. If you need to learn about any other specific articles, please let me know.HTTP
curl
Contoh permintaan
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \ --header "Authorization: Bearer $DASHSCOPE_API_KEY" \ --header 'Content-Type: application/json' \ --data '{ "input": { "prompt": "Dormitory convention content", "biz_params": { "user_defined_params": { "{your_plugin_code}": { "article_index": 2 } } } }, "parameters": {}, "debug":{} }'Ganti
YOUR_APP_IDdengan ID aplikasi Anda.Contoh tanggapan
{"output": {"finish_reason":"stop", "session_id":"e151267ffded4fbdb13d91439011d31e", "text":"The second article of the dormitory convention is: \"Roommates must help, care for, and learn from each other to achieve mutual improvement. They must be tolerant, forgiving, respectful, and sincere.\" This means that in dormitory life, everyone must support each other to create a harmonious and positive living environment."}, "usage":{"models":[{"output_tokens":94,"model_id":"qwen-max","input_tokens":453}]}, "request_id":"a39fd2b5-7e2c-983e-84a1-1039f726f18a"}%PHP
Contoh permintaan
<?php # Jika variabel lingkungan belum diatur, Anda dapat menggunakan Kunci API Model Studio Anda dengan mengganti baris berikut menjadi $api_key="sk-xxx". Kami merekomendasikan penggunaan variabel lingkungan di lingkungan produksi untuk menghindari kebocoran kunci API Anda. $api_key = getenv("DASHSCOPE_API_KEY"); $application_id = 'YOUR_APP_ID'; // Ganti dengan ID aplikasi Anda. $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion"; // Ganti `{your_plugin_code}` dengan ID plugin Anda. // Bangun data permintaan. $data = [ "input" => [ 'prompt' => 'Dormitory convention content', 'biz_params' => [ 'user_defined_params' => [ '{your_plugin_code}' => [ 'article_index' => 2 ] ] ] ], ]; // Encode data sebagai JSON. $dataString = json_encode($data); // Periksa apakah json_encode berhasil. if (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg()); } // Inisialisasi sesi cURL. $ch = curl_init($url); // Atur opsi 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 ]); // Jalankan permintaan. $response = curl_exec($ch); // Periksa apakah eksekusi cURL berhasil. if ($response === false) { die("cURL Error: " . curl_error($ch)); } // Dapatkan kode status HTTP. $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Tutup sesi cURL. curl_close($ch); // Decode data tanggapan. $response_data = json_decode($response, true); // Proses tanggapan. 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";} } ?>Contoh tanggapan
The second article of the dormitory convention states: Roommates must help, care for, and learn from each other to achieve mutual improvement. They must be tolerant, forgiving, respectful, and sincere. This is to ensure that everyone can live and study in a harmonious and friendly environment. If you want to learn about other specific articles or have other questions, feel free to ask.Node.js
Dependencies:
npm install axiosContoh permintaan
const axios = require('axios'); async function callDashScope() { // Jika variabel lingkungan belum diatur, Anda dapat menggunakan Kunci API Model Studio Anda dengan mengganti baris berikut menjadi apiKey='sk-xxx'. Kami merekomendasikan penggunaan variabel lingkungan di lingkungan produksi untuk menghindari kebocoran kunci API Anda. const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID';// Ganti dengan ID aplikasi Anda. const pluginCode = 'YOUR_PLUGIN_CODE';// Ganti dengan ID plugin Anda. const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "Dormitory convention content", biz_params: { user_defined_params: { [pluginCode]: { // 'article_index' adalah contoh parameter plugin kustom. 'article_index': 2 } } } }, 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();Contoh tanggapan
The second article of the dormitory convention states: Roommates must help, care for, and learn from each other to achieve mutual improvement. They must be tolerant, forgiving, respectful, and sincere. This is to ensure that everyone can live and study in a harmonious and friendly environment. If you want to learn about other specific articles or have other questions, feel free to ask.C#
Contoh permintaan
using System.Text; class Program { static async Task Main(string[] args) { // Jika variabel lingkungan belum diatur, Anda dapat menggunakan Kunci API Model Studio Anda dengan mengganti baris berikut menjadi apiKey="sk-xxx". Kami merekomendasikan penggunaan variabel lingkungan di lingkungan produksi untuk menghindari kebocoran kunci API Anda. string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");; string appId = "YOUR_APP_ID";// Ganti dengan ID aplikasi Anda. if (string.IsNullOrEmpty(apiKey)) { Console.WriteLine("Please ensure that the DASHSCOPE_API_KEY environment variable is set."); return; } string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); string pluginCode = "{your_plugin_code}"; // Ganti `{your_plugin_code}` dengan ID plugin Anda. string jsonContent = $@"{{ ""input"": {{ ""prompt"": ""Dormitory convention content"", ""biz_params"": {{ ""user_defined_params"": {{ ""{pluginCode}"": {{ ""article_index"": 2 }} }} }} }}, ""parameters"": {{}}, ""debug"": {{}} }}"; HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await client.PostAsync(url, content); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine("Request successful:"); Console.WriteLine(responseBody); } else { Console.WriteLine($"Request failed with status code: {response.StatusCode}"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch (Exception ex) { Console.WriteLine($"Error calling DashScope: {ex.Message}"); } } } }Contoh tanggapan
{ "output": { "finish_reason": "stop", "session_id": "237ca6187c814f3b9e7461090a5f8b74", "text": "The second article of the dormitory convention is as follows:\n\n\"Roommates must help, care for, and learn from each other to achieve mutual improvement. They must be tolerant, forgiving, respectful, and sincere.\"\n\nThis indicates that in the dormitory, roommates need to establish a positive relationship, creating a harmonious living and learning environment by helping, caring for, and supporting each other. They should also learn to understand and accept differences between roommates and communicate with sincerity. If you want to learn about other articles or specific content, please let me know!" }, "usage": { "models": [ { "output_tokens": 133, "model_id": "qwen-max", "input_tokens": 829 } ] }, "request_id": "64e8c359-d071-9d2e-bb94-187e86cc3a79" }Go
Contoh permintaan
package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // Jika variabel lingkungan tidak disetel, Anda dapat menggunakan Kunci API Model Studio Anda dengan mengganti baris berikut dengan apiKey := "sk-xxx". Kami merekomendasikan penggunaan variabel lingkungan di lingkungan produksi untuk menghindari kebocoran kunci API Anda. apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // Ganti dengan ID aplikasi Anda. pluginCode := "YOUR_PLUGIN_CODE" // Ganti dengan ID plugin Anda. if apiKey == "" { fmt.Println("Pastikan variabel lingkungan DASHSCOPE_API_KEY telah disetel.") return } url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId) // Buat badan permintaan. requestBody := map[string]interface{}{ "input": map[string]interface{}{ "prompt": "Dormitory convention content", "biz_params": map[string]interface{}{ "user_defined_params": map[string]interface{}{ pluginCode: map[string]interface{}{ "article_index": 2, }, }, }, }, "parameters": map[string]interface{}{}, "debug": map[string]interface{}{}, } jsonData, err := json.Marshal(requestBody) if err != nil { fmt.Printf("Gagal membuat marshal JSON: %v\n", err) return } // Buat permintaan HTTP POST. req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Gagal membuat permintaan: %v\n", err) return } // Atur header permintaan. req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") // Kirim permintaan. client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("Gagal mengirim permintaan: %v\n", err) return } defer resp.Body.Close() // Baca tanggapan. body, err := io.ReadAll(resp.Body) if err != nil { fmt.Printf("Gagal membaca tanggapan: %v\n", err) return } // Proses tanggapan. if resp.StatusCode == http.StatusOK { fmt.Println("Permintaan berhasil:") fmt.Println(string(body)) } else { fmt.Printf("Permintaan gagal dengan kode status: %d\n", resp.StatusCode) fmt.Println(string(body)) } }Contoh tanggapan
{ "output": { "finish_reason": "stop", "session_id": "860d2a4c1f3649ac880298537993cb51", "text": "The second article of the dormitory convention is as follows:\n\nRoommates must help, care for, and learn from each other to achieve mutual improvement. They must be tolerant, forgiving, respectful, and sincere.\n\nThis emphasizes that in dormitory life, roommates should maintain a supportive relationship and respect each other. Would you like to learn about the content of other articles?" }, "usage": { "models": [ { "output_tokens": 84, "model_id": "qwen-max", "input_tokens": 876 } ] }, "request_id": "0a250055-90a4-992d-9276-e268ad35d1ab" }Saat otentikasi diperlukan: Skenario ini menjelaskan cara memanggil plugin kustom yang memiliki Authentication diaktifkan dan dikonfigurasi dengan User-level Authentication.
Anda dapat menemukan ID plugin pada kartu plugin.
Gunakan
user_defined_paramsdi bidangbiz_paramsuntuk meneruskan informasi plugin kustom. Gantiyour_plugin_codedengan ID plugin Anda, dan berikan parameter input sebagai pasangan kunci-nilai.Gunakan
user_defined_tokensdi bidangbiz_paramsuntuk meneruskan kredensial otentikasi. Gantiyour_plugin_codedengan ID plugin Anda, dan atur nilaiuser_tokenke token otentikasi Anda, seperti kunci API DashScope.Setelah otentikasi berhasil, layanan menanyakan item yang ditentukan berdasarkan parameter indeks yang diberikan dan mengembalikan hasil yang benar.
Dalam contoh ini, parameter
article_indexdiatur ke 2, dan nilaiuser_token,YOUR_TOKEN, diganti dengan DASHSCOPE_API_KEY sebenarnya. Setelah otentikasi berhasil, konten aturan asrama kedua ditanyakan, dan hasil yang benar dikembalikan.Python
Minta contoh
from http import HTTPStatus import os # Kami merekomendasikan menggunakan DashScope SDK v1.14.0 atau yang lebih baru. import dashscope from dashscope import Application dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1' biz_params = { # Teruskan kredensial otentikasi untuk plugin kustom aplikasi agen. # Ganti your_plugin_code dengan ID plugin Anda dan YOUR_TOKEN dengan token otentikasi Anda, seperti kunci API. "user_defined_params": { "your_plugin_code": { "article_index": 2}}, "user_defined_tokens": { "your_plugin_code": { "user_token": "YOUR_TOKEN"}}} response = Application.call( # Jika variabel lingkungan belum dikonfigurasi, Anda dapat menggunakan kunci API DashScope dengan mengganti baris berikut menjadi: api_key="sk-xxx". # Namun, kami tidak merekomendasikan hardcoding kunci API di lingkungan produksi untuk mengurangi risiko kebocoran kunci. api_key=os.getenv("DASHSCOPE_API_KEY"), app_id='YOUR_APP_ID', prompt='Dormitory convention content', biz_params=biz_params) if response.status_code != HTTPStatus.OK: print(f'request_id={response.request_id}') print(f'code={response.status_code}') print(f'message={response.message}') print(f'Untuk informasi lebih lanjut, lihat: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code') else: print('%s\n' % (response.output.text)) # Proses dan keluarkan hanya teksnya. # print('%s\n' % (response.usage))Contoh tanggapan
The second article of the dormitory convention is as follows: Roommates must help, care for, and learn from each other to achieve mutual improvement. They must be tolerant, forgiving, respectful, and sincere. If you need to know about other articles of the convention, please let me know.Java
Minta contoh
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 = // Ganti {your_plugin_code} dengan ID plugin Anda, dan YOUR_TOKEN dengan token Anda, seperti kunci API. "{\"user_defined_params\":{\"{your_plugin_code}\":{\"article_index\":2}}," + "\"user_defined_tokens\":{\"{your_plugin_code}\":{\"user_token\":\"YOUR_TOKEN\"}}}"; ApplicationParam param = ApplicationParam.builder() // Jika variabel lingkungan belum dikonfigurasi, Anda dapat menggunakan kunci API DashScope dengan mengganti baris berikut menjadi: .apiKey("sk-xxx"). // Namun, kami tidak merekomendasikan hardcoding kunci API di lingkungan produksi untuk mengurangi risiko kebocoran kunci. .apiKey(System.getenv("DASHSCOPE_API_KEY")) .appId("YOUR_APP_ID") .prompt("Dormitory convention content") .bizParams(JsonUtils.parse(bizParams)) .build(); Application application = new Application(); ApplicationResult result = application.call(param); System.out.printf("%s\n", result.getOutput().getText()); } public static void main(String[] args) { try { appCall(); } catch (ApiException | NoApiKeyException | InputRequiredException e) { System.out.printf("Exception: %s", e.getMessage()); System.out.println("Untuk informasi lebih lanjut, lihat: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code"); } System.exit(0); } }Contoh tanggapan
The second article of the dormitory convention is as follows: Roommates must help, care for, and learn from each other to achieve mutual improvement. They must be tolerant, forgiving, respectful, and sincere. If you need to query for more articles, please let me know.Ganti YOUR_APP_ID dengan ID aplikasi Anda, your_plugin_code dengan ID plugin kustom Anda, dan YOUR_TOKEN dengan token otentikasi Anda.
HTTP
curl
Minta contoh
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \ --header "Authorization: Bearer $DASHSCOPE_API_KEY" \ --header 'Content-Type: application/json' \ --data '{ "input": { "prompt": "Dormitory convention content", "biz_params": { "user_defined_params": { "{your_plugin_code}": { "article_index": 2 } }, "user_defined_tokens": { "{your_plugin_code}": { "user_token": "YOUR_TOKEN" } } } }, "parameters": {}, "debug":{} }'Ganti YOUR_APP_ID dengan ID aplikasi Anda, {your_plugin_code} dengan ID plugin kustom Anda, dan YOUR_TOKEN dengan token otentikasi Anda.
Contoh tanggapan
{"output":{"finish_reason":"stop", "session_id":"d3b5c3e269dc40479255a7a02df5c630", "text":"The second article of the dormitory convention is: \"Roommates must help, care for, and learn from each other to achieve mutual improvement. They must be tolerant, forgiving, respectful, and sincere.\" This emphasizes the importance of harmonious coexistence and mutual progress among members in dormitory life."}, "usage":{"models":[{"output_tokens":80,"model_id":"qwen-max","input_tokens":432}]}, "request_id":"1f77154c-edc3-9003-b622-816fa2f849cf"}%PHP
Minta contoh
<?php # Jika variabel lingkungan belum dikonfigurasi, Anda dapat menggunakan kunci API DashScope dengan mengganti baris berikut menjadi: $api_key="sk-xxx". # Namun, kami tidak merekomendasikan hardcoding kunci API di lingkungan produksi untuk mengurangi risiko kebocoran kunci. $api_key = getenv("DASHSCOPE_API_KEY"); $application_id = 'YOUR_APP_ID'; // Ganti dengan ID aplikasi Anda. $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion"; // Bangun data permintaan. $data = [ "input" => [ 'prompt' => 'Dormitory convention content', 'biz_params' => [ 'user_defined_params' => [ '{your_plugin_code}' => [//Ganti {your_plugin_code} dengan ID plugin Anda. 'article_index' => 2 ] ], 'user_defined_tokens' => [ '{your_plugin_code}' => [//Ganti {your_plugin_code} dengan ID plugin Anda. 'user_token' => 'YOUR_TOKEN'//Ganti dengan token Anda, seperti kunci API. ] ] ] ], ]; // Encode data sebagai JSON. $dataString = json_encode($data); // Periksa apakah json_encode berhasil. if (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg()); } // Inisialisasi sesi cURL. $ch = curl_init($url); // Atur opsi 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 ]); // Jalankan permintaan. $response = curl_exec($ch); // Periksa apakah eksekusi cURL berhasil. if ($response === false) { die("cURL Error: " . curl_error($ch)); } // Dapatkan kode status HTTP. $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Tutup sesi cURL. curl_close($ch); // Decode data tanggapan. $response_data = json_decode($response, true); // Proses tanggapan. 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";} } ?>Contoh tanggapan
The second article of the dormitory convention is as follows: > Roommates must help, care for, and learn from each other to achieve mutual improvement. They must be tolerant, forgiving, respectful, and sincere. If you need to know more about the convention or other information, please feel free to ask.Node.js
Dependencies:
npm install axiosMinta contoh
const axios = require('axios'); async function callDashScope() { // Jika variabel lingkungan belum dikonfigurasi, Anda dapat menggunakan kunci API DashScope dengan mengganti baris berikut menjadi: apiKey='sk-xxx'. // Namun, kami tidak merekomendasikan hardcoding kunci API di lingkungan produksi untuk mengurangi risiko kebocoran kunci. const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID';// Ganti dengan ID aplikasi Anda. const pluginCode = 'YOUR_PLUGIN_CODE';// Ganti dengan ID plugin Anda. const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "Dormitory convention content", biz_params: { user_defined_params: { [pluginCode]: { // `article_index` adalah parameter contoh untuk plugin kustom. Ganti dengan parameter Anda. 'article_index': 6 } }, user_defined_tokens: { [pluginCode]: { // Ganti YOUR_TOKEN dengan token otentikasi Anda, seperti kunci API. user_token: 'YOUR_TOKEN' } } } }, parameters: {}, debug: {} }; try { console.log("Sending request to DashScope API..."); const response = await axios.post(url, data, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' } }); if (response.status === 200) { if (response.data.output && response.data.output.text) { console.log(`${response.data.output.text}`); } } else { console.log("Request failed:"); if (response.data.request_id) { console.log(`request_id=${response.data.request_id}`); } console.log(`code=${response.status}`); if (response.data.message) { console.log(`message=${response.data.message}`); } else { console.log('message=Unknown error'); } } } catch (error) { console.error(`Error calling DashScope: ${error.message}`); if (error.response) { console.error(`Response status: ${error.response.status}`); console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();Contoh tanggapan
The sixth article of the dormitory convention states: Develop good sleep habits. Every roommate has the right to rest and the responsibility to ensure others' right to rest. If you need to know more about the regulations, please provide more details.C#
Minta contoh
using System.Text; class Program { static async Task Main(string[] args) { // Jika variabel lingkungan belum dikonfigurasi, Anda dapat menggunakan kunci API DashScope dengan mengganti baris berikut menjadi: apiKey="sk-xxx". // Namun, kami tidak merekomendasikan hardcoding kunci API di lingkungan produksi untuk mengurangi risiko kebocoran kunci. string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");; string appId = "YOUR_APP_ID";// Ganti dengan ID aplikasi Anda. if (string.IsNullOrEmpty(apiKey)) { Console.WriteLine("Please make sure the DASHSCOPE_API_KEY environment variable is set."); return; } string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); string pluginCode = "your_plugin_code"; // Ganti your_plugin_code dengan ID plugin Anda. // Ganti YOUR_TOKEN dengan token Anda, seperti kunci API. string jsonContent = $@"{{ ""input"": {{ ""prompt"": ""Dormitory convention content"", ""biz_params"": {{ ""user_defined_params"": {{ ""{pluginCode}"": {{ ""article_index"": 2 }} }}, ""user_defined_tokens"": {{ ""{pluginCode}"": {{ ""user_token"": ""YOUR_TOKEN"" }} }} }} }}, ""parameters"": {{}}, ""debug"": {{}} }}"; HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await client.PostAsync(url, content); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine("Request successful:"); Console.WriteLine(responseBody); } else { Console.WriteLine($"Request failed with status code: {response.StatusCode}"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch (Exception ex) { Console.WriteLine($"Error calling DashScope: {ex.Message}"); } } } }Contoh tanggapan
{ "output": { "finish_reason": "stop", "session_id": "1a1913a9922a401f8eba36df8ea1a062", "text": "The second article of the dormitory convention is as follows:\n\nRoommates must help, care for, and learn from each other to achieve mutual improvement. They must be tolerant, forgiving, respectful, and sincere.\n\nIf you need more details about the convention, please specify." }, "usage": { "models": [ { "output_tokens": 66, "model_id": "qwen-max", "input_tokens": 802 } ] }, "request_id": "04bac806-c5e6-9fab-a846-a66641862be9" }Go
Minta contoh
package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // Jika variabel lingkungan belum dikonfigurasi, Anda dapat menggunakan kunci API DashScope dengan mengganti baris berikut menjadi: apiKey := "sk-xxx". // Namun, kami tidak merekomendasikan hardcoding kunci API di lingkungan produksi untuk mengurangi risiko kebocoran kunci. apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // Ganti dengan ID aplikasi Anda. pluginCode := "YOUR_PLUGIN_CODE" // Ganti dengan ID plugin Anda. if apiKey == "" { fmt.Println("Please make sure the DASHSCOPE_API_KEY environment variable is set.") return } url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId) // Buat badan permintaan. requestBody := map[string]interface{}{ "input": map[string]interface{}{ "prompt": "Dormitory convention content", "biz_params": map[string]interface{}{ "user_defined_params": map[string]interface{}{ pluginCode: map[string]interface{}{ "article_index": 10, }, }, "user_defined_tokens": map[string]interface{}{ pluginCode: map[string]interface{}{ "user_token": "YOUR_TOKEN", // Ganti dengan token otentikasi Anda, seperti kunci API. }, }, }, }, "parameters": map[string]interface{}{}, "debug": map[string]interface{}{}, } jsonData, err := json.Marshal(requestBody) if err != nil { fmt.Printf("Failed to marshal JSON: %v\n", err) return } // Buat permintaan HTTP POST. req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Failed to create request: %v\n", err) return } // Atur header permintaan. req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") // Kirim permintaan. 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() // Baca tanggapan. body, err := io.ReadAll(resp.Body) if err != nil { fmt.Printf("Failed to read response: %v\n", err) return } // Proses tanggapan. 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)) } }Contoh tanggapan
{ "output": { "finish_reason": "stop", "session_id": "b8e051ba7e954ff8919208e7b84430fa", "text": "The tenth article of the dormitory convention states that roommates should work together to create and maintain a clean, tidy, aesthetically pleasing, and culturally rich dormitory environment. To understand the full content of the dormitory convention, you may need to view other articles or directly consult the dormitory management department. Is there any other specific content you would like to know about?" }, "usage": { "models": [ { "output_tokens": 70, "model_id": "qwen-max", "input_tokens": 855 } ] }, "request_id": "0921ee34-2754-9616-a826-cea33a0e0a14" }
Teruskan parameter node kustom
Topik ini menggunakan contoh Menanyakan pembagian administratif berdasarkan nama kota untuk menunjukkan cara meneruskan parameter node kustom ke aplikasi melalui panggilan API.
Parameter node kustom untuk aplikasi diteruskan melalui node awal Workflow Application.
Contoh berikut menunjukkan cara meneruskan parameter kustom ke node awal dalam Workflow Application.
Penggunaan
Langkah 1: Konfigurasikan parameter node kustom
Buka halaman My Applications di Konsol Model Studio. Pilih Workflow Application dan definisikan parameter kustom untuk start node-nya. Untuk contoh ini, buat variabel String bernama city. Kemudian, masukkan variabel city dan query ke dalam prompt dan Publish aplikasi tersebut.
Langkah 2: Lakukan panggilan API
Saat melakukan panggilan API, teruskan nilai city di bidang biz_params dan nilai query di bidang prompt.
Python
contoh permintaan
import os
from http import HTTPStatus
import dashscope
from dashscope import Application
# Teruskan parameter kustom untuk aplikasi alur kerja.
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
biz_params = {"city": "Hangzhou"}
response = Application.call(
# Jika Anda belum mengonfigurasi variabel lingkungan, Anda dapat menggunakan Kunci API Model Studio Anda dengan mengganti baris berikut menjadi: api_key="sk-xxx".
# Kami merekomendasikan agar Anda tidak melakukan hardcoding kunci API di kode Anda di lingkungan produksi untuk mengurangi risiko kebocoran kunci API.
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID', # Ganti dengan ID aplikasi sebenarnya Anda.
prompt='Query the administrative divisions of this city',
biz_params=biz_params # Teruskan parameter bisnis.
)
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'Untuk informasi lebih lanjut, lihat: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
else:
print(f'{response.output.text}') # Proses dan keluarkan hanya teksnya.contoh tanggapan
Hangzhou, ibu kota Provinsi Zhejiang, dibagi menjadi 10 distrik kota: Shangcheng, Gongshu, Xihu, Binjiang, Xiaoshan, Yuhang, Linping, Qiantang, Fuyang, dan Lin'an. Setiap distrik memiliki fitur unik dan prioritas pengembangan sendiri.
- Distrik Shangcheng: Terletak di pusat Hangzhou, merupakan salah satu pusat politik, ekonomi, dan budaya kota.
- Distrik Gongshu: Dikenal dengan budaya kanalnya dan banyak situs warisan sejarah dan budaya.
- Distrik Xihu: Rumah bagi kawasan wisata Danau Barat yang terkenal, destinasi wisata utama.
- Distrik Binjiang: Pusat industri teknologi tinggi, tempat perusahaan terkenal seperti Alibaba berlokasi.
- Distrik Xiaoshan: Distrik administratif di tenggara yang dikenal karena perkembangan ekonominya yang pesat, terutama di sektor manufaktur.
- Distrik Yuhang: Berkembang pesat dalam beberapa tahun terakhir, terutama di ekonomi internet. Kantor pusat Alibaba juga berlokasi di sini (Catatan: Kantor pusat Alibaba sebenarnya berada di Distrik Binjiang).
- Distrik Linping: Distrik administratif yang baru dibentuk bertujuan untuk mendorong pengembangan ekonomi dan sosial komprehensif di wilayah tersebut.
- Distrik Qiantang: Juga hasil penyesuaian pembagian administratif baru-baru ini, menekankan pengembangan inovatif dan perlindungan ekologis.
- Distrik Fuyang: Terletak di barat daya Hangzhou, dikenal karena lanskap alamnya yang kaya dan sejarah serta budayanya yang panjang.
- Distrik Lin'an: Terletak di bagian barat Hangzhou, terkenal karena ekologinya yang indah dan warisan budaya yang mendalam.
Catatan bahwa perencanaan perkotaan spesifik dapat berubah seiring waktu. Rujuk informasi resmi terbaru.Java
contoh permintaan
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import io.reactivex.Flowable;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void appCall() throws NoApiKeyException, InputRequiredException {
String bizParams =
"{\"city\":\"Hangzhou\"}";
ApplicationParam param = ApplicationParam.builder()
// Jika Anda belum mengonfigurasi variabel lingkungan, Anda dapat menggunakan Kunci API Model Studio Anda dengan mengganti baris berikut menjadi: .apiKey("sk-xxx").
// Kami merekomendasikan agar Anda tidak melakukan hardcoding kunci API di kode Anda di lingkungan produksi untuk mengurangi risiko kebocoran kunci API.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("YOUR_APP_ID")
.prompt("Query the administrative divisions of this city")
.bizParams(JsonUtils.parse(bizParams))
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("%s\n",
result.getOutput().getText());
}
public static void main(String[] args) {
try {
appCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("Untuk informasi lebih lanjut, lihat: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}contoh tanggapan
Hangzhou adalah ibu kota Provinsi Zhejiang. Pembagian administratifnya terutama mencakup 10 distrik kota: Shangcheng, Gongshu, Xihu, Binjiang, Xiaoshan, Yuhang, Linping, Qiantang, Fuyang, dan Lin'an. Setiap distrik memiliki karakteristik dan prioritas pengembangan sendiri.
- Distrik Shangcheng: Terletak di pusat Hangzhou, memiliki banyak situs warisan sejarah dan budaya.
- Distrik Gongshu: Terkenal dengan budaya Kanal Besar, juga merupakan area komersial dan perumahan penting.
- Distrik Xihu: Dikenal karena pemandangan alamnya yang indah, termasuk kawasan wisata Danau Barat yang terkenal.
- Distrik Binjiang: Pusat industri teknologi tinggi. Zona Pengembangan Industri Teknologi Tinggi Nasional Hangzhou berlokasi di sini.
- Distrik Xiaoshan: Mengalami pertumbuhan ekonomi pesat, dengan kinerja luar biasa di sektor manufaktur.
- Distrik Yuhang: Berkembang pesat dalam beberapa tahun terakhir dengan munculnya perusahaan teknologi tinggi seperti Alibaba. (Catatan: Kantor pusat Alibaba sebenarnya berada di Distrik Binjiang.)
- Distrik Linping: Dibentuk dari bagian Distrik Yuhang asli pada tahun 2021, fokus pada pengembangan ekologis dan inovasi teknologi.
- Distrik Qiantang: Juga didirikan pada tahun 2021, distrik baru ini diposisikan sebagai pusat pengembangan transportasi dan industri di timur Hangzhou.
- Distrik Fuyang: Merupakan kota dengan sejarah panjang dan pusat utama industri kertas.
- Distrik Lin'an: Terletak di barat Hangzhou, memiliki tutupan hutan tinggi dan lingkungan ekologis yang baik.
Bersama-sama, distrik-distrik ini membentuk tata letak geografis dan struktur sosial-ekonomi Hangzhou yang unik. Jika Anda tertarik pada area tertentu atau membutuhkan informasi lebih rinci, beri tahu saya!HTTP
curl
contoh permintaan
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "Query the administrative divisions of this city",
"biz_params": {
"city": "Hangzhou"}
},
"parameters": {}
}'
Ganti YOUR_APP_ID dengan ID aplikasi sebenarnya Anda.
contoh tanggapan
{"output":{"finish_reason":"stop","session_id":"c211219896004b50a1f6f66f2ec5413e",
"text":"Hangzhou administers 10 districts, 1 county, and 2 county-level cities, which are:\nShangcheng District, Gongshu District, Xihu District, Binjiang District, Xiaoshan District, Yuhang District, Linping District, Qiantang District, Fuyang District, Lin'an District, Tonglu County, Chun'an County, Jiande City, and Zhuji City.\nNote: Zhuji City is directly administered by Zhejiang Province and jointly managed by Hangzhou and Shaoxing cities."},"usage":{},
"request_id":"02c3c9e1-7912-9505-91aa-248d04fb1f5d"}PHP
contoh permintaan
<?php
# Jika Anda belum mengonfigurasi variabel lingkungan, Anda dapat menggunakan Kunci API Model Studio Anda dengan mengganti baris berikut menjadi: $api_key="sk-xxx".
# Kami merekomendasikan agar Anda tidak melakukan hardcoding kunci API di kode Anda di lingkungan produksi untuk mengurangi risiko kebocoran kunci API.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Ganti dengan ID aplikasi sebenarnya Anda.
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// Bangun data permintaan.
$data = [
"input" => [
'prompt' => 'Query the administrative divisions of this city',
'biz_params' => [
'city' => 'Hangzhou'
]
],
];
// Encode data sebagai JSON.
$dataString = json_encode($data);
// Periksa apakah json_encode berhasil.
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Inisialisasi sesi cURL.
$ch = curl_init($url);
// Atur opsi 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
]);
// Jalankan permintaan.
$response = curl_exec($ch);
// Periksa apakah eksekusi cURL berhasil.
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// Dapatkan kode status HTTP.
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Tutup sesi cURL.
curl_close($ch);
// Decode data tanggapan.
$response_data = json_decode($response, true);
// Proses tanggapan.
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";
}
}contoh tanggapan
Hangzhou adalah ibu kota Provinsi Zhejiang. Pembagian administratifnya terutama mencakup 10 distrik kota: Shangcheng, Gongshu, Xihu, Binjiang, Xiaoshan, Yuhang, Linping, Qiantang, Fuyang, dan Lin'an.
Setiap distrik memiliki karakteristik dan prioritas pengembangan sendiri, seperti:
- Distrik Shangcheng dan Gongshu terletak di pusat Hangzhou, dengan perdagangan yang ramai dan sejarah panjang.
- Distrik Xihu terkenal dengan Danau Barat yang indah dan juga merupakan area ilmiah, pendidikan, dan budaya penting.
- Distrik Binjiang dikenal karena pengembangan industri teknologi tingginya.
- Distrik Xiaoshan, Distrik Yuhang, dan lainnya adalah area perkotaan baru atau zona pengembangan ekonomi yang berkembang pesat dalam beberapa tahun terakhir.
- Distrik Lin'an, Distrik Fuyang, dan area lainnya telah mempertahankan lebih banyak pemandangan alam dan fitur pedesaannya.
Harap dicatat bahwa pembagian administratif Tiongkok dapat disesuaikan sesuai kebijakan nasional. Dapatkan informasi terbaru melalui saluran resmi.Node.js
Instal dependensi yang diperlukan:
npm install axioscontoh permintaan
const axios = require('axios');
async function callDashScope() {
// Jika Anda belum mengonfigurasi variabel lingkungan, Anda dapat menggunakan Kunci API Model Studio Anda dengan mengganti baris berikut menjadi: apiKey='sk-xxx'.
// Kami merekomendasikan agar Anda tidak melakukan hardcoding kunci API di kode Anda di lingkungan produksi untuk mengurangi risiko kebocoran kunci API.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID'; // Ganti dengan ID aplikasi sebenarnya Anda.
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "Query the administrative divisions of this city",
biz_params: {
'city': 'Hangzhou',
},
},
parameters: {},
debug: {},
};
try {
console.log("Sending request to DashScope API...");
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
if (response.data.output && response.data.output.text) {
console.log(`${response.data.output.text}`);
}
} else {
console.log("Request failed:");
if (response.data.request_id) {
console.log(`request_id=${response.data.request_id}`);
}
console.log(`code=${response.status}`);
if (response.data.message) {
console.log(`message=${response.data.message}`);
} else {
console.log('message=Unknown error');
}
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
contoh tanggapan
Hangzhou adalah ibu kota Provinsi Zhejiang. Pembagian administratifnya mencakup 10 distrik kota. Mereka adalah sebagai berikut:
1. Distrik Shangcheng (Shàngchéng Qū): Terletak di selatan pusat kota, merupakan salah satu area tertua dan paling kaya budaya di Hangzhou.
2. Distrik Gongshu (Gǒngshù Qū): Distrik baru yang dibentuk dari penggabungan bekas distrik Xiacheng dan Gongshu, terletak di bagian utara Hangzhou.
3. Distrik Xihu (Xīhú Qū): Terkenal dengan Danau Barat, situs Warisan Dunia UNESCO, memiliki lanskap alam dan budaya yang kaya.
4. Distrik Binjiang (Bīnjiāng Qū): Terletak di tepi selatan Sungai Qiantang, merupakan pusat industri teknologi tinggi.
5. Distrik Xiaoshan (Xiāoshān Qū): Terletak di bagian timur Hangzhou, merupakan salah satu basis manufaktur penting Tiongkok.
6. Distrik Yuhang (Yúháng Qū): Dulunya rumah bagi Linping, salah satu dari empat kota terkenal Tiongkok, kini telah menjadi zona pengembangan ekonomi penting di Hangzhou.
7. Distrik Fuyang (Fùyáng Qū): Terletak di barat daya Hangzhou, dinamai menurut Sungai Fuchun yang mengalir melaluinya.
8. Distrik Lin'an (Lín'ān Qū): Terletak di daerah pegunungan barat Hangzhou, dikenal karena pemandangan alamnya yang indah.
9. Distrik Qiantang (Qiántáng Qū): Didirikan pada tahun 2021, terdiri dari bekas Klaster Industri Dajiangdong dan bagian Distrik Xiaoshan, bertujuan untuk mendorong pengembangan timur Hangzhou.
10. Distrik Linping (Lín Píng Qū): Pembagian administratif baru yang dipisahkan dari Distrik Yuhang, terutama mencakup area seperti bekas Sub-distrik Linping dalam Yuhang.
Informasi di atas mencerminkan situasi hingga pembaruan terakhir saya. Harap dicatat bahwa pembagian administratif dapat disesuaikan. Rujuk pengumuman resmi terbaru untuk informasi paling akurat.C#
contoh permintaan
using System.Text;
class Program
{
static async Task Main(string[] args)
{
//Jika Anda belum mengonfigurasi variabel lingkungan, Anda dapat menggunakan Kunci API Model Studio Anda dengan mengganti baris berikut menjadi: apiKey="sk-xxx".
//Kami merekomendasikan agar Anda tidak melakukan hardcoding kunci API di kode Anda di lingkungan produksi untuk mengurangi risiko kebocoran kunci API.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "YOUR_APP_ID"; // Ganti dengan ID aplikasi sebenarnya Anda.
string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string jsonContent = @"{
""input"": {
""prompt"": ""Query the administrative divisions of this city"",
""biz_params"":{
""city"":""Hangzhou""
}
},
""parameters"": {},
""debug"": {}
}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Request successful:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}contoh tanggapan
{
"output": {
"finish_reason": "stop",
"session_id": "7a9ff57eec7d475fa5d487de5f5178d2",
"text": "Hangzhou adalah ibu kota Provinsi Zhejiang. Mengelola 10 distrik kota: Shangcheng, Gongshu, Xihu, Binjiang, Xiaoshan, Yuhang, Linping, Qiantang, Fuyang, dan Lin'an. Setiap distrik memiliki lokasi geografis dan karakteristik pengembangan uniknya sendiri. Misalnya, Distrik Xihu dikenal karena pemandangan alamnya yang indah, terutama Danau Barat yang terkenal. Distrik Binjiang lebih dikenal karena industri teknologi tingginya. Selain itu, seiring perkembangan kota, pembagian administratif dapat disesuaikan. Rujuk informasi terbaru dari sumber resmi."
},
"usage": {
},
"request_id": "d2c2fcc9-f821-98c9-9430-8704a2a41225"
}Go
contoh permintaan
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// Jika Anda belum mengonfigurasi variabel lingkungan, Anda dapat menggunakan Kunci API Model Studio Anda dengan mengganti baris berikut menjadi: apiKey := "sk-xxx".
// Kami merekomendasikan agar Anda tidak melakukan hardcoding kunci API di kode Anda di lingkungan produksi untuk mengurangi risiko kebocoran kunci API.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // Ganti dengan ID aplikasi sebenarnya Anda.
if apiKey == "" {
fmt.Println("Ensure that the DASHSCOPE_API_KEY environment variable is set.")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Buat badan permintaan.
requestBody := map[string]interface{}{
"input": map[string]interface{}{
"prompt": "Query the administrative divisions of this city",
"biz_params": map[string]interface{}{
"city": "Hangzhou",
},
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// Buat permintaan HTTP POST.
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// Atur header permintaan.
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Kirim permintaan.
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()
// Baca tanggapan.
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// Proses tanggapan.
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))
}
}
contoh tanggapan
{
"output": {
"finish_reason": "stop",
"session_id": "2dc3e1a9dcd248c6bb9ca92bffc3e745",
"text": "Hangzhou, disingkat 'Hang', adalah ibu kota Provinsi Zhejiang. Menurut penyesuaian pembagian administratif terbaru, Hangzhou kini mengelola 10 distrik kota, 2 kota tingkat kabupaten, dan 1 kabupaten, sebagai berikut:\n\n- Distrik kota (10): Shangcheng, Gongshu, Xihu, Binjiang, Xiaoshan, Yuhang, Linping, Qiantang, Fuyang, dan Lin'an.\n- Kota tingkat kabupaten (2): Kota Jiande, Kabupaten Tonglu (Catatan bahwa Tonglu diperlakukan sebagai kota tingkat kabupaten di sini, tetapi secara teknis merupakan kabupaten).\n- Kabupaten (1): Kabupaten Chun'an.\n\nHarap dicatat bahwa pembagian administratif dapat disesuaikan seiring waktu. Rujuk pengumuman resmi terbaru untuk informasi paling akurat. Informasi di atas dikompilasi dari data terbaru. Untuk perubahan terbaru, silakan konsultasikan situs web pemerintah resmi untuk informasi paling akurat."
},
"usage": {
},
"request_id": "d3c8f368-b645-9446-bfe4-20ca51821a02"
}Dokumentasi terkait
Plugin kustom: Pelajari cara membuat plugin kustom.
Pemanggilan aplikasi: Pelajari cara memanggil aplikasi dan jelajahi lebih banyak kasus penggunaan.
API pemanggilan aplikasi: Referensi daftar parameter lengkap dan contoh pemanggilan.