Badan permintaan | Contoh permintaanPercakapan satu putaranPythonPermintaan contoh 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(
# Jika variabel lingkungan belum dikonfigurasi, Anda dapat mengganti baris berikut dengan api_key="sk-xxx". Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID',# Ganti dengan ID aplikasi yang sebenarnya
prompt='Siapa kamu?')
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'Lihat: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
else:
print(response.output.text)
JavaPermintaan contoh // Versi SDK dashscope yang direkomendasikan >= 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()
// Jika variabel lingkungan belum dikonfigurasi, Anda dapat mengganti baris berikut dengan .apiKey("sk-xxx"). Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("YOUR_APP_ID")
.prompt("Siapa kamu?")
.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("Lihat: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPCurlPermintaan 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": "Siapa kamu?"
},
"parameters": {},
"debug": {}
}'
Ganti YOUR_APP_ID dengan ID aplikasi yang sebenarnya. PHPPermintaan contoh <?php
# Jika variabel lingkungan belum dikonfigurasi, Anda dapat mengganti baris berikut dengan API Key Anda: $api_key="sk-xxx". Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Ganti dengan ID aplikasi yang sebenarnya
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// Membuat data permintaan
$data = [
"input" => [
'prompt' => 'Siapa kamu?'
]
];
// Enkode data sebagai JSON
$dataString = json_encode($data);
// Periksa apakah json_encode berhasil
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding gagal dengan kesalahan: " . json_last_error_msg());
}
// Inisialisasi sesi curl
$ch = curl_init($url);
// Set 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
]);
// Eksekusi 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);
// Dekode data respons
$response_data = json_decode($response, true);
// Tangani respons
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "Tidak ada teks dalam respons.\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=Kesalahan tidak dikenal\n";}
}
?>
Node.jsDependensi: npm install axios
Permintaan contoh const axios = require('axios');
async function callDashScope() {
// Jika variabel lingkungan belum dikonfigurasi, Anda dapat mengganti baris berikut dengan apiKey='sk-xxx'. Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// Ganti dengan ID aplikasi yang sebenarnya
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "Siapa kamu?"
},
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 memanggil DashScope: ${error.message}`);
if (error.response) {
console.error(`Status respons: ${error.response.status}`);
console.error(`Data respons: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
C#Permintaan contoh using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
//Jika variabel lingkungan belum dikonfigurasi, Anda dapat mengganti baris berikut dengan apiKey="sk-xxx". Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("Variabel lingkungan DASHSCOPE_API_KEY belum diset.");
string appId = "YOUR_APP_ID"; // Ganti dengan ID aplikasi yang sebenarnya
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"": ""Siapa kamu?""
},
""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("Permintaan berhasil:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Permintaan gagal dengan kode status: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error memanggil DashScope: {ex.Message}");
}
}
}
}
GoPermintaan contoh package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// Jika variabel lingkungan belum dikonfigurasi, Anda dapat mengganti baris berikut dengan apiKey := "sk-xxx". Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // Ganti dengan ID aplikasi yang sebenarnya
if apiKey == "" {
fmt.Println("Pastikan DASHSCOPE_API_KEY telah diset.")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Buat body permintaan
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "Siapa kamu?",
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Gagal melakukan 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
}
// Set 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 respons
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Gagal membaca respons: %v\n", err)
return
}
// Proses respons
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))
}
}
Percakapan multi-putaranLewati session_id atau messages untuk mengimplementasikan percakapan multi-putaran. Untuk informasi lebih lanjut, lihat Percakapan multi-putaran. Saat ini, hanya Agent Applications dan Dialog Workflow Applications yang mendukung percakapan multi-putaran. PythonPermintaan contoh 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(
# Jika variabel lingkungan belum dikonfigurasi, Anda dapat mengganti baris berikut dengan api_key="sk-xxx". Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID', # Ganti dengan ID aplikasi yang sebenarnya
prompt='Siapa kamu?')
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'Lihat: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
return response
responseNext = Application.call(
# Jika variabel lingkungan belum dikonfigurasi, Anda dapat mengganti baris berikut dengan api_key="sk-xxx". Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID', # Ganti dengan ID aplikasi yang sebenarnya
prompt='Apa saja kemampuanmu?',
session_id=response.output.session_id) # session_id dari respons sebelumnya
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'Lihat: https://www.alibabacloud.com/help/en/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()
JavaPermintaan 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 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()
// Jika variabel lingkungan belum dikonfigurasi, Anda dapat mengganti baris berikut dengan .apiKey("sk-xxx"). Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// Ganti dengan ID aplikasi yang sebenarnya
.appId("YOUR_APP_ID")
.prompt("Siapa kamu?")
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
param.setSessionId(result.getOutput().getSessionId());
param.setPrompt("Apa saja kemampuanmu?");
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("Lihat: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPCurlPermintaan contoh (putaran 1) curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "Siapa kamu?"
},
"parameters": {},
"debug": {}
}'
Permintaan contoh (putaran 2) curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "Apa saja kemampuanmu?",
"session_id":"4f8ef7233dc641aba496cb201fa59f8c"
},
"parameters": {},
"debug": {}
}'
PHPPermintaan contoh (putaran 1) <?php
# Jika variabel lingkungan belum dikonfigurasi, Anda dapat mengganti baris berikut dengan API Key Anda: $api_key="sk-xxx". Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Ganti dengan ID aplikasi yang sebenarnya
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// Membuat data permintaan
$data = [
"input" => [
'prompt' => 'Siapa kamu?'
]
];
// Enkode data sebagai JSON
$dataString = json_encode($data);
// Periksa apakah json_encode berhasil
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding gagal dengan kesalahan: " . json_last_error_msg());
}
// Inisialisasi sesi curl
$ch = curl_init($url);
// Set 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
]);
// Eksekusi 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);
// Dekode data respons
$response_data = json_decode($response, true);
// Tangani respons
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "Tidak ada teks dalam respons.\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=Kesalahan tidak dikenal\n";
}
}
?>
Permintaan contoh (putaran 2) <?php
# Jika variabel lingkungan belum dikonfigurasi, Anda dapat mengganti baris berikut dengan API Key Anda: $api_key="sk-xxx". Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Ganti dengan ID aplikasi yang sebenarnya
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// Membuat data permintaan
$data = [
"input" => [
'prompt' => 'Apa saja kemampuanmu?',
// Ganti dengan session_id yang dikembalikan dari percakapan putaran sebelumnya
'session_id' => '2e658bcb514f4d30ab7500b4766a8d43'
]
];
// Enkode data sebagai JSON
$dataString = json_encode($data);
// Periksa apakah json_encode berhasil
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding gagal dengan kesalahan: " . json_last_error_msg());
}
// Inisialisasi sesi curl
$ch = curl_init($url);
// Set 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
]);
// Eksekusi 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);
// Dekode data respons
$response_data = json_decode($response, true);
// Tangani respons
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "Tidak ada teks dalam respons.\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=Kesalahan tidak dikenal\n";
}
}
?>
Node.jsDependensi: npm install axios
Permintaan contoh (putaran 1) const axios = require('axios');
async function callDashScope() {
// Jika variabel lingkungan belum dikonfigurasi, Anda dapat mengganti baris berikut dengan apiKey='sk-xxx'. Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// Ganti dengan ID aplikasi yang sebenarnya
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "Siapa kamu?"
},
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 memanggil DashScope: ${error.message}`);
if (error.response) {
console.error(`Status respons: ${error.response.status}`);
console.error(`Data respons: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
Permintaan contoh (putaran 2) const axios = require('axios');
async function callDashScope() {
// Jika variabel lingkungan belum dikonfigurasi, Anda dapat mengganti baris berikut dengan apiKey='sk-xxx'. Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// Ganti dengan ID aplikasi yang sebenarnya
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
// Ganti session_id dengan session_id yang sebenarnya dari percakapan sebelumnya
const data = {
input: {
prompt: "Apa saja kemampuanmu?",
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 memanggil DashScope: ${error.message}`);
if (error.response) {
console.error(`Status respons: ${error.response.status}`);
console.error(`Data respons: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
C#Permintaan contoh (putaran 1) using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
//Jika variabel lingkungan belum dikonfigurasi, Anda dapat mengganti baris berikut dengan apiKey="sk-xxx". Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("Variabel lingkungan DASHSCOPE_API_KEY belum diset.");
string appId = "YOUR_APP_ID"; // Ganti dengan ID aplikasi yang sebenarnya
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"": ""Siapa kamu?""
},
""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("Permintaan berhasil:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Permintaan gagal dengan kode status: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error memanggil DashScope: {ex.Message}");
}
}
}
}
Permintaan contoh (putaran 2) using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
//Jika variabel lingkungan belum dikonfigurasi, Anda dapat mengganti baris berikut dengan apiKey="sk-xxx". Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("Variabel lingkungan DASHSCOPE_API_KEY belum diset.");
string appId = "YOUR_APP_ID"; // Ganti dengan ID aplikasi yang sebenarnya
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"": ""Apa saja kemampuanmu?"",
""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("Permintaan berhasil:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Permintaan gagal dengan kode status: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error memanggil DashScope: {ex.Message}");
}
}
}
}
GoPermintaan contoh (putaran 1) package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// Jika variabel lingkungan belum dikonfigurasi, Anda dapat mengganti baris berikut dengan apiKey := "sk-xxx". Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // Ganti dengan ID aplikasi yang sebenarnya
if apiKey == "" {
fmt.Println("Pastikan DASHSCOPE_API_KEY telah diset.")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Buat body permintaan
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "Siapa kamu?",
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Gagal melakukan 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
}
// Set 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 respons
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Gagal membaca respons: %v\n", err)
return
}
// Proses respons
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))
}
}
Permintaan contoh (putaran 2) package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// Jika variabel lingkungan belum dikonfigurasi, Anda dapat mengganti baris berikut dengan apiKey := "sk-xxx". Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // Ganti dengan ID aplikasi yang sebenarnya
if apiKey == "" {
fmt.Println("Pastikan DASHSCOPE_API_KEY telah diset.")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Buat body permintaan
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "Apa saja kemampuanmu?",
"session_id": "f7eea37f0c734c20998a021b688d6de2", // Ganti dengan session_id yang sebenarnya dari percakapan sebelumnya
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Gagal melakukan 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
}
// Set 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 respons
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Gagal membaca respons: %v\n", err)
return
}
// Proses respons
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))
}
}
Ganti YOUR_APP_ID dengan ID aplikasi yang sebenarnya. Untuk putaran 2, ganti session_id dengan session_id yang sebenarnya yang dikembalikan dari putaran 1. Pengiriman parameterPythonPermintaan contoh import os
from http import HTTPStatus
# Versi SDK dashscope yang direkomendasikan >= 1.14.0
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
biz_params = {
# Pengiriman parameter input plugin kustom untuk aplikasi agen, ganti your_plugin_code dengan ID plugin kustom Anda
"user_defined_params": {
"your_plugin_code": {
"article_index": 2}}}
response = Application.call(
# Jika variabel lingkungan belum dikonfigurasi, Anda dapat mengganti baris berikut dengan api_key="sk-xxx". Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID',
prompt='Konten konvensi asrama',
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'Lihat: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
else:
print('%s\n' % (response.output.text)) # Proses hanya teks keluaran
# print('%s\n' % (response.usage))
JavaPermintaan 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 =
// Pengiriman parameter input plugin kustom untuk aplikasi agen, ganti {your_plugin_code} dengan ID plugin kustom Anda
"{\"user_defined_params\":{\"{your_plugin_code}\":{\"article_index\":2}}}";
ApplicationParam param = ApplicationParam.builder()
// Jika variabel lingkungan belum dikonfigurasi, Anda dapat mengganti baris berikut dengan .apiKey("sk-xxx"). Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("YOUR_APP_ID")
.prompt("Konten konvensi asrama")
.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("Lihat: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPCurlPermintaan 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": "Konten konvensi asrama",
"biz_params":
{
"user_defined_params":
{
"{your_plugin_code}":
{
"article_index": 2
}
}
}
},
"parameters": {},
"debug":{}
}'
Ganti YOUR_APP_ID dengan ID aplikasi yang sebenarnya. PHPPermintaan contoh <?php
# Jika variabel lingkungan belum dikonfigurasi, ganti dengan Dashscope API Key: $api_key="sk-xxx". Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Ganti dengan ID aplikasi yang sebenarnya
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// Ganti {your_plugin_code} dengan ID plugin yang sebenarnya
// Membuat data permintaan
$data = [
"input" => [
'prompt' => 'Konten konvensi asrama',
'biz_params' => [
'user_defined_params' => [
'{your_plugin_code}' => [
'article_index' => 2
]
]
]
],
];
// Enkode data sebagai JSON
$dataString = json_encode($data);
// Periksa apakah json_encode berhasil
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding gagal dengan kesalahan: " . json_last_error_msg());
}
// Inisialisasi sesi curl
$ch = curl_init($url);
// Set 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
]);
// Eksekusi 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);
// Dekode data respons
$response_data = json_decode($response, true);
// Tangani respons
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "Tidak ada teks dalam respons.\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=Kesalahan tidak dikenal\n";}
}
?>
Node.jsDependensi: npm install axios
Permintaan contoh const axios = require('axios');
async function callDashScope() {
// Jika variabel lingkungan belum dikonfigurasi, Anda dapat mengganti baris berikut dengan apiKey='sk-xxx'. Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// Ganti dengan ID aplikasi yang sebenarnya
const pluginCode = 'YOUR_PLUGIN_CODE';// Ganti dengan ID plugin yang sebenarnya
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "Konten konvensi asrama",
biz_params: {
user_defined_params: {
[pluginCode]: {
// article_index adalah variabel untuk plugin kustom, ganti dengan variabel plugin yang sebenarnya
'article_index': 3
}
}
}
},
parameters: {},
debug: {}
};
try {
console.log("Mengirim permintaan ke API DashScope...");
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("Permintaan gagal:");
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=Kesalahan tidak dikenal');
}
}
} catch (error) {
console.error(`Error memanggil DashScope: ${error.message}`);
if (error.response) {
console.error(`Status respons: ${error.response.status}`);
console.error(`Data respons: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
C#Permintaan contoh using System.Text;
class Program
{
static async Task Main(string[] args)
{
// Jika variabel lingkungan belum dikonfigurasi, Anda dapat mengganti baris berikut dengan apiKey="sk-xxx". Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("Variabel lingkungan DASHSCOPE_API_KEY belum diset.");;
string appId = "YOUR_APP_ID";// Ganti dengan ID aplikasi yang sebenarnya
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("Pastikan Anda telah menyetel DASHSCOPE_API_KEY.");
return;
}
string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string pluginCode = "{your_plugin_code}"; // Ganti {your_plugin_code} dengan ID plugin yang sebenarnya
string jsonContent = $@"{{
""input"": {{
""prompt"": ""Konten konvensi asrama"",
""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("Permintaan berhasil:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Permintaan gagal dengan kode status: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error memanggil DashScope: {ex.Message}");
}
}
}
}
GoPermintaan contoh package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// Jika variabel lingkungan belum dikonfigurasi, Anda dapat mengganti baris berikut dengan apiKey := "sk-xxx". Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // Ganti dengan ID aplikasi yang sebenarnya
pluginCode := "YOUR_PLUGIN_CODE" // Ganti dengan ID plugin yang sebenarnya
if apiKey == "" {
fmt.Println("Pastikan Anda telah menyetel DASHSCOPE_API_KEY.")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Buat body permintaan
requestBody := map[string]interface{}{
"input": map[string]interface{}{
"prompt": "Konten konvensi asrama",
"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 melakukan 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
}
// Set 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 respons
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Gagal membaca respons: %v\n", err)
return
}
// Proses respons
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))
}
}
Keluaran streamingPythonPermintaan contoh 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(
# Jika variabel lingkungan belum dikonfigurasi, ganti baris berikut dengan: api_key="sk-xxx". Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID',
prompt='Siapa kamu?',
stream=True, // Keluaran streaming
incremental_output=True) // Keluaran inkremental
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'Lihat dokumentasi: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
else:
print(f'{response.output.text}\n') // Proses hanya teks keluaran
JavaPermintaan contoh // Versi SDK dashscope yang direkomendasikan >= 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;// Keluaran streaming
// Implementasi aplikasi agen untuk hasil keluaran streaming
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()
// Jika variabel lingkungan belum dikonfigurasi, ganti baris berikut dengan: .apiKey("sk-xxx"). Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// Ganti dengan ID aplikasi yang sebenarnya
.appId("YOUR_APP_ID")
.prompt("Siapa kamu?")
// Keluaran inkremental
.incrementalOutput(true)
.build();
Application application = new Application();
// .streamCall(): Keluaran konten streaming
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("Lihat dokumentasi: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPCurlPermintaan 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' \
--header 'X-DashScope-SSE: enable' \
--data '{
"input": {
"prompt": "Siapa kamu?"
},
"parameters": {
"incremental_output":true
},
"debug": {}
}'
Ganti YOUR_APP_ID dengan ID aplikasi yang sebenarnya. PHPPermintaan contoh <?php
// Jika variabel lingkungan belum dikonfigurasi, ganti baris berikut dengan: $api_key="sk-xxx". Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Ganti dengan ID aplikasi yang sebenarnya
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// Membuat data permintaan
$data = [
"input" => [
'prompt' => 'Siapa kamu?'],
"parameters" => [
'incremental_output' => true]];// Keluaran inkremental
// Enkode data sebagai JSON
$dataString = json_encode($data);
// Periksa apakah json_encode berhasil
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding gagal dengan kesalahan: " . json_last_error_msg());
}
// Inisialisasi sesi curl
$ch = curl_init($url);
// Set opsi curl
curl_setopt($ch, curlOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, curlOPT_POSTFIELDS, $dataString);
curl_setopt($ch, curlOPT_RETURNTRANSFER, false); // Jangan kembalikan data yang ditransfer
curl_setopt($ch, curlOPT_WRITEFUNCTION, function ($ch, $string) {
echo $string; // Proses data streaming
return strlen($string);
});
curl_setopt($ch, curlOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key,
'X-DashScope-SSE: enable' // Keluaran streaming
]);
// Eksekusi 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);
if ($status_code != 200) {
echo "HTTP Status Code: $status_code\n";
echo "Permintaan gagal.\n";
}
?>
Node.jsDependensi: npm install axios
Permintaan contoh 1. Keluaran respons lengkap const axios = require('axios');
async function callDashScope() {
// Jika variabel lingkungan belum dikonfigurasi, ganti baris berikut dengan: apiKey='sk-xxx'. Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// Ganti dengan ID aplikasi yang sebenarnya
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "Siapa kamu?"
},
parameters: {
'incremental_output' : 'true' // Keluaran inkremental
},
debug: {}
};
try {
console.log("Mengirim permintaan ke API DashScope...");
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
'X-DashScope-SSE': 'enable' // Keluaran streaming
},
responseType: 'stream' // Untuk menangani respons streaming
});
if (response.status === 200) {
// Proses respons streaming
response.data.on('data', (chunk) => {
console.log(`Menerima chunk: ${chunk.toString()}`);
});
} else {
console.log("Permintaan gagal:");
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=Kesalahan tidak dikenal');
}
}
} catch (error) {
console.error(`Error memanggil DashScope: ${error.message}`);
if (error.response) {
console.error(`Status respons: ${error.response.status}`);
console.error(`Data respons: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
Perluas panel untuk melihat kode contoh: 2. Keluaran hanya bidang teks const axios = require('axios');
const { Transform } = require('stream');
async function callDashScope() {
// Jika variabel lingkungan belum dikonfigurasi, ganti baris berikut dengan: apiKey='sk-xxx'. Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID'; // Ganti dengan ID aplikasi yang sebenarnya
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: { prompt: "Siapa kamu?" },
parameters: { incremental_output: true }, // Keluaran inkremental
debug: {}
};
try {
console.log("Mengirim permintaan ke API DashScope...");
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
'X-DashScope-SSE': 'enable' // Keluaran streaming
},
responseType: 'stream' // Untuk menangani respons streaming
});
if (response.status === 200) {
// // Proses respons streaming SSE protocol parsing transformer
const sseTransformer = new Transform({
transform(chunk, encoding, callback) {
this.buffer += chunk.toString();
// Pisah berdasarkan event SSE (dua line feed)
const events = this.buffer.split(/\n\n/);
this.buffer = events.pop() || ''; // Simpan bagian yang tidak lengkap
events.forEach(eventData => {
const lines = eventData.split('\n');
let textContent = '';
// Parsing konten event
lines.forEach(line => {
if (line.startsWith('data:')) {
try {
const jsonData = JSON.parse(line.slice(5).trim());
if (jsonData.output?.text) {
textContent = jsonData.output.text;
}
} catch(e) {
console.error('JSON parsing error:', e.message);
}
}
});
if (textContent) {
// Tambahkan line feed dan dorong
this.push(textContent + '\n');
}
});
callback();
},
flush(callback) {
if (this.buffer) {
this.push(this.buffer + '\n');
}
callback();
}
});
sseTransformer.buffer = '';
// Pipeline processing
response.data
.pipe(sseTransformer)
.on('data', (textWithNewline) => {
process.stdout.write(textWithNewline); // Output otomatis dengan line feed
})
.on('end', () => console.log(""))
.on('error', err => console.error("Pipeline error:", err));
} else {
console.log("Permintaan gagal, kode status:", response.status);
response.data.on('data', chunk => console.log(chunk.toString()));
}
} catch (error) {
console.error(`Pemanggilan API gagal: ${error.message}`);
if (error.response) {
console.error(`Kode status: ${error.response.status}`);
error.response.data.on('data', chunk => console.log(chunk.toString()));
}
}
}
callDashScope();
C#Permintaan contoh using System.Net;
using System.Text;
class Program
{
static async Task Main(string[] args)
{
// Jika variabel lingkungan belum dikonfigurasi, ganti baris berikut dengan: apiKey="sk-xxx". Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("Variabel lingkungan DASHSCOPE_API_KEY belum diset.");
string appId = "YOUR_APP_ID"; // Ganti dengan ID aplikasi yang sebenarnya
string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
client.DefaultRequestHeaders.Add("X-DashScope-SSE", "enable");
string jsonContent = @"{
""input"": {
""prompt"": ""Siapa kamu""
},
""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("Permintaan berhasil:");
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; // Deklarasikan sebagai string nullable
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($"Permintaan gagal dengan kode status: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error memanggil DashScope: {ex.Message}");
}
}
}
}
GoPermintaan contoh package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
)
func main() {
// Jika variabel lingkungan belum dikonfigurasi, ganti baris berikut dengan: apiKey := "sk-xxx". Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // Ganti dengan ID aplikasi yang sebenarnya
if apiKey == "" {
fmt.Println("Pastikan DASHSCOPE_API_KEY telah diset.")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Buat body permintaan, di mana incremental_output menunjukkan apakah akan mengaktifkan respons streaming
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "Siapa kamu?",
},
"parameters": map[string]interface{}{
"incremental_output": true,
},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Gagal melakukan 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
}
// Set header permintaan, di mana X-DashScope-SSE diset ke enable menunjukkan pengaktifan respons streaming
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-DashScope-SSE", "enable")
// 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()
if resp.StatusCode != http.StatusOK {
fmt.Printf("Permintaan gagal dengan kode status: %d\n", resp.StatusCode)
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
return
}
// Proses respons streaming
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 membaca respons: %v\n", err)
break
}
}
}
Ambil basis pengetahuanPythonPermintaan contoh import os
from http import HTTPStatus
# Versi SDK dashscope yang direkomendasikan >= 1.20.11
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
response = Application.call(
# Jika variabel lingkungan belum dikonfigurasi, Anda dapat mengganti baris berikut dengan api_key="sk-xxx". Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID', # Ganti YOUR_APP_ID dengan ID aplikasi
prompt='Rekomendasikan ponsel di bawah 3000 yuan',
rag_options={
"pipeline_ids": ["YOUR_PIPELINE_ID1,YOUR_PIPELINE_ID2"], # Ganti dengan ID basis pengetahuan yang sebenarnya, pisahkan beberapa ID dengan koma
}
)
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'Lihat: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
else:
print('%s\n' % (response.output.text)) # Proses hanya teks keluaran
# print('%s\n' % (response.usage))
JavaPermintaan contoh // Versi SDK dashscope yang direkomendasikan >= 2.16.8;
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import java.util.Collections;
import java.util.List;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void streamCall() throws NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// Jika variabel lingkungan belum dikonfigurasi, Anda dapat mengganti baris berikut dengan .apiKey("sk-xxx"). Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("YOUR_APP_ID") // Ganti dengan ID aplikasi yang sebenarnya
.prompt("Rekomendasikan ponsel sekitar 3000 yuan")
.ragOptions(RagOptions.builder()
// Ganti dengan ID basis pengetahuan yang sebenarnya, pisahkan beberapa dengan koma
.pipelineIds(List.of("PIPELINES_ID1", "PIPELINES_ID2"))
.build())
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("%s\n",
result.getOutput().getText());// Proses hanya teks keluaran
}
public static void main(String[] args) {
try {
streamCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("Lihat: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPCurlPermintaan 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": "Rekomendasikan ponsel di bawah 3000 yuan"
},
"parameters": {
"rag_options" : {
"pipeline_ids":["YOUR_PIPELINE_ID1"]}
},
"debug": {}
}'
Ganti YOUR_APP_ID dengan ID aplikasi yang sebenarnya, dan YOUR_PIPELINE_ID1 dengan ID basis pengetahuan yang ditentukan. PHPPermintaan contoh <?php
# Jika variabel lingkungan belum dikonfigurasi, Anda dapat mengganti baris berikut dengan API Key Anda: $api_key="sk-xxx". Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Ganti dengan ID aplikasi yang sebenarnya
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// Membuat data permintaan
$data = [
"input" => [
'prompt' => 'Rekomendasikan smartphone di bawah 3000 yuan.'
],
"parameters" => [
'rag_options' => [
'pipeline_ids' => ['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'] // Ganti dengan ID basis pengetahuan yang ditentukan; gunakan koma untuk memisahkan beberapa ID
]
]
];
// Enkode data sebagai JSON
$dataString = json_encode($data);
// Periksa apakah json_encode berhasil
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding gagal dengan kesalahan: " . json_last_error_msg());
}
// Inisialisasi sesi curl
$ch = curl_init($url);
// Set 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
]);
// Eksekusi 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);
// Dekode data respons
$response_data = json_decode($response, true);
// Tangani respons
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "Tidak ada teks dalam respons.\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=Kesalahan tidak dikenal\n";
}
}
?>
Node.jsDependensi: npm install axios
Permintaan contoh const axios = require('axios');
async function callDashScope() {
// Jika variabel lingkungan belum dikonfigurasi, Anda dapat mengganti baris berikut dengan apiKey='sk-xxx'. Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';//Ganti dengan ID aplikasi yang sebenarnya
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "Rekomendasikan ponsel di bawah 3000 yuan"
},
parameters: {
rag_options:{
pipeline_ids:['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'] // Ganti dengan ID basis pengetahuan yang ditentukan, pisahkan beberapa dengan koma
}
},
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 memanggil DashScope: ${error.message}`);
if (error.response) {
console.error(`Status respons: ${error.response.status}`);
console.error(`Data respons: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
C#Permintaan contoh using System.Text;
class Program
{
static async Task Main(string[] args)
{
// Jika variabel lingkungan belum dikonfigurasi, Anda dapat mengganti baris berikut dengan apiKey="sk-xxx". Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("Variabel lingkungan DASHSCOPE_API_KEY belum diset.");;
string appId = "YOUR_APP_ID";// Ganti dengan ID aplikasi yang sebenarnya
// YOUR_PIPELINE_ID1 ganti dengan ID basis pengetahuan yang ditentukan
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("Pastikan DASHSCOPE_API_KEY telah diset.");
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"": ""Rekomendasikan ponsel di bawah 3000 yuan""
}},
""parameters"": {{
""rag_options"" : {{
""pipeline_ids"":[""YOUR_PIPELINE_ID1""]
}}
}},
""debug"": {{}}
}}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Permintaan gagal dengan kode status: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error memanggil DashScope: {ex.Message}");
}
}
}
}
GoPermintaan contoh package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// Jika variabel lingkungan belum dikonfigurasi, Anda dapat mengganti baris berikut dengan apiKey := "sk-xxx". Namun, tidak disarankan untuk menuliskan API Key secara langsung ke dalam kode di lingkungan produksi untuk mengurangi risiko kebocoran API Key.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // Ganti dengan ID aplikasi yang sebenarnya
if apiKey == "" {
fmt.Println("Pastikan DASHSCOPE_API_KEY telah diset.")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Buat body permintaan
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "Rekomendasikan ponsel di bawah 3000 yuan",
},
"parameters": map[string]interface{}{
"rag_options": map[string]interface{}{
"pipeline_ids": []string{"YOUR_PIPELINE_ID1"}, // Ganti dengan ID basis pengetahuan yang ditentukan
},
},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Gagal melakukan 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
}
// Set 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 respons
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Gagal membaca respons: %v\n", err)
return
}
// Proses respons
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))
}
}
Lihat proses pengambilan: Saat melakukan panggilan, tambahkan has_thoughts ke dalam kode dan atur menjadi True. Proses pengambilan akan dikembalikan dalam bidang thoughts dari output. |