All Products
Search
Document Center

Alibaba Cloud Model Studio:Referensi API DashScope untuk Aplikasi

Last Updated:Apr 29, 2026

Topik ini menjelaskan parameter input dan output untuk memanggil aplikasi Agent dan Workflow Alibaba Cloud Model Studio menggunakan API DashScope, serta menyediakan contoh pemanggilan untuk skenario umum.

Penting

Topik ini hanya berlaku untuk Edisi Internasional (Wilayah Singapura).

Panduan terkait

Lihat Pemanggilan aplikasi.

Prasyarat

Sebelum memulai, selesaikan tugas-tugas berikut:

  1. Buat aplikasi: Buka Manajemen Aplikasi untuk membuat aplikasi Alibaba Cloud Model Studio dan dapatkan ID aplikasinya.

  2. Dapatkan Kunci API: Ambil kunci API Anda dari Manajemen Kunci dan konfigurasikan kunci API sebagai Variabel lingkungan.

  3. Instal SDK (opsional): Jika Anda menggunakan SDK untuk melakukan panggilan, instal DashScope SDK untuk bahasa pemrograman Anda.

Metode pemanggilan

  • Panggilan API HTTP

    URL Permintaan: POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion

    Ganti APP_ID dengan ID aplikasi aktual Anda.
  • Panggilan SDK

    Python/Java SDK: Titik akhir yang benar dikonfigurasi secara default.

    Titik akhir kustom: Konfigurasikan menggunakan parameter base_url.

Isi permintaan

Percakapan satu putaran

Python

Contoh permintaan

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 Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan api_key="sk-xxx" menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    app_id='APP_ID',# Ganti dengan ID aplikasi aktual Anda
    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 dokumentasi: https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code')
else:
    print(response.output.text)

Java

Contoh permintaan

// Kami merekomendasikan versi dashscope SDK >= 2.12.0
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
    static {
      Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
    }
    public static void appCall()
            throws ApiException, NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                // Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan .apiKey("sk-xxx") menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("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 dokumentasi: https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

HTTP

curl

Contoh permintaan

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "Siapa kamu?"
    },
    "parameters":  {},
    "debug": {}
}' 
Ganti APP_ID dengan ID aplikasi aktual Anda.

PHP

Contoh permintaan

<?php

# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan $api_key="sk-xxx" menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Ganti dengan ID aplikasi aktual Anda

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

// Buat data permintaan
$data = [
    "input" => [
        'prompt' => 'Siapa kamu?'
    ]
];

// 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);

// Setel 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);
// Decode 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 "No text in response.\n";
    }}
else {
    if (isset($response_data['request_id'])) {
        echo "request_id={$response_data['request_id']}\n";}
    echo "code={$status_code}\n";
    if (isset($response_data['message'])) {
        echo "message={$response_data['message']}\n";} 
    else {
        echo "message=Unknown error\n";}
}
?>

Node.js

Instal dependensi yang diperlukan:

npm install axios

Contoh permintaan

const axios = require('axios');

async function callDashScope() {
    // Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan apiKey='sk-xxx' menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// Ganti dengan ID aplikasi aktual Anda

    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 calling DashScope: ${error.message}`);
        if (error.response) {
            console.error(`Response status: ${error.response.status}`);
            console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
        }
    }
}

callDashScope();

C#

Contoh permintaan

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

class Program
{
    static async Task Main(string[] args)
    {
        //Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan apiKey="sk-xxx" menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna 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 = "APP_ID"; // Ganti dengan ID aplikasi aktual 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"": ""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("Request successful:");
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error calling DashScope: {ex.Message}");
            }
        }
    }
}

Go

Contoh permintaan

package main

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

func main() {
	// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan apiKey := "sk-xxx" menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // Ganti dengan ID aplikasi aktual Anda

	if apiKey == "" {
		fmt.Println("Make sure DASHSCOPE_API_KEY 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]string{
			"prompt": "Siapa kamu?",
		},
		"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 POST HTTP
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("Failed to create request: %v\n", err)
		return
	}

	// Setel 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 respons
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Failed to read response: %v\n", err)
		return
	}

	// Tangani respons
	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))
	}
}

Percakapan multi-putaran

Aktifkan percakapan multi-putaran menggunakan session_id atau messages.

Python

Contoh permintaan

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 Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan api_key="sk-xxx" menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        app_id='APP_ID',  # Ganti dengan ID aplikasi aktual Anda
        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 dokumentasi: https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code')
        return response

    responseNext = Application.call(
                # Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan api_key="sk-xxx" menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
                api_key=os.getenv("DASHSCOPE_API_KEY"),
                app_id='APP_ID',  # Ganti dengan ID aplikasi aktual Anda
                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 dokumentasi: https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code')
    else:
        print('%s\n session_id=%s\n' % (responseNext.output.text, responseNext.output.session_id))
        # print('%s\n' % (response.usage))

if __name__ == '__main__':
    call_with_session()

Java

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 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 Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan .apiKey("sk-xxx") menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // Ganti dengan ID aplikasi aktual Anda
                .appId("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 dokumentasi: https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

HTTP

curl

Contoh permintaan (putaran percakapan sebelumnya)

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "Siapa kamu?"
    },
    "parameters":  {},
    "debug": {}
}' 

Contoh permintaan (putaran berikutnya)

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "Apa saja kemampuanmu?",
        "session_id":"4f8ef7233dc641aba496cb201fa59f8c"
    },
    "parameters":  {},
    "debug": {}
}' 

PHP

Contoh permintaan (putaran percakapan sebelumnya)

<?php
# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan $api_key="sk-xxx" menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Ganti dengan ID aplikasi aktual Anda

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

// Buat data permintaan
$data = [
    "input" => [
        'prompt' => 'Siapa kamu?'
    ]
];

// 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);

// Setel 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);
// Decode 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 "No text in response.\n";
    };
    if (isset($response_data['output']['session_id'])) {
        echo "session_id={$response_data['output']['session_id']}\n";
    }
}else {
    if (isset($response_data['request_id'])) {
        echo "request_id={$response_data['request_id']}\n";}
    echo "code={$status_code}\n";
    if (isset($response_data['message'])) {
        echo "message={$response_data['message']}\n";} 
    else {
        echo "message=Unknown error\n";}
}
?>

Contoh permintaan (putaran berikutnya)

<?php
# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan $api_key="sk-xxx" menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Ganti dengan ID aplikasi aktual Anda

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

// Buat data permintaan
$data = [
    "input" => [
        'prompt' => 'Apa saja kemampuanmu?',
        // Ganti dengan session_id aktual yang dikembalikan dari percakapan sebelumnya
        'session_id' => '2e658bcb514f4d30ab7500b4766a8d43'
    ]
];

// 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);

// Setel 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);
// Decode 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 "No text in response.\n";
    };
    if (isset($response_data['output']['session_id'])) {
        echo "session_id={$response_data['output']['session_id']}\n";
    }
}else {
    if (isset($response_data['request_id'])) {
        echo "request_id={$response_data['request_id']}\n";}
    echo "code={$status_code}\n";
    if (isset($response_data['message'])) {
        echo "message={$response_data['message']}\n";} 
    else {
        echo "message=Unknown error\n";}
}
?>

Node.js

Instal dependensi yang diperlukan:

npm install axios

Contoh permintaan (percakapan sebelumnya)

const axios = require('axios');

async function callDashScope() {
    // Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan apiKey='sk-xxx' menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// Ganti dengan ID aplikasi aktual Anda

    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 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 permintaan (putaran berikutnya)

const axios = require('axios');

async function callDashScope() {
    // Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan apiKey='sk-xxx' menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// Ganti dengan ID aplikasi aktual Anda

    const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
    // Ganti session_id dengan session_id aktual 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 calling DashScope: ${error.message}`);
        if (error.response) {
            console.error(`Response status: ${error.response.status}`);
            console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
        }
    }
}
callDashScope();

C#

Contoh permintaan (putaran pertama)

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

class Program
{
    static async Task Main(string[] args)
    {
        //Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan apiKey="sk-xxx" menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna 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 = "APP_ID"; // Ganti dengan ID aplikasi aktual 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"": ""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("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 permintaan (putaran berikutnya)

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

class Program
{
    static async Task Main(string[] args)
    {
        //Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan apiKey="sk-xxx" menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna 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 = "APP_ID"; // Ganti dengan ID aplikasi aktual 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"": ""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("Request successful:");
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error calling DashScope: {ex.Message}");
            }
        }
    }
}

Go

Contoh permintaan (putaran percakapan sebelumnya)

package main

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

func main() {
	// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan apiKey := "sk-xxx" menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // Ganti dengan ID aplikasi aktual Anda

	if apiKey == "" {
		fmt.Println("Make sure DASHSCOPE_API_KEY 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]string{
			"prompt": "Siapa kamu?",
		},
		"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 POST HTTP
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("Failed to create request: %v\n", err)
		return
	}

	// Setel 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 respons
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Failed to read response: %v\n", err)
		return
	}

	// Tangani respons
	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 permintaan (putaran berikutnya)

package main

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

func main() {
	// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan apiKey := "sk-xxx" menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // Ganti dengan ID aplikasi aktual Anda

	if apiKey == "" {
		fmt.Println("Make sure DASHSCOPE_API_KEY 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]string{
			"prompt":     "Apa saja kemampuanmu?",
			"session_id": "f7eea37f0c734c20998a021b688d6de2", // Ganti dengan session_id aktual dari percakapan sebelumnya
		},
		"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 POST HTTP
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("Failed to create request: %v\n", err)
		return
	}

	// Setel 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 respons
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Failed to read response: %v\n", err)
		return
	}

	// Tangani respons
	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))
	}
}
Ganti APP_ID dengan ID aplikasi aktual Anda. Ganti nilai session_id pada parameter input putaran berikutnya dengan nilai session_id aktual yang dikembalikan dari percakapan sebelumnya.

Pass parameters

Pass parameter kustom menggunakan biz_params.

Python

Contoh permintaan

import os
from http import HTTPStatus
# Kami merekomendasikan versi dashscope SDK >= 1.14.0
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
biz_params = {
    # Pass parameter input plugin kustom untuk aplikasi agent. Ganti <TOOL_ID> dengan ID plugin kustom Anda.
    "user_defined_params": {
        "<TOOL_ID>": {
            "article_index": 2}}}
response = Application.call(
        # Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan api_key="sk-xxx" menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        app_id='APP_ID',
        prompt='Konten aturan 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 dokumentasi: https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code')
else:
    print('%s\n' % (response.output.text))  # Proses untuk hanya menampilkan teks
    # print('%s\n' % (response.usage))

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 =
                // Pass parameter input plugin kustom untuk aplikasi agent. Ganti <TOOL_ID> dengan ID plugin kustom Anda.
                "{\"user_defined_params\":{\"<TOOL_ID>\":{\"article_index\":2}}}";
        ApplicationParam param = ApplicationParam.builder()
                // Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan .apiKey("sk-xxx") menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("APP_ID")
                .prompt("Konten aturan 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 dokumentasi: https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}      

HTTP

curl

Contoh permintaan

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "Konten aturan asrama",
        "biz_params": 
        {
            "user_defined_params":
            {
                "<TOOL_ID>":
                    {
                    "article_index": 2
                    }
            }
        } 
    },
    "parameters":  {},
    "debug":{}
}'
Ganti APP_ID dengan ID aplikasi aktual Anda. Ganti <TOOL_ID> dengan ID plugin Anda.

PHP

Contoh permintaan

<?php

# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan $api_key="sk-xxx" menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Ganti dengan ID aplikasi aktual Anda
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
//Ganti <TOOL_ID> dengan ID plugin aktual Anda
// Buat data permintaan
$data = [
    "input" => [
        'prompt' => 'Konten aturan asrama',
        'biz_params' => [
        'user_defined_params' => [
            '<TOOL_ID>' => [
                '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);

// Setel 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);
// Decode 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 "No text in response.\n";
    }
}else {
    if (isset($response_data['request_id'])) {
        echo "request_id={$response_data['request_id']}\n";}
    echo "code={$status_code}\n";
    if (isset($response_data['message'])) {
        echo "message={$response_data['message']}\n";} 
    else {
        echo "message=Unknown error\n";}
}
?>

Node.js

Instal dependensi yang diperlukan:

npm install axios

Contoh permintaan

const axios = require('axios');

async function callDashScope() {
    // Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan apiKey='sk-xxx' menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// Ganti dengan ID aplikasi aktual Anda
    const pluginCode = 'TOOL_ID';// Ganti dengan ID plugin aktual Anda
    const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;

    const data = {
        input: {
            prompt: "Konten aturan asrama",
            biz_params: {
                user_defined_params: {
                    [pluginCode]: {
                        // article_index adalah variabel untuk plugin kustom. Ganti dengan variabel plugin aktual Anda.
                        'article_index': 3
                    }
                }
            }
        },
        parameters: {},
        debug: {}
    };

    try {
        console.log("Sending request to DashScope API...");

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

        if (response.status === 200) {
            if (response.data.output && response.data.output.text) {
                console.log(`${response.data.output.text}`);
            }
        } else {
            console.log("Request failed:");
            if (response.data.request_id) {
                console.log(`request_id=${response.data.request_id}`);
            }
            console.log(`code=${response.status}`);
            if (response.data.message) {
                console.log(`message=${response.data.message}`);
            } else {
                console.log('message=Unknown error');
            }
        }
    } catch (error) {
        console.error(`Error calling DashScope: ${error.message}`);
        if (error.response) {
            console.error(`Response status: ${error.response.status}`);
            console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
        }
    }
}
callDashScope();

C#

Contoh permintaan

using System.Text;

class Program
{
    static async Task Main(string[] args)
    {
        // Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan apiKey="sk-xxx" menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna 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 = "APP_ID";// Ganti dengan ID aplikasi aktual Anda

        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("Make sure DASHSCOPE_API_KEY is set.");
            return;
        }

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

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
            string pluginCode = "TOOL_ID"; // Ganti TOOL_ID dengan ID plugin aktual Anda
            string jsonContent = $@"{{
                ""input"": {{
                    ""prompt"": ""Konten aturan 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("Request successful:");
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error calling DashScope: {ex.Message}");
            }
        }
    }
}

Go

Contoh permintaan

package main

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

func main() {
	// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan apiKey := "sk-xxx" menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID"           // Ganti dengan ID aplikasi aktual Anda
	pluginCode := "TOOL_ID" // Ganti dengan ID plugin aktual Anda

	if apiKey == "" {
		fmt.Println("Make sure DASHSCOPE_API_KEY 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": "Konten aturan 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("Failed to marshal JSON: %v\n", err)
		return
	}

	// Buat permintaan POST HTTP
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("Failed to create request: %v\n", err)
		return
	}

	// Setel 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 respons
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Failed to read response: %v\n", err)
		return
	}

	// Tangani respons
	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))
	}
}

keluaran streaming

Aktifkan keluaran streaming menggunakan stream.

Python

Contoh permintaan

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 Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan api_key="sk-xxx" menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
            api_key=os.getenv("DASHSCOPE_API_KEY"), 
            app_id='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/zh/model-studio/developer-reference/error-code')
    else:
        print(f'{response.output.text}\n')  # Proses untuk hanya menampilkan teks

Java

Contoh permintaan

// Kami merekomendasikan versi dashscope SDK >= 2.15.0
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.reactivex.Flowable;// keluaran streaming
// Implementasi keluaran streaming untuk panggilan aplikasi agent

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 Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan .apiKey("sk-xxx") menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // Ganti dengan ID aplikasi aktual Anda
                .appId("APP_ID")
                .prompt("Siapa kamu?")
                // keluaran inkremental
                .incrementalOutput(true)
                .build();
        Application application = new Application();
        // .streamCall(): konten keluaran 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/zh/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

HTTP

curl

Contoh permintaan

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--header 'X-DashScope-SSE: enable' \
--data '{
    "input": {
        "prompt": "Siapa kamu?"

    },
    "parameters":  {
        "incremental_output":true
    },
    "debug": {}
}'
Ganti APP_ID dengan ID aplikasi aktual Anda.

PHP

Contoh permintaan

<?php

// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan $api_key="sk-xxx" menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Ganti dengan ID aplikasi aktual Anda

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

// Buat data permintaan
$data = [
    "input" => [
        'prompt' => 'Siapa kamu?'],
    "parameters" => [
        'incremental_output' => true]];// keluaran inkremental
// 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);

// Setel opsi cURL
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); // Jangan mengembalikan data transfer
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $string) {
    echo $string; // Tangani 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 "Request Failed.\n";
}
?>

Node.js

Instal dependensi yang diperlukan:

npm install axios

Contoh permintaan

1. Keluaran respons lengkap

const axios = require('axios');

async function callDashScope() {
    //Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan apiKey='sk-xxx' menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// Ganti dengan ID aplikasi aktual Anda

    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("Sending request to DashScope API...");

        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) {
            // Tangani respons streaming
            response.data.on('data', (chunk) => {
                console.log(`Received chunk: ${chunk.toString()}`);
            });
        } else {
            console.log("Request failed:");
            if (response.data.request_id) {
                console.log(`request_id=${response.data.request_id}`);
            }
            console.log(`code=${response.status}`);
            if (response.data.message) {
                console.log(`message=${response.data.message}`);
            } else {
                console.log('message=Unknown error');
            }
        }
    } catch (error) {
        console.error(`Error calling DashScope: ${error.message}`);
        if (error.response) {
            console.error(`Response status: ${error.response.status}`);
            console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
        }
    }
}

callDashScope();

Anda dapat memperluas panel yang dapat dilipat untuk melihat konten spesifik:

2. Hanya menampilkan konten field teks

const axios = require('axios');
const { Transform } = require('stream');

async function callDashScope() {
    //Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan apiKey='sk-xxx' menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID'; // Ganti dengan ID aplikasi aktual Anda

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

    const data = {
        input: { prompt: "Siapa kamu?" },
        parameters: { incremental_output: true }, // keluaran inkremental
        debug: {}
    };

    try {
        console.log("Sending request to DashScope API...");

        const response = await axios.post(url, data, {
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json',
                'X-DashScope-SSE': 'enable' // keluaran streaming
            },
            responseType: 'stream' // Untuk menangani respons streaming
        });

        if (response.status === 200) {
            // // Tangani transformasi aliran parsing protokol SSE respons streaming
            const sseTransformer = new Transform({
                transform(chunk, encoding, callback) {
                    this.buffer += chunk.toString();
                    
                    // Pisahkan berdasarkan event SSE (dua baris baru)
                    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 = '';
                        
                        // Parse 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 baris baru dan push
                            this.push(textContent + '\n');
                        }
                    });
                    
                    callback();
                },
                flush(callback) {
                    if (this.buffer) {
                        this.push(this.buffer + '\n');
                    }
                    callback();
                }
            });
            sseTransformer.buffer = '';

            // Proses pipa
            response.data
                .pipe(sseTransformer)
                .on('data', (textWithNewline) => {
                    process.stdout.write(textWithNewline); // Keluaran otomatis membungkus
                })
                .on('end', () => console.log(""))
                .on('error', err => console.error("Pipe error:", err));

        } else {
            console.log("Request failed, status code:", response.status);
            response.data.on('data', chunk => console.log(chunk.toString()));
        }
    } catch (error) {
        console.error(`API call failed: ${error.message}`);
        if (error.response) {
            console.error(`Status code: ${error.response.status}`);
            error.response.data.on('data', chunk => console.log(chunk.toString()));
        }
    }
}

callDashScope();

C#

Contoh permintaan

using System.Net;
using System.Text;

class Program
{
    static async Task Main(string[] args)
    {
        //Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan apiKey="sk-xxx" menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna 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 = "APP_ID"; // Ganti dengan ID aplikasi aktual Anda
        string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
            client.DefaultRequestHeaders.Add("X-DashScope-SSE", "enable");

            string jsonContent = @"{
                ""input"": {
                    ""prompt"": ""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("Request successful:");
                    Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
                    using (var stream = await response.Content.ReadAsStreamAsync())
                    using (var reader = new StreamReader(stream))
                    {
                        string? line; // 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($"Request failed with status code: {response.StatusCode}");
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error calling DashScope: {ex.Message}");
            }
        }
    }
}

Go

Contoh permintaan

package main

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

func main() {
	// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan apiKey := "sk-xxx" menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // Ganti dengan ID aplikasi aktual Anda

	if apiKey == "" {
		fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
		return
	}

	url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)

	// Buat badan permintaan, di mana incremental_output 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("Failed to marshal JSON: %v\n", err)
		return
	}

	// Buat permintaan POST HTTP
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("Failed to create request: %v\n", err)
		return
	}

	// Setel header permintaan, di mana X-DashScope-SSE diatur ke enable untuk 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("Failed to send request: %v\n", err)
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
		body, _ := io.ReadAll(resp.Body)
		fmt.Println(string(body))
		return
	}

	// Tangani 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 reading response: %v\n", err)
			break
		}
	}
}

Pengambilan basis pengetahuan

Saat memanggil Agent Application, gunakan rag_options untuk mengaktifkan pengambilan basis pengetahuan.

Python

Contoh permintaan

import os
from http import HTTPStatus
# Kami merekomendasikan versi dashscope SDK >= 1.20.11
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

response = Application.call(
    # Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan api_key="sk-xxx" menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
    api_key=os.getenv("DASHSCOPE_API_KEY"), 
    app_id='APP_ID',  # Ganti APP_ID dengan ID aplikasi Anda
    prompt='Tolong rekomendasikan ponsel di bawah 3000 yuan',
    rag_options={
        "pipeline_ids": ["PIPELINE_ID1","PIPELINE_ID2"],  # Ganti dengan ID basis pengetahuan aktual Anda, pisahkan dengan koma untuk beberapa
    }
)

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/zh/model-studio/developer-reference/error-code')
else:
    print('%s\n' % (response.output.text))  # Proses untuk hanya menampilkan teks
    # print('%s\n' % (response.usage))

Java

Contoh permintaan

// Kami merekomendasikan versi dashscope SDK >= 2.16.8;
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import java.util.Arrays;

import com.alibaba.dashscope.utils.Constants;

public class Main {
    static {
        Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
    }
    public static void streamCall() throws NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                // Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan .apiKey("sk-xxx") menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("APP_ID") // Ganti dengan ID aplikasi aktual Anda
                .prompt("Tolong rekomendasikan ponsel sekitar 3000 yuan")
                .ragOptions(RagOptions.builder()
                        // Ganti dengan ID basis pengetahuan aktual yang ditentukan, pisahkan dengan koma untuk beberapa
                        .pipelineIds(Arrays.asList("PIPELINES_ID1", "PIPELINES_ID2"))
                        .build())
                .build();

        Application application = new Application();
        ApplicationResult result = application.call(param);
        System.out.printf("%s\n",
                result.getOutput().getText());// Proses untuk hanya menampilkan teks
    }

    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/zh/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

HTTP

curl

Contoh permintaan

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/{APP_ID}/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "Tolong rekomendasikan ponsel di bawah 3000 yuan"
    },
    "parameters":  {
                    "rag_options" : {
                    "pipeline_ids":["PIPELINE_ID1"]}
    },
    "debug": {}
}'
Ganti APP_ID dengan ID aplikasi aktual Anda dan PIPELINE_ID1 dengan ID basis pengetahuan yang ditentukan.

PHP

Contoh permintaan

<?php
# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan $api_key="sk-xxx" menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Ganti dengan ID aplikasi aktual Anda

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

// Buat data permintaan
$data = [
    "input" => [
        'prompt' => 'Tolong rekomendasikan ponsel di bawah 3000 yuan'
    ],
    "parameters" => [
        'rag_options' => [
            'pipeline_ids' => ['PIPELINE_ID1','PIPELINE_ID2']//Ganti dengan ID basis pengetahuan yang ditentukan, pisahkan dengan koma untuk beberapa
        ]
    ]
];
// 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);

// Setel 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);
// Decode 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 "No text in response.\n";
    }
}else {
    if (isset($response_data['request_id'])) {
        echo "request_id={$response_data['request_id']}\n";}
    echo "code={$status_code}\n";
    if (isset($response_data['message'])) {
        echo "message={$response_data['message']}\n";} 
    else {
        echo "message=Unknown error\n";}
}
?>

Node.js

Instal dependensi yang diperlukan:

npm install axios

Contoh permintaan

const axios = require('axios');
async function callDashScope() {
    // Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan apiKey='sk-xxx' menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';//Ganti dengan ID aplikasi aktual Anda

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

    const data = {
        input: {
            prompt: "Tolong rekomendasikan ponsel di bawah 3000 yuan"
        },
        parameters: {
            rag_options:{
                pipeline_ids:['PIPELINE_ID1','PIPELINE_ID2']  // Ganti dengan ID basis pengetahuan yang ditentukan, pisahkan dengan koma untuk beberapa
            }
        },
        debug: {}
    };

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

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

callDashScope();

C#

Contoh permintaan

using System.Text;

class Program
{
    static async Task Main(string[] args)
    {
        // Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan apiKey="sk-xxx" menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna 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 = "APP_ID";// Ganti dengan ID aplikasi aktual Anda
        // Ganti PIPELINE_ID1 dengan ID basis pengetahuan yang ditentukan
        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("Make sure DASHSCOPE_API_KEY is set.");
            return;
        }

        string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
        
        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
            string jsonContent = $@"{{
                ""input"": {{
                    ""prompt"": ""Tolong rekomendasikan ponsel di bawah 3000 yuan""
                }},
                ""parameters"": {{
                    ""rag_options"" : {{
                        ""pipeline_ids"":[""PIPELINE_ID1""]
                    }}
                }},
                ""debug"": {{}}
            }}";

            HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            try
            {
                HttpResponseMessage response = await client.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error calling DashScope: {ex.Message}");
            }
        }
    }
}

Go

Contoh permintaan

package main

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

func main() {
	// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan apiKey := "sk-xxx" menggunakan Kunci API Model Studio Anda. Namun, jangan hard code kunci API Anda langsung di kode untuk lingkungan produksi guna mengurangi risiko kebocoran kunci API.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // Ganti dengan ID aplikasi aktual Anda

	if apiKey == "" {
		fmt.Println("Make sure DASHSCOPE_API_KEY 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]string{
			"prompt": "Tolong rekomendasikan ponsel di bawah 3000 yuan",
		},
		"parameters": map[string]interface{}{
			"rag_options": map[string]interface{}{
				"pipeline_ids": []string{"PIPELINE_ID1"}, // Ganti dengan ID basis pengetahuan yang ditentukan
			},
		},
		"debug": map[string]interface{}{},
	}

	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		fmt.Printf("Failed to marshal JSON: %v\n", err)
		return
	}

	// Buat permintaan POST HTTP
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("Failed to create request: %v\n", err)
		return
	}

	// Setel 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 respons
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Failed to read response: %v\n", err)
		return
	}

	// Tangani respons
	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))
	}
}

Lihat informasi proses pengambilan: Tambahkan has_thoughts ke kode Anda dan atur ke True. Informasi proses pengambilan akan dikembalikan di field output's field thoughts.

app_id string (wajib)

Identifier aplikasi.

Anda bisa mendapatkan ID aplikasi dari kartu aplikasi di halaman Manajemen Aplikasi.

Dalam Java SDK, ini adalah appId. Saat memanggil via HTTP, masukkan ID aplikasi aktual Anda di URL, menggantikan APP_ID.

prompt string (wajib)

Instruksi input pengguna yang memandu aplikasi untuk menghasilkan respons.

Saat memanggil via HTTP, masukkan prompt di objek input.

session_id string (opsional)

Identifier percakapan historis.

Saat Anda melewatkan session_id, permintaan secara otomatis menyertakan riwayat percakapan yang disimpan di cloud. Dalam kasus ini, Anda harus melewatkan prompt.

ID ini secara otomatis kedaluwarsa setelah 1 jam tidak aktif.

Dalam Java SDK, ini adalah setSessionId. Saat memanggil via HTTP, masukkan session_id di objek input.

messages array (opsional)

Konteks yang diberikan ke model bahasa besar diatur dalam urutan percakapan.

Saat menggunakan parameter messages untuk percakapan multi-putaran, Anda tidak perlu menyertakan prompt atau session_id.

Jika Anda menyertakan keduanya, session_id dan messages, model bahasa besar akan menggunakan konten dalam messages serta mengabaikan session_id dan prompt.

Saat memanggil via HTTP, masukkan messages di objek input.
Untuk menggunakan parameter ini, versi Python Dashscope SDK Anda minimal 1.20.14, dan versi Java Dashscope SDK Anda minimal 2.17.0.

Jenis pesan

Pesan Sistem object (opsional)

Pesan sistem yang menetapkan peran, nada, tujuan tugas, atau batasan model. Biasanya ditempatkan pertama dalam array messages.

Properti

content string (wajib)

Instruksi sistem yang menentukan peran, pedoman perilaku, gaya respons, dan batasan tugas model.

role string (wajib)

Peran pesan sistem, tetap sebagai system.

Pesan Pengguna object(wajib)

Pesan pengguna yang melewatkan pertanyaan, instruksi, atau konteks ke model.

Properti

content string (wajib)

Konten pesan.

Properti

text string (wajib)

Teks input.

role string (wajib)

Peran pesan pengguna, tetap sebagai user.

Pesan Asisten object (opsional)

Respons model, biasanya digunakan sebagai konteks yang dikembalikan ke model dalam percakapan multi-putaran.

Properti

content string (wajib)

Konten teks respons model.

role string (wajib)

Peran pesan asisten, tetap sebagai assistant.

workspace string (opsional)

Identifier ruang bisnis. Dokumentasi terkait: Dapatkan ID Ruang Kerja.

Anda hanya perlu melewatkan ID workspace saat memanggil aplikasi di sub-workspace.

Saat memanggil via HTTP, tentukan header X-DashScope-WorkSpace.

stream boolean (opsional) Nilai default adalah False

Apakah merespons menggunakan keluaran streaming.

Kami merekomendasikan mengatur ini ke True untuk meningkatkan pengalaman membaca dan mengurangi risiko timeout.

Nilai parameter:

  • False (default): Model mengembalikan semua konten sekaligus setelah generasi selesai.

  • True (direkomendasikan): Model mengeluarkan konten saat menghasilkannya, mengembalikan potongan data setiap kali menghasilkan konten baru. Anda harus membaca potongan ini secara real-time untuk menyusun respons lengkap.

Untuk mengimplementasikan keluaran streaming dengan Java SDK, gunakan antarmuka streamCall. Untuk mengimplementasikan keluaran streaming via HTTP, atur header X-DashScope-SSE ke enable.

incremental_output boolean (opsional) Nilai default adalah False

Apakah mengaktifkan keluaran inkremental dalam mode streaming.

Kami merekomendasikan mengatur ini ke True untuk meningkatkan pengalaman membaca.

Nilai parameter:

  • False (default): Setiap keluaran berisi seluruh urutan yang dihasilkan sejauh ini. Keluaran akhir adalah hasil lengkap.

    I
    I like
    I like apple
    I like apple.
  • True (direkomendasikan): Keluaran inkremental. Keluaran selanjutnya tidak menyertakan konten yang telah dikeluarkan sebelumnya. Anda harus membaca segmen-segmen ini secara real-time untuk mendapatkan hasil lengkap.

    I
    like
    apple
    .
Dalam Java SDK, ini adalah incrementalOutputincremental_output di objek parameters.

flow_stream_mode string (opsional) Nilai default adalah full_thoughts

Mode keluaran streaming untuk Workflow Application.

Nilai parameter:

  • message_format (direkomendasikan):

    Mengeluarkan hasil dari node yang ditentukan (baik node Output atau node End) di field message.

    Penting

    Di aplikasi konsol, aktifkan sakelar Stream untuk node target agar mengembalikan hasil dalam mode streaming. Jika dinonaktifkan, hasil akhir node dikembalikan sekaligus.

    Dalam Java SDK, ini adalah FlowStreamMode.MESSAGE_FORMAT.
  • full_thoughts (default):

    Mengeluarkan hasil dari semua node di field thoughts.

    Penting

    Saat menggunakan mode ini, Anda juga harus mengatur parameter has_thoughts ke True.

    Dalam Java SDK, ini adalah FlowStreamMode.FULL_THOUGHTS.
  • agent_format:

    Mengeluarkan hasil dari node yang ditentukan (node model bahasa besar atau node akhir) di field text .

    Di aplikasi konsol, aktifkan sakelar Response untuk node target agar mengembalikan hasil dalam mode streaming.

    Penting

    Jangan gunakan mode ini dengan node paralel, karena dapat menyebabkan pencampuran konten. Pastikan node yang diaktifkan memiliki urutan eksekusi yang jelas.

    Dalam Java SDK, ini adalah FlowStreamMode.AGENT_FORMAT.
Versi Python SDK Anda minimal 1.24.0, dan versi Java SDK Anda minimal 2.21.0. Saat memanggil via HTTP, masukkan flow_stream_mode di objek parameters.

biz_params object (opsional)

Gunakan field ini untuk melewatkan parameter saat aplikasi Anda menggunakan variabel kustom, node, atau plugin.

Dalam Java SDK, ini adalah bizParams. Saat memanggil via HTTP, masukkan biz_params di objek input.

Untuk Workflow Application, lewatkan variabel kustom untuk node awal secara langsung, contoh:

biz_params = {"city": "Hangzhou"}

Untuk Agent Application, lewatkan variabel prompt atau variabel plugin menggunakan field berikut:

Properti

user_defined_params object (opsional)

Merupakan informasi parameter plugin kustom.

Plugin yang ditambahkan dalam aplikasi tidak boleh duplikat, maksimal 10 plugin.

Properti

tool_id string (opsional)

ID Plugin, tersedia di kartu plugin.

${plugin_params} string (opsional)

Objek paling dalam berisi beberapa pasangan kunci-nilai. Setiap pasangan kunci-nilai merepresentasikan nama parameter yang ditentukan pengguna dan nilainya. Contoh:

"article_index": 2

Langkah penggunaan:

  1. Asosiasikan plugin yang ditentukan dengan aplikasi Anda dan Publish aplikasi.

  2. Lewatkan informasi plugin melalui parameter ini selama pemanggilan API.

Anda dapat memberikan beberapa pasangan kunci-nilai, di mana setiap kunci adalah TOOL_ID plugin dan nilai adalah objek parameter yang dibutuhkan plugin tersebut. Contoh:

"user_defined_params": {
        "<TOOL_ID>": {
            "article_index": 2},
        "<TOOL_ID>": {
            "article_index": 8}
        }

user_defined_tokens object (opsional)

Merupakan informasi otentikasi tingkat pengguna untuk plugin kustom.

Plugin yang ditambahkan dalam aplikasi tidak boleh duplikat, maksimal 10 plugin.

Properti

tool_id string (opsional)

ID Plugin, tersedia di kartu plugin. Lewatkan melalui field <TOOL_ID>.

user_token string (opsional)

Lewatkan informasi otentikasi pengguna yang dibutuhkan plugin ini, seperti nilai aktual DASHSCOPE_API_KEY.

Langkah penggunaan:

  1. Asosiasikan plugin yang ditentukan dengan aplikasi Anda dan Publish aplikasi.

  2. Lewatkan informasi otentikasi tingkat pengguna plugin melalui parameter ini selama pemanggilan API.

Anda dapat memberikan beberapa pasangan kunci-nilai, di mana setiap kunci adalah TOOL_ID plugin dan nilai adalah objek user_token.

has_thoughts boolean (opsional) Nilai default adalah False

Anda dapat memeriksa apakah proses pemanggilan plugin dan pengambilan basis pengetahuan, dikeluarkan di field thoughts.

Nilai parameter:

  • True: Keluaran disertakan.

  • False (default): Keluaran tidak disertakan.

Dalam Java SDK, ini adalah hasThoughts. Saat memanggil via HTTP, masukkan has_thoughts di objek parameters.

rag_options object (opsional)

Digunakan untuk mengonfigurasi parameter terkait pengambilan, termasuk tetapi tidak terbatas pada mengambil basis pengetahuan atau dokumen tertentu.

Catatan

Hanya Agent Application yang mendukung parameter ini.

Dalam Java SDK, ini adalah ragOptions. Saat memanggil via HTTP, masukkan rag_options di objek parameters.

Properti

pipeline_ids array wajib)

Daftar yang berisi satu atau lebih ID basis pengetahuan. Maksimal 5.

Mengambil semua dokumen dalam basis pengetahuan yang ditentukan.

Cara mendapatkan:

  • Basis Pengetahuan untuk mendapatkan ID basis pengetahuan;

  • Atau melalui API CreateIndex (hanya mendukung basis pengetahuan tak terstruktur), yang mengembalikan Data.Id.

Dalam Java SDK, ini adalah pipelineIds.

file_ids array (opsional)

Daftar yang berisi satu atau lebih ID dokumen tak terstruktur. Maksimal 5.

Mengambil dokumen tak terstruktur dalam basis pengetahuan yang ditentukan.

Saat melewatkan ID dokumen, Anda juga harus melewatkan ID basis pengetahuan yang dimiliki dokumen-dokumen ini di field pipeline_ids.

Cara mendapatkan:

Dalam Java SDK, ini adalah fileIds.

metadata_filter object (opsional)

Digunakan untuk memfilter dokumen tak terstruktur berdasarkan metadata. Dengan menentukan satu atau lebih pasangan kunci-nilai, ambil dokumen tak terstruktur dalam basis pengetahuan yang ditentukan yang memiliki metadata ini.

Prasyarat:

Saat melewatkan metadata, Anda juga harus melewatkan ID basis pengetahuan yang dimiliki metadata ini di field pipeline_ids.

Cara melihat:

  • Kunjungi halaman Basis Pengetahuan, klik View Details > Metadata Information di kartu basis pengetahuan untuk melihat.

  • Atau melalui API ListChunks untuk mendapatkan.

Objek ini terdiri dari satu atau lebih pasangan kunci-nilai:

  • Kunci: tipe String, merepresentasikan nama metadata.

  • Nilai:

    • Pencocokan eksak: Nilai adalah String, artinya hanya dokumen dengan nilai field ini yang persis sama dengan string ini yang diambil.

      • Contoh: "author": "John.Doe"

    • Pencocokan "ATAU" multi-nilai: Nilai adalah Array (array) atau List (list) yang berisi beberapa String. Ini berarti dokumen dengan nilai field ini yang cocok dengan nilai apa pun dalam array diambil (logika ATAU).

      • Contoh: "source": ["internal_wiki", "public_docs"]

Logika kombinasi:
Kunci berbeda menggunakan logika "DAN". Misalnya, "author": "John.Doe", "source": ["internal_wiki", "public_docs"] berarti memfilter dokumen yang ditulis oleh "John.Doe" DAN berasal dari "internal_wiki" ATAU "public_docs".

Dalam Java SDK, ini adalah metadataFilter.

tags array (opsional)

Daftar yang berisi satu atau lebih tag untuk dokumen tak terstruktur.

Mengambil dokumen tak terstruktur dengan tag-tag ini.

Cara melihat:

Objek respons

Contoh respons percakapan satu putaran

{
    "output": {
        "finish_reason": "stop",
        "session_id": "6105c965c31b40958a43dc93c28c7a59",
        "text": "Saya Qwen, asisten AI yang dikembangkan oleh Alibaba Cloud. Saya dirancang untuk menjawab berbagai pertanyaan, memberikan informasi, dan berdialog dengan pengguna. Bagaimana saya bisa membantu Anda?"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 36,
                "model_id": "qwen-plus",
                "input_tokens": 74
            }
        ]
    },
    "request_id": "f97ee37d-0f9c-9b93-b6bf-bd263a232bf9"
}

Contoh respons basis pengetahuan yang ditentukan

Saat memanggil fitur basis pengetahuan aplikasi dan ingin mengeluarkan informasi dokumen referensi dari dokumen yang diambil, buka konsol Model Studio Anda Agent Application, klik Retrieve Configuration, aktifkan sakelar Show Source, dan Publish aplikasi.

{
    "text": "Berdasarkan anggaran Anda, saya merekomendasikan mempertimbangkan Bailian Zephyr Z9. Ponsel ini ringan dan portabel, dilengkapi layar 6,4 inci dengan resolusi 1080 x 2340 piksel, dipasangkan dengan penyimpanan 128GB dan RAM 6GB, menjadikannya sempurna untuk penggunaan sehari-hari<ref>[1]</ref>. Selain itu, dilengkapi baterai 4000mAh dan lensa zoom digital 30x untuk menangkap detail jarak jauh, dengan harga antara 2499-2799 yuan, sepenuhnya memenuhi persyaratan anggaran Anda<ref>[1]</ref>.",
    "finish_reason": "stop",
    "session_id": "6c1d47fa5eca46b2ad0668c04ccfbf13",
    "thoughts": null,
    "doc_references": [
        {
            "index_id": "1",
            "title": "Pengenalan Produk Ponsel Bailian",
            "doc_id": "file_7c0e9abee4f142f386e488c9baa9cf38_10317360",
            "doc_name": "Pengenalan Produk Ponsel Seri Bailian",
            "doc_url": null,
            "text": "【Nama Dokumen】:Pengenalan Produk Ponsel Seri Bailian\n【Judul】:Pengenalan Produk Ponsel Bailian\n【Konten】:Harga Referensi: 5999- 6499. Bailian Ace Ultra ——Untuk Gamer: Dilengkapi layar 6,67 inci 1080 x 2400 piksel, RAM internal 10GB dan penyimpanan 256GB, memastikan gaming lancar. Bailian Ace Ultra ——Untuk Gamer: Dilengkapi layar 6,67 inci 1080 x 2400 piksel, RAM internal 10GB dan penyimpanan 256GB, memastikan gaming lancar. Baterai 5500mAh dengan sistem pendingin cair menjaga perangkat tetap dingin selama sesi gaming berkepanjangan. Speaker ganda dinamis tinggi meningkatkan audio imersif untuk gaming. Harga Referensi: 3999- 4299. Bailian Zephyr Z9 ——Seni Desain Tipis: Desain ringan 6,4 inci 1080 x 2340 piksel, dipasangkan dengan penyimpanan 128GB dan RAM 6GB, menangani tugas sehari-hari dengan mudah. Baterai 4000mAh memastikan penggunaan sepanjang hari, sedangkan lensa zoom digital 30x menangkap detail jarak jauh tanpa mengorbankan daya. Harga Referensi: 2499- 2799. Bailian Flex Fold+ ——Era Baru Ponsel Lipat: Menggabungkan inovasi dan kemewahan dengan layar utama 7,6 inci 1800 x 2400 piksel dan layar luar 4,7 inci 1080 x 2400 piksel, mendukung desain henti-bebas multi-sudut untuk skenario berbeda. Penyimpanan 512GB, RAM 12GB, ditambah baterai 4700mAh dan kaca fleksibel ultra-tipis UTG, membuka babak baru untuk ponsel lipat. Selain itu, ponsel ini mendukung Dual SIM Dual Standby dan panggilan satelit, menjaga Anda tetap terhubung di seluruh dunia. Harga Eceran Referensi: 9999- 10999.\n",
            "biz_id": null,
            "images": [

            ],
            "page_number": [
                0]
        }]
}

Contoh respons kesalahan

Saat permintaan gagal, respons menyertakan detail kesalahan melalui kode dan pesan.

Contoh ini menunjukkan respons kesalahan untuk API-KEY yang tidak valid.

request_id=1d14958f-0498-91a3-9e15-be477971967b, 
code=401, 
message=Invalid API-key provided.

status_code string

Kode status yang dikembalikan.

200 menunjukkan keberhasilan; jika tidak, permintaan gagal.

Jika gagal, dapatkan kode kesalahan dari code dan detail kesalahan dari message.

Java SDK tidak mengembalikan parameter ini. Jika gagal, melemparkan exception yang berisi konten status_code dan message.

request_id string

Identifier unik untuk pemanggilan ini.

Java SDK mengembalikan ini sebagai requestId.

code string

Kode kesalahan. Kosong saat pemanggilan berhasil.

Hanya dikembalikan oleh Python SDK.

message string

Detail kesalahan. Diabaikan saat berhasil.

Hanya dikembalikan oleh Python SDK.

output object

Informasi hasil pemanggilan.

properti output

text string

Konten respons yang dihasilkan model.

finish_reason string

Alasan penyelesaian.

stop berarti penyelesaian alami (menemui penanda yang telah ditentukan), null berarti gangguan paksa (misalnya, mencapai batas panjang maksimum atau penghentian manual).

session_id string

Identifier unik untuk percakapan saat ini.

Lewatkan ini dalam permintaan berikutnya untuk membawa catatan percakapan historis.

thoughts array

Saat Anda mengatur parameter has_thoughts ke True selama pemanggilan, Anda dapat melihat pemanggilan plugin, proses pengambilan basis pengetahuan, atau proses berpikir model pemikiran mendalam di thoughts.

thoughts properties

thought string

Proses berpikir model.

Saat Anda memilih model pemikiran mendalam di konsol Anda Agent Application dan berhasil mempublikasikannya, jika Anda mengatur parameter has_thoughts ke True selama pemanggilan API, proses berpikir model akan dikembalikan di field ini.

reasoningContent string

Proses berpikir model.

Saat Anda memilih model pemikiran mendalam di konsol Anda Workflow Application dan berhasil mempublikasikannya, jika Anda mengatur parameter has_thoughts ke True selama pemanggilan API, proses berpikir model akan dikembalikan di field ini.

action_type string

Jenis langkah eksekusi yang dikembalikan oleh model besar. Misalnya, API berarti mengeksekusi plugin API, agentRag berarti mengeksekusi pengambilan basis pengetahuan, dan reasoning berarti mengeksekusi proses berpikir model pemikiran mendalam.

action_name string

Nama aksi yang dieksekusi, seperti pengambilan basis pengetahuan, plugin API, atau proses berpikir.

action string

Langkah-langkah eksekusi.

action_input_stream string

Hasil streaming dari parameter input.

action_input string

Parameter input plugin.

observation string

Proses pengambilan atau eksekusi plugin.

doc_references array

Informasi tentang dokumen referensi dari dokumen yang diambil yang dikutip model.

Di konsol Model Studio Anda Agent Application, aktifkan sakelar Show Source dan Publish aplikasi agar doc_references mungkin berisi informasi valid.

properti doc_references

index_id string

Indeks dokumen yang direferensikan, misalnya, [1].

title string

Judul segmen teks yang direferensikan.

doc_id string

ID dokumen yang direferensikan.

doc_name string

Nama dokumen yang direferensikan.

text string

Konten teks spesifik yang direferensikan model.

biz_id string

Identifier asosiasi bisnis yang direferensikan model.

images array

Daftar URL gambar yang direferensikan model.

usage object

Merupakan informasi penggunaan data untuk permintaan ini.

Properti Penggunaan

models array

Informasi model untuk pemanggilan ini.

properti model

model_id string

ID model yang dipanggil oleh aplikasi ini.

input_tokens integer

Panjang teks input pengguna setelah dikonversi ke token.

output_tokens integer

Panjang respons yang dihasilkan model setelah dikonversi ke token.

Batas QPM

QPM (queries per minute) default untuk satu aplikasi adalah 15.000.

Kode kesalahan

Jika pemanggilan gagal dan mengembalikan kesalahan, lihat Informasi kesalahan untuk solusi.