1. 初始化用戶端在開始上傳檔案和建立知識庫之前,您需要使用配置好的AccessKey和AccessKey Secret初始化用戶端(Client),以完成身分識別驗證和存取點endpoint配置。 公網接入地址: 請確保您的用戶端可以訪問公網。 VPC接入地址: 若您的用戶端部署在阿里雲新加坡地區ap-southeast-1(公用雲端),且處於VPC網路環境中,可以使用以下VPC接入地址(不支援跨地區訪問)。
建立完成後,您將得到一個Client對象,用於後續的 API 呼叫。 | Pythondef create_client() -> bailian20231229Client:
"""
建立並配置用戶端(Client)。
返回:
bailian20231229Client: 配置好的用戶端(Client)。
"""
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')
)
# 下方接入地址以公用雲端的公網接入地址為例,可按需更換接入地址。
config.endpoint = 'bailian.ap-southeast-1.aliyuncs.com'
return bailian20231229Client(config)
Java/**
* 初始化用戶端(Client)。
*
* @return 配置好的用戶端對象
*/
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"));
// 下方接入地址以公用雲端的公網接入地址為例,可按需更換接入地址。
config.endpoint = "bailian-vpc.ap-southeast-1.aliyuncs.com";
return new com.aliyun.bailian20231229.Client(config);
}
PHP/**
* 初始化用戶端(Client)。
*
* @return Bailian 配置好的用戶端對象(Client)。
*/
public static function createClient(){
$config = new Config([
"accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
"accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
]);
// 下方接入地址以公用雲端的公網接入地址為例,可按需更換接入地址。
$config->endpoint = 'bailian-vpc.ap-southeast-1.aliyuncs.com';
return new Bailian($config);
}
Node.js/**
* 建立並配置用戶端(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
});
// 下方接入地址以公用雲端的公網接入地址為例,可按需更換接入地址
config.endpoint = `bailian-vpc.ap-southeast-1.aliyuncs.com`;
return new bailian20231229.default(config);
}
C#/// <summary>
/// 初始化用戶端(Client)。
/// </summary>
/// <returns>配置好的用戶端對象</returns>
/// <exception cref="Exception">初始化過程中發生錯誤時拋出異常</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"),
};
// 下方接入地址以公用雲端的公網接入地址為例,可按需更換接入地址.
config.Endpoint = "bailian-vpc.ap-southeast-1.aliyuncs.com";
return new AlibabaCloud.SDK.Bailian20231229.Client(config);
}
Go// CreateClient 建立並配置用戶端(Client)。
//
// 返回:
// - *client.Bailian20231229Client: 配置好的用戶端(Client)。
// - error: 錯誤資訊。
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")),
}
// 下方接入地址以公用雲端的公網接入地址為例,可按需更換接入地址。
config.Endpoint = tea.String("bailian-vpc.ap-southeast-1.aliyuncs.com")
_result = &bailian20231229.Client{}
_result, _err = bailian20231229.NewClient(config)
return _result, _err
}
|
2. 上傳知識庫檔案 |
2.1. 申請檔案上傳租約在建立知識庫前,您需先將檔案上傳至同一業務空間,作為知識庫的知識來源。上傳檔案前,需調用ApplyFileUploadLease介面申請一個檔案上傳租約。該租約是一個臨時的授權,允許您在限定時間內(有效期間為分鐘級)上傳檔案。 workspace_id:如何擷取業務空間ID category_id:本樣本中,請傳入default。阿里雲百鍊使用類目管理您上傳的檔案,系統會自動建立一個預設類目。您亦可調用AddCategory介面建立新類目,並擷取對應的category_id。 file_name:請傳入上傳檔案的名稱(包括尾碼)。其值必須與實際檔案名稱一致。例如,上傳圖中的檔案時,請傳入阿里雲百鍊系列手機產品介紹.docx。 
file_md5:請傳入上傳檔案的MD5值(但當前阿里雲不對該值進行校正,便於您使用URL地址上傳檔案)。 以Python為例,MD5值可使用hashlib模組擷取。其他語言請參見完整範例程式碼。 程式碼範例 import hashlib
def calculate_md5(file_path):
"""
計算檔案的MD5值。
參數:
file_path (str): 檔案本地路徑。
返回:
str: 檔案的MD5值。
"""
md5_hash = hashlib.md5()
# 以二進位形式讀取檔案
with open(file_path, "rb") as f:
# 按塊讀取檔案,避免大檔案佔用過多記憶體
for chunk in iter(lambda: f.read(4096), b""):
md5_hash.update(chunk)
return md5_hash.hexdigest()
# 使用樣本
file_path = "請替換為您需要上傳檔案的實際本地路徑,例如/xxx/xxx/xxx/阿里雲百鍊系列手機產品介紹.docx"
md5_value = calculate_md5(file_path)
print(f"檔案的MD5值為: {md5_value}")
將代碼中的file_path變數替換為檔案的實際本地路徑後運行,即可擷取目標檔案的MD5值(下方為樣本值): 檔案的MD5值為: 2ef7361ea907f3a1b91e3b9936f5643a
file_size:請傳入上傳檔案的位元組大小。 以Python為例,該值可使用os模組擷取。其他語言請參見完整範例程式碼。 程式碼範例 import os
def get_file_size(file_path: str) -> int:
"""
擷取檔案的位元組大小(以位元組為單位)。
參數:
file_path (str): 檔案的實際本地路徑。
返回:
int: 檔案大小(以位元組為單位)。
"""
return os.path.getsize(file_path)
# 使用樣本
file_path = "請替換為您需要上傳檔案的實際本地路徑,例如/xxx/xxx/xxx/阿里雲百鍊系列手機產品介紹.docx"
file_size = get_file_size(file_path)
print(f"檔案的位元組大小為: {file_size}")
將代碼中的file_path變數替換為檔案的實際本地路徑後運行,即可擷取目標檔案的位元組大小(下方為樣本值): 檔案的位元組大小為: 14015
申請臨時上傳租約成功後,您將獲得: 一組臨時上傳參數: 一個臨時上傳URL:Data.Param.Url
您將在下一步中用到它們。 | Pythondef apply_lease(client, category_id, file_name, file_md5, file_size, workspace_id):
"""
從阿里雲百鍊服務申請檔案上傳租約。
參數:
client (bailian20231229Client): 用戶端(Client)。
category_id (str): 類目ID。
file_name (str): 檔案名稱。
file_md5 (str): 檔案的MD5值。
file_size (int): 檔案大小(以位元組為單位)。
workspace_id (str): 業務空間ID。
返回:
阿里雲百鍊服務的響應。
"""
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/**
* 申請檔案上傳租約。
*
* @param client 用戶端對象
* @param categoryId 類目ID
* @param fileName 檔案名稱
* @param fileMd5 檔案的MD5值
* @param fileSize 檔案大小(以位元組為單位)
* @param workspaceId 業務空間ID
* @return 阿里雲百鍊服務的響應對象
*/
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/**
* 申請檔案上傳租約。
*
* @param Bailian $client 用戶端(Client)。
* @param string $categoryId 類目ID。
* @param string $fileName 檔案名稱。
* @param string $fileMd5 檔案的MD5值。
* @param int $fileSize 檔案大小(以位元組為單位)。
* @param string $workspaceId 業務空間ID。
* @return ApplyFileUploadLeaseResponse 阿里雲百鍊服務的響應。
*/
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/**
* 申請檔案上傳租約
* @param {Bailian20231229Client} client - 用戶端(Client)
* @param {string} categoryId - 類目ID
* @param {string} fileName - 檔案名稱
* @param {string} fileMd5 - 檔案的MD5值
* @param {string} fileSize - 檔案大小(以位元組為單位)
* @param {string} workspaceId - 業務空間ID
* @returns {Promise<bailian20231229.ApplyFileUploadLeaseResponse>} - 阿里雲百鍊服務的響應
*/
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>
/// 申請檔案上傳租約。
/// </summary>
/// <param name="client">用戶端對象</param>
/// <param name="categoryId">類目ID</param>
/// <param name="fileName">檔案名稱</param>
/// <param name="fileMd5">檔案的MD5值</param>
/// <param name="fileSize">檔案大小(以位元組為單位)</param>
/// <param name="workspaceId">業務空間ID</param>
/// <returns>阿里雲百鍊服務的響應對象</returns>
/// <exception cref="Exception">調用過程中發生錯誤時拋出異常</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 從阿里雲百鍊服務申請檔案上傳租約。
//
// 參數:
// - client (bailian20231229.Client): 用戶端(Client)。
// - categoryId (string): 類目ID。
// - fileName (string): 檔案名稱。
// - fileMD5 (string): 檔案的MD5值。
// - fileSize (string): 檔案大小(以位元組為單位)。
// - workspaceId (string): 業務空間ID。
//
// 返回:
// - *bailian20231229.ApplyFileUploadLeaseResponse: 阿里雲百鍊服務的響應。
// - error: 錯誤資訊。
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)
}
請求樣本 {
"CategoryId": "default",
"FileName": "阿里雲百鍊系列手機產品介紹.docx",
"Md5": "2ef7361ea907f3a1b91e3b9936f5643a",
"SizeInBytes": "14015",
"WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}
響應樣本 {
"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. 上傳檔案到臨時儲存取得上傳租約後,您即可使用租約中的臨時上傳參數和臨時上傳URL,將本機存放區或可通過公網訪問的檔案上傳至阿里雲百鍊伺服器。請注意,每個業務空間最多支援1萬個檔案。目前支援上傳的格式包括:PDF、DOCX、DOC、TXT、Markdown、PPTX、PPT、XLSX、XLS、HTML、PNG、JPG、JPEG、BMP 和 GIF。 |
重要 本樣本不支援線上調試和多語言範例程式碼產生。 本地上傳Pythonimport requests
from urllib.parse import urlparse
def upload_file(pre_signed_url, file_path):
"""
將本地檔案上傳至臨時儲存。
參數:
pre_signed_url (str): 上傳租約中的URL。
file_path (str): 檔案本地路徑。
返回:
阿里雲百鍊服務的響應。
"""
try:
# 佈建要求頭
headers = {
"X-bailian-extra": "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中X-bailian-extra欄位的值",
"Content-Type": "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中Content-Type欄位的值(返回空值時,傳空值即可)"
}
# 讀取檔案並上傳
with open(file_path, 'rb') as file:
# 下方佈建要求方法用於檔案上傳,需與您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param中Method欄位的值一致
response = requests.put(pre_signed_url, data=file, headers=headers)
# 檢查響應狀態代碼
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 = "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param中Url欄位的值"
# 將本地檔案上傳至臨時儲存
file_path = "請替換為您需要上傳檔案的實際本地路徑(以Linux為例:/xxx/xxx/阿里雲百鍊系列手機產品介紹.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 {
// 建立URL對象
URL url = new URL(preSignedUrl);
connection = (HttpURLConnection) url.openConnection();
// 佈建要求方法用於檔案上傳,需與您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param中Method欄位的值一致
connection.setRequestMethod("PUT");
// 允許向connection輸出,因為這個串連是用於上傳檔案的
connection.setDoOutput(true);
connection.setRequestProperty("X-bailian-extra", "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中X-bailian-extra欄位的值");
connection.setRequestProperty("Content-Type", "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中Content-Type欄位的值(返回空值時,傳空值即可)");
// 讀取檔案並通過串連上傳
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();
}
// 檢查響應
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 檔案上傳成功處理
System.out.println("File uploaded successfully.");
} else {
// 檔案上傳失敗處理
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 = "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param中Url欄位的值";
// 將本地檔案上傳至臨時儲存
String filePath = "請替換為您需要上傳檔案的實際本地路徑(以Linux為例:/xxx/xxx/阿里雲百鍊系列手機產品介紹.docx)";
uploadFile(preSignedUrlOrHttpUrl, filePath);
}
}
PHP<?php
/**
* 將本地檔案上傳至臨時儲存
*
* @param string $preSignedUrl 從 ApplyFileUploadLease 介面擷取的預簽名 URL 或 HTTP 地址
* @param array $headers 包含 "X-bailian-extra" 和 "Content-Type" 的要求標頭數組
* @param string $filePath 本地檔案路徑
* @throws Exception 如果上傳失敗
*/
function uploadFile($preSignedUrl, $headers, $filePath) {
// 讀取檔案內容
$fileContent = file_get_contents($filePath);
if ($fileContent === false) {
throw new Exception("無法讀取檔案: " . $filePath);
}
// 初始化 cURL 會話
$ch = curl_init();
// 設定 cURL 選項
curl_setopt($ch, CURLOPT_URL, $preSignedUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); // 使用 PUT 方法
curl_setopt($ch, CURLOPT_POSTFIELDS, $fileContent); // 佈建要求體為檔案內容
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返迴響應結果而不是直接輸出
// 構建要求標頭
$uploadHeaders = [
"X-bailian-extra: " . $headers["X-bailian-extra"],
"Content-Type: " . $headers["Content-Type"]
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $uploadHeaders);
// 執行請求
$response = curl_exec($ch);
// 擷取 HTTP 響應碼
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 關閉 cURL 會話
curl_close($ch);
// 檢查響應碼
if ($httpCode != 200) {
throw new Exception("上傳失敗,HTTP 狀態代碼: " . $httpCode . ",錯誤資訊: " . $response);
}
// 上傳成功
echo "File uploaded successfully.\n";
}
/**
* 主函數:本地檔案上傳
*/
function main() {
// 請替換為您在上一步中調用 ApplyFileUploadLease 介面實際返回的 Data.Param 中 Url 欄位的值
$preSignedUrl = "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param中Url欄位的值";
// 請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中的 X-bailian-extra 和 Content-Type
$headers = [
"X-bailian-extra" => "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中X-bailian-extra欄位的值",
"Content-Type" => "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中Content-Type欄位的值(返回空值時,傳空值即可)"
];
// 將本地檔案上傳至臨時儲存
$filePath = "請替換為您需要上傳檔案的實際本地路徑(以Linux為例:/xxx/xxx/阿里雲百鍊系列手機產品介紹.docx)";
try {
uploadFile($preSignedUrl, $headers, $filePath);
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
}
// 調用主函數
main();
?>
Node.jsconst fs = require('fs');
const axios = require('axios');
/**
* 將本地檔案上傳至臨時儲存
*
* @param {string} preSignedUrl - 上傳租約中的URL
* @param {Object} headers - 上傳請求的頭部
* @param {string} filePath - 檔案本地路徑
* @throws {Error} 如果上傳失敗
*/
async function uploadFile(preSignedUrl, headers, filePath) {
// 構建上傳所需的要求標頭
const uploadHeaders = {
"X-bailian-extra": headers["X-bailian-extra"],
"Content-Type": headers["Content-Type"]
};
// 建立檔案讀取流
const fileStream = fs.createReadStream(filePath);
try {
// 使用 axios 發送 PUT 請求
const response = await axios.put(preSignedUrl, fileStream, {
headers: uploadHeaders
});
// 檢查響應狀態代碼
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) {
// 處理錯誤
console.error("Error during upload:", error.message);
throw new Error(`上傳失敗: ${error.message}`);
}
}
/**
* 主函數:本地檔案上傳
*/
function main() {
const preSignedUrl = "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param中Url欄位的值";
const headers = {
"X-bailian-extra": "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中X-bailian-extra欄位的值",
"Content-Type": "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中Content-Type欄位的值(返回空值時,傳空值即可)"
};
// 將本地檔案上傳至臨時儲存
const filePath = "請替換為您需要上傳檔案的實際本地路徑(以Linux為例:/xxx/xxx/阿里雲百鍊系列手機產品介紹.docx)";
uploadFile(preSignedUrl, headers, filePath)
.then(() => {
console.log("Upload completed.");
})
.catch((err) => {
console.error("Upload failed:", err.message);
});
}
// 調用主函數
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
{
// 建立 URL 對象
Uri url = new Uri(preSignedUrl);
connection = (HttpWebRequest)WebRequest.Create(url);
// 佈建要求方法用於檔案上傳,需與您在上一步中調用 ApplyFileUploadLease 介面實際返回的 Data.Param 中 Method 欄位的值一致
connection.Method = "PUT";
// 允許向 connection 輸出,因為這個串連是用於上傳檔案的
connection.AllowWriteStreamBuffering = false;
connection.SendChunked = false;
// 佈建要求頭,需與您在上一步中調用 ApplyFileUploadLease 介面實際返回的 Data.Param.Headers 中的欄位值一致
connection.Headers["X-bailian-extra"] = "請替換為您在上一步中調用 ApplyFileUploadLease 介面實際返回的 Data.Param.Headers 中 X-bailian-extra 欄位的值";
connection.ContentType = "請替換為您在上一步中調用 ApplyFileUploadLease 介面實際返回的 Data.Param.Headers 中 Content-Type 欄位的值(返回空值時,傳空值即可)";
// 讀取檔案並通過串連上傳
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();
}
// 檢查響應
using (HttpWebResponse response = (HttpWebResponse)connection.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
// 檔案上傳成功處理
Console.WriteLine("File uploaded successfully.");
}
else
{
// 檔案上傳失敗處理
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 = "請替換為您在上一步中調用 ApplyFileUploadLease 介面實際返回的 Data.Param 中 Url 欄位的值";
// 將本地檔案上傳至臨時儲存
string filePath = "請替換為您需要上傳檔案的實際本地路徑(以Linux為例:/xxx/xxx/阿里雲百鍊系列手機產品介紹.docx)";
UploadFile(preSignedUrlOrHttpUrl, filePath);
}
}
Gopackage main
import (
"fmt"
"io"
"os"
"github.com/go-resty/resty/v2"
)
// UploadFile 將本地檔案上傳至臨時儲存。
//
// 參數:
// - preSignedUrl (string): 上傳租約中的 URL。
// - headers (map[string]string): 上傳請求的頭部。
// - filePath (string): 檔案本地路徑。
//
// 返回:
// - error: 如果上傳失敗返回錯誤資訊,否則返回 nil
func UploadFile(preSignedUrl string, headers map[string]string, filePath string) error {
// 開啟本地檔案
file, err := os.Open(filePath)
if err != nil {
return fmt.Errorf("開啟檔案失敗: %w", err)
}
defer file.Close()
// 讀取內容
body, err := io.ReadAll(file)
if err != nil {
return fmt.Errorf("讀取檔案失敗: %w", err)
}
// 建立 REST 用戶端
client := resty.New()
// 構建上傳所需的要求標頭
uploadHeaders := map[string]string{
"X-bailian-extra": headers["X-bailian-extra"],
"Content-Type": headers["Content-Type"],
}
// 發送 PUT 請求
resp, err := client.R().
SetHeaders(uploadHeaders).
SetBody(body).
Put(preSignedUrl)
if err != nil {
return fmt.Errorf("發送請求失敗: %w", err)
}
// 檢查 HTTP 響應狀態代碼
if resp.IsError() {
return fmt.Errorf("HTTP 錯誤: %d", resp.StatusCode())
}
fmt.Println("File uploaded successfully.")
return nil
}
// main 主函數
func main() {
// 請替換為您在上一步中調用 ApplyFileUploadLease 介面實際返回的 Data.Param 中 Url 欄位的值
preSignedUrl := "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param中Url欄位的值"
// 請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中的 X-bailian-extra 和 Content-Type
headers := map[string]string{
"X-bailian-extra": "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中X-bailian-extra欄位的值",
"Content-Type": "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中Content-Type欄位的值(返回空值時,傳空值即可)",
}
// 將本地檔案上傳至臨時儲存
filePath := "請替換為您需要上傳檔案的實際本地路徑(以Linux為例:/xxx/xxx/阿里雲百鍊系列手機產品介紹.docx)"
// 調用上傳函數
err := UploadFile(preSignedUrl, headers, filePath)
if err != nil {
fmt.Printf("上傳失敗: %v\n", err)
}
}
URL地址上傳請確保URL公開可訪問且指向一個有效檔案。 Pythonimport requests
from urllib.parse import urlparse
def upload_file_link(pre_signed_url, source_url_string):
"""
將可通過公網訪問的檔案上傳至臨時儲存。
參數:
pre_signed_url (str): 上傳租約中的 URL。
source_url_string (str): 檔案的URL地址。
返回:
阿里雲百鍊服務的響應。
"""
try:
# 佈建要求頭
headers = {
"X-bailian-extra": "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中X-bailian-extra欄位的值",
"Content-Type": "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中Content-Type欄位的值(返回空值時,傳空值即可)"
}
# 設定訪問檔案URL地址的要求方法為GET
source_response = requests.get(source_url_string)
if source_response.status_code != 200:
raise RuntimeError("Failed to get source file.")
# 下方佈建要求方法用於檔案上傳,需與您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param中Method欄位的值一致
response = requests.put(pre_signed_url, data=source_response.content, headers=headers)
# 檢查響應狀態代碼
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 = "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param中Url欄位的值(返回空值時,傳空值即可)"
# 檔案的URL地址
source_url = "請替換為您需要上傳檔案的URL地址"
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 {
// 建立URL對象
URL url = new URL(preSignedUrl);
connection = (HttpURLConnection) url.openConnection();
// 佈建要求方法用於檔案上傳,需與您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param中Method欄位的值一致
connection.setRequestMethod("PUT");
// 允許向connection輸出,因為這個串連是用於上傳檔案的
connection.setDoOutput(true);
connection.setRequestProperty("X-bailian-extra", "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中X-bailian-extra欄位的值");
connection.setRequestProperty("Content-Type", "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中Content-Type欄位的值(返回空值時,傳空值即可)");
URL sourceUrl = new URL(sourceUrlString);
HttpURLConnection sourceConnection = (HttpURLConnection) sourceUrl.openConnection();
// 設定訪問檔案URL地址的要求方法為GET
sourceConnection.setRequestMethod("GET");
// 擷取響應碼,200表示請求成功
int sourceFileResponseCode = sourceConnection.getResponseCode();
// 從URL地址讀取檔案並通過串連上傳
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();
}
// 檢查響應
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 檔案上傳成功
System.out.println("File uploaded successfully.");
} else {
// 檔案上傳失敗
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 = "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param中Url欄位的值";
String sourceUrl = "請替換為您需要上傳檔案的URL地址";
uploadFileLink(preSignedUrlOrHttpUrl, sourceUrl);
}
}
PHP<?php
/**
* 將可通過公網訪問的檔案上傳至臨時儲存
*
* @param string $preSignedUrl 從 ApplyFileUploadLease 介面擷取的預簽名 URL 或 HTTP 地址
* @param array $headers 包含 "X-bailian-extra" 和 "Content-Type" 的要求標頭數組
* @param string $sourceUrl 檔案的URL地址
* @throws Exception 如果上傳失敗
*/
function uploadFile($preSignedUrl, $headers, $sourceUrl) {
$fileContent = file_get_contents($sourceUrl);
if ($fileContent === false) {
throw new Exception("無法從給定的URL地址下載檔案: " . $sourceUrl);
}
// 初始化 cURL 會話
$ch = curl_init();
// 設定 cURL 選項
curl_setopt($ch, CURLOPT_URL, $preSignedUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); // 使用 PUT 方法
curl_setopt($ch, CURLOPT_POSTFIELDS, $fileContent); // 佈建要求體為檔案內容
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返迴響應結果而不是直接輸出
// 構建要求標頭
$uploadHeaders = [
"X-bailian-extra: " . $headers["X-bailian-extra"],
"Content-Type: " . $headers["Content-Type"]
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $uploadHeaders);
// 執行請求
$response = curl_exec($ch);
// 擷取 HTTP 響應碼
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 關閉 cURL 會話
curl_close($ch);
// 檢查響應碼
if ($httpCode != 200) {
throw new Exception("上傳失敗,HTTP 狀態代碼: " . $httpCode . ",錯誤資訊: " . $response);
}
// 上傳成功
echo "File uploaded successfully.\n";
}
/**
* 主函數:將可通過公網訪問的檔案上傳至臨時儲存
*/
function main() {
// 請替換為您在上一步中調用 ApplyFileUploadLease 介面實際返回的 Data.Param 中 Url 欄位的值
$preSignedUrl = "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param中Url欄位的值";
// 請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中的 X-bailian-extra 和 Content-Type
$headers = [
"X-bailian-extra" => "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中X-bailian-extra欄位的值",
"Content-Type" => "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中Content-Type欄位的值(返回空值時,傳空值即可)"
];
$sourceUrl = "請替換為您需要上傳檔案的URL地址";
try {
uploadFile($preSignedUrl, $headers, $sourceUrl);
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
}
// 調用主函數
main();
?>
Node.jsconst axios = require('axios');
/**
* 將可通過公網訪問的檔案上傳至臨時儲存
*
* @param {string} preSignedUrl - 上傳租約中的URL
* @param {Object} headers - 上傳請求的頭部
* @param {string} sourceUrl - 檔案的URL地址
* @throws {Error} 如果上傳失敗
*/
async function uploadFileFromUrl(preSignedUrl, headers, sourceUrl) {
// 構建上傳所需的要求標頭
const uploadHeaders = {
"X-bailian-extra": headers["X-bailian-extra"],
"Content-Type": headers["Content-Type"]
};
try {
// 從給定的URL地址下載檔案
const response = await axios.get(sourceUrl, {
responseType: 'stream'
});
// 使用 axios 發送 PUT 請求
const uploadResponse = await axios.put(preSignedUrl, response.data, {
headers: uploadHeaders
});
// 檢查響應狀態代碼
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) {
// 處理錯誤
console.error("Error during upload:", error.message);
throw new Error(`上傳失敗: ${error.message}`);
}
}
/**
* 主函數:將一個可公開直接下載的檔案上傳到臨時儲存
*/
function main() {
const preSignedUrl = "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param中Url欄位的值";
const headers = {
"X-bailian-extra": "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中X-bailian-extra欄位的值",
"Content-Type": "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中Content-Type欄位的值(返回空值時,傳空值即可)"
};
const sourceUrl = "請替換為您需要上傳檔案的URL地址";
uploadFileFromUrl(preSignedUrl, headers, sourceUrl)
.then(() => {
console.log("Upload completed.");
})
.catch((err) => {
console.error("Upload failed:", err.message);
});
}
// 調用主函數
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
{
// 建立 HTTP 用戶端從給定的URL地址下載檔案
using (HttpClient httpClient = new HttpClient())
{
HttpResponseMessage response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
response.EnsureSuccessStatusCode();
// 擷取檔案流
using (Stream fileStream = await response.Content.ReadAsStreamAsync())
{
// 建立 URL 對象
Uri urlObj = new Uri(preSignedUrl);
HttpWebRequest connection = (HttpWebRequest)WebRequest.Create(urlObj);
// 佈建要求方法用於檔案上傳
connection.Method = "PUT";
connection.AllowWriteStreamBuffering = false;
connection.SendChunked = false;
// 佈建要求頭(請替換為實際值)
connection.Headers["X-bailian-extra"] = "請替換為您在上一步中調用 ApplyFileUploadLease 介面實際返回的 Data.Param.Headers 中 X-bailian-extra 欄位的值";
connection.ContentType = "請替換為您在上一步中調用 ApplyFileUploadLease 介面實際返回的 Data.Param.Headers 中 Content-Type 欄位的值(返回空值時,傳空值即可)";
// 擷取請求流並寫入檔案流
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();
}
// 檢查響應
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 = "請替換為您在上一步中調用 ApplyFileUploadLease 介面實際返回的 Data.Param 中 Url 欄位的值";
string url = "請替換為您需要上傳檔案的URL地址";
await UploadFileFromUrl(preSignedUrlOrHttpUrl, url);
}
}
Gopackage main
import (
"fmt"
"net/http"
"github.com/go-resty/resty/v2"
)
// UploadFileFromUrl 將可通過公網訪問的檔案上傳至臨時儲存。
//
// 參數:
// - preSignedUrl (string): 上傳租約中的 URL。
// - headers (map[string]string): 上傳請求的頭部。
// - sourceUrl (string): 檔案的URL地址。
//
// 返回:
// - error: 如果上傳失敗返回錯誤資訊,否則返回 nil
func UploadFileFromUrl(preSignedUrl string, headers map[string]string, sourceUrl string) error {
// 從給定的URL地址下載檔案
resp, err := http.Get(sourceUrl)
if err != nil {
return fmt.Errorf("擷取檔案失敗: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("擷取檔案失敗,狀態代碼: %d", resp.StatusCode)
}
// 建立 REST 用戶端
client := resty.New()
// 構建上傳所需的要求標頭
uploadHeaders := map[string]string{
"X-bailian-extra": headers["X-bailian-extra"],
"Content-Type": headers["Content-Type"],
}
// 發送 PUT 請求
response, err := client.R().
SetHeaders(uploadHeaders).
SetBody(resp.Body).
Put(preSignedUrl)
if err != nil {
return fmt.Errorf("發送請求失敗: %w", err)
}
if err != nil {
return fmt.Errorf("發送請求失敗: %w", err)
}
// 檢查 HTTP 響應狀態代碼
if response.IsError() {
return fmt.Errorf("HTTP 錯誤: %d", response.StatusCode())
}
fmt.Println("File uploaded successfully from URL.")
return nil
}
// main 主函數
func main() {
// 請替換為您在上一步中調用 ApplyFileUploadLease 介面實際返回的 Data.Param 中 Url 欄位的值
preSignedUrl := "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param中Url欄位的值"
// 請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中的 X-bailian-extra 和 Content-Type
headers := map[string]string{
"X-bailian-extra": "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中X-bailian-extra欄位的值",
"Content-Type": "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中Content-Type欄位的值(返回空值時,傳空值即可)",
}
sourceUrl := "請替換為您需要上傳檔案的URL地址"
// 調用上傳函數
err := UploadFileFromUrl(preSignedUrl, headers, sourceUrl)
if err != nil {
fmt.Printf("上傳失敗: %v\n", err)
}
}
|
2.3. 添加檔案到類目中阿里雲百鍊使用類目管理您上傳的檔案。因此,接下來您需要調用AddFile介面將已上傳的檔案添加到同一業務空間下的類目中。 parser:請傳入DASHSCOPE_DOCMIND。 lease_id:請傳入申請檔案上傳租約時介面返回的Data.FileUploadLeaseId。 category_id:本樣本中,請傳入default。若您使用了自建類目上傳,則需傳入對應的category_id。
完成添加後,阿里雲百鍊將返回該檔案的FileId,並自動開始解析您的檔案。同時lease_id(租約ID)隨即失效,請勿再使用相同的租約ID重複提交。 | Pythondef add_file(client: bailian20231229Client, lease_id: str, parser: str, category_id: str, workspace_id: str):
"""
將檔案添加到阿里雲百鍊服務的指定類目中。
參數:
client (bailian20231229Client): 用戶端(Client)。
lease_id (str): 租約ID。
parser (str): 用於檔案的解析器。
category_id (str): 類目ID。
workspace_id (str): 業務空間ID。
返回:
阿里雲百鍊服務的響應。
"""
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/**
* 將檔案添加到類目中。
*
* @param client 用戶端對象
* @param leaseId 租約ID
* @param parser 用於檔案的解析器
* @param categoryId 類目ID
* @param workspaceId 業務空間ID
* @return 阿里雲百鍊服務的響應對象
*/
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/**
* 將檔案添加到類目中。
*
* @param Bailian $client 用戶端(Client)。
* @param string $leaseId 租約ID。
* @param string $parser 用於檔案的解析器。
* @param string $categoryId 類目ID。
* @param string $workspaceId 業務空間ID。
* @return AddFileResponse 阿里雲百鍊服務的響應。
*/
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/**
* 添加檔案到類目中
* @param {Bailian20231229Client} client - 用戶端(Client)
* @param {string} leaseId - 租約ID
* @param {string} parser - 用於檔案的解析器
* @param {string} categoryId - 類目ID
* @param {string} workspaceId - 業務空間ID
* @returns {Promise<bailian20231229.AddFileResponse>} - 阿里雲百鍊服務的響應
*/
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>
/// 將檔案添加到類目中。
/// </summary>
/// <param name="client">用戶端對象</param>
/// <param name="leaseId">租約ID</param>
/// <param name="parser">用於檔案的解析器</param>
/// <param name="categoryId">類目ID</param>
/// <param name="workspaceId">業務空間ID</param>
/// <returns>阿里雲百鍊服務的響應對象</returns>
/// <exception cref="Exception">調用過程中發生錯誤時拋出異常</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 將檔案添加到阿里雲百鍊服務的指定類目中。
//
// 參數:
// - client (bailian20231229.Client): 用戶端(Client)。
// - leaseId (string): 租約ID。
// - parser (string): 用於檔案的解析器。
// - categoryId (string): 類目ID。
// - workspaceId (string): 業務空間ID。
//
// 返回:
// - *bailian20231229.AddFileResponse: 阿里雲百鍊服務的響應。
// - error: 錯誤資訊。
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)
}
請求樣本 {
"CategoryId": "default",
"LeaseId": "d92bd94fa9b54326a2547415e100c9e2.1742195250069",
"Parser": "DASHSCOPE_DOCMIND",
"WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}
響應樣本 {
"Status": "200",
"Message": "",
"RequestId": "5832A1F4-AF91-5242-8B75-35BDC9XXXXXX",
"Data": {
"FileId": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
"Parser": "DASHSCOPE_DOCMIND"
},
"Code": "Success",
"Success": "true"
}
|
2.4. 查詢檔案的解析狀態未解析完成的檔案無法用於知識庫,在請求高峰時段,該過程可能需要數小時。您可以調用DescribeFile介面查詢檔案的解析狀態。 當本介面返回的Data.Status欄位值為PARSE_SUCCESS時,表示檔案已解析完成,可以將其匯入知識庫。 | Pythondef describe_file(client, workspace_id, file_id):
"""
擷取檔案的基本資料。
參數:
client (bailian20231229Client): 用戶端(Client)。
workspace_id (str): 業務空間ID。
file_id (str): 檔案ID。
返回:
阿里雲百鍊服務的響應。
"""
headers = {}
runtime = util_models.RuntimeOptions()
return client.describe_file_with_options(workspace_id, file_id, headers, runtime)
Java/**
* 查詢檔案的基本資料。
*
* @param client 用戶端對象
* @param workspaceId 業務空間ID
* @param fileId 檔案ID
* @return 阿里雲百鍊服務的響應對象
*/
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/**
* 查詢檔案的基本資料。
*
* @param Bailian $client 用戶端(Client)。
* @param string $workspaceId 業務空間ID。
* @param string $fileId 檔案ID。
* @return DescribeFileResponse 阿里雲百鍊服務的響應。
*/
public function describeFile($client, $workspaceId, $fileId) {
$headers = [];
$runtime = new RuntimeOptions([]);
return $client->describeFileWithOptions($workspaceId, $fileId, $headers, $runtime);
}
Node.js/**
* 查詢檔案的解析狀態
* @param {Bailian20231229Client} client - 用戶端(Client)
* @param {string} workspaceId - 業務空間ID
* @param {string} fileId - 檔案ID
* @returns {Promise<bailian20231229.DescribeFileResponse>} - 阿里雲百鍊服務的響應
*/
async function describeFile(client, workspaceId, fileId) {
const headers = {};
const runtime = new Util.RuntimeOptions({});
return await client.describeFileWithOptions(workspaceId, fileId, headers, runtime);
}
C#/// <summary>
/// 查詢檔案的基本資料。
/// </summary>
/// <param name="client">用戶端對象</param>
/// <param name="workspaceId">業務空間ID</param>
/// <param name="fileId">檔案ID</param>
/// <returns>阿里雲百鍊服務的響應對象</returns>
/// <exception cref="Exception">調用過程中發生錯誤時拋出異常</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 擷取檔案的基本資料。
//
// 參數:
// - client (bailian20231229.Client): 用戶端(Client)。
// - workspaceId (string): 業務空間ID。
// - fileId (string): 檔案ID。
//
// 返回:
// - any: 阿里雲百鍊服務的響應。
// - error: 錯誤資訊。
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)
}
請求樣本 {
"FileId": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
"WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}
響應樣本 {
"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": "阿里雲百鍊系列手機產品介紹.docx",
"FileId": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
"SizeInBytes": "14015",
"Parser": "DASHSCOPE_DOCMIND"
},
"Code": "Success",
"Success": "true"
}
|
3. 建立知識庫 |
3.1. 初始化知識庫檔案解析完成後,您即可將其匯入同一業務空間下的知識庫。初始化(非最終提交)一個文檔搜尋類知識庫,可以調用CreateIndex介面。 workspace_id:如何擷取業務空間ID file_id:請傳入添加檔案到類目中時介面返回的FileId。 若source_type為DATA_CENTER_FILE,則該參數為必傳,否則介面將報錯。 structure_type:本樣本中,請傳入unstructured。 資料查詢、圖片問答類知識庫不支援通過API建立,請使用阿里雲百鍊控制台建立。 source_type:本樣本中,請傳入DATA_CENTER_FILE。 sink_type:本樣本中,請傳入BUILT_IN。
本介面返回的Data.Id欄位值即為知識庫ID,用於後續的索引構建。 請您妥善保管知識庫ID,後續該知識庫所有相關API操作都將用到它。 | Pythondef create_index(client, workspace_id, file_id, name, structure_type, source_type, sink_type):
"""
在阿里雲百鍊服務中建立知識庫(初始化)。
參數:
client (bailian20231229Client): 用戶端(Client)。
workspace_id (str): 業務空間ID。
file_id (str): 檔案ID。
name (str): 知識庫名稱。
structure_type (str): 知識庫的資料類型。
source_type (str): 應用資料的資料類型,支援類目類型和檔案類型。
sink_type (str): 知識庫的向量儲存類型。
返回:
阿里雲百鍊服務的響應。
"""
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/**
* 在阿里雲百鍊服務中建立知識庫(初始化)。
*
* @param client 用戶端對象
* @param workspaceId 業務空間ID
* @param fileId 檔案ID
* @param name 知識庫名稱
* @param structureType 知識庫的資料類型
* @param sourceType 應用資料的資料類型,支援類目類型和檔案類型
* @param sinkType 知識庫的向量儲存類型
* @return 阿里雲百鍊服務的響應對象
*/
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/**
* 在阿里雲百鍊服務中建立知識庫(初始化)。
*
* @param Bailian $client 用戶端(Client)。
* @param string $workspaceId 業務空間ID。
* @param string $fileId 檔案ID。
* @param string $name 知識庫名稱。
* @param string $structureType 知識庫的資料類型。
* @param string $sourceType 應用資料的資料類型,支援類目類型和檔案類型。
* @param string $sinkType 知識庫的向量儲存類型。
* @return CreateIndexResponse 阿里雲百鍊服務的響應。
*/
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/**
* 初始化知識庫(索引)
* @param {Bailian20231229Client} client - 用戶端(Client)
* @param {string} workspaceId - 業務空間ID
* @param {string} fileId - 檔案ID
* @param {string} name - 知識庫名稱
* @param {string} structureType - 知識庫的資料類型
* @param {string} sourceType - 應用資料的資料類型,支援類目類型和檔案類型
* @param {string} sinkType - 知識庫的向量儲存類型
* @returns {Promise<bailian20231229.CreateIndexResponse>} - 阿里雲百鍊服務的響應
*/
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>
/// 在阿里雲百鍊服務中建立知識庫(初始化)。
/// </summary>
/// <param name="client">用戶端對象</param>
/// <param name="workspaceId">業務空間ID</param>
/// <param name="fileId">檔案ID</param>
/// <param name="name">知識庫名稱</param>
/// <param name="structureType">知識庫的資料類型</param>
/// <param name="sourceType">應用資料的資料類型,支援類目類型和檔案類型</param>
/// <param name="sinkType">知識庫的向量儲存類型</param>
/// <returns>阿里雲百鍊服務的響應對象</returns>
/// <exception cref="Exception">調用過程中發生錯誤時拋出異常</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 在阿里雲百鍊服務中建立知識庫(初始化)。
//
// 參數:
// - client (bailian20231229.Client): 用戶端(Client)。
// - workspaceId (string): 業務空間ID。
// - fileId (string): 檔案ID。
// - name (string): 知識庫名稱。
// - structureType (string): 知識庫的資料類型。
// - sourceType (string): 應用資料的資料類型,支援類目類型和檔案類型。
// - sinkType (string): 知識庫的向量儲存類型。
//
// 返回:
// - *bailian20231229.CreateIndexResponse: 阿里雲百鍊服務的響應。
// - error: 錯誤資訊。
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)
}
請求樣本 {
"Name": "阿里雲百鍊手機知識庫",
"SinkType": "BUILT_IN",
"SourceType": "DATA_CENTER_FILE",
"StructureType": "unstructured",
"WorkspaceId": "llm-4u5xpd1xdjqpxxxx",
"DocumentIds": [
"file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx"
]
}
響應樣本 {
"Status": "200",
"Message": "success",
"RequestId": "87CB0999-F1BB-5290-8C79-A875B2XXXXXX",
"Data": {
"Id": "mymxbdxxxx"
},
"Code": "Success",
"Success": "true"
}
|
3.2. 提交索引任務初始化知識庫後,您需要調用SubmitIndexJob介面提交索引任務,以啟動知識庫的索引構建。 完成提交後,阿里雲百鍊隨即以非同步任務方式開始構建索引。本介面返回的Data.Id為對應的任務ID。下一步中,您將用到此ID查詢任務的最新狀態。 | Pythondef submit_index(client, workspace_id, index_id):
"""
向阿里雲百鍊服務提交索引任務。
參數:
client (bailian20231229Client): 用戶端(Client)。
workspace_id (str): 業務空間ID。
index_id (str): 知識庫ID。
返回:
阿里雲百鍊服務的響應。
"""
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/**
* 向阿里雲百鍊服務提交索引任務。
*
* @param client 用戶端對象
* @param workspaceId 業務空間ID
* @param indexId 知識庫ID
* @return 阿里雲百鍊服務的響應對象
*/
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/**
* 向阿里雲百鍊服務提交索引任務。
*
* @param Bailian $client 用戶端(Client)。
* @param string $workspaceId 業務空間ID。
* @param string $indexId 知識庫ID。
* @return SubmitIndexJobResponse 阿里雲百鍊服務的響應。
*/
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/**
* 提交索引任務
* @param {Bailian20231229Client} client - 用戶端(Client)
* @param {string} workspaceId - 業務空間ID
* @param {string} indexId - 知識庫ID
* @returns {Promise<bailian20231229.SubmitIndexJobResponse>} - 阿里雲百鍊服務的響應
*/
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>
/// 向阿里雲百鍊服務提交索引任務。
/// </summary>
/// <param name="client">用戶端對象</param>
/// <param name="workspaceId">業務空間ID</param>
/// <param name="indexId">知識庫ID</param>
/// <returns>阿里雲百鍊服務的響應對象</returns>
/// <exception cref="Exception">調用過程中發生錯誤時拋出異常</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 提交索引任務。
//
// 參數:
// - client (bailian20231229.Client): 用戶端(Client)。
// - workspaceId (string): 業務空間ID。
// - indexId (string): 知識庫ID。
//
// 返回:
// - *bailian20231229.SubmitIndexJobResponse: 阿里雲百鍊服務的響應。
// - error: 錯誤資訊。
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)
}
請求樣本 {
"IndexId": "mymxbdxxxx",
"WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}
響應樣本 {
"Status": "200",
"Message": "success",
"RequestId": "7774575F-571D-5854-82C2-634AB8XXXXXX",
"Data": {
"IndexId": "mymxbdxxxx",
"Id": "3cd6fb57aaf44cd0b4dd2ca584xxxxxx"
},
"Code": "Success",
"Success": "true"
}
|
3.3. 等待索引任務完成索引任務的執行需要一定時間,在請求高峰時段,該過程可能需要數小時。查詢其執行狀態可以調用GetIndexJobStatus介面。 當本介面返回的Data.Status欄位值為COMPLETED時,表示知識庫已建立完成。 | Pythondef get_index_job_status(client, workspace_id, index_id, job_id):
"""
查詢索引任務狀態。
參數:
client (bailian20231229Client): 用戶端(Client)。
workspace_id (str): 業務空間ID。
index_id (str): 知識庫ID。
job_id (str): 任務ID。
返回:
阿里雲百鍊服務的響應。
"""
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/**
* 查詢索引任務狀態。
*
* @param client 用戶端對象
* @param workspaceId 業務空間ID
* @param jobId 任務ID
* @param indexId 知識庫ID
* @return 阿里雲百鍊服務的響應對象
*/
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/**
* 查詢索引任務狀態。
*
* @param Bailian $client 用戶端(Client)。
* @param string $workspaceId 業務空間ID。
* @param string $indexId 知識庫ID。
* @param string $jobId 任務ID。
* @return GetIndexJobStatusResponse 阿里雲百鍊服務的響應。
*/
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/**
* 查詢索引任務狀態
* @param {Bailian20231229Client} client - 用戶端(Client)
* @param {string} workspaceId - 業務空間ID
* @param {string} jobId - 任務ID
* @param {string} indexId - 知識庫ID
* @returns {Promise<bailian20231229.GetIndexJobStatusResponse>} - 阿里雲百鍊服務的響應
*/
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>
/// 查詢索引任務狀態。
/// </summary>
/// <param name="client">用戶端對象</param>
/// <param name="workspaceId">業務空間ID</param>
/// <param name="jobId">任務ID</param>
/// <param name="indexId">知識庫ID</param>
/// <returns>阿里雲百鍊服務的響應對象</returns>
/// <exception cref="Exception">調用過程中發生錯誤時拋出異常</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 查詢索引任務狀態。
//
// 參數:
// - client (bailian20231229.Client): 用戶端(Client)。
// - workspaceId (string): 業務空間ID。
// - jobId (string): 任務ID。
// - indexId (string): 知識庫ID。
//
// 返回:
// - *bailian20231229.GetIndexJobStatusResponse: 阿里雲百鍊服務的響應。
// - error: 錯誤資訊。
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)
}
請求樣本 {
"IndexId": "mymxbdxxxx",
"JobId": "3cd6fb57aaf44cd0b4dd2ca584xxxxxx",
"WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}
響應樣本 {
"Status": "200",
"Message": "success",
"RequestId": "E83423B9-7D6D-5283-836B-CF7EAEXXXXXX",
"Data": {
"Status": "COMPLETED",
"Documents": [
{
"Status": "FINISH",
"DocId": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
"Message": "匯入成功",
"DocName": "阿里雲百鍊系列手機產品介紹",
"Code": "FINISH"
}
],
"JobId": "3cd6fb57aaf44cd0b4dd2ca584xxxxxx"
},
"Code": "Success",
"Success": "true"
}
|