1. Initialize clientUntuk mengunggah file dan membuat basis pengetahuan, pertama-tama inisialisasi klien. Gunakan AccessKey dan AccessKey Secret Anda untuk memverifikasi identitas dan mengonfigurasi endpoint. Public endpoints Klien Anda harus memiliki akses internet. VPC endpoints Jika klien Anda dideploy di public cloud di wilayah Alibaba Cloud Singapura (ap-southeast-1) dan berada dalam VPC, Anda dapat menggunakan endpoint VPC berikut. Akses lintas wilayah tidak didukung.
Inisialisasi klien mengembalikan objek Client untuk panggilan API selanjutnya. | Pythondef create_client() -> bailian20231229Client:
"""
Membuat dan mengonfigurasi klien.
Mengembalikan:
bailian20231229Client: Klien yang telah dikonfigurasi.
"""
config = open_api_models.Config(
access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
)
# Titik akhir berikut ini adalah contoh titik akhir publik untuk cloud publik. Anda dapat mengubah titik akhir sesuai kebutuhan.
config.endpoint = 'bailian.ap-southeast-1.aliyuncs.com'
return bailian20231229Client(config)
Java/**
* Initialize a client.
*
* @return The configured client object.
*/
public static com.aliyun.bailian20231229.Client createClient() throws Exception {
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// Contoh endpoint berikut adalah endpoint VPC untuk public cloud. Anda dapat mengubah endpoint sesuai kebutuhan.
config.endpoint = "bailian-vpc.ap-southeast-1.aliyuncs.com";
return new com.aliyun.bailian20231229.Client(config);
}
PHP/**
* Initialize a client.
*
* @return Bailian The configured client object.
*/
public static function createClient(){
$config = new Config([
"accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
"accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
]);
// Contoh endpoint berikut adalah endpoint VPC untuk public cloud. Anda dapat mengubah endpoint sesuai kebutuhan.
$config->endpoint = 'bailian-vpc.ap-southeast-1.aliyuncs.com';
return new Bailian($config);
}
Node.js/**
* Create and configure a client.
* @return Client
* @throws Exception
*/
static createClient() {
const config = new OpenApi.Config({
accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET
});
// Contoh endpoint berikut adalah endpoint VPC untuk public cloud. Anda dapat mengubah endpoint sesuai kebutuhan.
config.endpoint = `bailian-vpc.ap-southeast-1.aliyuncs.com`;
return new bailian20231229.default(config);
}
C#/// <summary>
/// Initialize a client.
/// </summary>
/// <returns>The configured client object.</returns>
/// <exception cref="Exception">Thrown when an error occurs during initialization.</exception>
public static AlibabaCloud.SDK.Bailian20231229.Client CreateClient()
{
var config = new AlibabaCloud.OpenApiClient.Models.Config
{
AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
};
// Contoh endpoint berikut adalah endpoint VPC untuk public cloud. Anda dapat mengubah endpoint sesuai kebutuhan.
config.Endpoint = "bailian-vpc.ap-southeast-1.aliyuncs.com";
return new AlibabaCloud.SDK.Bailian20231229.Client(config);
}
Go// CreateClient creates and configures a client.
//
// Returns:
// - *client.Bailian20231229Client: The configured client.
// - error: The error message.
func CreateClient() (_result *bailian20231229.Client, _err error) {
config := &openapi.Config{
AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
}
// Contoh endpoint berikut adalah endpoint VPC untuk public cloud. Anda dapat mengubah endpoint sesuai kebutuhan.
config.Endpoint = tea.String("bailian-vpc.ap-southeast-1.aliyuncs.com")
_result = &bailian20231229.Client{}
_result, _err = bailian20231229.NewClient(config)
return _result, _err
}
|
2. Upload knowledge base files |
2.1. Request a file upload leaseSebelum membuat basis pengetahuan, unggah file sumbernya ke ruang kerja yang sama. Untuk melakukannya, panggil operasi ApplyFileUploadLease untuk meminta sewa unggah file. Sewa ini merupakan otorisasi sementara untuk mengunggah file dan berlaku selama beberapa menit. workspace_id: Lihat Cara mendapatkan ID ruang kerja. category_id: Dalam contoh ini, gunakan default. Model Studio menggunakan kategori untuk mengelola file yang Anda unggah. Sistem secara otomatis membuat kategori default. Anda juga dapat memanggil API AddCategory untuk membuat kategori baru dan mendapatkan category_id yang sesuai. file_name: Masukkan nama file yang diunggah, termasuk ekstensinya. Nilainya harus sesuai dengan nama file sebenarnya. Misalnya, saat Anda mengunggah file seperti pada gambar, gunakan Alibaba_Cloud_Model_Studio_Mobile_Phone_Series_Introduction.docx. 
file_md5: Masukkan hash MD5 dari file yang akan diunggah. Saat ini, Alibaba Cloud tidak memverifikasi nilai ini, sehingga memudahkan pengunggahan file dari URL. Di Python, Anda bisa mendapatkan hash MD5 dengan menggunakan modul hashlib. Untuk bahasa lainnya, lihat kode contoh lengkap. Contoh kode import hashlib
def calculate_md5(file_path):
"""
Calculate the MD5 hash of a file.
Args:
file_path (str): The local path of the file.
Returns:
str: The MD5 hash of the file.
"""
md5_hash = hashlib.md5()
# Read the file in binary mode.
with open(file_path, "rb") as f:
# Read the file in chunks to avoid high memory usage for large files.
for chunk in iter(lambda: f.read(4096), b""):
md5_hash.update(chunk)
return md5_hash.hexdigest()
# Example usage
file_path = "Ganti dengan path lokal aktual file yang akan diunggah, misalnya /path/to/your/Alibaba Cloud Model Studio Product Overview.docx"
md5_value = calculate_md5(file_path)
print(f"The MD5 hash of the file is: {md5_value}")
Ganti variabel file_path dalam kode dengan path lokal aktual file tersebut dan jalankan kode untuk mendapatkan hash MD5 file target. Berikut adalah contoh nilainya: The MD5 hash of the file is: 2ef7361ea907f3a1b91e3b9936f5643a
file_size: Masukkan ukuran file yang akan diunggah dalam byte. Di Python, Anda bisa mendapatkan nilai ini dengan menggunakan modul os. Untuk bahasa lainnya, lihat kode contoh lengkap. Contoh kode import os
def get_file_size(file_path: str) -> int:
"""
Get the size of a file in bytes.
Args:
file_path (str): The actual local path of the file.
Returns:
int: The file size in bytes.
"""
return os.path.getsize(file_path)
# Example usage
file_path = "Ganti dengan path lokal aktual file yang akan diunggah, misalnya /path/to/your/Alibaba Cloud Model Studio Product Overview.docx"
file_size = get_file_size(file_path)
print(f"The size of the file in bytes is: {file_size}")
Ganti variabel file_path dengan path lokal aktual file tersebut dan jalankan kode untuk mendapatkan ukuran file target dalam byte. Berikut adalah contoh nilainya: The size of the file in bytes is: 14015
Permintaan sewa unggah sementara yang berhasil akan mengembalikan hal berikut: | Pythondef apply_lease(client, category_id, file_name, file_md5, file_size, workspace_id):
"""
Request a file upload lease from Alibaba Cloud Model Studio.
Args:
client (bailian20231229Client): The client.
category_id (str): The category ID.
file_name (str): The file name.
file_md5 (str): The MD5 hash of the file.
file_size (int): The file size in bytes.
workspace_id (str): The workspace ID.
Returns:
The response from Alibaba Cloud Model Studio.
"""
headers = {}
request = bailian_20231229_models.ApplyFileUploadLeaseRequest(
file_name=file_name,
md_5=file_md5,
size_in_bytes=file_size,
)
runtime = util_models.RuntimeOptions()
return client.apply_file_upload_lease_with_options(category_id, workspace_id, request, headers, runtime)
Java/**
* Request a file upload lease.
*
* @param client The client object.
* @param categoryId The category ID.
* @param fileName The file name.
* @param fileMd5 The MD5 hash of the file.
* @param fileSize The file size in bytes.
* @param workspaceId The workspace ID.
* @return The response object from Alibaba Cloud Model Studio.
*/
public ApplyFileUploadLeaseResponse applyLease(com.aliyun.bailian20231229.Client client, String categoryId, String fileName, String fileMd5, String fileSize, String workspaceId) throws Exception {
Map<String, String> headers = new HashMap<>();
com.aliyun.bailian20231229.models.ApplyFileUploadLeaseRequest applyFileUploadLeaseRequest = new com.aliyun.bailian20231229.models.ApplyFileUploadLeaseRequest();
applyFileUploadLeaseRequest.setFileName(fileName);
applyFileUploadLeaseRequest.setMd5(fileMd5);
applyFileUploadLeaseRequest.setSizeInBytes(fileSize);
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
ApplyFileUploadLeaseResponse applyFileUploadLeaseResponse = null;
applyFileUploadLeaseResponse = client.applyFileUploadLeaseWithOptions(categoryId, workspaceId, applyFileUploadLeaseRequest, headers, runtime);
return applyFileUploadLeaseResponse;
}
PHP/**
* Request a file upload lease.
*
* @param Bailian $client The client.
* @param string $categoryId The category ID.
* @param string $fileName The file name.
* @param string $fileMd5 The MD5 hash of the file.
* @param int $fileSize The file size in bytes.
* @param string $workspaceId The workspace ID.
* @return ApplyFileUploadLeaseResponse The response from Alibaba Cloud Model Studio.
*/
public function applyLease($client, $categoryId, $fileName, $fileMd5, $fileSize, $workspaceId) {
$headers = [];
$applyFileUploadLeaseRequest = new ApplyFileUploadLeaseRequest([
"fileName" => $fileName,
"md5" => $fileMd5,
"sizeInBytes" => $fileSize
]);
$runtime = new RuntimeOptions([]);
return $client->applyFileUploadLeaseWithOptions($categoryId, $workspaceId, $applyFileUploadLeaseRequest, $headers, $runtime);
}
Node.js/**
* Request a file upload lease.
* @param {Bailian20231229Client} client - The client.
* @param {string} categoryId - The category ID.
* @param {string} fileName - The file name.
* @param {string} fileMd5 - The MD5 hash of the file.
* @param {string} fileSize - The file size in bytes.
* @param {string} workspaceId - The workspace ID.
* @returns {Promise<bailian20231229.ApplyFileUploadLeaseResponse>} - The response from Alibaba Cloud Model Studio.
*/
async function applyLease(client, categoryId, fileName, fileMd5, fileSize, workspaceId) {
const headers = {};
const req = new bailian20231229.ApplyFileUploadLeaseRequest({
md5: fileMd5,
fileName,
sizeInBytes: fileSize
});
const runtime = new Util.RuntimeOptions({});
return await client.applyFileUploadLeaseWithOptions(
categoryId,
workspaceId,
req,
headers,
runtime
);
}
C#/// <summary>
/// Request a file upload lease.
/// </summary>
/// <param name="client">The client object.</param>
/// <param name="categoryId">The category ID.</param>
/// <param name="fileName">The file name.</param>
/// <param name="fileMd5">The MD5 hash of the file.</param>
/// <param name="fileSize">The file size in bytes.</param>
/// <param name="workspaceId">The workspace ID.</param>
/// <returns>The response object from Alibaba Cloud Model Studio.</returns>
/// <exception cref="Exception">An exception is thrown if an error occurs during the call.</exception>
public AlibabaCloud.SDK.Bailian20231229.Models.ApplyFileUploadLeaseResponse ApplyLease(
AlibabaCloud.SDK.Bailian20231229.Client client,
string categoryId,
string fileName,
string fileMd5,
string fileSize,
string workspaceId)
{
var headers = new Dictionary<string, string>() { };
var applyFileUploadLeaseRequest = new AlibabaCloud.SDK.Bailian20231229.Models.ApplyFileUploadLeaseRequest
{
FileName = fileName,
Md5 = fileMd5,
SizeInBytes = fileSize
};
var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
return client.ApplyFileUploadLeaseWithOptions(categoryId, workspaceId, applyFileUploadLeaseRequest, headers, runtime);
}
Go// ApplyLease requests a file upload lease from Alibaba Cloud Model Studio.
//
// Parameters:
// - client (bailian20231229.Client): The client.
// - categoryId (string): The category ID.
// - fileName (string): The file name.
// - fileMD5 (string): The MD5 hash of the file.
// - fileSize (string): The file size in bytes.
// - workspaceId (string): The workspace ID.
//
// Returns:
// - *bailian20231229.ApplyFileUploadLeaseResponse: The response from Alibaba Cloud Model Studio.
// - error: The error message.
func ApplyLease(client *bailian20231229.Client, categoryId, fileName, fileMD5 string, fileSize string, workspaceId string) (_result *bailian20231229.ApplyFileUploadLeaseResponse, _err error) {
headers := make(map[string]*string)
applyFileUploadLeaseRequest := &bailian20231229.ApplyFileUploadLeaseRequest{
FileName: tea.String(fileName),
Md5: tea.String(fileMD5),
SizeInBytes: tea.String(fileSize),
}
runtime := &util.RuntimeOptions{}
return client.ApplyFileUploadLeaseWithOptions(tea.String(categoryId), tea.String(workspaceId), applyFileUploadLeaseRequest, headers, runtime)
}
Contoh permintaan {
"CategoryId": "default",
"FileName": "Alibaba Cloud Model Studio Product Overview.docx",
"Md5": "2ef7361ea907f3a1b91e3b9936f5643a",
"SizeInBytes": "14015",
"WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}
Contoh respons {
"RequestId": "778C0B3B-59C2-5FC1-A947-36EDD1XXXXXX",
"Success": true,
"Message": "",
"Code": "success",
"Status": "200",
"Data": {
"FileUploadLeaseId": "1e6a159107384782be5e45ac4759b247.1719325231035",
"Type": "HTTP",
"Param": {
"Method": "PUT",
"Url": "https://bailian-datahub-data-origin-prod.oss-cn-hangzhou.aliyuncs.com/1005426495169178/10024405/68abd1dea7b6404d8f7d7b9f7fbd332d.1716698936847.pdf?Expires=1716699536&OSSAccessKeyId=TestID&Signature=HfwPUZo4pR6DatSDym0zFKVh9Wg%3D",
"Headers": " \"X-bailian-extra\": \"MTAwNTQyNjQ5NTE2OTE3OA==\",\n \"Content-Type\": \"application/pdf\""
}
}
}
|
2.2. Upload file to temporary storageDengan sewa unggah tersebut, gunakan parameter dan URL unggah sementara untuk mengunggah file dari penyimpanan lokal atau URL yang dapat diakses publik ke server Model Studio. Setiap ruang kerja mendukung hingga 10.000 file. Format yang didukung mencakup PDF, DOCX, DOC, TXT, Markdown, PPTX, PPT, XLSX, XLS, HTML, PNG, JPG, JPEG, BMP, dan GIF. |
Penting Contoh ini tidak mendukung debugging online atau pembuatan kode contoh. Local uploadPythonimport requests
from urllib.parse import urlparse
def upload_file(pre_signed_url, file_path):
"""
Upload a local file to temporary storage.
Args:
pre_signed_url (str): The URL from the upload lease.
file_path (str): The local path of the file.
Returns:
The response from Alibaba Cloud Model Studio.
"""
try:
# Set the request headers.
headers = {
"X-bailian-extra": "Ganti dengan nilai bidang X-bailian-extra dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.",
"Content-Type": "Ganti dengan nilai bidang Content-Type dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya. Jika dikembalikan nilai null, berikan nilai null."
}
# Read and upload the file.
with open(file_path, 'rb') as file:
# Metode permintaan untuk unggah file harus sama dengan nilai bidang Method dalam Data.Param yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.
response = requests.put(pre_signed_url, data=file, headers=headers)
# Periksa kode status respons.
if response.status_code == 200:
print("File uploaded successfully.")
else:
print(f"Failed to upload the file. ResponseCode: {response.status_code}")
except Exception as e:
print(f"An error occurred: {str(e)}")
if __name__ == "__main__":
pre_signed_url_or_http_url = "Ganti dengan nilai bidang Url dalam Data.Param yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya."
# Unggah file lokal ke penyimpanan sementara.
file_path = "Ganti dengan path lokal aktual file yang akan diunggah, misalnya di Linux: /path/to/your/Alibaba Cloud Model Studio Product Overview.docx"
upload_file(pre_signed_url_or_http_url, file_path)
Javaimport java.io.DataOutputStream;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class UploadFile {
public static void uploadFile(String preSignedUrl, String filePath) {
HttpURLConnection connection = null;
try {
// Buat objek URL.
URL url = new URL(preSignedUrl);
connection = (HttpURLConnection) url.openConnection();
// Metode permintaan untuk unggah file harus sama dengan nilai bidang Method dalam Data.Param yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.
connection.setRequestMethod("PUT");
// Izinkan output ke koneksi karena koneksi ini digunakan untuk mengunggah file.
connection.setDoOutput(true);
connection.setRequestProperty("X-bailian-extra", "Ganti dengan nilai bidang X-bailian-extra dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.");
connection.setRequestProperty("Content-Type", "Ganti dengan nilai bidang Content-Type dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya. Jika dikembalikan nilai null, berikan nilai null.");
// Baca file dan unggah melalui koneksi.
try (DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
FileInputStream fileInputStream = new FileInputStream(filePath)) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
outStream.flush();
}
// Periksa respons.
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// File berhasil diunggah.
System.out.println("File uploaded successfully.");
} else {
// File gagal diunggah.
System.out.println("Failed to upload the file. ResponseCode: " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
public static void main(String[] args) {
String preSignedUrlOrHttpUrl = "Ganti dengan nilai bidang Url dalam Data.Param yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.";
// Unggah file lokal ke penyimpanan sementara.
String filePath = "Ganti dengan path lokal aktual file yang akan diunggah, misalnya di Linux: /path/to/your/Alibaba Cloud Model Studio Product Overview.docx";
uploadFile(preSignedUrlOrHttpUrl, filePath);
}
}
PHP<?php
/**
* Upload a local file to temporary storage.
*
* @param string $preSignedUrl The pre-signed URL or HTTP address obtained from the ApplyFileUploadLease operation.
* @param array $headers An array of request headers containing "X-bailian-extra" and "Content-Type".
* @param string $filePath The local file path.
* @throws Exception If the upload fails.
*/
function uploadFile($preSignedUrl, $headers, $filePath) {
// Baca konten file.
$fileContent = file_get_contents($filePath);
if ($fileContent === false) {
throw new Exception("Cannot read the file: " . $filePath);
}
// Inisialisasi sesi cURL.
$ch = curl_init();
// Atur opsi cURL.
curl_setopt($ch, CURLOPT_URL, $preSignedUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); // Gunakan metode PUT.
curl_setopt($ch, CURLOPT_POSTFIELDS, $fileContent); // Atur badan permintaan ke konten file.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Kembalikan respons alih-alih menampilkannya langsung.
// Bangun header permintaan.
$uploadHeaders = [
"X-bailian-extra: " . $headers["X-bailian-extra"],
"Content-Type: " . $headers["Content-Type"]
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $uploadHeaders);
// Jalankan permintaan.
$response = curl_exec($ch);
// Dapatkan kode status HTTP.
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Tutup sesi cURL.
curl_close($ch);
// Periksa kode respons.
if ($httpCode != 200) {
throw new Exception("Upload failed. HTTP status code: " . $httpCode . ", error message: " . $response);
}
// Unggahan berhasil.
echo "File uploaded successfully.\n";
}
/**
* Fungsi utama: Unggah file lokal.
*/
function main() {
// Ganti dengan nilai bidang Url dalam Data.Param yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.
$preSignedUrl = "Ganti dengan nilai bidang Url dalam Data.Param yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.";
// Ganti dengan nilai X-bailian-extra dan Content-Type dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.
$headers = [
"X-bailian-extra" => "Ganti dengan nilai bidang X-bailian-extra dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.",
"Content-Type" => "Ganti dengan nilai bidang Content-Type dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya. Jika dikembalikan nilai null, berikan nilai null."
];
// Unggah file lokal ke penyimpanan sementara.
$filePath = "Ganti dengan path lokal aktual file yang akan diunggah, misalnya di Linux: /path/to/your/Alibaba Cloud Model Studio Product Overview.docx";
try {
uploadFile($preSignedUrl, $headers, $filePath);
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
}
// Panggil fungsi utama.
main();
?>
Node.jsconst fs = require('fs');
const axios = require('axios');
/**
* Upload a local file to temporary storage.
*
* @param {string} preSignedUrl - The URL from the upload lease.
* @param {Object} headers - The headers for the upload request.
* @param {string} filePath - The local path of the file.
* @throws {Error} If the upload fails.
*/
async function uploadFile(preSignedUrl, headers, filePath) {
// Bangun header permintaan yang diperlukan untuk unggahan.
const uploadHeaders = {
"X-bailian-extra": headers["X-bailian-extra"],
"Content-Type": headers["Content-Type"]
};
// Buat stream baca file.
const fileStream = fs.createReadStream(filePath);
try {
// Gunakan axios untuk mengirim permintaan PUT.
const response = await axios.put(preSignedUrl, fileStream, {
headers: uploadHeaders
});
// Periksa kode status respons.
if (response.status === 200) {
console.log("File uploaded successfully.");
} else {
console.error(`Failed to upload the file. ResponseCode: ${response.status}`);
throw new Error(`Upload failed with status code: ${response.status}`);
}
} catch (error) {
// Tangani error.
console.error("Error during upload:", error.message);
throw new Error(`Upload failed: ${error.message}`);
}
}
/**
* Fungsi utama: Unggah file lokal.
*/
function main() {
const preSignedUrl = "Ganti dengan nilai bidang Url dalam Data.Param yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.";
const headers = {
"X-bailian-extra": "Ganti dengan nilai bidang X-bailian-extra dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.",
"Content-Type": "Ganti dengan nilai bidang Content-Type dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya. Jika dikembalikan nilai null, berikan nilai null."
};
// Unggah file lokal ke penyimpanan sementara.
const filePath = "Ganti dengan path lokal aktual file yang akan diunggah, misalnya di Linux: /path/to/your/Alibaba Cloud Model Studio Product Overview.docx";
uploadFile(preSignedUrl, headers, filePath)
.then(() => {
console.log("Upload completed.");
})
.catch((err) => {
console.error("Upload failed:", err.message);
});
}
// Panggil fungsi utama.
main();
C#using System;
using System.IO;
using System.Net;
public class UploadFilExample
{
public static void UploadFile(string preSignedUrl, string filePath)
{
HttpWebRequest connection = null;
try
{
// Buat objek URL.
Uri url = new Uri(preSignedUrl);
connection = (HttpWebRequest)WebRequest.Create(url);
// Metode permintaan untuk unggah file harus sama dengan nilai bidang Method dalam Data.Param yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.
connection.Method = "PUT";
// Izinkan buffering aliran tulis karena koneksi ini digunakan untuk mengunggah file.
connection.AllowWriteStreamBuffering = false;
connection.SendChunked = false;
// Atur header permintaan agar sesuai dengan nilai bidang dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.
connection.Headers["X-bailian-extra"] = "Ganti dengan nilai bidang X-bailian-extra dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.";
connection.ContentType = "Ganti dengan nilai bidang Content-Type dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya. Jika dikembalikan nilai null, berikan nilai null.";
// Baca file dan unggah melalui koneksi.
using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
using (var requestStream = connection.GetRequestStream())
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
requestStream.Flush();
}
// Periksa respons.
using (HttpWebResponse response = (HttpWebResponse)connection.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
// File berhasil diunggah.
Console.WriteLine("File uploaded successfully.");
}
else
{
// File gagal diunggah.
Console.WriteLine($"Failed to upload the file. ResponseCode: {response.StatusCode}");
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
e.StackTrace.ToString();
}
finally
{
if (connection != null)
{
connection.Abort();
}
}
}
public static void Main(string[] args)
{
string preSignedUrlOrHttpUrl = "Ganti dengan nilai bidang Url dalam Data.Param yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.";
// Unggah file lokal ke penyimpanan sementara.
string filePath = "Ganti dengan path lokal aktual file yang akan diunggah, misalnya di Linux: /path/to/your/Alibaba Cloud Model Studio Product Overview.docx";
UploadFile(preSignedUrlOrHttpUrl, filePath);
}
}
Gopackage main
import (
"fmt"
"io"
"os"
"github.com/go-resty/resty/v2"
)
// UploadFile uploads a local file to temporary storage.
//
// Parameters:
// - preSignedUrl (string): The URL from the upload lease.
// - headers (map[string]string): The headers for the upload request.
// - filePath (string): The local path of the file.
//
// Returns:
// - error: An error message if the upload fails, otherwise nil.
func UploadFile(preSignedUrl string, headers map[string]string, filePath string) error {
// Buka file lokal.
file, err := os.Open(filePath)
if err != nil {
return fmt.Errorf("failed to open file: %w", err)
}
defer file.Close()
// Baca konten.
body, err := io.ReadAll(file)
if err != nil {
return fmt.Errorf("failed to read file: %w", err)
}
// Buat client REST.
client := resty.New()
// Bangun header permintaan yang diperlukan untuk unggahan.
uploadHeaders := map[string]string{
"X-bailian-extra": headers["X-bailian-extra"],
"Content-Type": headers["Content-Type"],
}
// Kirim permintaan PUT.
resp, err := client.R().
SetHeaders(uploadHeaders).
SetBody(body).
Put(preSignedUrl)
if err != nil {
return fmt.Errorf("failed to send request: %w", err)
}
// Periksa kode status respons HTTP.
if resp.IsError() {
return fmt.Errorf("HTTP error: %d", resp.StatusCode())
}
fmt.Println("File uploaded successfully.")
return nil
}
// Fungsi utama
func main() {
// Ganti dengan nilai bidang Url dalam Data.Param yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.
preSignedUrl := "Ganti dengan nilai bidang Url dalam Data.Param yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya."
// Ganti dengan nilai X-bailian-extra dan Content-Type dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.
headers := map[string]string{
"X-bailian-extra": "Ganti dengan nilai bidang X-bailian-extra dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.",
"Content-Type": "Ganti dengan nilai bidang Content-Type dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya. Jika dikembalikan nilai null, berikan nilai null.",
}
// Unggah file lokal ke penyimpanan sementara.
filePath := "Ganti dengan path lokal aktual file yang akan diunggah, misalnya di Linux: /path/to/your/Alibaba Cloud Model Studio Product Overview.docx"
// Panggil fungsi unggah.
err := UploadFile(preSignedUrl, headers, filePath)
if err != nil {
fmt.Printf("Upload failed: %v\n", err)
}
}
URL uploadURL harus dapat diakses publik dan menunjuk ke file yang valid. Pythonimport requests
from urllib.parse import urlparse
def upload_file_link(pre_signed_url, source_url_string):
"""
Upload a file from a public URL to temporary storage.
Args:
pre_signed_url (str): The URL from the upload lease.
source_url_string (str): The URL of the file.
Returns:
The response from Alibaba Cloud Model Studio.
"""
try:
// Atur header permintaan.
headers = {
"X-bailian-extra": "Ganti dengan nilai bidang X-bailian-extra dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.",
"Content-Type": "Ganti dengan nilai bidang Content-Type dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya. Jika dikembalikan nilai null, berikan nilai null."
}
// Atur metode permintaan ke GET untuk mengakses URL file.
source_response = requests.get(source_url_string)
if source_response.status_code != 200:
raise RuntimeError("Failed to get source file.")
// Metode permintaan untuk unggah file harus sama dengan nilai bidang Method dalam Data.Param yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.
response = requests.put(pre_signed_url, data=source_response.content, headers=headers)
// Periksa kode status respons.
if response.status_code == 200:
print("File uploaded successfully.")
else:
print(f"Failed to upload the file. ResponseCode: {response.status_code}")
except Exception as e:
print(f"An error occurred: {str(e)}")
if __name__ == "__main__":
pre_signed_url_or_http_url = "Ganti dengan nilai bidang Url dalam Data.Param yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya."
// URL file.
source_url = "Ganti dengan URL file yang akan diunggah."
upload_file_link(pre_signed_url_or_http_url, source_url)
Javaimport java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class UploadFile {
public static void uploadFileLink(String preSignedUrl, String sourceUrlString) {
HttpURLConnection connection = null;
try {
// Buat objek URL.
URL url = new URL(preSignedUrl);
connection = (HttpURLConnection) url.openConnection();
// Metode permintaan untuk unggah file harus sama dengan nilai bidang Method dalam Data.Param yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.
connection.setRequestMethod("PUT");
// Izinkan output ke koneksi karena koneksi ini digunakan untuk mengunggah file.
connection.setDoOutput(true);
connection.setRequestProperty("X-bailian-extra", "Ganti dengan nilai bidang X-bailian-extra dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.");
connection.setRequestProperty("Content-Type", "Ganti dengan nilai bidang Content-Type dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya. Jika dikembalikan nilai null, berikan nilai null.");
URL sourceUrl = new URL(sourceUrlString);
HttpURLConnection sourceConnection = (HttpURLConnection) sourceUrl.openConnection();
// Atur metode permintaan ke GET untuk mengakses URL file.
sourceConnection.setRequestMethod("GET");
// Dapatkan kode respons. 200 menunjukkan bahwa permintaan berhasil.
int sourceFileResponseCode = sourceConnection.getResponseCode();
// Baca file dari URL dan unggah melalui koneksi.
if (sourceFileResponseCode != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Failed to get source file.");
}
try (DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
InputStream in = new BufferedInputStream(sourceConnection.getInputStream())) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
outStream.flush();
}
// Periksa respons.
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// File berhasil diunggah.
System.out.println("File uploaded successfully.");
} else {
// File gagal diunggah.
System.out.println("Failed to upload the file. ResponseCode: " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
public static void main(String[] args) {
String preSignedUrlOrHttpUrl = "Ganti dengan nilai bidang Url dalam Data.Param yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.";
String sourceUrl = "Ganti dengan URL file yang akan diunggah.";
uploadFileLink(preSignedUrlOrHttpUrl, sourceUrl);
}
}
PHP<?php
/**
* Upload a file from a public URL to temporary storage.
*
* @param string $preSignedUrl The pre-signed URL or HTTP address obtained from the ApplyFileUploadLease operation.
* @param array $headers An array of request headers containing "X-bailian-extra" and "Content-Type".
* @param string $sourceUrl The URL of the file.
* @throws Exception If the upload fails.
*/
function uploadFile($preSignedUrl, $headers, $sourceUrl) {
$fileContent = file_get_contents($sourceUrl);
if ($fileContent === false) {
throw new Exception("Cannot download the file from the given URL: " . $sourceUrl);
}
// Inisialisasi sesi cURL.
$ch = curl_init();
// Atur opsi cURL.
curl_setopt($ch, CURLOPT_URL, $preSignedUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); // Gunakan metode PUT.
curl_setopt($ch, CURLOPT_POSTFIELDS, $fileContent); // Atur badan permintaan ke konten file.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Kembalikan respons alih-alih menampilkannya langsung.
// Bangun header permintaan.
$uploadHeaders = [
"X-bailian-extra: " . $headers["X-bailian-extra"],
"Content-Type: " . $headers["Content-Type"]
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $uploadHeaders);
// Jalankan permintaan.
$response = curl_exec($ch);
// Dapatkan kode status HTTP.
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Tutup sesi cURL.
curl_close($ch);
// Periksa kode respons.
if ($httpCode != 200) {
throw new Exception("Upload failed. HTTP status code: " . $httpCode . ", error message: " . $response);
}
// Unggahan berhasil.
echo "File uploaded successfully.\n";
}
/**
* Fungsi utama: Unggah file dari URL publik ke penyimpanan sementara.
*/
function main() {
// Ganti dengan nilai bidang Url dalam Data.Param yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.
$preSignedUrl = "Ganti dengan nilai bidang Url dalam Data.Param yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.";
// Ganti dengan nilai X-bailian-extra dan Content-Type dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.
$headers = [
"X-bailian-extra" => "Ganti dengan nilai bidang X-bailian-extra dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.",
"Content-Type" => "Ganti dengan nilai bidang Content-Type dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya. Jika dikembalikan nilai null, berikan nilai null."
];
$sourceUrl = "Ganti dengan URL file yang akan diunggah.";
try {
uploadFile($preSignedUrl, $headers, $sourceUrl);
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
}
// Panggil fungsi utama.
main();
?>
Node.jsconst axios = require('axios');
/**
* Upload a file from a public URL to temporary storage.
*
* @param {string} preSignedUrl - The URL from the upload lease.
* @param {Object} headers - The headers for the upload request.
* @param {string} sourceUrl - The URL of the file.
* @throws {Error} If the upload fails.
*/
async function uploadFileFromUrl(preSignedUrl, headers, sourceUrl) {
// Bangun header permintaan yang diperlukan untuk unggahan.
const uploadHeaders = {
"X-bailian-extra": headers["X-bailian-extra"],
"Content-Type": headers["Content-Type"]
};
try {
// Unduh file dari URL yang diberikan.
const response = await axios.get(sourceUrl, {
responseType: 'stream'
});
// Gunakan axios untuk mengirim permintaan PUT.
const uploadResponse = await axios.put(preSignedUrl, response.data, {
headers: uploadHeaders
});
// Periksa kode status respons.
if (uploadResponse.status === 200) {
console.log("File uploaded successfully from URL.");
} else {
console.error(`Failed to upload the file. ResponseCode: ${uploadResponse.status}`);
throw new Error(`Upload failed with status code: ${uploadResponse.status}`);
}
} catch (error) {
// Tangani error.
console.error("Error during upload:", error.message);
throw new Error(`Upload failed: ${error.message}`);
}
}
/**
* Fungsi utama: Unggah file yang dapat diunduh publik ke penyimpanan sementara.
*/
function main() {
const preSignedUrl = "Ganti dengan nilai bidang Url dalam Data.Param yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.";
const headers = {
"X-bailian-extra": "Ganti dengan nilai bidang X-bailian-extra dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.",
"Content-Type": "Ganti dengan nilai bidang Content-Type dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya. Jika dikembalikan nilai null, berikan nilai null."
};
const sourceUrl = "Ganti dengan URL file yang akan diunggah.";
uploadFileFromUrl(preSignedUrl, headers, sourceUrl)
.then(() => {
console.log("Upload completed.");
})
.catch((err) => {
console.error("Upload failed:", err.message);
});
}
// Panggil fungsi utama.
main();
C#using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
public class UploadFileExample
{
public static async Task UploadFileFromUrl(string preSignedUrl, string url)
{
try
{
// Buat client HTTP untuk mengunduh file dari URL yang diberikan.
using (HttpClient httpClient = new HttpClient())
{
HttpResponseMessage response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
response.EnsureSuccessStatusCode();
// Dapatkan stream file.
using (Stream fileStream = await response.Content.ReadAsStreamAsync())
{
// Buat objek URL.
Uri urlObj = new Uri(preSignedUrl);
HttpWebRequest connection = (HttpWebRequest)WebRequest.Create(urlObj);
// Atur metode permintaan untuk unggah file.
connection.Method = "PUT";
connection.AllowWriteStreamBuffering = false;
connection.SendChunked = false;
// Atur header permintaan. Ganti dengan nilai aktual.
connection.Headers["X-bailian-extra"] = "Ganti dengan nilai bidang X-bailian-extra dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.";
connection.ContentType = "Ganti dengan nilai bidang Content-Type dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya. Jika dikembalikan nilai null, berikan nilai null.";
// Dapatkan stream permintaan dan tulis stream file ke dalamnya.
using (Stream requestStream = connection.GetRequestStream())
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = await fileStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await requestStream.WriteAsync(buffer, 0, bytesRead);
}
await requestStream.FlushAsync();
}
// Periksa respons.
using (HttpWebResponse responseResult = (HttpWebResponse)connection.GetResponse())
{
if (responseResult.StatusCode == HttpStatusCode.OK)
{
Console.WriteLine("File uploaded successfully from URL.");
}
else
{
Console.WriteLine($"Failed to upload the file. ResponseCode: {responseResult.StatusCode}");
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
}
}
public static async Task Main(string[] args)
{
string preSignedUrlOrHttpUrl = "Ganti dengan nilai bidang Url dalam Data.Param yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.";
string url = "Ganti dengan URL file yang akan diunggah.";
await UploadFileFromUrl(preSignedUrlOrHttpUrl, url);
}
}
Gopackage main
import (
"fmt"
"net/http"
"github.com/go-resty/resty/v2"
)
// UploadFileFromUrl uploads a file from a public URL to temporary storage.
//
// Parameters:
// - preSignedUrl (string): The URL from the upload lease.
// - headers (map[string]string): The headers for the upload request.
// - sourceUrl (string): The URL of the file.
//
// Returns:
// - error: An error message if the upload fails, otherwise nil.
func UploadFileFromUrl(preSignedUrl string, headers map[string]string, sourceUrl string) error {
// Unduh file dari URL yang diberikan.
resp, err := http.Get(sourceUrl)
if err != nil {
return fmt.Errorf("failed to get file: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("failed to get file, status code: %d", resp.StatusCode)
}
// Buat client REST.
client := resty.New()
// Bangun header permintaan yang diperlukan untuk unggahan.
uploadHeaders := map[string]string{
"X-bailian-extra": headers["X-bailian-extra"],
"Content-Type": headers["Content-Type"],
}
// Kirim permintaan PUT.
response, err := client.R().
SetHeaders(uploadHeaders).
SetBody(resp.Body).
Put(preSignedUrl)
if err != nil {
return fmt.Errorf("failed to send request: %w", err)
}
// Periksa kode status respons HTTP.
if response.IsError() {
return fmt.Errorf("HTTP error: %d", response.StatusCode())
}
fmt.Println("File uploaded successfully from URL.")
return nil
}
// Fungsi utama
func main() {
// Ganti dengan nilai bidang Url dalam Data.Param yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.
preSignedUrl := "Ganti dengan nilai bidang Url dalam Data.Param yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya."
// Ganti dengan nilai X-bailian-extra dan Content-Type dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.
headers := map[string]string{
"X-bailian-extra": "Ganti dengan nilai bidang X-bailian-extra dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya.",
"Content-Type": "Ganti dengan nilai bidang Content-Type dalam Data.Param.Headers yang dikembalikan oleh operasi ApplyFileUploadLease pada langkah sebelumnya. Jika dikembalikan nilai null, berikan nilai null.",
}
sourceUrl := "Ganti dengan URL file yang akan diunggah."
// Panggil fungsi unggah.
err := UploadFileFromUrl(preSignedUrl, headers, sourceUrl)
if err != nil {
fmt.Printf("Upload failed: %v\n", err)
}
}
|
2.3. Add file to a categorySetelah mengunggah file, tambahkan file tersebut ke kategori dalam ruang kerja yang sama dengan memanggil operasi AddFile. parser: Tentukan DASHSCOPE_DOCMIND. lease_id: Atur parameter ini ke Data.FileUploadLeaseId yang dikembalikan saat Anda meminta sewa unggah file. category_id: Dalam contoh ini, gunakan default. Jika Anda menggunakan kategori khusus untuk unggahan, Anda harus memberikan category_id yang sesuai.
Penting CategoryId yang diberikan di sini harus sesuai dengan CategoryId yang digunakan dalam langkah Apply for a file upload lease. Jika tidak, Anda akan menerima error Category is mismatched.
Setelah Anda menambahkan file, Model Studio mengembalikan FileId untuk file tersebut dan secara otomatis mulai menguraikannya. lease_id segera tidak berlaku. Jangan gunakan kembali ID sewa yang sama untuk pengiriman lain. | Pythondef add_file(client: bailian20231229Client, lease_id: str, parser: str, category_id: str, workspace_id: str):
"""
Add a file to a specified category in Alibaba Cloud Model Studio.
Args:
client (bailian20231229Client): The client.
lease_id (str): The lease ID.
parser (str): The parser for the file.
category_id (str): The category ID.
workspace_id (str): The workspace ID.
Returns:
The response from Alibaba Cloud Model Studio.
"""
headers = {}
request = bailian_20231229_models.AddFileRequest(
lease_id=lease_id,
parser=parser,
category_id=category_id,
)
runtime = util_models.RuntimeOptions()
return client.add_file_with_options(workspace_id, request, headers, runtime)
Java/**
* Add a file to a category.
*
* @param client The client object.
* @param leaseId The lease ID.
* @param parser The parser for the file.
* @param categoryId The category ID.
* @param workspaceId The workspace ID.
* @return The response object from Alibaba Cloud Model Studio.
*/
public AddFileResponse addFile(com.aliyun.bailian20231229.Client client, String leaseId, String parser, String categoryId, String workspaceId) throws Exception {
Map<String, String> headers = new HashMap<>();
com.aliyun.bailian20231229.models.AddFileRequest addFileRequest = new com.aliyun.bailian20231229.models.AddFileRequest();
addFileRequest.setLeaseId(leaseId);
addFileRequest.setParser(parser);
addFileRequest.setCategoryId(categoryId);
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
return client.addFileWithOptions(workspaceId, addFileRequest, headers, runtime);
}
PHP/**
* Add a file to a category.
*
* @param Bailian $client The client.
* @param string $leaseId The lease ID.
* @param string $parser The parser for the file.
* @param string $categoryId The category ID.
* @param string $workspaceId The workspace ID.
* @return AddFileResponse The response from Alibaba Cloud Model Studio.
*/
public function addFile($client, $leaseId, $parser, $categoryId, $workspaceId) {
$headers = [];
$addFileRequest = new AddFileRequest([
"leaseId" => $leaseId,
"parser" => $parser,
"categoryId" => $categoryId
]);
$runtime = new RuntimeOptions([]);
return $client->addFileWithOptions($workspaceId, $addFileRequest, $headers, $runtime);
}
Node.js/**
* Add a file to a category.
* @param {Bailian20231229Client} client - The client.
* @param {string} leaseId - The lease ID.
* @param {string} parser - The parser for the file.
* @param {string} categoryId - The category ID.
* @param {string} workspaceId - The workspace ID.
* @returns {Promise<bailian20231229.AddFileResponse>} - The response from Alibaba Cloud Model Studio.
*/
async function addFile(client, leaseId, parser, categoryId, workspaceId) {
const headers = {};
const req = new bailian20231229.AddFileRequest({
leaseId,
parser,
categoryId
});
const runtime = new Util.RuntimeOptions({});
return await client.addFileWithOptions(workspaceId, req, headers, runtime);
}
C#/// <summary>
/// Add a file to a category.
/// </summary>
/// <param name="client">The client object.</param>
/// <param name="leaseId">The lease ID.</param>
/// <param name="parser">The parser for the file.</param>
/// <param name="categoryId">The category ID.</param>
/// <param name="workspaceId">The workspace ID.</param>
/// <returns>The response object from Alibaba Cloud Model Studio.</returns>
/// <exception cref="Exception">An exception is thrown if an error occurs during the call.</exception>
public AlibabaCloud.SDK.Bailian20231229.Models.AddFileResponse AddFile(
AlibabaCloud.SDK.Bailian20231229.Client client,
string leaseId,
string parser,
string categoryId,
string workspaceId)
{
var headers = new Dictionary<string, string>() { };
var addFileRequest = new AlibabaCloud.SDK.Bailian20231229.Models.AddFileRequest
{
LeaseId = leaseId,
Parser = parser,
CategoryId = categoryId
};
var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
return client.AddFileWithOptions(workspaceId, addFileRequest, headers, runtime);
}
Go// AddFile adds a file to a specified category in Alibaba Cloud Model Studio.
//
// Parameters:
// - client (bailian20231229.Client): The client.
// - leaseId (string): The lease ID.
// - parser (string): The parser for the file.
// - categoryId (string): The category ID.
// - workspaceId (string): The workspace ID.
//
// Returns:
// - *bailian20231229.AddFileResponse: The response from Alibaba Cloud Model Studio.
// - error: The error message.
func AddFile(client *bailian20231229.Client, leaseId, parser, categoryId, workspaceId string) (_result *bailian20231229.AddFileResponse, _err error) {
headers := make(map[string]*string)
addFileRequest := &bailian20231229.AddFileRequest{
LeaseId: tea.String(leaseId),
Parser: tea.String(parser),
CategoryId: tea.String(categoryId),
}
runtime := &util.RuntimeOptions{}
return client.AddFileWithOptions(tea.String(workspaceId), addFileRequest, headers, runtime)
}
Contoh permintaan {
"CategoryId": "default",
"LeaseId": "d92bd94fa9b54326a2547415e100c9e2.1742195250069",
"Parser": "DASHSCOPE_DOCMIND",
"WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}
Contoh respons {
"Status": "200",
"Message": "",
"RequestId": "5832A1F4-AF91-5242-8B75-35BDC9XXXXXX",
"Data": {
"FileId": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
"Parser": "DASHSCOPE_DOCMIND"
},
"Code": "Success",
"Success": "true"
}
|
2.4. Query file parsing statusFile tidak dapat digunakan dalam basis pengetahuan sampai selesai diurai. Selama jam sibuk, proses ini dapat memakan waktu beberapa jam. Anda dapat memanggil operasi DescribeFile untuk menanyakan status penguraiannya. Jika bidang Data.Status bernilai PARSE_SUCCESS, file telah berhasil diurai dan Anda dapat mengimpornya ke basis pengetahuan. |
Penting Sebelum memanggil operasi ini, RAM user harus diberikan izin API yang diperlukan (kebijakan AliyunBailianDataFullAccess atau AliyunBailianDataReadOnlyAccess). Operasi ini mendukung debugging online dan pembuatan kode contoh untuk berbagai bahasa.
Pythondef describe_file(client, workspace_id, file_id):
"""
Get the basic information of a file.
Args:
client (bailian20231229Client): The client.
workspace_id (str): The workspace ID.
file_id (str): The file ID.
Returns:
The response from Alibaba Cloud Model Studio.
"""
headers = {}
runtime = util_models.RuntimeOptions()
return client.describe_file_with_options(workspace_id, file_id, headers, runtime)
Java/**
* Query the basic information of a file.
*
* @param client The client object.
* @param workspaceId The workspace ID.
* @param fileId The file ID.
* @return The response object from Alibaba Cloud Model Studio.
*/
public DescribeFileResponse describeFile(com.aliyun.bailian20231229.Client client, String workspaceId, String fileId) throws Exception {
Map<String, String> headers = new HashMap<>();
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
return client.describeFileWithOptions(workspaceId, fileId, headers, runtime);
}
PHP/**
* Query the basic information of a file.
*
* @param Bailian $client The client.
* @param string $workspaceId The workspace ID.
* @param string $fileId The file ID.
* @return DescribeFileResponse The response from Alibaba Cloud Model Studio.
*/
public function describeFile($client, $workspaceId, $fileId) {
$headers = [];
$runtime = new RuntimeOptions([]);
return $client->describeFileWithOptions($workspaceId, $fileId, $headers, $runtime);
}
Node.js/**
* Query the parsing status of a file.
* @param {Bailian20231229Client} client - The client.
* @param {string} workspaceId - The workspace ID.
* @param {string} fileId - The file ID.
* @returns {Promise<bailian20231229.DescribeFileResponse>} - The response from Alibaba Cloud Model Studio.
*/
async function describeFile(client, workspaceId, fileId) {
const headers = {};
const runtime = new Util.RuntimeOptions({});
return await client.describeFileWithOptions(workspaceId, fileId, headers, runtime);
}
C#/// <summary>
/// Query the basic information of a file.
/// </summary>
/// <param name="client">The client object.</param>
/// <param name="workspaceId">The workspace ID.</param>
/// <param name="fileId">The file ID.</param>
/// <returns>The response object from Alibaba Cloud Model Studio.</returns>
/// <exception cref="Exception">An exception is thrown if an error occurs during the call.</exception>
public AlibabaCloud.SDK.Bailian20231229.Models.DescribeFileResponse DescribeFile(
AlibabaCloud.SDK.Bailian20231229.Client client,
string workspaceId,
string fileId)
{
var headers = new Dictionary<string, string>() { };
var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
return client.describeFileWithOptions(workspaceId, fileId, headers, runtime);
}
Go// DescribeFile gets the basic information of a file.
//
// Parameters:
// - client (bailian20231229.Client): The client.
// - workspaceId (string): The workspace ID.
// - fileId (string): The file ID.
//
// Returns:
// - *bailian20231229.DescribeFileResponse: The response from Alibaba Cloud Model Studio.
// - error: The error message.
func DescribeFile(client *bailian20231229.Client, workspaceId, fileId string) (_result *bailian20231229.DescribeFileResponse, _err error) {
headers := make(map[string]*string)
runtime := &util.RuntimeOptions{}
return client.DescribeFileWithOptions(tea.String(workspaceId), tea.String(fileId), headers, runtime)
}
Contoh permintaan {
"FileId": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
"WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}
Contoh respons {
"Status": "200",
"Message": "",
"RequestId": "B9246251-987A-5628-8E1E-17BB39XXXXXX",
"Data": {
"CategoryId": "cate_206ea350f0014ea4a324adff1ca13011_10xxxxxx",
"Status": "PARSE_SUCCESS",
"FileType": "docx",
"CreateTime": "2025-03-17 15:47:13",
"FileName": "Alibaba Cloud Model Studio Product Overview.docx",
"FileId": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
"SizeInBytes": "14015",
"Parser": "DASHSCOPE_DOCMIND"
},
"Code": "Success",
"Success": "true"
}
|
3. Create a knowledge base |
3.1. Initialize knowledge baseSetelah file diurai, Anda dapat membuat basis pengetahuan darinya di ruang kerja yang sama. Untuk memulai, panggil operasi CreateIndex untuk menginisialisasi (namun belum menyelesaikan) basis pengetahuan pengambilan dokumen. workspace_id: Lihat Cara mendapatkan ID ruang kerja. file_id: Tentukan FileId yang dikembalikan oleh API saat Anda menambahkan file ke kategori. Jika source_type diatur ke DATA_CENTER_FILE, parameter ini wajib diisi, dan API akan mengembalikan error jika tidak ditentukan. structure_type: Dalam contoh ini, gunakan unstructured. source_type: Dalam contoh ini, gunakan DATA_CENTER_FILE. sink_type: Dalam contoh ini, tentukan BUILT_IN.
Nilai bidang Data.Id yang dikembalikan oleh API ini adalah ID basis pengetahuan, yang digunakan untuk pembuatan indeks selanjutnya. Simpan ID basis pengetahuan dengan aman, karena diperlukan untuk semua operasi API selanjutnya terkait basis pengetahuan ini. | Pythondef create_index(client, workspace_id, file_id, name, structure_type, source_type, sink_type):
"""
Create (initialize) a knowledge base in Alibaba Cloud Model Studio.
Args:
client (bailian20231229Client): The client.
workspace_id (str): The workspace ID.
file_id (str): The file ID.
name (str): The name of the knowledge base.
structure_type (str): The data structure type of the knowledge base.
source_type (str): The data source type. Category and file types are supported.
sink_type (str): The vector storage type of the knowledge base.
Returns:
The response from Alibaba Cloud Model Studio.
"""
headers = {}
request = bailian_20231229_models.CreateIndexRequest(
structure_type=structure_type,
name=name,
source_type=source_type,
sink_type=sink_type,
document_ids=[file_id]
)
runtime = util_models.RuntimeOptions()
return client.create_index_with_options(workspace_id, request, headers, runtime)
Java/**
* Create (initialize) a knowledge base in Alibaba Cloud Model Studio.
*
* @param client The client object.
* @param workspaceId The workspace ID.
* @param fileId The file ID.
* @param name The name of the knowledge base.
* @param structureType The data structure type of the knowledge base.
* @param sourceType The data source type. Category and file types are supported.
* @param sinkType The vector storage type of the knowledge base.
* @return The response object from Alibaba Cloud Model Studio.
*/
public CreateIndexResponse createIndex(com.aliyun.bailian20231229.Client client, String workspaceId, String fileId, String name, String structureType, String sourceType, String sinkType) throws Exception {
Map<String, String> headers = new HashMap<>();
com.aliyun.bailian20231229.models.CreateIndexRequest createIndexRequest = new com.aliyun.bailian20231229.models.CreateIndexRequest();
createIndexRequest.setStructureType(structureType);
createIndexRequest.setName(name);
createIndexRequest.setSourceType(sourceType);
createIndexRequest.setSinkType(sinkType);
createIndexRequest.setDocumentIds(Collections.singletonList(fileId));
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
return client.createIndexWithOptions(workspaceId, createIndexRequest, headers, runtime);
}
PHP/**
* Create (initialize) a knowledge base in Alibaba Cloud Model Studio.
*
* @param Bailian $client The client.
* @param string $workspaceId The workspace ID.
* @param string $fileId The file ID.
* @param string $name The name of the knowledge base.
* @param string $structureType The data structure type of the knowledge base.
* @param string $sourceType The data source type. Category and file types are supported.
* @param string $sinkType The vector storage type of the knowledge base.
* @return CreateIndexResponse The response from Alibaba Cloud Model Studio.
*/
public function createIndex($client, $workspaceId, $fileId, $name, $structureType, $sourceType, $sinkType) {
$headers = [];
$createIndexRequest = new CreateIndexRequest([
"structureType" => $structureType,
"name" => $name,
"sourceType" => $sourceType,
"documentIds" => [
$fileId
],
"sinkType" => $sinkType
]);
$runtime = new RuntimeOptions([]);
return $client->createIndexWithOptions($workspaceId, $createIndexRequest, $headers, $runtime);
}
Node.js/**
* Initialize a knowledge base (index).
* @param {Bailian20231229Client} client - The client.
* @param {string} workspaceId - The workspace ID.
* @param {string} fileId - The file ID.
* @param {string} name - The name of the knowledge base.
* @param {string} structureType - The data structure type of the knowledge base.
* @param {string} sourceType - The data source type. Category and file types are supported.
* @param {string} sinkType - The vector storage type of the knowledge base.
* @returns {Promise<bailian20231229.CreateIndexResponse>} - The response from Alibaba Cloud Model Studio.
*/
async function createIndex(client, workspaceId, fileId, name, structureType, sourceType, sinkType) {
const headers = {};
const req = new bailian20231229.CreateIndexRequest({
name,
structureType,
documentIds: [fileId],
sourceType,
sinkType
});
const runtime = new Util.RuntimeOptions({});
return await client.createIndexWithOptions(workspaceId, req, headers, runtime);
}
C#/// <summary>
/// Create (initialize) a knowledge base in Alibaba Cloud Model Studio.
/// </summary>
/// <param name="client">The client object.</param>
/// <param name="workspaceId">The workspace ID.</param>
/// <param name="fileId">The file ID.</param>
/// <param name="name">The name of the knowledge base.</param>
/// <param name="structureType">The data structure type of the knowledge base.</param>
/// <param name="sourceType">The data source type. Category and file types are supported.</param>
/// <param name="sinkType">The vector storage type of the knowledge base.</param>
/// <returns>The response object from Alibaba Cloud Model Studio.</returns>
/// <exception cref="Exception">An exception is thrown if an error occurs during the call.</exception>
public AlibabaCloud.SDK.Bailian20231229.Models.CreateIndexResponse CreateIndex(
AlibabaCloud.SDK.Bailian20231229.Client client,
string workspaceId,
string fileId,
string name,
string structureType,
string sourceType,
string sinkType)
{
var headers = new Dictionary<string, string>() { };
var createIndexRequest = new AlibabaCloud.SDK.Bailian20231229.Models.CreateIndexRequest
{
StructureType = structureType,
Name = name,
SourceType = sourceType,
SinkType = sinkType,
DocumentIds = new List<string> { fileId }
};
var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
return client.CreateIndexWithOptions(workspaceId, createIndexRequest, headers, runtime);
}
Go// CreateIndex creates (initializes) a knowledge base in Alibaba Cloud Model Studio.
//
// Parameters:
// - client (bailian20231229.Client): The client.
// - workspaceId (string): The workspace ID.
// - fileId (string): The file ID.
// - name (string): The name of the knowledge base.
// - structureType (string): The data structure type of the knowledge base.
// - sourceType (string): The data source type. Category and file types are supported.
// - sinkType (string): The vector storage type of the knowledge base.
//
// Returns:
// - *bailian20231229.CreateIndexResponse: The response from Alibaba Cloud Model Studio.
// - error: The error message.
func CreateIndex(client *bailian20231229.Client, workspaceId, fileId, name, structureType, sourceType, sinkType string) (_result *bailian20231229.CreateIndexResponse, _err error) {
headers := make(map[string]*string)
createIndexRequest := &bailian20231229.CreateIndexRequest{
StructureType: tea.String(structureType),
Name: tea.String(name),
SourceType: tea.String(sourceType),
SinkType: tea.String(sinkType),
DocumentIds: []*string{tea.String(fileId)},
}
runtime := &util.RuntimeOptions{}
return client.CreateIndexWithOptions(tea.String(workspaceId), createIndexRequest, headers, runtime)
}
Contoh permintaan {
"Name": "Alibaba Cloud Model Studio Phone Knowledge Base",
"SinkType": "BUILT_IN",
"SourceType": "DATA_CENTER_FILE",
"StructureType": "unstructured",
"WorkspaceId": "llm-4u5xpd1xdjqpxxxx",
"DocumentIds": [
"file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx"
]
}
Contoh respons {
"Status": "200",
"Message": "success",
"RequestId": "87CB0999-F1BB-5290-8C79-A875B2XXXXXX",
"Data": {
"Id": "mymxbdxxxx"
},
"Code": "Success",
"Success": "true"
}
|
3.2. Submit an index jobSetelah menginisialisasi basis pengetahuan, panggil operasi SubmitIndexJob untuk memulai proses pembuatan indeks. Setelah pengiriman selesai, Model Studio segera memulai pembuatan indeks sebagai tugas asinkron. Data.Id yang dikembalikan oleh pemanggilan API ini adalah ID tugas yang sesuai. Anda akan menggunakan ID ini pada langkah berikutnya untuk menanyakan status terbaru tugas tersebut. | Pythondef submit_index(client, workspace_id, index_id):
"""
Submit an index job to Alibaba Cloud Model Studio.
Args:
client (bailian20231229Client): The client.
workspace_id (str): The workspace ID.
index_id (str): The knowledge base ID.
Returns:
The response from Alibaba Cloud Model Studio.
"""
headers = {}
submit_index_job_request = bailian_20231229_models.SubmitIndexJobRequest(
index_id=index_id
)
runtime = util_models.RuntimeOptions()
return client.submit_index_job_with_options(workspace_id, submit_index_job_request, headers, runtime)
Java/**
* Submit an index job to Alibaba Cloud Model Studio.
*
* @param client The client object.
* @param workspaceId The workspace ID.
* @param indexId The knowledge base ID.
* @return The response object from Alibaba Cloud Model Studio.
*/
public SubmitIndexJobResponse submitIndex(com.aliyun.bailian20231229.Client client, String workspaceId, String indexId) throws Exception {
Map<String, String> headers = new HashMap<>();
com.aliyun.bailian20231229.models.SubmitIndexJobRequest submitIndexJobRequest = new com.aliyun.bailian20231229.models.SubmitIndexJobRequest();
submitIndexJobRequest.setIndexId(indexId);
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
return client.submitIndexJobWithOptions(workspaceId, submitIndexJobRequest, headers, runtime);
}
PHP/**
* Submit an index job to Alibaba Cloud Model Studio.
*
* @param Bailian $client The client.
* @param string $workspaceId The workspace ID.
* @param string $indexId The knowledge base ID.
* @return SubmitIndexJobResponse The response from Alibaba Cloud Model Studio.
*/
public static function submitIndex($client, $workspaceId, $indexId) {
$headers = [];
$submitIndexJobRequest = new SubmitIndexJobRequest([
'indexId' => $indexId
]);
$runtime = new RuntimeOptions([]);
return $client->submitIndexJobWithOptions($workspaceId, $submitIndexJobRequest, $headers, $runtime);
}
Node.js/**
* Submit an index job.
* @param {Bailian20231229Client} client - The client.
* @param {string} workspaceId - The workspace ID.
* @param {string} indexId - The knowledge base ID.
* @returns {Promise<bailian20231229.SubmitIndexJobResponse>} - The response from Alibaba Cloud Model Studio.
*/
async function submitIndex(client, workspaceId, indexId) {
const headers = {};
const req = new bailian20231229.SubmitIndexJobRequest({ indexId });
const runtime = new Util.RuntimeOptions({});
return await client.submitIndexJobWithOptions(workspaceId, req, headers, runtime);
}
C#/// <summary>
/// Submit an index job to Alibaba Cloud Model Studio.
/// </summary>
/// <param name="client">The client object.</param>
/// <param name="workspaceId">The workspace ID.</param>
/// <param name="indexId">The knowledge base ID.</param>
/// <returns>The response object from Alibaba Cloud Model Studio.</returns>
/// <exception cref="Exception">An exception is thrown if an error occurs during the call.</exception>
public AlibabaCloud.SDK.Bailian20231229.Models.SubmitIndexJobResponse SubmitIndex(
AlibabaCloud.SDK.Bailian20231229.Client client,
string workspaceId,
string indexId)
{
var headers = new Dictionary<string, string>() { };
var submitIndexJobRequest = new AlibabaCloud.SDK.Bailian20231229.Models.SubmitIndexJobRequest
{
IndexId = indexId
};
var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
return client.SubmitIndexJobWithOptions(workspaceId, submitIndexJobRequest, headers, runtime);
}
Go// SubmitIndex submits an index job.
//
// Parameters:
// - client (bailian20231229.Client): The client.
// - workspaceId (string): The workspace ID.
// - indexId (string): The knowledge base ID.
//
// Returns:
// - *bailian20231229.SubmitIndexJobResponse: The response from Alibaba Cloud Model Studio.
// - error: The error message.
func SubmitIndex(client *bailian20231229.Client, workspaceId, indexId string) (_result *bailian20231229.SubmitIndexJobResponse, _err error) {
headers := make(map[string]*string)
submitIndexJobRequest := &bailian20231229.SubmitIndexJobRequest{
IndexId: tea.String(indexId),
}
runtime := &util.RuntimeOptions{}
return client.SubmitIndexJobWithOptions(tea.String(workspaceId), submitIndexJobRequest, headers, runtime)
}
Contoh permintaan {
"IndexId": "mymxbdxxxx",
"WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}
Contoh respons {
"Status": "200",
"Message": "success",
"RequestId": "7774575F-571D-5854-82C2-634AB8XXXXXX",
"Data": {
"IndexId": "mymxbdxxxx",
"Id": "3cd6fb57aaf44cd0b4dd2ca584xxxxxx"
},
"Code": "Success",
"Success": "true"
}
|
3.3. Query index job statusTugas indeks memerlukan waktu untuk diselesaikan. Selama jam sibuk, proses ini dapat memakan waktu beberapa jam. Panggil operasi GetIndexJobStatus untuk menanyakan status eksekusinya. Ketika bidang Data.Status bernilai COMPLETED, basis pengetahuan telah dibuat. | Pythondef get_index_job_status(client, workspace_id, index_id, job_id):
"""
Query the status of an index job.
Args:
client (bailian20231229Client): The client.
workspace_id (str): The workspace ID.
index_id (str): The knowledge base ID.
job_id (str): The job ID.
Returns:
The response from Alibaba Cloud Model Studio.
"""
headers = {}
get_index_job_status_request = bailian_20231229_models.GetIndexJobStatusRequest(
index_id=index_id,
job_id=job_id
)
runtime = util_models.RuntimeOptions()
return client.get_index_job_status_with_options(workspace_id, get_index_job_status_request, headers, runtime)
Java/**
* Query the status of an index job.
*
* @param client The client object.
* @param workspaceId The workspace ID.
* @param jobId The job ID.
* @param indexId The knowledge base ID.
* @return The response object from Alibaba Cloud Model Studio.
*/
public GetIndexJobStatusResponse getIndexJobStatus(com.aliyun.bailian20231229.Client client, String workspaceId, String jobId, String indexId) throws Exception {
Map<String, String> headers = new HashMap<>();
com.aliyun.bailian20231229.models.GetIndexJobStatusRequest getIndexJobStatusRequest = new com.aliyun.bailian20231229.models.GetIndexJobStatusRequest();
getIndexJobStatusRequest.setIndexId(indexId);
getIndexJobStatusRequest.setJobId(jobId);
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
GetIndexJobStatusResponse getIndexJobStatusResponse = null;
getIndexJobStatusResponse = client.getIndexJobStatusWithOptions(workspaceId, getIndexJobStatusRequest, headers, runtime);
return getIndexJobStatusResponse;
}
PHP/**
* Query the status of an index job.
*
* @param Bailian $client The client.
* @param string $workspaceId The workspace ID.
* @param string $indexId The knowledge base ID.
* @param string $jobId The job ID.
* @return GetIndexJobStatusResponse The response from Alibaba Cloud Model Studio.
*/
public function getIndexJobStatus($client, $workspaceId, $jobId, $indexId) {
$headers = [];
$getIndexJobStatusRequest = new GetIndexJobStatusRequest([
'indexId' => $indexId,
'jobId' => $jobId
]);
$runtime = new RuntimeOptions([]);
return $client->getIndexJobStatusWithOptions($workspaceId, $getIndexJobStatusRequest, $headers, $runtime);
}
Node.js/**
* Query the status of an index job.
* @param {Bailian20231229Client} client - The client.
* @param {string} workspaceId - The workspace ID.
* @param {string} jobId - The job ID.
* @param {string} indexId - The knowledge base ID.
* @returns {Promise<bailian20231229.GetIndexJobStatusResponse>} - The response from Alibaba Cloud Model Studio.
*/
async function getIndexJobStatus(client, workspaceId, jobId, indexId) {
const headers = {};
const req = new bailian20231229.GetIndexJobStatusRequest({ jobId, indexId });
const runtime = new Util.RuntimeOptions({});
return await client.getIndexJobStatusWithOptions(workspaceId, req, headers, runtime);
}
C#/// <summary>
/// Query the status of an index job.
/// </summary>
/// <param name="client">The client object.</param>
/// <param name="workspaceId">The workspace ID.</param>
/// <param name="jobId">The job ID.</param>
/// <param name="indexId">The knowledge base ID.</param>
/// <returns>The response object from Alibaba Cloud Model Studio.</returns>
/// <exception cref="Exception">An exception is thrown if an error occurs during the call.</exception>
public AlibabaCloud.SDK.Bailian20231229.Models.GetIndexJobStatusResponse GetIndexJobStatus(
AlibabaCloud.SDK.Bailian20231229.Client client,
string workspaceId,
string jobId,
string indexId)
{
var headers = new Dictionary<string, string>() { };
var getIndexJobStatusRequest = new AlibabaCloud.SDK.Bailian20231229.Models.GetIndexJobStatusRequest
{
IndexId = indexId,
JobId = jobId
};
var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
return client.GetIndexJobStatusWithOptions(workspaceId, getIndexJobStatusRequest, headers, runtime);
}
Go// GetIndexJobStatus queries the status of an index job.
//
// Parameters:
// - client (bailian20231229.Client): The client.
// - workspaceId (string): The workspace ID.
// - jobId (string): The job ID.
// - indexId (string): The knowledge base ID.
//
// Returns:
// - *bailian20231229.GetIndexJobStatusResponse: The response from Alibaba Cloud Model Studio.
// - error: The error message.
func GetIndexJobStatus(client *bailian20231229.Client, workspaceId, jobId, indexId string) (_result *bailian20231229.GetIndexJobStatusResponse, _err error) {
headers := make(map[string]*string)
getIndexJobStatusRequest := &bailian20231229.GetIndexJobStatusRequest{
JobId: tea.String(jobId),
IndexId: tea.String(indexId),
}
runtime := &util.RuntimeOptions{}
return client.GetIndexJobStatusWithOptions(tea.String(workspaceId), getIndexJobStatusRequest, headers, runtime)
}
Contoh permintaan {
"IndexId": "mymxbdxxxx",
"JobId": "3cd6fb57aaf44cd0b4dd2ca584xxxxxx",
"WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}
Contoh respons {
"Status": "200",
"Message": "success",
"RequestId": "E83423B9-7D6D-5283-836B-CF7EAEXXXXXX",
"Data": {
"Status": "COMPLETED",
"Documents": [
{
"Status": "FINISH",
"DocId": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
"Message": "Imported successfully.",
"DocName": "Alibaba Cloud Model Studio Product Overview",
"Code": "FINISH"
}
],
"JobId": "3cd6fb57aaf44cd0b4dd2ca584xxxxxx"
},
"Code": "Success",
"Success": "true"
}
|