阿里雲百鍊知識庫提供開放的API介面,便於您快速接入現有業務系統,實現自動化操作,並應對複雜的檢索需求。
重要知識庫相關功能僅能在中國站華北2(北京)地區開通和使用,其他地區如新加坡、德國(法蘭克福)等均不支援知識庫功能。
前置步驟
-
子帳號(主帳號不需要)需擷取API許可權(AliyunBailianDataFullAccess策略),並加入一個業務空間,然後才能通過阿里雲API操作知識庫。
子帳號只能操作已加入業務空間中的知識庫;主帳號可操作所有業務空間下的知識庫。
-
安裝最新版阿里雲百鍊SDK,以調用知識庫相關的阿里雲API。如何安裝請參考阿里雲SDK開發參考目錄下文檔。
-
擷取AccessKey和AccessKey Secret以及業務空間 ID,並將它們配置到系統內容變數,以運行範例程式碼。以Linux作業系統為例:
如果您使用了 IDE 或其他輔助開發外掛程式,需自行將ALIBABA_CLOUD_ACCESS_KEY_ID、ALIBABA_CLOUD_ACCESS_KEY_SECRET和WORKSPACE_ID變數配置到相應的開發環境中。
export ALIBABA_CLOUD_ACCESS_KEY_ID='您的阿里雲存取金鑰ID'
export ALIBABA_CLOUD_ACCESS_KEY_SECRET='您的阿里雲存取金鑰密碼'
export WORKSPACE_ID='您的阿里雲百鍊業務空間ID'
- 準備好樣本知識文檔阿里雲百鍊系列手機產品介紹.docx,用於建立知識庫。
完整範例程式碼
建立知識庫
重要
- 在調用本樣本之前,請務必完成上述所有前置步驟。子帳號調用本樣本前需擷取AliyunBailianDataFullAccess策略。
- 若您使用了 IDE 或其他輔助開發外掛程式,需將
ALIBABA_CLOUD_ACCESS_KEY_ID、ALIBABA_CLOUD_ACCESS_KEY_SECRET和WORKSPACE_ID變數配置到相應的開發環境中。
# 範例程式碼僅供參考,請勿在生產環境中直接使用
import hashlib
import os
import time
import requests
from alibabacloud_bailian20231229 import models as bailian_20231229_models
from alibabacloud_bailian20231229.client import Client as bailian20231229Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models
def check_environment_variables():
"""檢查並提示設定必要的環境變數"""
required_vars = {
'ALIBABA_CLOUD_ACCESS_KEY_ID': '阿里雲存取金鑰ID',
'ALIBABA_CLOUD_ACCESS_KEY_SECRET': '阿里雲存取金鑰密碼',
'WORKSPACE_ID': '阿里雲百鍊業務空間ID'
}
missing_vars = []
for var, description in required_vars.items():
if not os.environ.get(var):
missing_vars.append(var)
print(f"錯誤:請設定 {var} 環境變數 ({description})")
return len(missing_vars) == 0
def calculate_md5(file_path: str) -> str:
"""
計算檔案的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()
def get_file_size(file_path: str) -> int:
"""
擷取檔案大小(以位元組為單位)。
參數:
file_path (str): 檔案本地路徑。
返回:
int: 檔案大小(以位元組為單位)。
"""
return os.path.getsize(file_path)
# 初始化用戶端(Client)
def 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)
# 申請檔案上傳租約
def 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)
# 上傳檔案到臨時儲存
def upload_file(pre_signed_url, headers, file_path):
"""
將檔案上傳到阿里雲百鍊服務。
參數:
pre_signed_url (str): 上傳租約中的 URL。
headers (dict): 上傳請求的頭部。
file_path (str): 檔案本地路徑。
"""
with open(file_path, 'rb') as f:
file_content = f.read()
upload_headers = {
"X-bailian-extra": headers["X-bailian-extra"],
"Content-Type": headers["Content-Type"]
}
response = requests.put(pre_signed_url, data=file_content, headers=upload_headers)
response.raise_for_status()
# 添加檔案到類目中
def 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)
# 查詢檔案的解析狀態
def 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)
# 初始化知識庫(索引)
def 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)
# 提交索引任務
def 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)
# 等待索引任務完成
def get_index_job_status(client, workspace_id, job_id, index_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)
def create_knowledge_base(
file_path: str,
workspace_id: str,
name: str
):
"""
使用阿里雲百鍊服務建立知識庫。
參數:
file_path (str): 檔案本地路徑。
workspace_id (str): 業務空間ID。
name (str): 知識庫名稱。
返回:
str or None: 如果成功,返回知識庫ID;否則返回None。
"""
# 設定預設值
category_id = 'default'
parser = 'DASHSCOPE_DOCMIND'
source_type = 'DATA_CENTER_FILE'
structure_type = 'unstructured'
sink_type = 'DEFAULT'
try:
# 步驟1:建立用戶端(Client)
print("步驟1:建立Client")
client = create_client()
# 步驟2:準備檔案資訊
print("步驟2:準備檔案資訊")
file_name = os.path.basename(file_path)
file_md5 = calculate_md5(file_path)
file_size = get_file_size(file_path)
# 步驟3:申請上傳租約
print("步驟3:向阿里雲百鍊申請上傳租約")
lease_response = apply_lease(client, category_id, file_name, file_md5, file_size, workspace_id)
lease_id = lease_response.body.data.file_upload_lease_id
upload_url = lease_response.body.data.param.url
upload_headers = lease_response.body.data.param.headers
# 步驟4:上傳檔案
print("步驟4:上傳檔案到阿里雲百鍊")
upload_file(upload_url, upload_headers, file_path)
# 步驟5:將檔案添加到伺服器
print("步驟5:將檔案添加到阿里雲百鍊伺服器")
add_response = add_file(client, lease_id, parser, category_id, workspace_id)
file_id = add_response.body.data.file_id
# 步驟6:檢查檔案狀態
print("步驟6:檢查阿里雲百鍊中的檔案狀態")
while True:
describe_response = describe_file(client, workspace_id, file_id)
status = describe_response.body.data.status
print(f"當前檔案狀態:{status}")
if status == 'INIT':
print("檔案待解析,請稍候...")
elif status == 'PARSING':
print("檔案解析中,請稍候...")
elif status == 'PARSE_SUCCESS':
print("檔案解析完成!")
break
else:
print(f"未知的檔案狀態:{status},請聯絡支援人員。")
return None
time.sleep(5)
# 步驟7:初始化知識庫
print("步驟7:在阿里雲百鍊中建立知識庫")
index_response = create_index(client, workspace_id, file_id, name, structure_type, source_type, sink_type)
index_id = index_response.body.data.id
# 步驟8:提交索引任務
print("步驟8:向阿里雲百鍊提交索引任務")
submit_response = submit_index(client, workspace_id, index_id)
job_id = submit_response.body.data.id
# 步驟9:擷取索引任務狀態
print("步驟9:擷取阿里雲百鍊索引任務狀態")
while True:
get_index_job_status_response = get_index_job_status(client, workspace_id, job_id, index_id)
status = get_index_job_status_response.body.data.status
print(f"當前索引任務狀態:{status}")
if status == 'COMPLETED':
break
time.sleep(5)
print("阿里雲百鍊知識庫建立成功!")
return index_id
except Exception as e:
print(f"發生錯誤:{e}")
return None
def main():
if not check_environment_variables():
print("環境變數校正未通過。")
return
file_path = input("請輸入您需要上傳檔案的實際本地路徑(以Linux為例:/xxx/xxx/阿里雲百鍊系列手機產品介紹.docx):")
kb_name = input("請為您的知識庫輸入一個名稱:")
workspace_id = os.environ.get('WORKSPACE_ID')
create_knowledge_base(file_path, workspace_id, kb_name)
if __name__ == '__main__':
main()
// 範例程式碼僅供參考,請勿在生產環境中直接使用
import com.aliyun.bailian20231229.models.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class KnowledgeBaseCreate {
/**
* 檢查並提示設定必要的環境變數。
*
* @return true 如果所有必需的環境變數都已設定,否則 false
*/
public static boolean checkEnvironmentVariables() {
Map<String, String> requiredVars = new HashMap<>();
requiredVars.put("ALIBABA_CLOUD_ACCESS_KEY_ID", "阿里雲存取金鑰ID");
requiredVars.put("ALIBABA_CLOUD_ACCESS_KEY_SECRET", "阿里雲存取金鑰密碼");
requiredVars.put("WORKSPACE_ID", "阿里雲百鍊業務空間ID");
List<String> missingVars = new ArrayList<>();
for (Map.Entry<String, String> entry : requiredVars.entrySet()) {
String value = System.getenv(entry.getKey());
if (value == null || value.isEmpty()) {
missingVars.add(entry.getKey());
System.out.println("錯誤:請設定 " + entry.getKey() + " 環境變數 (" + entry.getValue() + ")");
}
}
return missingVars.isEmpty();
}
/**
* 計算檔案的MD5值。
*
* @param filePath 檔案本地路徑
* @return 檔案的MD5值
* @throws Exception 如果計算過程中發生錯誤
*/
public static String calculateMD5(String filePath) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
try (FileInputStream fis = new FileInputStream(filePath)) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
md.update(buffer, 0, bytesRead);
}
}
StringBuilder sb = new StringBuilder();
for (byte b : md.digest()) {
sb.append(String.format("%02x", b & 0xff));
}
return sb.toString();
}
/**
* 擷取檔案大小(以位元組為單位)。
*
* @param filePath 檔案本地路徑
* @return 檔案大小(以位元組為單位)
*/
public static String getFileSize(String filePath) {
File file = new File(filePath);
long fileSize = file.length();
return String.valueOf(fileSize);
}
/**
* 初始化用戶端(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.ap-southeast-1.aliyuncs.com";
return new com.aliyun.bailian20231229.Client(config);
}
/**
* 申請檔案上傳租約。
*
* @param client 用戶端對象
* @param categoryId 類目ID
* @param fileName 檔案名稱
* @param fileMd5 檔案的MD5值
* @param fileSize 檔案大小(以位元組為單位)
* @param workspaceId 業務空間ID
* @return 阿里雲百鍊服務的響應對象
*/
public static 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;
}
/**
* 上傳檔案到臨時儲存。
*
* @param preSignedUrl 上傳租約中的 URL
* @param headers 上傳請求的頭部
* @param filePath 檔案本地路徑
* @throws Exception 如果上傳過程中發生錯誤
*/
public static void uploadFile(String preSignedUrl, Map<String, String> headers, String filePath) throws Exception {
File file = new File(filePath);
if (!file.exists() || !file.isFile()) {
throw new IllegalArgumentException("檔案不存在或不是普通檔案: " + filePath);
}
try (FileInputStream fis = new FileInputStream(file)) {
URL url = new URL(preSignedUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("PUT");
conn.setDoOutput(true);
// 設定上傳要求標頭
conn.setRequestProperty("X-bailian-extra", headers.get("X-bailian-extra"));
conn.setRequestProperty("Content-Type", headers.get("Content-Type"));
// 分塊讀取並上傳檔案
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
conn.getOutputStream().write(buffer, 0, bytesRead);
}
int responseCode = conn.getResponseCode();
if (responseCode != 200) {
throw new RuntimeException("上傳失敗: " + responseCode);
}
}
}
/**
* 將檔案添加到類目中。
*
* @param client 用戶端對象
* @param leaseId 租約ID
* @param parser 用於檔案的解析器
* @param categoryId 類目ID
* @param workspaceId 業務空間ID
* @return 阿里雲百鍊服務的響應對象
*/
public static 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);
}
/**
* 查詢檔案的基本資料。
*
* @param client 用戶端對象
* @param workspaceId 業務空間ID
* @param fileId 檔案ID
* @return 阿里雲百鍊服務的響應對象
*/
public static 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);
}
/**
* 在阿里雲百鍊服務中建立知識庫(初始化)。
*
* @param client 用戶端對象
* @param workspaceId 業務空間ID
* @param fileId 檔案ID
* @param name 知識庫名稱
* @param structureType 知識庫的資料類型
* @param sourceType 應用資料的資料類型,支援類目類型和檔案類型
* @param sinkType 知識庫的向量儲存類型
* @return 阿里雲百鍊服務的響應對象
*/
public static 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);
}
/**
* 向阿里雲百鍊服務提交索引任務。
*
* @param client 用戶端對象
* @param workspaceId 業務空間ID
* @param indexId 知識庫ID
* @return 阿里雲百鍊服務的響應對象
*/
public static 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);
}
/**
* 查詢索引任務狀態。
*
* @param client 用戶端對象
* @param workspaceId 業務空間ID
* @param jobId 任務ID
* @param indexId 知識庫ID
* @return 阿里雲百鍊服務的響應對象
*/
public static 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;
}
/**
* 使用阿里雲百鍊服務建立知識庫。
*
* @param filePath 檔案本地路徑
* @param workspaceId 業務空間ID
* @param name 知識庫名稱
* @return 如果成功,返回知識庫ID;否則返回 null
*/
public static String createKnowledgeBase(String filePath, String workspaceId, String name) {
// 設定預設值
String categoryId = "default";
String parser = "DASHSCOPE_DOCMIND";
String sourceType = "DATA_CENTER_FILE";
String structureType = "unstructured";
String sinkType = "DEFAULT";
try {
// 步驟1:初始化用戶端(Client)
System.out.println("步驟1:初始化Client");
com.aliyun.bailian20231229.Client client = createClient();
// 步驟2:準備檔案資訊
System.out.println("步驟2:準備檔案資訊");
String fileName = new File(filePath).getName();
String fileMd5 = calculateMD5(filePath);
String fileSize = getFileSize(filePath);
// 步驟3:申請上傳租約
System.out.println("步驟3:向阿里雲百鍊申請上傳租約");
ApplyFileUploadLeaseResponse leaseResponse = applyLease(client, categoryId, fileName, fileMd5, fileSize, workspaceId);
String leaseId = leaseResponse.getBody().getData().getFileUploadLeaseId();
String uploadUrl = leaseResponse.getBody().getData().getParam().getUrl();
Object uploadHeaders = leaseResponse.getBody().getData().getParam().getHeaders();
// 步驟4:上傳檔案
System.out.println("步驟4:上傳檔案到阿里雲百鍊");
// 請自行安裝jackson-databind
// 將上一步的uploadHeaders轉換為Map(Key-Value形式)
ObjectMapper mapper = new ObjectMapper();
Map<String, String> uploadHeadersMap = (Map<String, String>) mapper.readValue(mapper.writeValueAsString(uploadHeaders), Map.class);
uploadFile(uploadUrl, uploadHeadersMap, filePath);
// 步驟5:將檔案添加到伺服器
System.out.println("步驟5:將檔案添加到阿里雲百鍊伺服器");
AddFileResponse addResponse = addFile(client, leaseId, parser, categoryId, workspaceId);
String fileId = addResponse.getBody().getData().getFileId();
// 步驟6:檢查檔案狀態
System.out.println("步驟6:檢查阿里雲百鍊中的檔案狀態");
while (true) {
DescribeFileResponse describeResponse = describeFile(client, workspaceId, fileId);
String status = describeResponse.getBody().getData().getStatus();
System.out.println("當前檔案狀態:" + status);
if (status.equals("INIT")) {
System.out.println("檔案待解析,請稍候...");
} else if (status.equals("PARSING")) {
System.out.println("檔案解析中,請稍候...");
} else if (status.equals("PARSE_SUCCESS")) {
System.out.println("檔案解析完成!");
break;
} else {
System.out.println("未知的檔案狀態:" + status + ",請聯絡支援人員。");
return null;
}
TimeUnit.SECONDS.sleep(5);
}
// 步驟7:初始化知識庫
System.out.println("步驟7:在阿里雲百鍊中建立知識庫");
CreateIndexResponse indexResponse = createIndex(client, workspaceId, fileId, name, structureType, sourceType, sinkType);
String indexId = indexResponse.getBody().getData().getId();
// 步驟8:提交索引任務
System.out.println("步驟8:向阿里雲百鍊提交索引任務");
SubmitIndexJobResponse submitResponse = submitIndex(client, workspaceId, indexId);
String jobId = submitResponse.getBody().getData().getId();
// 步驟9:擷取索引任務狀態
System.out.println("步驟9:擷取阿里雲百鍊索引任務狀態");
while (true) {
GetIndexJobStatusResponse getStatusResponse = getIndexJobStatus(client, workspaceId, jobId, indexId);
String status = getStatusResponse.getBody().getData().getStatus();
System.out.println("當前索引任務狀態:" + status);
if (status.equals("COMPLETED")) {
break;
}
TimeUnit.SECONDS.sleep(5);
}
System.out.println("阿里雲百鍊知識庫建立成功!");
return indexId;
} catch (Exception e) {
System.out.println("發生錯誤:" + e.getMessage());
e.printStackTrace();
return null;
}
}
/**
* 主函數。
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
if (!checkEnvironmentVariables()) {
return;
}
System.out.print("請輸入您需要上傳檔案的實際本地路徑(以Linux為例:/xxx/xxx/阿里雲百鍊系列手機產品介紹.docx):");
String filePath = scanner.nextLine();
System.out.print("請為您的知識庫輸入一個名稱:");
String kbName = scanner.nextLine();
String workspaceId = System.getenv("WORKSPACE_ID");
String result = createKnowledgeBase(filePath, workspaceId, kbName);
if (result != null) {
System.out.println("知識庫ID: " + result);
}
}
}
<?php
// 範例程式碼僅供參考,請勿在生產環境中直接使用
namespace AlibabaCloud\SDK\Sample;
use AlibabaCloud\Dara\Models\RuntimeOptions;
use AlibabaCloud\SDK\Bailian\V20231229\Bailian;
use AlibabaCloud\SDK\Bailian\V20231229\Models\AddFileRequest;
use \Exception;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Bailian\V20231229\Models\ApplyFileUploadLeaseRequest;
use AlibabaCloud\SDK\Bailian\V20231229\Models\CreateIndexRequest;
use AlibabaCloud\SDK\Bailian\V20231229\Models\SubmitIndexJobRequest;
use AlibabaCloud\SDK\Bailian\V20231229\Models\GetIndexJobStatusRequest;
class KnowledgeBaseCreate {
/**
* 檢查並提示設定必要的環境變數。
*
* @return bool 返回 true 如果所有必需的環境變數都已設定,否則 false。
*/
public static function checkEnvironmentVariables() {
$requiredVars = [
'ALIBABA_CLOUD_ACCESS_KEY_ID' => '阿里雲存取金鑰ID',
'ALIBABA_CLOUD_ACCESS_KEY_SECRET' => '阿里雲存取金鑰密碼',
'WORKSPACE_ID' => '阿里雲百鍊業務空間ID'
];
$missingVars = [];
foreach ($requiredVars as $var => $description) {
if (!getenv($var)) {
$missingVars[] = $var;
echo "錯誤:請設定 $var 環境變數 ($description)\n";
}
}
return count($missingVars) === 0;
}
/**
* 計算檔案的MD5值。
*
* @param string $filePath 檔案本地路徑。
* @return string 檔案的MD5值。
*/
public static function calculateMd5($filePath) {
$md5Hash = hash_init("md5");
$handle = fopen($filePath, "rb");
while (!feof($handle)) {
$chunk = fread($handle, 4096);
hash_update($md5Hash, $chunk);
}
fclose($handle);
return hash_final($md5Hash);
}
/**
* 擷取檔案大小(以位元組為單位)。
*
* @param string $filePath 檔案本地路徑。
* @return int 檔案大小(以位元組為單位)。
*/
public static function getFileSize($filePath) {
return (string)filesize($filePath);
}
/**
* 初始化用戶端(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.ap-southeast-1.aliyuncs.com';
return new Bailian($config);
}
/**
* 申請檔案上傳租約。
*
* @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 static 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);
}
/**
* 上傳檔案到臨時儲存。
*
* @param string $preSignedUrl 上傳租約中的 URL。
* @param array $headers 上傳請求的頭部。
* @param string $filePath 檔案本地路徑。
*/
public static function uploadFile($preSignedUrl, $headers, $filePath) {
$fileContent = file_get_contents($filePath);
// 設定上傳要求標頭
$uploadHeaders = [
"X-bailian-extra" => $headers["X-bailian-extra"],
"Content-Type" => $headers["Content-Type"]
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $preSignedUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $fileContent);
curl_setopt($ch, CURLOPT_HTTPHEADER, array_map(function($key, $value) {
return "$key: $value";
}, array_keys($uploadHeaders), $uploadHeaders));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode != 200) {
throw new Exception("上傳失敗: " . curl_error($ch));
}
curl_close($ch);
}
/**
* 將檔案添加到類目中。
*
* @param Bailian $client 用戶端(Client)。
* @param string $leaseId 租約ID。
* @param string $parser 用於檔案的解析器。
* @param string $categoryId 類目ID。
* @param string $workspaceId 業務空間ID。
* @return AddFileResponse 阿里雲百鍊服務的響應。
*/
public static 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);
}
/**
* 查詢檔案的基本資料。
*
* @param Bailian $client 用戶端(Client)。
* @param string $workspaceId 業務空間ID。
* @param string $fileId 檔案ID。
* @return DescribeFileResponse 阿里雲百鍊服務的響應。
*/
public static function describeFile($client, $workspaceId, $fileId) {
$headers = [];
$runtime = new RuntimeOptions([]);
return $client->describeFileWithOptions($workspaceId, $fileId, $headers, $runtime);
}
/**
* 在阿里雲百鍊服務中建立知識庫(初始化)。
*
* @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 static 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);
}
/**
* 向阿里雲百鍊服務提交索引任務。
*
* @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);
}
/**
* 查詢索引任務狀態。
*
* @param Bailian $client 用戶端(Client)。
* @param string $workspaceId 業務空間ID。
* @param string $indexId 知識庫ID。
* @param string $jobId 任務ID。
* @return GetIndexJobStatusResponse 阿里雲百鍊服務的響應。
*/
public static function getIndexJobStatus($client, $workspaceId, $jobId, $indexId) {
$headers = [];
$getIndexJobStatusRequest = new GetIndexJobStatusRequest([
'indexId' => $indexId,
'jobId' => $jobId
]);
$runtime = new RuntimeOptions([]);
return $client->getIndexJobStatusWithOptions($workspaceId, $getIndexJobStatusRequest, $headers, $runtime);
}
/**
* 使用阿里雲百鍊服務建立知識庫。
*
* @param string $filePath 檔案本地路徑。
* @param string $workspaceId 業務空間ID。
* @param string $name 知識庫名稱。
* @return string|null 如果成功,返回知識庫ID;否則返回null。
*/
public static function createKnowledgeBase($filePath, $workspaceId, $name) {
// 設定預設值
$categoryId = 'default';
$parser = 'DASHSCOPE_DOCMIND';
$sourceType = 'DATA_CENTER_FILE';
$structureType = 'unstructured';
$sinkType = 'DEFAULT';
try {
// 步驟1:初始化用戶端(Client)
echo "步驟1:初始化Client\n";
$client = self::createClient();
// 步驟2:準備檔案資訊
echo "步驟2:準備檔案資訊\n";
$fileName = basename($filePath);
echo("this is filename : $fileName");
$fileMd5 = self::calculateMd5($filePath);
$fileSize = self::getFileSize($filePath);
// 步驟3:申請上傳租約
echo "步驟3:向阿里雲百鍊申請上傳租約\n";
$leaseResponse = self::applyLease($client, $categoryId, $fileName, $fileMd5, $fileSize, $workspaceId);
$leaseId = $leaseResponse->body->data->fileUploadLeaseId;
$uploadUrl = $leaseResponse->body->data->param->url;
$uploadHeaders = $leaseResponse->body->data->param->headers;
$uploadHeadersMap = json_decode(json_encode($uploadHeaders), true);
// 步驟4:上傳檔案
echo "步驟4:上傳檔案到阿里雲百鍊\n";
self::uploadFile($uploadUrl, $uploadHeadersMap, $filePath);
// 步驟5:將檔案添加到伺服器
echo "步驟5:將檔案添加到阿里雲百鍊伺服器\n";
$addResponse = self::addFile($client, $leaseId, $parser, $categoryId, $workspaceId);
$fileId = $addResponse->body->data->fileId;
echo("fileid: $fileId\n");
// 步驟6:檢查檔案狀態
echo "步驟6:檢查阿里雲百鍊中的檔案狀態\n";
while (true) {
$describeResponse = self::describeFile($client, $workspaceId, $fileId);
$status = $describeResponse->body->data->status;
echo "當前檔案狀態:$status\n";
if ($status == 'INIT') {
echo "檔案待解析,請稍候...\n";
} elseif ($status == 'PARSING') {
echo "檔案解析中,請稍候...\n";
} elseif ($status == 'PARSE_SUCCESS') {
echo "檔案解析完成!\n";
break;
} else {
echo "未知的檔案狀態:$status, 請聯絡支援人員。\n";
return null;
}
sleep(5);
}
// 步驟7:初始化知識庫
echo "步驟7:在阿里雲百鍊中初始化知識庫\n";
$indexResponse = self::createIndex($client, $workspaceId, $fileId, $name, $structureType, $sourceType, $sinkType);
$indexId = $indexResponse->body->data->id;
// 步驟8:提交索引任務
echo "步驟8:向阿里雲百鍊提交索引任務\n";
$submitResponse = self::submitIndex($client, $workspaceId, $indexId);
$jobId = $submitResponse->body->data->id;
// 步驟9:擷取索引任務狀態
echo "步驟9:擷取阿里雲百鍊索引任務狀態\n";
while (true) {
$getIndexJobStatusResponse = self::getIndexJobStatus($client, $workspaceId, $jobId, $indexId);
$status = $getIndexJobStatusResponse->body->data->status;
echo "當前索引任務狀態:$status\n";
if ($status == 'COMPLETED') {
break;
}
sleep(5);
}
echo "阿里雲百鍊知識庫建立成功!\n";
return $indexId;
} catch (Exception $e) {
echo "發生錯誤:{$e->getMessage()}\n";
return null;
}
}
/**
* 主函數。
*/
public static function main($args){
if (!self::checkEnvironmentVariables()) {
echo "環境變數校正未通過。\n";
return;
}
$filePath = readline("請輸入您需要上傳檔案的實際本地路徑(以Linux為例:/xxx/xxx/阿里雲百鍊系列手機產品介紹.docx):");
$kbName = readline("請為您的知識庫輸入一個名稱:");
$workspaceId = getenv('WORKSPACE_ID');
$result = self::createKnowledgeBase($filePath, $workspaceId, $kbName);
if ($result) {
echo "知識庫ID: $result\n";
} else {
echo "知識庫建立失敗。\n";
}
}
}
// 假定autoload.php位於當前代碼檔案所在目錄的上一級目錄中,請根據您的專案實際結構調整。
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
require_once $path;
}
KnowledgeBaseCreate::main(array_slice($argv, 1));
// 範例程式碼僅供參考,請勿在生產環境中直接使用
'use strict';
const fs = require('fs');
const path = require('path');
const axios = require('axios');
const crypto = require('crypto');
const bailian20231229 = require('@alicloud/bailian20231229');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Tea = require('@alicloud/tea-typescript');
class KbCreate {
/**
* 檢查並提示設定必要的環境變數
* @returns {boolean} - 如果所有必需的環境變數都已設定,返回 true;否則返回 false
*/
static checkEnvironmentVariables() {
const requiredVars = {
'ALIBABA_CLOUD_ACCESS_KEY_ID': '阿里雲存取金鑰ID',
'ALIBABA_CLOUD_ACCESS_KEY_SECRET': '阿里雲存取金鑰密碼',
'WORKSPACE_ID': '阿里雲百鍊業務空間ID'
};
const missing = [];
for (const [varName, desc] of Object.entries(requiredVars)) {
if (!process.env[varName]) {
console.error(`錯誤:請設定 ${varName} 環境變數 (${desc})`);
missing.push(varName);
}
}
return missing.length === 0;
}
/**
* 計算檔案的MD5值
* @param {string} filePath - 檔案本地路徑
* @returns {Promise<string>} - 檔案的MD5值
*/
static async calculateMD5(filePath) {
const hash = crypto.createHash('md5');
const stream = fs.createReadStream(filePath);
return new Promise((resolve, reject) => {
stream.on('data', chunk => hash.update(chunk));
stream.on('end', () => resolve(hash.digest('hex')));
stream.on('error', reject);
});
}
/**
* 擷取檔案大小(以位元組為單位),返回字串格式
* @param {string} filePath - 檔案本地路徑
* @returns {string} - 檔案大小(如 "123456")
*/
static getFileSize(filePath) {
try {
const stats = fs.statSync(filePath);
return stats.size.toString();
} catch (err) {
console.error(`擷取檔案大小失敗: ${err.message}`);
throw err;
}
}
/**
* 建立並配置用戶端(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.ap-southeast-1.aliyuncs.com`;
return new bailian20231229.default(config);
}
/**
* 申請檔案上傳租約
* @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>} - 阿里雲百鍊服務的響應
*/
static async 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
);
}
/**
* 上傳檔案到臨時儲存
* @param {string} preSignedUrl - 上傳租約中的URL
* @param {Object} headers - 上傳請求的頭部
* @param {string} filePath - 檔案本地路徑
*/
static async uploadFile(preSignedUrl, headers, filePath) {
const uploadHeaders = {
"X-bailian-extra": headers["X-bailian-extra"],
"Content-Type": headers["Content-Type"]
};
const stream = fs.createReadStream(filePath);
try {
await axios.put(preSignedUrl, stream, { headers: uploadHeaders });
} catch (e) {
throw new Error(`上傳失敗: ${e.message}`);
}
}
/**
* 添加檔案到類目中
* @param {Bailian20231229Client} client - 用戶端(Client)
* @param {string} leaseId - 租約ID
* @param {string} parser - 用於檔案的解析器
* @param {string} categoryId - 類目ID
* @param {string} workspaceId - 業務空間ID
* @returns {Promise<bailian20231229.AddFileResponse>} - 阿里雲百鍊服務的響應
*/
static async 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);
}
/**
* 查詢檔案的解析狀態
* @param {Bailian20231229Client} client - 用戶端(Client)
* @param {string} workspaceId - 業務空間ID
* @param {string} fileId - 檔案ID
* @returns {Promise<bailian20231229.DescribeFileResponse>} - 阿里雲百鍊服務的響應
*/
static async describeFile(client, workspaceId, fileId) {
const headers = {};
const runtime = new Util.RuntimeOptions({});
return await client.describeFileWithOptions(workspaceId, fileId, headers, runtime);
}
/**
* 初始化知識庫(索引)
* @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>} - 阿里雲百鍊服務的響應
*/
static async 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);
}
/**
* 提交索引任務
* @param {Bailian20231229Client} client - 用戶端(Client)
* @param {string} workspaceId - 業務空間ID
* @param {string} indexId - 知識庫ID
* @returns {Promise<bailian20231229.SubmitIndexJobResponse>} - 阿里雲百鍊服務的響應
*/
static async 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);
}
/**
* 查詢索引任務狀態
* @param {Bailian20231229Client} client - 用戶端(Client)
* @param {string} workspaceId - 業務空間ID
* @param {string} jobId - 任務ID
* @param {string} indexId - 知識庫ID
* @returns {Promise<bailian20231229.GetIndexJobStatusResponse>} - 阿里雲百鍊服務的響應
*/
static async 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);
}
/**
* 建立知識庫
* @param {string} filePath - 檔案本地路徑
* @param {string} workspaceId - 業務空間ID
* @param {string} name - 知識庫名稱
* @returns {Promise<string | null>} - 如果成功,返回知識庫ID;否則返回null
*/
static async createKnowledgeBase(filePath, workspaceId, name) {
const categoryId = 'default';
const parser = 'DASHSCOPE_DOCMIND';
const sourceType = 'DATA_CENTER_FILE';
const structureType = 'unstructured';
const sinkType = 'DEFAULT';
try {
console.log("步驟1:初始化Client");
const client = this.createClient();
console.log("步驟2:準備檔案資訊");
const fileName = path.basename(filePath);
const fileMd5 = await this.calculateMD5(filePath);
const fileSize = this.getFileSize(filePath);
console.log("步驟3:向阿里雲百鍊申請上傳租約")
const leaseRes = await this.applyLease(client, categoryId, fileName, fileMd5, fileSize, workspaceId);
const leaseId = leaseRes.body.data.fileUploadLeaseId;
const uploadUrl = leaseRes.body.data.param.url;
const uploadHeaders = leaseRes.body.data.param.headers;
console.log("步驟4:上傳檔案到阿里雲百鍊")
await this.uploadFile(uploadUrl, uploadHeaders, filePath);
console.log("步驟5:將檔案添加到阿里雲百鍊伺服器")
const addRes = await this.addFile(client, leaseId, parser, categoryId, workspaceId);
const fileId = addRes.body.data.fileId;
console.log("步驟6:檢查阿里雲百鍊中的檔案狀態")
while (true) {
const descRes = await this.describeFile(client, workspaceId, fileId);
const status = descRes.body.data.status;
console.log(`當前檔案狀態:${status}`);
if (status === 'INIT') console.log("檔案待解析,請稍候...");
else if (status === 'PARSING') console.log("檔案解析中,請稍候...");
else if (status === 'PARSE_SUCCESS') break;
else {
console.error(`未知的檔案狀態:${status},請聯絡支援人員。`);
return null;
}
await this.sleep(5);
}
console.log("步驟7:在阿里雲百鍊中初始化知識庫")
const indexRes = await this.createIndex(client, workspaceId, fileId, name, structureType, sourceType, sinkType);
const indexId = indexRes.body.data.id;
console.log("步驟8:向阿里雲百鍊提交索引任務")
const submitRes = await this.submitIndex(client, workspaceId, indexId);
const jobId = submitRes.body.data.id;
console.log("步驟9:擷取阿里雲百鍊索引任務狀態")
while (true) {
const jobRes = await this.getIndexJobStatus(client, workspaceId, jobId, indexId);
const status = jobRes.body.data.status;
console.log(`當前索引任務狀態:${status}`);
if (status === 'COMPLETED') break;
await this.sleep(5);
}
console.log("阿里雲百鍊知識庫建立成功!");
return indexId;
} catch (e) {
console.error(`發生錯誤:${e.message}`);
return null;
}
}
/**
* 等待指定時間(秒)
* @param {number} seconds - 等待時間(秒)
* @returns {Promise<void>}
*/
static sleep(seconds) {
return new Promise(resolve => setTimeout(resolve, seconds * 1000));
}
static async main(args) {
if (!this.checkEnvironmentVariables()) {
console.log("環境變數校正未通過。");
return;
}
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
try {
const filePath = await new Promise((resolve, reject) => {
readline.question("請輸入您需要上傳檔案的實際本地路徑(以Linux為例:/xxx/xxx/阿里雲百鍊系列手機產品介紹.docx):", (ans) => {
ans.trim() ? resolve(ans) : reject(new Error("路徑不可為空"));
});
});
const kbName = await new Promise((resolve, reject) => {
readline.question("請為您的知識庫輸入一個名稱:", (ans) => {
ans.trim() ? resolve(ans) : reject(new Error("知識庫名稱不可為空"));
});
});
const workspaceId = process.env.WORKSPACE_ID;
const result = await KbCreate.createKnowledgeBase(filePath, workspaceId, kbName);
if (result) console.log(`知識庫ID: ${result}`);
else console.log("知識庫建立失敗。");
} catch (err) {
console.error(err.message);
} finally {
readline.close();
}
}
}
exports.KbCreate = KbCreate;
KbCreate.main(process.argv.slice(2));
// 範例程式碼僅供參考,請勿在生產環境中直接使用
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Tea;
using Tea.Utils;
namespace AlibabaCloud.SDK.KnowledgeBase
{
public class KnowledgeBaseCreate
{
/// <summary>
/// 檢查並提示設定必要的環境變數。
/// </summary>
/// <returns>如果所有必需的環境變數都已設定,返回 true;否則返回 false。</returns>
public static bool CheckEnvironmentVariables()
{
var requiredVars = new Dictionary<string, string>
{
{ "ALIBABA_CLOUD_ACCESS_KEY_ID", "阿里雲存取金鑰ID" },
{ "ALIBABA_CLOUD_ACCESS_KEY_SECRET", "阿里雲存取金鑰密碼" },
{ "WORKSPACE_ID", "阿里雲百鍊業務空間ID" }
};
var missingVars = new List<string>();
foreach (var entry in requiredVars)
{
string value = Environment.GetEnvironmentVariable(entry.Key);
if (string.IsNullOrEmpty(value))
{
missingVars.Add(entry.Key);
Console.WriteLine($"錯誤:請設定 {entry.Key} 環境變數({entry.Value})");
}
}
return missingVars.Count == 0;
}
/// <summary>
/// 計算檔案的MD5值。
/// </summary>
/// <param name="filePath">檔案本地路徑</param>
/// <returns>檔案的MD5值</returns>
/// <exception cref="Exception">計算過程中發生錯誤時拋出異常</exception>
public static string CalculateMD5(string filePath)
{
using (var md5 = MD5.Create())
{
using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
byte[] hashBytes = md5.ComputeHash(stream);
StringBuilder sb = new StringBuilder();
foreach (byte b in hashBytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
}
/// <summary>
/// 擷取檔案大小(以位元組為單位)。
/// </summary>
/// <param name="filePath">檔案本地路徑</param>
/// <returns>檔案大小(以位元組為單位)</returns>
public static string GetFileSize(string filePath)
{
var file = new FileInfo(filePath);
return file.Length.ToString();
}
/// <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.ap-southeast-1.aliyuncs.com";
return new AlibabaCloud.SDK.Bailian20231229.Client(config);
}
/// <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 static 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);
}
/// <summary>
/// 上傳檔案到臨時儲存。
/// </summary>
/// <param name="preSignedUrl">上傳租約中的 URL</param>
/// <param name="headers">上傳請求的頭部</param>
/// <param name="filePath">檔案本地路徑</param>
/// <exception cref="Exception">上傳過程中發生錯誤時拋出異常</exception>
public static void UploadFile(string preSignedUrl, Dictionary<string, string> headers, string filePath)
{
var file = new FileInfo(filePath);
if (!File.Exists(filePath))
{
throw new ArgumentException($"檔案不存在或不是普通檔案: {filePath}");
}
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
var url = new Uri(preSignedUrl);
var conn = (HttpWebRequest)WebRequest.Create(url);
conn.Method = "PUT";
conn.ContentType = headers["Content-Type"];
conn.Headers.Add("X-bailian-extra", headers["X-bailian-extra"]);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)
{
conn.GetRequestStream().Write(buffer, 0, bytesRead);
}
using (var response = (HttpWebResponse)conn.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception($"上傳失敗: {response.StatusCode}");
}
}
}
}
/// <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 static 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);
}
/// <summary>
/// 查詢檔案的基本資料。
/// </summary>
/// <param name="client">用戶端對象</param>
/// <param name="workspaceId">業務空間ID</param>
/// <param name="fileId">檔案ID</param>
/// <returns>阿里雲百鍊服務的響應對象</returns>
/// <exception cref="Exception">調用過程中發生錯誤時拋出異常</exception>
public static 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);
}
/// <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 static 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);
}
/// <summary>
/// 向阿里雲百鍊服務提交索引任務。
/// </summary>
/// <param name="client">用戶端對象</param>
/// <param name="workspaceId">業務空間ID</param>
/// <param name="indexId">知識庫ID</param>
/// <returns>阿里雲百鍊服務的響應對象</returns>
/// <exception cref="Exception">調用過程中發生錯誤時拋出異常</exception>
public static 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);
}
/// <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 static 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);
}
/// <summary>
/// 使用阿里雲百鍊服務建立知識庫。
/// </summary>
/// <param name="filePath">檔案本地路徑</param>
/// <param name="workspaceId">業務空間ID</param>
/// <param name="name">知識庫名稱</param>
/// <returns>如果成功,返回知識庫ID;否則返回 null</returns>
public static string CreateKnowledgeBase(string filePath, string workspaceId, string name)
{
// 設定預設值
string categoryId = "default";
string parser = "DASHSCOPE_DOCMIND";
string sourceType = "DATA_CENTER_FILE";
string structureType = "unstructured";
string sinkType = "DEFAULT";
try
{
Console.WriteLine("步驟1:初始化Client");
AlibabaCloud.SDK.Bailian20231229.Client client = CreateClient();
Console.WriteLine("步驟2:準備檔案資訊");
var fileInfo = new FileInfo(filePath);
string fileName = fileInfo.Name;
string fileMd5 = CalculateMD5(filePath);
string fileSize = GetFileSize(filePath);
Console.WriteLine("步驟3:向阿里雲百鍊申請上傳租約");
Bailian20231229.Models.ApplyFileUploadLeaseResponse leaseResponse = ApplyLease(client, categoryId, fileName, fileMd5, fileSize, workspaceId);
string leaseId = leaseResponse.Body.Data.FileUploadLeaseId;
string uploadUrl = leaseResponse.Body.Data.Param.Url;
var uploadHeaders = leaseResponse.Body.Data.Param.Headers;
Console.WriteLine("步驟4:上傳檔案到阿里雲百鍊");
// 請自行安裝Newtonsoft.Json
var uploadHeadersMap = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(uploadHeaders));
UploadFile(uploadUrl, uploadHeadersMap, filePath);
Console.WriteLine("步驟5:將檔案添加到阿里雲百鍊伺服器");
Bailian20231229.Models.AddFileResponse addResponse = AddFile(client, leaseId, parser, categoryId, workspaceId);
string fileId = addResponse.Body.Data.FileId;
Console.WriteLine("步驟6:檢查阿里雲百鍊中的檔案狀態");
while (true)
{
Bailian20231229.Models.DescribeFileResponse describeResponse = DescribeFile(client, workspaceId, fileId);
string status = describeResponse.Body.Data.Status;
Console.WriteLine($"當前檔案狀態:{status}");
if (status == "INIT")
{
Console.WriteLine("檔案待解析,請稍候...");
}
else if (status == "PARSING")
{
Console.WriteLine("檔案解析中,請稍候...");
}
else if (status == "PARSE_SUCCESS")
{
Console.WriteLine("檔案解析完成!");
break;
}
else
{
Console.WriteLine($"未知的檔案狀態:{status},請聯絡支援人員。");
return null;
}
Thread.Sleep(5000);
}
Console.WriteLine("步驟7:在阿里雲百鍊中建立知識庫");
Bailian20231229.Models.CreateIndexResponse indexResponse = CreateIndex(client, workspaceId, fileId, name, structureType, sourceType, sinkType);
string indexId = indexResponse.Body.Data.Id;
Console.WriteLine("步驟8:向阿里雲百鍊提交索引任務");
Bailian20231229.Models.SubmitIndexJobResponse submitResponse = SubmitIndex(client, workspaceId, indexId);
string jobId = submitResponse.Body.Data.Id;
Console.WriteLine("步驟9:擷取阿里雲百鍊索引任務狀態");
while (true)
{
Bailian20231229.Models.GetIndexJobStatusResponse getStatusResponse = GetIndexJobStatus(client, workspaceId, jobId, indexId);
string status = getStatusResponse.Body.Data.Status;
Console.WriteLine($"當前索引任務狀態:{status}");
if (status == "COMPLETED")
{
break;
}
Thread.Sleep(5000);
}
Console.WriteLine("阿里雲百鍊知識庫建立成功!");
return indexId;
}
catch (Exception ex)
{
Console.WriteLine($"發生錯誤:{ex.Message}");
Console.WriteLine("錯誤詳情: " + ex.StackTrace);
return null;
}
}
/// <summary>
/// 主函數。
/// </summary>
public static void Main(string[] args)
{
if (!CheckEnvironmentVariables())
{
return;
}
Console.Write("請輸入您需要上傳檔案的實際本地路徑(以Linux為例:/xxx/xxx/阿里雲百鍊系列手機產品介紹.docx):");
string filePath = Console.ReadLine();
Console.Write("請為您的知識庫輸入一個名稱:");
string kbName = Console.ReadLine();
string workspaceId = Environment.GetEnvironmentVariable("WORKSPACE_ID");
string result = CreateKnowledgeBase(filePath, workspaceId, kbName);
if (result != null)
{
Console.WriteLine($"知識庫ID: {result}");
}
}
}
}
// 範例程式碼僅供參考,請勿在生產環境中直接使用
package main
import (
"bufio"
"crypto/md5"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"time"
bailian20231229 "github.com/alibabacloud-go/bailian-20231229/v2/client"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
"github.com/go-resty/resty/v2"
)
// CheckEnvironmentVariables 檢查並提示設定必要的環境變數。
func CheckEnvironmentVariables() bool {
// 必要的環境變數及其描述.
requiredVars := map[string]string{
"ALIBABA_CLOUD_ACCESS_KEY_ID": "阿里雲存取金鑰ID",
"ALIBABA_CLOUD_ACCESS_KEY_SECRET": "阿里雲存取金鑰密碼",
"WORKSPACE_ID": "阿里雲百鍊業務空間ID",
}
var missingVars []string
for varName, desc := range requiredVars {
if os.Getenv(varName) == "" {
fmt.Printf("錯誤:請設定 %s 環境變數 (%s)\n", varName, desc)
missingVars = append(missingVars, varName)
}
}
return len(missingVars) == 0
}
// CalculateMD5 計算檔案的MD5值。
//
// 參數:
// - filePath (string): 檔案本地路徑。
//
// 返回:
// - string: 檔案的MD5值。
// - error: 錯誤資訊.
func CalculateMD5(filePath string) (_result string, _err error) {
file, err := os.Open(filePath)
if err != nil {
return "", err
}
defer file.Close()
md5Hash := md5.New()
_, err = io.Copy(md5Hash, file)
if err != nil {
return "", err
}
return fmt.Sprintf("%x", md5Hash.Sum(nil)), nil
}
// GetFileSize 擷取檔案大小(以位元組為單位)。
//
// 參數:
// - filePath (string): 檔案本地路徑。
//
// 返回:
// - string: 檔案大小(以位元組為單位)。
// - error: 錯誤資訊。
func GetFileSize(filePath string) (_result string, _err error) {
info, err := os.Stat(filePath)
if err != nil {
return "", err
}
return fmt.Sprintf("%d", info.Size()), nil
}
// 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.ap-southeast-1.aliyuncs.com")
_result = &bailian20231229.Client{}
_result, _err = bailian20231229.NewClient(config)
return _result, _err
}
// 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)
}
// UploadFile 將檔案上傳到阿里雲百鍊服務。
//
// 參數:
// - preSignedUrl (string): 上傳租約中的 URL。
// - headers (map[string]string): 上傳請求的頭部。
// - filePath (string): 檔案本地路徑。
func UploadFile(preSignedUrl string, headers map[string]string, filePath string) error {
file, err := os.Open(filePath)
if err != nil {
return err
}
defer file.Close()
body, err := io.ReadAll(file)
if err != nil {
return err
}
client := resty.New()
uploadHeaders := map[string]string{
"X-bailian-extra": headers["X-bailian-extra"],
"Content-Type": headers["Content-Type"],
}
resp, err := client.R().
SetHeaders(uploadHeaders).
SetBody(body).
Put(preSignedUrl)
if err != nil {
return err
}
if resp.IsError() {
return fmt.Errorf("HTTP 錯誤: %d", resp.StatusCode())
}
return nil
}
// 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)
}
// 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)
}
// 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)
}
// 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)
}
// 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)
}
// CreateKnowledgeBase 使用阿里雲百鍊服務建立知識庫。
//
// 參數:
// - filePath (string): 檔案本地路徑。
// - workspaceId (string): 業務空間ID。
// - name (string): 知識庫名稱。
//
// 返回:
// - string or nil: 如果成功,返回知識庫ID;否則返回nil。
// - error: 錯誤資訊。
func CreateKnowledgeBase(filePath, workspaceId, name string) (_result string, _err error) {
categoryId := "default"
parser := "DASHSCOPE_DOCMIND"
sourceType := "DATA_CENTER_FILE"
structureType := "unstructured"
sinkType := "DEFAULT"
fmt.Println("步驟1:初始化Client")
client, err := CreateClient()
if err != nil {
return "", err
}
fmt.Println("步驟2:準備檔案資訊")
fileName := filepath.Base(filePath)
fileMD5, err := CalculateMD5(filePath)
if err != nil {
return "", err
}
fileSizeStr, err := GetFileSize(filePath)
if err != nil {
return "", err
}
fmt.Println("步驟3:向阿里雲百鍊申請上傳租約")
leaseResponse, err := ApplyLease(client, categoryId, fileName, fileMD5, fileSizeStr, workspaceId)
if err != nil {
return "", err
}
leaseId := tea.StringValue(leaseResponse.Body.Data.FileUploadLeaseId)
uploadURL := tea.StringValue(leaseResponse.Body.Data.Param.Url)
uploadHeaders := leaseResponse.Body.Data.Param.Headers
jsonData, err := json.Marshal(uploadHeaders)
if err != nil {
return "", err
}
var uploadHeadersMap map[string]string
err = json.Unmarshal(jsonData, &uploadHeadersMap)
if err != nil {
return "", err
}
fmt.Println("步驟4:上傳檔案到阿里雲百鍊")
err = UploadFile(uploadURL, uploadHeadersMap, filePath)
if err != nil {
return "", err
}
fmt.Println("步驟5:將檔案添加到阿里雲百鍊伺服器")
addResponse, err := AddFile(client, leaseId, parser, categoryId, workspaceId)
if err != nil {
return "", err
}
fileID := tea.StringValue(addResponse.Body.Data.FileId)
fmt.Println("步驟6:檢查阿里雲百鍊中的檔案狀態")
for {
describeResponse, err := DescribeFile(client, workspaceId, fileID)
if err != nil {
return "", err
}
status := tea.StringValue(describeResponse.Body.Data.Status)
fmt.Printf("當前檔案狀態:%s\n", status)
if status == "INIT" {
fmt.Println("檔案待解析,請稍候...")
} else if status == "PARSING" {
fmt.Println("檔案解析中,請稍候...")
} else if status == "PARSE_SUCCESS" {
fmt.Println("檔案解析完成!")
break
} else {
fmt.Printf("未知的檔案狀態:%s,請聯絡支援人員。\n", status)
return "", fmt.Errorf("unknown document status: %s", status)
}
time.Sleep(5 * time.Second)
}
fmt.Println("步驟7:在阿里雲百鍊中初始化知識庫")
indexResponse, err := CreateIndex(client, workspaceId, fileID, name, structureType, sourceType, sinkType)
if err != nil {
return "", err
}
indexID := tea.StringValue(indexResponse.Body.Data.Id)
fmt.Println("步驟8:向阿里雲百鍊提交索引任務")
submitResponse, err := SubmitIndex(client, workspaceId, indexID)
if err != nil {
return "", err
}
jobID := tea.StringValue(submitResponse.Body.Data.Id)
fmt.Println("步驟9:擷取阿里雲百鍊索引任務狀態")
for {
getIndexJobStatusResponse, err := GetIndexJobStatus(client, workspaceId, jobID, indexID)
if err != nil {
return "", err
}
status := tea.StringValue(getIndexJobStatusResponse.Body.Data.Status)
fmt.Printf("當前索引任務狀態:%s\n", status)
if status == "COMPLETED" {
break
}
time.Sleep(5 * time.Second)
}
fmt.Println("阿里雲百鍊知識庫建立成功!")
return indexID, nil
}
// 主函數。
func main() {
if !CheckEnvironmentVariables() {
fmt.Println("環境變數校正未通過。")
return
}
// 建立 scanner 用於讀取輸入
reader := bufio.NewReader(os.Stdin)
fmt.Print("請輸入您需要上傳檔案的實際本地路徑(以Linux為例:/xxx/xxx/阿里雲百鍊系列手機產品介紹.docx):")
filePath, _ := reader.ReadString('\n')
filePath = strings.TrimSpace(filePath)
fmt.Print("請為您的知識庫輸入一個名稱:")
kbName, _ := reader.ReadString('\n')
kbName = strings.TrimSpace(kbName)
workspaceID := os.Getenv("WORKSPACE_ID")
indexID, err := CreateKnowledgeBase(filePath, workspaceID, kbName)
if err != nil {
fmt.Printf("發生錯誤:%v\n", err)
return
}
fmt.Printf("知識庫建立成功,ID為:%s\n", indexID)
}
檢索知識庫
重要
- 在調用本樣本之前,請務必完成上述所有前置步驟。子帳號調用本樣本前需擷取AliyunBailianDataFullAccess策略。
- 若您使用了 IDE 或其他輔助開發外掛程式,需將
ALIBABA_CLOUD_ACCESS_KEY_ID、ALIBABA_CLOUD_ACCESS_KEY_SECRET和WORKSPACE_ID變數配置到相應的開發環境中。
# 範例程式碼僅供參考,請勿在生產環境中直接使用
import os
from alibabacloud_bailian20231229 import models as bailian_20231229_models
from alibabacloud_bailian20231229.client import Client as bailian20231229Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient
def check_environment_variables():
"""檢查並提示設定必要的環境變數"""
required_vars = {
'ALIBABA_CLOUD_ACCESS_KEY_ID': '阿里雲存取金鑰ID',
'ALIBABA_CLOUD_ACCESS_KEY_SECRET': '阿里雲存取金鑰密碼',
'WORKSPACE_ID': '阿里雲百鍊業務空間ID'
}
missing_vars = []
for var, description in required_vars.items():
if not os.environ.get(var):
missing_vars.append(var)
print(f"錯誤:請設定 {var} 環境變數 ({description})")
return len(missing_vars) == 0
# 建立用戶端(Client)
def 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)
# 檢索知識庫
def retrieve_index(client, workspace_id, index_id, query):
"""
在指定的知識庫中檢索資訊。
參數:
client (bailian20231229Client): 用戶端(Client)。
workspace_id (str): 業務空間ID。
index_id (str): 知識庫ID。
query (str): 檢索 query。
返回:
阿里雲百鍊服務的響應。
"""
headers = {}
retrieve_request = bailian_20231229_models.RetrieveRequest(
index_id=index_id,
query=query
)
runtime = util_models.RuntimeOptions()
return client.retrieve_with_options(workspace_id, retrieve_request, headers, runtime)
def main():
"""
使用阿里雲百鍊服務檢索知識庫。
返回:
str or None: 如果成功,返回檢索召回的文本切片;否則返回None。
"""
if not check_environment_variables():
print("環境變數校正未通過。")
return
try:
print("步驟1:建立Client")
client = create_client()
print("步驟2:檢索知識庫")
index_id = input("請輸入知識庫ID:") # 即 CreateIndex 介面返回的 Data.Id,您也可以在阿里雲百鍊控制台的知識庫頁面擷取。
query = input("請輸入檢索query:")
workspace_id = os.environ.get('WORKSPACE_ID')
resp = retrieve_index(client, workspace_id, index_id, query)
result = UtilClient.to_jsonstring(resp.body)
print(result)
except Exception as e:
print(f"發生錯誤:{e}")
return None
if __name__ == '__main__':
main()
// 範例程式碼僅供參考,請勿在生產環境中直接使用
import com.aliyun.bailian20231229.models.RetrieveRequest;
import com.aliyun.bailian20231229.models.RetrieveResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.*;
public class KnowledgeBaseRetrieve {
/**
* 檢查並提示設定必要的環境變數。
*
* @return true 如果所有必需的環境變數都已設定,否則 false
*/
public static boolean checkEnvironmentVariables() {
Map<String, String> requiredVars = new HashMap<>();
requiredVars.put("ALIBABA_CLOUD_ACCESS_KEY_ID", "阿里雲存取金鑰ID");
requiredVars.put("ALIBABA_CLOUD_ACCESS_KEY_SECRET", "阿里雲存取金鑰密碼");
requiredVars.put("WORKSPACE_ID", "阿里雲百鍊業務空間ID");
List<String> missingVars = new ArrayList<>();
for (Map.Entry<String, String> entry : requiredVars.entrySet()) {
String value = System.getenv(entry.getKey());
if (value == null || value.isEmpty()) {
missingVars.add(entry.getKey());
System.out.println("錯誤:請設定 " + entry.getKey() + " 環境變數 (" + entry.getValue() + ")");
}
}
return missingVars.isEmpty();
}
/**
* 初始化用戶端(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.ap-southeast-1.aliyuncs.com";
return new com.aliyun.bailian20231229.Client(config);
}
/**
* 在指定的知識庫中檢索資訊。
*
* @param client 用戶端對象(bailian20231229Client)
* @param workspaceId 業務空間ID
* @param indexId 知識庫ID
* @param query 檢索查詢語句
* @return 阿里雲百鍊服務的響應
*/
public static RetrieveResponse retrieveIndex(com.aliyun.bailian20231229.Client client, String workspaceId, String indexId, String query) throws Exception {
RetrieveRequest retrieveRequest = new RetrieveRequest();
retrieveRequest.setIndexId(indexId);
retrieveRequest.setQuery(query);
RuntimeOptions runtime = new RuntimeOptions();
return client.retrieveWithOptions(workspaceId, retrieveRequest, null, runtime);
}
/**
* 使用阿里雲百鍊服務檢索知識庫。
*/
public static void main(String[] args) {
if (!checkEnvironmentVariables()) {
System.out.println("環境變數校正未通過。");
return;
}
try {
// 步驟1:初始化用戶端(Client)
System.out.println("步驟1:建立Client");
com.aliyun.bailian20231229.Client client = createClient();
// 步驟2:檢索知識庫
System.out.println("步驟2:檢索知識庫");
Scanner scanner = new Scanner(System.in);
System.out.print("請輸入知識庫ID:"); // 即 CreateIndex 介面返回的 Data.Id,您也可以在阿里雲百鍊控制台的知識庫頁面擷取。
String indexId = scanner.nextLine();
System.out.print("請輸入檢索query:");
String query = scanner.nextLine();
String workspaceId = System.getenv("WORKSPACE_ID");
RetrieveResponse resp = retrieveIndex(client, workspaceId, indexId, query);
// 請自行安裝jackson-databind將響應體responsebody轉換為 JSON 字串
ObjectMapper mapper = new ObjectMapper();
String result = mapper.writeValueAsString(resp.getBody());
System.out.println(result);
} catch (Exception e) {
System.out.println("發生錯誤:" + e.getMessage());
}
}
}
<?php
// 範例程式碼僅供參考,請勿在生產環境中直接使用
namespace AlibabaCloud\SDK\Sample;
use AlibabaCloud\Dara\Models\RuntimeOptions;
use AlibabaCloud\SDK\Bailian\V20231229\Bailian;
use \Exception;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Bailian\V20231229\Models\RetrieveRequest;
class KnowledgeBaseRetrieve {
/**
* 檢查並提示設定必要的環境變數。
*
* @return bool 返回 true 如果所有必需的環境變數都已設定,否則 false。
*/
public static function checkEnvironmentVariables() {
$requiredVars = [
'ALIBABA_CLOUD_ACCESS_KEY_ID' => '阿里雲存取金鑰ID',
'ALIBABA_CLOUD_ACCESS_KEY_SECRET' => '阿里雲存取金鑰密碼',
'WORKSPACE_ID' => '阿里雲百鍊業務空間ID'
];
$missingVars = [];
foreach ($requiredVars as $var => $description) {
if (!getenv($var)) {
$missingVars[] = $var;
echo "錯誤:請設定 $var 環境變數 ($description)\n";
}
}
return count($missingVars) === 0;
}
/**
* 初始化用戶端(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.ap-southeast-1.aliyuncs.com';
return new Bailian($config);
}
/**
* 在指定的知識庫中檢索資訊。
*
* @param Bailian $client 用戶端對象(Client)。
* @param string $workspaceId 業務空間ID
* @param string $indexId 知識庫ID
* @param string $query 檢索查詢語句
* @return RetrieveResponse 阿里雲百鍊服務的響應
* @throws Exception
*/
public static function retrieveIndex($client, $workspaceId, $indexId, $query) {
$headers = [];
$retrieveRequest = new RetrieveRequest([
"query" => $query,
"indexId" => $indexId
]);
$runtime = new RuntimeOptions([]);
return $client->retrieveWithOptions($workspaceId, $retrieveRequest, $headers, $runtime);
}
/**
* 使用阿里雲百鍊服務檢索知識庫。
*/
public static function main($args){
if (!self::checkEnvironmentVariables()) {
echo "環境變數校正未通過。\n";
return;
}
try {
// 步驟1:建立Client
echo "步驟1:建立Client\n";
$client = self::createClient();
// 步驟2:檢索知識庫
echo "步驟2:檢索知識庫\n";
$indexId = readline("請輸入知識庫ID:"); // 即 CreateIndex 介面返回的 Data.Id,您也可以在阿里雲百鍊控制台的知識庫頁面擷取。
$query = readline("請輸入檢索query:");
$workspaceId = getenv("WORKSPACE_ID");
// 調用檢索方法
$resp = self::retrieveIndex($client, $workspaceId, $indexId, $query);
// 將響應體responsebody轉換為 JSON 字串
$result = json_encode($resp->body, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
echo $result . "\n";
} catch (Exception $e) {
echo "發生錯誤:" . $e->getMessage() . "\n";
}
}
}
// 假定autoload.php位於當前代碼檔案所在目錄的上一級目錄中,請根據您的專案實際結構調整。
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
require_once $path;
}
KnowledgeBaseRetrieve::main(array_slice($argv, 1));
// 範例程式碼僅供參考,請勿在生產環境中直接使用
'use strict';
const bailian20231229 = require('@alicloud/bailian20231229');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Tea = require('@alicloud/tea-typescript');
class KbRetrieve {
/**
* 檢查並提示設定必要的環境變數
* @returns {boolean} - 如果所有必需的環境變數都已設定,返回 true;否則返回 false
*/
static checkEnvironmentVariables() {
const requiredVars = {
'ALIBABA_CLOUD_ACCESS_KEY_ID': '阿里雲存取金鑰ID',
'ALIBABA_CLOUD_ACCESS_KEY_SECRET': '阿里雲存取金鑰密碼',
'WORKSPACE_ID': '阿里雲百鍊業務空間ID'
};
const missing = [];
for (const [varName, desc] of Object.entries(requiredVars)) {
if (!process.env[varName]) {
console.error(`錯誤:請設定 ${varName} 環境變數 (${desc})`);
missing.push(varName);
}
}
return missing.length === 0;
}
/**
* 建立並配置用戶端(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.ap-southeast-1.aliyuncs.com';
return new bailian20231229.default(config);
}
/**
* 在指定的知識庫中檢索資訊
* @param {bailian20231229.Client} client 用戶端(Client)
* @param {string} workspaceId 業務空間ID
* @param {string} indexId 知識庫ID
* @param {string} query 檢索query
* @returns {Promise<bailian20231229.RetrieveResponse>} 阿里雲百鍊服務的響應
*/
static async retrieveIndex(client, workspaceId, indexId, query) {
const headers = {};
const req = new bailian20231229.RetrieveRequest({
indexId,
query
});
const runtime = new Util.RuntimeOptions({});
return await client.retrieveWithOptions(workspaceId, req, headers, runtime);
}
/**
* 使用阿里雲百鍊服務檢索知識庫
*/
static async main(args) {
if (!this.checkEnvironmentVariables()) {
console.log("環境變數校正未通過。");
return;
}
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
try {
console.log("步驟1:建立Client")
const client = this.createClient();
console.log("步驟2:檢索知識庫")
const indexId = await new Promise((resolve, reject) => {
// 知識庫ID即 CreateIndex 介面返回的 Data.Id,您也可以在阿里雲百鍊控制台的知識庫頁面擷取
readline.question("請輸入知識庫ID:", (ans) => {
ans.trim() ? resolve(ans) : reject(new Error("知識庫ID不可為空"));
});
});
const query = await new Promise((resolve, reject) => {
readline.question("請輸入檢索query:", (ans) => {
ans.trim() ? resolve(ans) : reject(new Error("檢索query不可為空"));
});
});
const workspaceId = process.env.WORKSPACE_ID;
const resp = await this.retrieveIndex(client, workspaceId, indexId, query);
const result = JSON.stringify(resp.body);
console.log(result);
} catch (err) {
console.error(`發生錯誤:${err.message}`);
return;
} finally {
readline.close();
}
}
}
exports.KbRetrieve = KbRetrieve;
KbRetrieve.main(process.argv.slice(2));
// 範例程式碼僅供參考,請勿在生產環境中直接使用
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using Tea;
using Tea.Utils;
namespace AlibabaCloud.SDK.KnowledgeBase
{
public class KnowledgeBaseRetrieve
{
/// <summary>
/// 檢查並提示設定必要的環境變數。
/// </summary>
/// <returns>如果所有必需的環境變數都已設定,返回 true;否則返回 false。</returns>
public static bool CheckEnvironmentVariables()
{
var requiredVars = new Dictionary<string, string>
{
{ "ALIBABA_CLOUD_ACCESS_KEY_ID", "阿里雲存取金鑰ID" },
{ "ALIBABA_CLOUD_ACCESS_KEY_SECRET", "阿里雲存取金鑰密碼" },
{ "WORKSPACE_ID", "阿里雲百鍊業務空間ID" }
};
var missingVars = new List<string>();
foreach (var entry in requiredVars)
{
string value = Environment.GetEnvironmentVariable(entry.Key);
if (string.IsNullOrEmpty(value))
{
missingVars.Add(entry.Key);
Console.WriteLine($"錯誤:請設定 {entry.Key} 環境變數({entry.Value})");
}
}
return missingVars.Count == 0;
}
/// <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.ap-southeast-1.aliyuncs.com";
return new AlibabaCloud.SDK.Bailian20231229.Client(config);
}
/// <summary>
/// 在指定的知識庫中檢索資訊。
/// </summary>
/// <param name="client">用戶端對象(bailian20231229Client)</param>
/// <param name="workspaceId">業務空間ID</param>
/// <param name="indexId">知識庫ID</param>
/// <param name="query">檢索查詢語句</param>
/// <returns>阿里雲百鍊服務的響應</returns>
/// <exception cref="Exception">如果調用失敗</exception>
public static AlibabaCloud.SDK.Bailian20231229.Models.RetrieveResponse RetrieveIndex(
AlibabaCloud.SDK.Bailian20231229.Client client,
string workspaceId,
string indexId,
string query)
{
var headers = new Dictionary<string, string>() { };
var retrieveRequest = new AlibabaCloud.SDK.Bailian20231229.Models.RetrieveRequest
{
IndexId = indexId,
Query = query
};
var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
return client.RetrieveWithOptions(workspaceId, retrieveRequest, headers, runtime);
}
/// <summary>
/// 使用阿里雲百鍊服務檢索知識庫。
/// </summary>
public static void Main(string[] args)
{
if (!CheckEnvironmentVariables())
{
Console.WriteLine("環境變數校正未通過。");
return;
}
try
{
// 步驟1:初始化用戶端(Client)
Console.WriteLine("步驟1:建立Client");
Bailian20231229.Client client = CreateClient();
// 步驟2:檢索知識庫
Console.WriteLine("步驟2:檢索知識庫");
Console.Write("請輸入知識庫ID:"); // 即 CreateIndex 介面返回的 Data.Id,您也可以在阿里雲百鍊控制台的知識庫頁面擷取。
string indexId = Console.ReadLine();
Console.Write("請輸入檢索query:");
string query = Console.ReadLine();
string workspaceId = Environment.GetEnvironmentVariable("WORKSPACE_ID");
Bailian20231229.Models.RetrieveResponse resp = RetrieveIndex(client, workspaceId, indexId, query);
// 請自行安裝Newtonsoft.Json。將響應體responsebody轉換為 JSON 字串
var mapper = new JsonSerializerSettings { Formatting = Formatting.Indented };
string result = JsonConvert.SerializeObject(resp.Body, mapper);
Console.WriteLine(result);
}
catch (Exception e)
{
Console.WriteLine("發生錯誤:" + e.Message);
}
}
}
}
// 範例程式碼僅供參考,請勿在生產環境中直接使用
package main
import (
"bufio"
"fmt"
"os"
"strings"
bailian20231229 "github.com/alibabacloud-go/bailian-20231229/v2/client"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
)
// checkEnvironmentVariables 檢查並提示設定必要的環境變數。
func checkEnvironmentVariables() bool {
// 必要的環境變數及其描述。
requiredVars := map[string]string{
"ALIBABA_CLOUD_ACCESS_KEY_ID": "阿里雲存取金鑰ID",
"ALIBABA_CLOUD_ACCESS_KEY_SECRET": "阿里雲存取金鑰密碼",
"WORKSPACE_ID": "阿里雲百鍊業務空間ID",
}
var missingVars []string
for varName, desc := range requiredVars {
if os.Getenv(varName) == "" {
fmt.Printf("錯誤:請設定 %s 環境變數 (%s)\n", varName, desc)
missingVars = append(missingVars, varName)
}
}
return len(missingVars) == 0
}
// 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.ap-southeast-1.aliyuncs.com")
_result = &bailian20231229.Client{}
_result, _err = bailian20231229.NewClient(config)
return _result, _err
}
// retrieveIndex 在指定的知識庫中檢索資訊。
//
// 參數:
// - client (bailian20231229.Client): 用戶端(Client)。
// - workspaceId (string): 業務空間ID。
// - indexId(string): 知識庫ID。
// - query(string): 檢索查詢語句
//
// 返回:
// - *bailian20231229.RetrieveResponse: 阿里雲百鍊服務的響應。
// - error: 錯誤資訊。
func retrieveIndex(client *bailian20231229.Client, workspaceId, indexId, query string) (*bailian20231229.RetrieveResponse, error) {
headers := make(map[string]*string)
request := &bailian20231229.RetrieveRequest{
IndexId: tea.String(indexId),
Query: tea.String(query),
}
runtime := &util.RuntimeOptions{}
return client.RetrieveWithOptions(tea.String(workspaceId), request, headers, runtime)
}
// 主函數。
func main() {
if !checkEnvironmentVariables() {
fmt.Println("環境變數校正未通過。")
return
}
// 步驟1:初始化用戶端(Client)
fmt.Println("步驟1:建立Client")
client, err := createClient()
if err != nil {
fmt.Println("建立用戶端失敗:", err)
return
}
// 步驟2:檢索知識庫
fmt.Println("步驟2:檢索知識庫")
reader := bufio.NewReader(os.Stdin)
fmt.Print("請輸入知識庫ID:") // 即 CreateIndex 介面返回的 Data.Id,您也可以在阿里雲百鍊控制台的知識庫頁面擷取。
indexId, _ := reader.ReadString('\n')
indexId = strings.TrimSpace(indexId)
fmt.Print("請輸入檢索query:")
query, _ := reader.ReadString('\n')
query = strings.TrimSpace(query)
workspaceId := os.Getenv("WORKSPACE_ID")
resp, err := retrieveIndex(client, workspaceId, indexId, query)
if err != nil {
fmt.Printf("檢索失敗:%v\n", err)
return
}
fmt.Println(resp.Body)
}
更新知識庫
重要
- 在調用本樣本之前,請務必完成上述所有前置步驟。子帳號調用本樣本前需擷取AliyunBailianDataFullAccess策略。
- 若您使用了 IDE 或其他輔助開發外掛程式,需將
ALIBABA_CLOUD_ACCESS_KEY_ID、ALIBABA_CLOUD_ACCESS_KEY_SECRET和WORKSPACE_ID變數配置到相應的開發環境中。
# 範例程式碼僅供參考,請勿在生產環境中直接使用
import hashlib
import os
import time
import requests
from alibabacloud_bailian20231229 import models as bailian_20231229_models
from alibabacloud_bailian20231229.client import Client as bailian20231229Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models
def check_environment_variables():
"""檢查並提示設定必要的環境變數"""
required_vars = {
'ALIBABA_CLOUD_ACCESS_KEY_ID': '阿里雲存取金鑰ID',
'ALIBABA_CLOUD_ACCESS_KEY_SECRET': '阿里雲存取金鑰密碼',
'WORKSPACE_ID': '百鍊工作空間ID'
}
missing_vars = []
for var, description in required_vars.items():
if not os.environ.get(var):
missing_vars.append(var)
print(f"錯誤:請設定 {var} 環境變數 ({description})")
return len(missing_vars) == 0
# 建立用戶端(Client)
def 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)
def calculate_md5(file_path: str) -> str:
"""
計算檔案的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()
def get_file_size(file_path: str) -> int:
"""
擷取檔案大小(以位元組為單位)。
參數:
file_path (str): 檔案本地路徑。
返回:
int: 檔案大小(以位元組為單位)。
"""
return os.path.getsize(file_path)
# 申請檔案上傳租約
def 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)
# 上傳檔案到臨時儲存
def upload_file(pre_signed_url, headers, file_path):
"""
將檔案上傳到阿里雲百鍊服務。
參數:
lease_id (str): 租約ID。
pre_signed_url (str): 上傳租約中的URL。
headers (dict): 上傳請求的頭部。
file_path (str): 檔案本地路徑。
"""
with open(file_path, 'rb') as f:
file_content = f.read()
upload_headers = {
"X-bailian-extra": headers["X-bailian-extra"],
"Content-Type": headers["Content-Type"]
}
response = requests.put(pre_signed_url, data=file_content, headers=upload_headers)
response.raise_for_status()
# 添加檔案到類目中
def 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)
# 查詢檔案的解析狀態
def 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)
# 提交追加檔案任務
def submit_index_add_documents_job(client, workspace_id, index_id, file_id, source_type):
"""
向一個文檔搜尋類知識庫追加匯入已解析的檔案。
參數:
client (bailian20231229Client): 用戶端(Client)。
workspace_id (str): 業務空間ID。
index_id (str): 知識庫ID。
file_id (str): 檔案ID。
source_type(str): 資料類型。
返回:
阿里雲百鍊服務的響應。
"""
headers = {}
submit_index_add_documents_job_request = bailian_20231229_models.SubmitIndexAddDocumentsJobRequest(
index_id=index_id,
document_ids=[file_id],
source_type=source_type
)
runtime = util_models.RuntimeOptions()
return client.submit_index_add_documents_job_with_options(workspace_id, submit_index_add_documents_job_request,
headers, runtime)
# 等待追加任務完成
def get_index_job_status(client, workspace_id, job_id, index_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)
# 刪除舊檔案
def delete_index_document(client, workspace_id, index_id, file_id):
"""
從指定的文檔搜尋類知識庫中永久刪除一個或多個檔案。
參數:
client (bailian20231229Client): 用戶端(Client)。
workspace_id (str): 業務空間ID。
index_id (str): 知識庫ID。
file_id (str): 檔案ID。
返回:
阿里雲百鍊服務的響應。
"""
headers = {}
delete_index_document_request = bailian_20231229_models.DeleteIndexDocumentRequest(
index_id=index_id,
document_ids=[file_id]
)
runtime = util_models.RuntimeOptions()
return client.delete_index_document_with_options(workspace_id, delete_index_document_request, headers, runtime)
def update_knowledge_base(
file_path: str,
workspace_id: str,
index_id: str,
old_file_id: str
):
"""
使用阿里雲百鍊服務更新知識庫。
參數:
file_path (str): 檔案(更新後的)的實際本地路徑。
workspace_id (str): 業務空間ID。
index_id (str): 需要更新的知識庫ID。
old_file_id (str): 需要更新的檔案的FileID。
返回:
str or None: 如果成功,返回知識庫ID;否則返回None。
"""
# 設定預設值
category_id = 'default'
parser = 'DASHSCOPE_DOCMIND'
source_type = 'DATA_CENTER_FILE'
try:
# 步驟1:建立用戶端(Client)
print("步驟1:建立Client")
client = create_client()
# 步驟2:準備檔案資訊
print("步驟2:準備檔案資訊")
file_name = os.path.basename(file_path)
file_md5 = calculate_md5(file_path)
file_size = get_file_size(file_path)
# 步驟3:申請上傳租約
print("步驟3:向阿里雲百鍊申請上傳租約")
lease_response = apply_lease(client, category_id, file_name, file_md5, file_size, workspace_id)
lease_id = lease_response.body.data.file_upload_lease_id
upload_url = lease_response.body.data.param.url
upload_headers = lease_response.body.data.param.headers
# 步驟4:上傳檔案到臨時儲存
print("步驟4:上傳檔案到臨時儲存")
upload_file(upload_url, upload_headers, file_path)
# 步驟5:添加檔案到類目中
print("步驟5:添加檔案到類目中")
add_response = add_file(client, lease_id, parser, category_id, workspace_id)
file_id = add_response.body.data.file_id
# 步驟6:檢查檔案狀態
print("步驟6:檢查阿里雲百鍊中的檔案狀態")
while True:
describe_response = describe_file(client, workspace_id, file_id)
status = describe_response.body.data.status
print(f"當前檔案狀態:{status}")
if status == 'INIT':
print("檔案待解析,請稍候...")
elif status == 'PARSING':
print("檔案解析中,請稍候...")
elif status == 'PARSE_SUCCESS':
print("檔案解析完成!")
break
else:
print(f"未知的檔案狀態:{status},請聯絡支援人員。")
return None
time.sleep(5)
# 步驟7:提交追加檔案任務
print("步驟7:提交追加檔案任務")
index_add_response = submit_index_add_documents_job(client, workspace_id, index_id, file_id, source_type)
job_id = index_add_response.body.data.id
# 步驟8:擷取索引任務狀態
print("步驟8:等待追加任務完成")
while True:
get_index_job_status_response = get_index_job_status(client, workspace_id, job_id, index_id)
status = get_index_job_status_response.body.data.status
print(f"當前索引任務狀態:{status}")
if status == 'COMPLETED':
break
time.sleep(5)
print("步驟9:刪除舊檔案")
delete_index_document(client, workspace_id, index_id, old_file_id)
print("阿里雲百鍊知識庫更新成功!")
return index_id
except Exception as e:
print(f"發生錯誤:{e}")
return None
def main():
if not check_environment_variables():
print("環境變數校正未通過。")
return
file_path = input("請輸入您需要上傳檔案(更新後的)的實際本地路徑(以Linux為例:/xxx/xxx/阿里雲百鍊系列手機產品介紹.docx):")
index_id = input("請輸入需要更新的知識庫ID:") # 即 CreateIndex 介面返回的 Data.Id,您也可以在阿里雲百鍊控制台的知識庫頁面擷取。
old_file_id = input("請輸入需要更新的檔案的FileID:") # 即 AddFile 介面返回的 FileId。您也可以在阿里雲百鍊控制台的應用資料頁面,單擊檔案名稱旁的 ID 表徵圖擷取。
workspace_id = os.environ.get('WORKSPACE_ID')
update_knowledge_base(file_path, workspace_id, index_id, old_file_id)
if __name__ == '__main__':
main()
// 範例程式碼僅供參考,請勿在生產環境中直接使用
import com.aliyun.bailian20231229.models.*;
import com.aliyun.teautil.models.RuntimeOptions;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.util.*;
public class KnowledgeBaseUpdate {
/**
* 檢查並提示設定必要的環境變數。
*
* @return true 如果所有必需的環境變數都已設定,否則 false
*/
public static boolean checkEnvironmentVariables() {
Map<String, String> requiredVars = new HashMap<>();
requiredVars.put("ALIBABA_CLOUD_ACCESS_KEY_ID", "阿里雲存取金鑰ID");
requiredVars.put("ALIBABA_CLOUD_ACCESS_KEY_SECRET", "阿里雲存取金鑰密碼");
requiredVars.put("WORKSPACE_ID", "阿里雲百鍊業務空間ID");
List<String> missingVars = new ArrayList<>();
for (Map.Entry<String, String> entry : requiredVars.entrySet()) {
String value = System.getenv(entry.getKey());
if (value == null || value.isEmpty()) {
missingVars.add(entry.getKey());
System.out.println("錯誤:請設定 " + entry.getKey() + " 環境變數 (" + entry.getValue() + ")");
}
}
return missingVars.isEmpty();
}
/**
* 建立並配置用戶端(Client)
*
* @return 配置好的用戶端(Client)
*/
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.ap-southeast-1.aliyuncs.com";
return new com.aliyun.bailian20231229.Client(config);
}
/**
* 計算檔案的MD5值
*
* @param filePath 檔案本地路徑
* @return 檔案的MD5值
*/
public static String calculateMD5(String filePath) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
try (FileInputStream fis = new FileInputStream(filePath)) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
md.update(buffer, 0, bytesRead);
}
}
StringBuilder sb = new StringBuilder();
for (byte b : md.digest()) {
sb.append(String.format("%02x", b & 0xff));
}
return sb.toString();
}
/**
* 擷取檔案大小(以位元組為單位)
*
* @param filePath 檔案本地路徑
* @return 檔案大小(以位元組為單位)
*/
public static String getFileSize(String filePath) {
File file = new File(filePath);
long fileSize = file.length();
return String.valueOf(fileSize);
}
/**
* 申請檔案上傳租約。
*
* @param client 用戶端對象
* @param categoryId 類目ID
* @param fileName 檔案名稱
* @param fileMd5 檔案的MD5值
* @param fileSize 檔案大小(以位元組為單位)
* @param workspaceId 業務空間ID
* @return 阿里雲百鍊服務的響應對象
*/
public static 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;
}
/**
* 上傳檔案到臨時儲存。
*
* @param preSignedUrl 上傳租約中的 URL
* @param headers 上傳請求的頭部
* @param filePath 檔案本地路徑
* @throws Exception 如果上傳過程中發生錯誤
*/
public static void uploadFile(String preSignedUrl, Map<String, String> headers, String filePath) throws Exception {
File file = new File(filePath);
if (!file.exists() || !file.isFile()) {
throw new IllegalArgumentException("檔案不存在或不是普通檔案: " + filePath);
}
try (FileInputStream fis = new FileInputStream(file)) {
URL url = new URL(preSignedUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("PUT");
conn.setDoOutput(true);
// 設定上傳要求標頭
conn.setRequestProperty("X-bailian-extra", headers.get("X-bailian-extra"));
conn.setRequestProperty("Content-Type", headers.get("Content-Type"));
// 分塊讀取並上傳檔案
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
conn.getOutputStream().write(buffer, 0, bytesRead);
}
int responseCode = conn.getResponseCode();
if (responseCode != 200) {
throw new RuntimeException("上傳失敗: " + responseCode);
}
}
}
/**
* 將檔案添加到類目中。
*
* @param client 用戶端對象
* @param leaseId 租約ID
* @param parser 用於檔案的解析器
* @param categoryId 類目ID
* @param workspaceId 業務空間ID
* @return 阿里雲百鍊服務的響應對象
*/
public static 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);
}
/**
* 查詢檔案的基本資料。
*
* @param client 用戶端對象
* @param workspaceId 業務空間ID
* @param fileId 檔案ID
* @return 阿里雲百鍊服務的響應對象
*/
public static 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);
}
/**
* 向一個文檔搜尋類知識庫追加匯入已解析的檔案
*
* @param client 用戶端(Client)
* @param workspaceId 業務空間ID
* @param indexId 知識庫ID
* @param fileId 檔案ID
* @param sourceType 資料類型
* @return 阿里雲百鍊服務的響應
*/
public static SubmitIndexAddDocumentsJobResponse submitIndexAddDocumentsJob(com.aliyun.bailian20231229.Client client, String workspaceId, String indexId, String fileId, String sourceType) throws Exception {
Map<String, String> headers = new HashMap<>();
SubmitIndexAddDocumentsJobRequest submitIndexAddDocumentsJobRequest = new SubmitIndexAddDocumentsJobRequest();
submitIndexAddDocumentsJobRequest.setIndexId(indexId);
submitIndexAddDocumentsJobRequest.setDocumentIds(Collections.singletonList(fileId));
submitIndexAddDocumentsJobRequest.setSourceType(sourceType);
RuntimeOptions runtime = new RuntimeOptions();
return client.submitIndexAddDocumentsJobWithOptions(workspaceId, submitIndexAddDocumentsJobRequest, headers, runtime);
}
/**
* 查詢索引任務狀態。
*
* @param client 用戶端對象
* @param workspaceId 業務空間ID
* @param jobId 任務ID
* @param indexId 知識庫ID
* @return 阿里雲百鍊服務的響應對象
*/
public static 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;
}
/**
* 從指定的文檔搜尋類知識庫中永久刪除一個或多個檔案
*
* @param client 用戶端(Client)
* @param workspaceId 業務空間ID
* @param indexId 知識庫ID
* @param fileId 檔案ID
* @return 阿里雲百鍊服務的響應
*/
public static DeleteIndexDocumentResponse deleteIndexDocument(com.aliyun.bailian20231229.Client client, String workspaceId, String indexId, String fileId) throws Exception {
Map<String, String> headers = new HashMap<>();
DeleteIndexDocumentRequest deleteIndexDocumentRequest = new DeleteIndexDocumentRequest();
deleteIndexDocumentRequest.setIndexId(indexId);
deleteIndexDocumentRequest.setDocumentIds(Collections.singletonList(fileId));
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
return client.deleteIndexDocumentWithOptions(workspaceId, deleteIndexDocumentRequest, headers, runtime);
}
/**
* 使用阿里雲百鍊服務更新知識庫
*
* @param filePath 檔案(更新後的)的實際本地路徑
* @param workspaceId 業務空間ID
* @param indexId 需要更新的知識庫ID
* @param oldFileId 需要更新的檔案的FileID
* @return 如果成功,返回知識庫ID;否則返回 null
*/
public static String updateKnowledgeBase(String filePath, String workspaceId, String indexId, String oldFileId) {
// 設定預設值
String categoryId = "default";
String parser = "DASHSCOPE_DOCMIND";
String sourceType = "DATA_CENTER_FILE";
try {
// 步驟1:初始化用戶端(Client)
System.out.println("步驟1:建立Client");
com.aliyun.bailian20231229.Client client = createClient();
// 步驟2:準備檔案資訊(更新後的檔案)
System.out.println("步驟2:準備檔案資訊");
String fileName = Paths.get(filePath).getFileName().toString();
String fileMd5 = calculateMD5(filePath);
String fileSize = getFileSize(filePath);
// 步驟3:申請上傳租約
System.out.println("步驟3:向阿里雲百鍊申請上傳租約");
ApplyFileUploadLeaseResponse leaseResponse = applyLease(client, categoryId, fileName, fileMd5, fileSize, workspaceId);
String leaseId = leaseResponse.getBody().getData().getFileUploadLeaseId();
String uploadUrl = leaseResponse.getBody().getData().getParam().getUrl();
Object uploadHeaders = leaseResponse.getBody().getData().getParam().getHeaders();
// 步驟4:上傳檔案到臨時儲存
// 請自行安裝jackson-databind
System.out.println("步驟4:上傳檔案到臨時儲存");
// 將上一步的uploadHeaders轉換為Map(Key-Value形式)
ObjectMapper mapper = new ObjectMapper();
Map<String, String> uploadHeadersMap = (Map<String, String>) mapper.readValue(mapper.writeValueAsString(uploadHeaders), Map.class);
uploadFile(uploadUrl, uploadHeadersMap, filePath);
// 步驟5:添加檔案到類目中
System.out.println("步驟5:添加檔案到類目中");
AddFileResponse addResponse = addFile(client, leaseId, parser, categoryId, workspaceId);
String fileId = addResponse.getBody().getData().getFileId();
// 步驟6:檢查更新後的檔案狀態
System.out.println("步驟6:檢查阿里雲百鍊中的檔案狀態");
while (true) {
DescribeFileResponse describeResponse = describeFile(client, workspaceId, fileId);
String status = describeResponse.getBody().getData().getStatus();
System.out.println("當前檔案狀態:" + status);
if ("INIT".equals(status)) {
System.out.println("檔案待解析,請稍候...");
} else if ("PARSING".equals(status)) {
System.out.println("檔案解析中,請稍候...");
} else if ("PARSE_SUCCESS".equals(status)) {
System.out.println("檔案解析完成!");
break;
} else {
System.out.println("未知的檔案狀態:" + status + ",請聯絡支援人員。");
return null;
}
Thread.sleep(5000);
}
// 步驟7:提交追加檔案任務
System.out.println("步驟7:提交追加檔案任務");
SubmitIndexAddDocumentsJobResponse indexAddResponse = submitIndexAddDocumentsJob(client, workspaceId, indexId, fileId, sourceType);
String jobId = indexAddResponse.getBody().getData().getId();
// 步驟8:等待追加任務完成
System.out.println("步驟8:等待追加任務完成");
while (true) {
GetIndexJobStatusResponse jobStatusResponse = getIndexJobStatus(client, workspaceId, jobId, indexId);
String status = jobStatusResponse.getBody().getData().getStatus();
System.out.println("當前索引任務狀態:" + status);
if ("COMPLETED".equals(status)) {
break;
}
Thread.sleep(5000);
}
// 步驟9:刪除舊檔案
System.out.println("步驟9:刪除舊檔案");
deleteIndexDocument(client, workspaceId, indexId, oldFileId);
System.out.println("阿里雲百鍊知識庫更新成功!");
return indexId;
} catch (Exception e) {
System.out.println("發生錯誤:" + e.getMessage());
return null;
}
}
/**
* 主函數。
*/
public static void main(String[] args) {
if (!checkEnvironmentVariables()) {
System.out.println("環境變數校正未通過。");
return;
}
Scanner scanner = new Scanner(System.in);
System.out.print("請輸入您需要上傳檔案(更新後的)的實際本地路徑(以Linux為例:/xxx/xxx/阿里雲百鍊系列手機產品介紹.docx):");
String filePath = scanner.nextLine();
System.out.print("請輸入需要更新的知識庫ID:"); // 即 CreateIndex 介面返回的 Data.Id,您也可以在阿里雲百鍊控制台的知識庫頁面擷取。
String indexId = scanner.nextLine();
System.out.print("請輸入需要更新的檔案的 FileID:"); // 即 AddFile 介面返回的 FileId。您也可以在阿里雲百鍊控制台的應用資料頁面,單擊檔案名稱旁的 ID 表徵圖擷取。
String oldFileId = scanner.nextLine();
String workspaceId = System.getenv("WORKSPACE_ID");
String result = updateKnowledgeBase(filePath, workspaceId, indexId, oldFileId);
if (result != null) {
System.out.println("知識庫更新成功,返回知識庫ID: " + result);
} else {
System.out.println("知識庫更新失敗。");
}
}
}
<?php
// 範例程式碼僅供參考,請勿在生產環境中直接使用
namespace AlibabaCloud\SDK\Sample;
use AlibabaCloud\Dara\Models\RuntimeOptions;
use AlibabaCloud\SDK\Bailian\V20231229\Bailian;
use AlibabaCloud\SDK\Bailian\V20231229\Models\AddFileRequest;
use \Exception;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Bailian\V20231229\Models\ApplyFileUploadLeaseRequest;
use AlibabaCloud\SDK\Bailian\V20231229\Models\DeleteIndexDocumentRequest;
use AlibabaCloud\SDK\Bailian\V20231229\Models\GetIndexJobStatusRequest;
use AlibabaCloud\SDK\Bailian\V20231229\Models\SubmitIndexAddDocumentsJobRequest;
class KnowledgeBaseUpdate {
/**
* 檢查並提示設定必要的環境變數。
*
* @return bool 返回 true 如果所有必需的環境變數都已設定,否則 false。
*/
public static function checkEnvironmentVariables() {
$requiredVars = [
'ALIBABA_CLOUD_ACCESS_KEY_ID' => '阿里雲存取金鑰ID',
'ALIBABA_CLOUD_ACCESS_KEY_SECRET' => '阿里雲存取金鑰密碼',
'WORKSPACE_ID' => '阿里雲百鍊業務空間ID'
];
$missingVars = [];
foreach ($requiredVars as $var => $description) {
if (!getenv($var)) {
$missingVars[] = $var;
echo "錯誤:請設定 $var 環境變數 ($description)\n";
}
}
return count($missingVars) === 0;
}
/**
* 計算檔案的MD5值。
*
* @param string $filePath 檔案本地路徑。
* @return string 檔案的MD5值。
*/
public static function calculateMd5($filePath) {
$md5Hash = hash_init("md5");
$handle = fopen($filePath, "rb");
while (!feof($handle)) {
$chunk = fread($handle, 4096);
hash_update($md5Hash, $chunk);
}
fclose($handle);
return hash_final($md5Hash);
}
/**
* 擷取檔案大小(以位元組為單位)。
*
* @param string $filePath 檔案本地路徑。
* @return int 檔案大小(以位元組為單位)。
*/
public static function getFileSize($filePath) {
return (string)filesize($filePath);
}
/**
* 初始化用戶端(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.ap-southeast-1.aliyuncs.com';
return new Bailian($config);
}
/**
* 申請檔案上傳租約。
*
* @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 static 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);
}
/**
* 上傳檔案到臨時儲存。
*
* @param string $preSignedUrl 上傳租約中的 URL。
* @param array $headers 上傳請求的頭部。
* @param string $filePath 檔案本地路徑。
*/
public static function uploadFile($preSignedUrl, $headers, $filePath) {
$fileContent = file_get_contents($filePath);
// 設定上傳要求標頭
$uploadHeaders = [
"X-bailian-extra" => $headers["X-bailian-extra"],
"Content-Type" => $headers["Content-Type"]
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $preSignedUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $fileContent);
curl_setopt($ch, CURLOPT_HTTPHEADER, array_map(function($key, $value) {
return "$key: $value";
}, array_keys($uploadHeaders), $uploadHeaders));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode != 200) {
throw new Exception("上傳失敗: " . curl_error($ch));
}
curl_close($ch);
}
/**
* 將檔案添加到類目中。
*
* @param Bailian $client 用戶端(Client)。
* @param string $leaseId 租約ID。
* @param string $parser 用於檔案的解析器。
* @param string $categoryId 類目ID。
* @param string $workspaceId 業務空間ID。
* @return AddFileResponse 阿里雲百鍊服務的響應。
*/
public static 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);
}
/**
* 查詢檔案的基本資料。
*
* @param Bailian $client 用戶端(Client)。
* @param string $workspaceId 業務空間ID。
* @param string $fileId 檔案ID。
* @return DescribeFileResponse 阿里雲百鍊服務的響應。
*/
public static function describeFile($client, $workspaceId, $fileId) {
$headers = [];
$runtime = new RuntimeOptions([]);
return $client->describeFileWithOptions($workspaceId, $fileId, $headers, $runtime);
}
/**
* 向一個文檔搜尋類知識庫追加匯入已解析的檔案
*
* @param Bailian $client 用戶端對象
* @param string $workspaceId 業務空間ID
* @param string $indexId 知識庫ID
* @param string $fileId 檔案ID
* @param string $sourceType 資料類型
* @return SubmitIndexAddDocumentsJobResponse 阿里雲百鍊服務的響應
* @throws Exception
*/
public static function submitIndexAddDocumentsJob($client, $workspaceId, $indexId, $fileId, $sourceType) {
$headers = [];
$submitIndexAddDocumentsJobRequest = new SubmitIndexAddDocumentsJobRequest([
"indexId" =>$indexId,
"sourceType" => $sourceType,
"documentIds" => [
$fileId
]
]);
$runtime = new RuntimeOptions([]);
return $client->submitIndexAddDocumentsJobWithOptions($workspaceId, $submitIndexAddDocumentsJobRequest, $headers, $runtime);
}
/**
* 查詢索引任務狀態。
*
* @param Bailian $client 用戶端(Client)。
* @param string $workspaceId 業務空間ID。
* @param string $indexId 知識庫ID。
* @param string $jobId 任務ID。
* @return GetIndexJobStatusResponse 阿里雲百鍊服務的響應。
*/
public static function getIndexJobStatus$client, $workspaceId, $jobId, $indexId) {
$headers = [];
$getIndexJobStatusRequest = new GetIndexJobStatusRequest([
'indexId' => $indexId,
'jobId' => $jobId
]);
$runtime = new RuntimeOptions([]);
return $client->getIndexJobStatusWithOptions($workspaceId, $getIndexJobStatusRequest, $headers, $runtime);
}
/**
* 從指定的文檔搜尋類知識庫中永久刪除檔案
*
* @param Bailian $client 用戶端對象
* @param string $workspaceId 業務空間ID
* @param string $indexId 知識庫ID
* @param string $fileId 檔案ID
* @return mixed 阿里雲百鍊服務的響應
* @throws Exception
*/
public static function deleteIndexDocument($client, $workspaceId, $indexId, $fileId) {
$headers = [];
$deleteIndexDocumentRequest = new DeleteIndexDocumentRequest([
"indexId" => $indexId,
"documentIds" => [
$fileId
]
]);
$runtime = new RuntimeOptions([]);
return $client->deleteIndexDocumentWithOptions($workspaceId, $deleteIndexDocumentRequest, $headers, $runtime);
}
/**
* 使用阿里雲百鍊服務更新知識庫
*
* @param string $filePath 檔案(更新後的)的實際本地路徑
* @param string $workspaceId 業務空間ID
* @param string $indexId 需要更新的知識庫ID
* @param string $oldFileId 需要更新的檔案的FileID
* @return string| null 如果成功,返回知識庫ID;否則返回 null
*/
public static function updateKnowledgeBase($filePath, $workspaceId, $indexId, $oldFileId) {
$categoryId = "default";
$parser = "DASHSCOPE_DOCMIND";
$sourceType = "DATA_CENTER_FILE";
try {
// 步驟1:建立Client
echo "步驟1:建立Client\n";
$client = self::createClient();
// 步驟2:準備檔案資訊
echo "步驟2:準備檔案資訊\n";
$fileName = basename($filePath);
$fileMd5 = self::calculateMD5($filePath);
$fileSize = self::getFileSize($filePath);
// 步驟3:申請上傳租約
echo "步驟3:向阿里雲百鍊申請上傳租約\n";
$leaseResponse = self::applyLease($client, $categoryId, $fileName, $fileMd5, $fileSize, $workspaceId);
$leaseId = $leaseResponse->body->data->fileUploadLeaseId;
$uploadUrl = $leaseResponse->body->data->param->url;
$uploadHeaders = $leaseResponse->body->data->param->headers;
$uploadHeadersMap = json_decode(json_encode($uploadHeaders), true);
// 步驟4:上傳檔案到臨時儲存
echo "步驟4:上傳檔案到臨時儲存\n";
self::uploadFile($uploadUrl, $uploadHeadersMap, $filePath);
// 步驟5:添加檔案到類目中
echo "步驟5:添加檔案到類目中\n";
$addResponse = self::addFile($client, $leaseId, $parser, $categoryId, $workspaceId);
$fileId = $addResponse->body->data->fileId;
// 步驟6:檢查檔案狀態
echo "步驟6:檢查阿里雲百鍊中的檔案狀態\n";
while (true) {
$describeResponse = self::describeFile($client, $workspaceId, $fileId);
$status = $describeResponse->body->data->status;
echo "當前檔案狀態:" . $status . "\n";
if ($status === "INIT") {
echo "檔案待解析,請稍候...\n";
} elseif ($status === "PARSING") {
echo "檔案解析中,請稍候...\n";
} elseif ($status === "PARSE_SUCCESS") {
echo "檔案解析完成!\n";
break;
} else {
echo "未知的檔案狀態:" . $status . ",請聯絡支援人員。\n";
return null;
}
sleep(5);
}
// 步驟7:提交追加檔案任務
echo "步驟7:提交追加檔案任務\n";
$indexAddResponse = self::submitIndexAddDocumentsJob($client, $workspaceId, $indexId, $fileId, $sourceType);
$jobId = $indexAddResponse->body->data->id;
// 步驟8:等待任務完成
echo "步驟8:等待追加任務完成\n";
while (true) {
$jobStatusResponse = self::getIndexJobStatus($client, $workspaceId, $jobId, $indexId);
$status = $jobStatusResponse->body->data->status;
echo "當前索引任務狀態:" . $status . "\n";
if ($status === "COMPLETED") {
break;
}
sleep(5);
}
// 步驟9:刪除舊檔案
echo "步驟9:刪除舊檔案\n";
self::deleteIndexDocument($client, $workspaceId, $indexId, $oldFileId);
echo "阿里雲百鍊知識庫更新成功!\n";
return $indexId;
} catch (Exception $e) {
echo "發生錯誤:" . $e->getMessage() . "\n";
return null;
}
}
/**
* 主函數。
*/
public static function main($args){
if (!self::checkEnvironmentVariables()) {
echo "環境變數校正未通過。\n";
return;
}
$filePath = readline("請輸入您需要上傳檔案(更新後的)的實際本地路徑(以Linux為例:/xxx/xxx/阿里雲百鍊系列手機產品介紹.docx):");
$indexId = readline("請輸入需要更新的知識庫ID:"); // 即 CreateIndex 介面返回的 Data.Id,您也可以在阿里雲百鍊控制台的知識庫頁面擷取。
$oldFileId = readline("請輸入需要更新的檔案的 FileID:"); // 即 AddFile 介面返回的 FileId。您也可以在阿里雲百鍊控制台的應用資料頁面,單擊檔案名稱旁的 ID 表徵圖擷取。
$workspaceId = getenv('WORKSPACE_ID');
$result = self::updateKnowledgeBase($filePath, $workspaceId, $indexId, $oldFileId);
if ($result !== null) {
echo "知識庫更新成功,返回知識庫ID: " . $result . "\n";
} else {
echo "知識庫更新失敗。\n";
}
}
}
// 假定autoload.php位於當前代碼檔案所在目錄的上一級目錄中,請根據您的專案實際結構調整。
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
require_once $path;
}
KnowledgeBaseUpdate::main(array_slice($argv, 1));
// 範例程式碼僅供參考,請勿在生產環境中直接使用
'use strict';
const fs = require('fs');
const path = require('path');
const axios = require('axios');
const crypto = require('crypto');
const bailian20231229 = require('@alicloud/bailian20231229');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Tea = require('@alicloud/tea-typescript');
class KbUpdate {
/**
* 檢查並提示設定必要的環境變數
* @returns {boolean} - 如果所有必需的環境變數都已設定,返回 true;否則返回 false
*/
static checkEnvironmentVariables() {
const requiredVars = {
'ALIBABA_CLOUD_ACCESS_KEY_ID': '阿里雲存取金鑰ID',
'ALIBABA_CLOUD_ACCESS_KEY_SECRET': '阿里雲存取金鑰密碼',
'WORKSPACE_ID': '阿里雲百鍊業務空間ID'
};
const missing = [];
for (const [varName, desc] of Object.entries(requiredVars)) {
if (!process.env[varName]) {
console.error(`錯誤:請設定 ${varName} 環境變數 (${desc})`);
missing.push(varName);
}
}
return missing.length === 0;
}
/**
* 計算檔案的MD5值
* @param {string} filePath - 檔案本地路徑
* @returns {Promise<string>} - 檔案的MD5值
*/
static async calculateMD5(filePath) {
const hash = crypto.createHash('md5');
const stream = fs.createReadStream(filePath);
return new Promise((resolve, reject) => {
stream.on('data', chunk => hash.update(chunk));
stream.on('end', () => resolve(hash.digest('hex')));
stream.on('error', reject);
});
}
/**
* 擷取檔案大小(以位元組為單位),返回字串格式
* @param {string} filePath - 檔案本地路徑
* @returns {string} - 檔案大小(如 "123456")
*/
static getFileSize(filePath) {
try {
const stats = fs.statSync(filePath);
return stats.size.toString();
} catch (err) {
console.error(`擷取檔案大小失敗: ${err.message}`);
throw err;
}
}
/**
* 建立並配置用戶端(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.ap-southeast-1.aliyuncs.com`;
return new bailian20231229.default(config);
}
/**
* 申請檔案上傳租約
* @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>} - 阿里雲百鍊服務的響應
*/
static async 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
);
}
/**
* 上傳檔案到臨時儲存
* @param {string} preSignedUrl - 上傳租約中的URL
* @param {Object} headers - 上傳請求的頭部
* @param {string} filePath - 檔案本地路徑
*/
static async uploadFile(preSignedUrl, headers, filePath) {
const uploadHeaders = {
"X-bailian-extra": headers["X-bailian-extra"],
"Content-Type": headers["Content-Type"]
};
const stream = fs.createReadStream(filePath);
try {
await axios.put(preSignedUrl, stream, { headers: uploadHeaders });
} catch (e) {
throw new Error(`上傳失敗: ${e.message}`);
}
}
/**
* 添加檔案到類目中
* @param {Bailian20231229Client} client - 用戶端(Client)
* @param {string} leaseId - 租約ID
* @param {string} parser - 用於檔案的解析器
* @param {string} categoryId - 類目ID
* @param {string} workspaceId - 業務空間ID
* @returns {Promise<bailian20231229.AddFileResponse>} - 阿里雲百鍊服務的響應
*/
static async 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);
}
/**
* 查詢檔案的解析狀態
* @param {Bailian20231229Client} client - 用戶端(Client)
* @param {string} workspaceId - 業務空間ID
* @param {string} fileId - 檔案ID
* @returns {Promise<bailian20231229.DescribeFileResponse>} - 阿里雲百鍊服務的響應
*/
static async describeFile(client, workspaceId, fileId) {
const headers = {};
const runtime = new Util.RuntimeOptions({});
return await client.describeFileWithOptions(workspaceId, fileId, headers, runtime);
}
/**
* 提交追加檔案任務
* @param {Bailian20231229Client} client - 用戶端(Client)
* @param {string} workspaceId - 業務空間ID
* @param {string} indexId - 知識庫ID
* @param {string} fileId - 檔案ID
* @param {string} sourceType - 資料類型
* @returns {Promise<bailian20231229.SubmitIndexAddDocumentsJobResponse>} - 阿里雲百鍊服務的響應
*/
static async submitIndexAddDocumentsJob(client, workspaceId, indexId, fileId, sourceType) {
const headers = {};
const req = new bailian20231229.SubmitIndexAddDocumentsJobRequest({
indexId,
documentIds: [fileId],
sourceType,
});
const runtime = new Util.RuntimeOptions({});
return await client.submitIndexAddDocumentsJobWithOptions(workspaceId, req, headers, runtime);
}
/**
* 查詢索引任務狀態
* @param {Bailian20231229Client} client - 用戶端(Client)
* @param {string} workspaceId - 業務空間ID
* @param {string} jobId - 任務ID
* @param {string} indexId - 知識庫ID
* @returns {Promise<bailian20231229.GetIndexJobStatusResponse>} - 阿里雲百鍊服務的響應
*/
static async 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);
}
/**
* 刪除舊檔案
* @param {Bailian20231229Client} client - 用戶端(Client)
* @param {string} workspaceId - 業務空間ID
* @param {string} indexId - 知識庫ID
* @param {string} fileId - 檔案ID
* @returns {Promise<bailian20231229.DeleteIndexDocumentResponse>} - 阿里雲百鍊服務的響應
*/
static async deleteIndexDocument(client, workspaceId, indexId, fileId) {
const headers = {};
const req = new bailian20231229.DeleteIndexDocumentRequest({
indexId,
documentIds: [fileId],
});
const runtime = new Util.RuntimeOptions({});
return await client.deleteIndexDocumentWithOptions(workspaceId, req, headers, runtime);
}
/**
* 使用阿里雲百鍊服務更新知識庫
* @param {string} filePath - 檔案(更新後的)的實際本地路徑
* @param {string} workspaceId - 業務空間ID
* @param {string} indexId - 需要更新的知識庫ID
* @param {string} oldFileId - 需要更新的檔案的FileID
* @returns {Promise<string | null>} - 如果成功,返回知識庫ID;否則返回null
*/
static async updateKnowledgeBase(filePath, workspaceId, indexId, oldFileId) {
const categoryId = 'default';
const parser = 'DASHSCOPE_DOCMIND';
const sourceType = 'DATA_CENTER_FILE';
try {
console.log("步驟1:建立Client");
const client = this.createClient();
console.log("步驟2:準備檔案資訊");
const fileName = path.basename(filePath);
const fileMd5 = await this.calculateMD5(filePath);
const fileSize = this.getFileSize(filePath);
console.log("步驟3:向阿里雲百鍊申請上傳租約");
const leaseRes = await this.applyLease(client, categoryId, fileName, fileMd5, fileSize, workspaceId);
const leaseId = leaseRes.body.data.fileUploadLeaseId;
const uploadUrl = leaseRes.body.data.param.url;
const uploadHeaders = leaseRes.body.data.param.headers;
console.log("步驟4:上傳檔案到臨時儲存");
await this.uploadFile(uploadUrl, uploadHeaders, filePath);
console.log("步驟5:添加檔案到類目中");
const addRes = await this.addFile(client, leaseId, parser, categoryId, workspaceId);
const fileId = addRes.body.data.fileId;
console.log("步驟6:檢查阿里雲百鍊中的檔案狀態");
while (true) {
const descRes = await this.describeFile(client, workspaceId, fileId);
const status = descRes.body.data.status;
console.log(`當前檔案狀態:${status}`);
if (status === 'INIT') {
console.log("檔案待解析,請稍候...");
} else if (status === 'PARSING') {
console.log("檔案解析中,請稍候...");
} else if (status === 'PARSE_SUCCESS') {
console.log("檔案解析完成!");
break;
} else {
console.error(`未知的檔案狀態:${status},請聯絡支援人員。`);
return null;
}
await this.sleep(5);
}
console.log("步驟7:提交追加檔案任務");
const indexAddResponse = await this.submitIndexAddDocumentsJob(client, workspaceId, indexId, fileId, sourceType);
const jobId = indexAddResponse.body.data.id;
console.log("步驟8:等待追加任務完成");
while (true) {
const getJobStatusResponse = await this.getIndexJobStatus(client, workspaceId, jobId, indexId);
const status = getJobStatusResponse.body.data.status;
console.log(`當前索引任務狀態:${status}`);
if (status === 'COMPLETED') {
break;
}
await this.sleep(5);
}
console.log("步驟9:刪除舊檔案");
await this.deleteIndexDocument(client, workspaceId, indexId, oldFileId);
console.log("阿里雲百鍊知識庫更新成功!");
return indexId;
} catch (e) {
console.error(`發生錯誤:${e.message}`);
return null;
}
}
/**
* 等待指定時間(秒)
* @param {number} seconds - 等待時間(秒)
* @returns {Promise<void>}
*/
static sleep(seconds) {
return new Promise(resolve => setTimeout(resolve, seconds * 1000));
}
static async main(args) {
if (!this.checkEnvironmentVariables()) {
console.log("環境變數校正未通過。");
return;
}
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
try {
const filePath = await new Promise((resolve, reject) => {
readline.question("請輸入您需要上傳檔案(更新後的)的實際本地路徑(以Linux為例:/xxx/xxx/阿里雲百鍊系列手機產品介紹.docx):", (ans) => {
ans.trim() ? resolve(ans) : reject(new Error("路徑不可為空"));
});
});
const indexId = await new Promise((resolve, reject) => {
// 知識庫ID即 CreateIndex 介面返回的 Data.Id,您也可以在阿里雲百鍊控制台的知識庫頁面擷取。
readline.question("請輸入需要更新的知識庫ID:", (ans) => {
ans.trim() ? resolve(ans) : reject(new Error("知識庫ID不可為空"));
});
});
const oldFileId = await new Promise((resolve, reject) => {
// FileId即 AddFile 介面返回的 FileId。您也可以在阿里雲百鍊控制台的應用資料頁面,單擊檔案名稱旁的 ID 表徵圖擷取。
readline.question("請輸入需要更新的檔案的 FileID:", (ans) => {
ans.trim() ? resolve(ans) : reject(new Error("FileID不可為空"));
});
});
const workspaceId = process.env.WORKSPACE_ID;
const result = await this.updateKnowledgeBase(filePath, workspaceId, indexId, oldFileId);
if (result) console.log(`知識庫ID: ${result}`);
else console.log("知識庫更新失敗。");
} catch (err) {
console.error(err.message);
} finally {
readline.close();
}
}
}
exports.KbUpdate = KbUpdate;
KbUpdate.main(process.argv.slice(2));
// 範例程式碼僅供參考,請勿在生產環境中直接使用
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Tea;
using Tea.Utils;
namespace AlibabaCloud.SDK.KnowledgeBase
{
public class KnowledgeBaseUpdate
{
/// <summary>
/// 檢查並提示設定必要的環境變數。
/// </summary>
/// <returns>如果所有必需的環境變數都已設定,返回 true;否則返回 false。</returns>
public static bool CheckEnvironmentVariables()
{
var requiredVars = new Dictionary<string, string>
{
{ "ALIBABA_CLOUD_ACCESS_KEY_ID", "阿里雲存取金鑰ID" },
{ "ALIBABA_CLOUD_ACCESS_KEY_SECRET", "阿里雲存取金鑰密碼" },
{ "WORKSPACE_ID", "阿里雲百鍊業務空間ID" }
};
var missingVars = new List<string>();
foreach (var entry in requiredVars)
{
string value = Environment.GetEnvironmentVariable(entry.Key);
if (string.IsNullOrEmpty(value))
{
missingVars.Add(entry.Key);
Console.WriteLine($"錯誤:請設定 {entry.Key} 環境變數({entry.Value})");
}
}
return missingVars.Count == 0;
}
/// <summary>
/// 計算檔案的MD5值。
/// </summary>
/// <param name="filePath">檔案本地路徑</param>
/// <returns>檔案的MD5值</returns>
/// <exception cref="Exception">計算過程中發生錯誤時拋出異常</exception>
public static string CalculateMD5(string filePath)
{
using (var md5 = MD5.Create())
{
using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
byte[] hashBytes = md5.ComputeHash(stream);
StringBuilder sb = new StringBuilder();
foreach (byte b in hashBytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
}
/// <summary>
/// 擷取檔案大小(以位元組為單位)。
/// </summary>
/// <param name="filePath">檔案本地路徑</param>
/// <returns>檔案大小(以位元組為單位)</returns>
public static string GetFileSize(string filePath)
{
var file = new FileInfo(filePath);
return file.Length.ToString();
}
/// <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.ap-southeast-1.aliyuncs.com";
return new AlibabaCloud.SDK.Bailian20231229.Client(config);
}
/// <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 static 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);
}
/// <summary>
/// 上傳檔案到臨時儲存。
/// </summary>
/// <param name="preSignedUrl">上傳租約中的 URL</param>
/// <param name="headers">上傳請求的頭部</param>
/// <param name="filePath">檔案本地路徑</param>
/// <exception cref="Exception">上傳過程中發生錯誤時拋出異常</exception>
public static void UploadFile(string preSignedUrl, Dictionary<string, string> headers, string filePath)
{
var file = new FileInfo(filePath);
if (!File.Exists(filePath))
{
throw new ArgumentException($"檔案不存在或不是普通檔案: {filePath}");
}
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
var url = new Uri(preSignedUrl);
var conn = (HttpWebRequest)WebRequest.Create(url);
conn.Method = "PUT";
conn.ContentType = headers["Content-Type"];
conn.Headers.Add("X-bailian-extra", headers["X-bailian-extra"]);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)
{
conn.GetRequestStream().Write(buffer, 0, bytesRead);
}
using (var response = (HttpWebResponse)conn.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception($"上傳失敗: {response.StatusCode}");
}
}
}
}
/// <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 static 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);
}
/// <summary>
/// 查詢檔案的基本資料。
/// </summary>
/// <param name="client">用戶端對象</param>
/// <param name="workspaceId">業務空間ID</param>
/// <param name="fileId">檔案ID</param>
/// <returns>阿里雲百鍊服務的響應對象</returns>
/// <exception cref="Exception">調用過程中發生錯誤時拋出異常</exception>
public static 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);
}
/// <summary>
/// 向一個文檔搜尋類知識庫追加匯入已解析的檔案
/// </summary>
/// <param name="client">用戶端(Client)</param>
/// <param name="workspaceId">業務空間ID</param>
/// <param name="indexId">知識庫ID</param>
/// <param name="fileId">檔案ID</param>
/// <param name="sourceType">資料類型</param>
/// <returns>阿里雲百鍊服務的響應</returns>
public static AlibabaCloud.SDK.Bailian20231229.Models.SubmitIndexAddDocumentsJobResponse SubmitIndexAddDocumentsJob(
AlibabaCloud.SDK.Bailian20231229.Client client,
string workspaceId,
string indexId,
string fileId,
string sourceType)
{
var headers = new Dictionary<string, string>() { };
var submitIndexAddDocumentsJobRequest = new AlibabaCloud.SDK.Bailian20231229.Models.SubmitIndexAddDocumentsJobRequest
{
IndexId = indexId,
DocumentIds = new List<string> { fileId },
SourceType = sourceType
};
var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
return client.SubmitIndexAddDocumentsJobWithOptions(workspaceId, submitIndexAddDocumentsJobRequest, headers, runtime);
}
/// <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 static 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);
}
/// <summary>
/// 從指定的文檔搜尋類知識庫中永久刪除一個或多個檔案
/// </summary>
/// <param name="client">用戶端(Client)</param>
/// <param name="workspaceId">業務空間ID</param>
/// <param name="indexId">知識庫ID</param>
/// <param name="fileId">檔案ID</param>
/// <returns>阿里雲百鍊服務的響應</returns>
public static AlibabaCloud.SDK.Bailian20231229.Models.DeleteIndexDocumentResponse DeleteIndexDocument(
AlibabaCloud.SDK.Bailian20231229.Client client,
string workspaceId,
string indexId,
string fileId)
{
var headers = new Dictionary<string, string>() { };
var deleteIndexDocumentRequest = new AlibabaCloud.SDK.Bailian20231229.Models.DeleteIndexDocumentRequest
{
IndexId = indexId,
DocumentIds = new List<string> { fileId }
};
var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
return client.DeleteIndexDocumentWithOptions(workspaceId, deleteIndexDocumentRequest, headers, runtime);
}
/// <summary>
/// 使用阿里雲百鍊服務更新知識庫
/// </summary>
/// <param name="filePath">檔案(更新後的)的實際本地路徑</param>
/// <param name="workspaceId">業務空間ID</param>
/// <param name="indexId">需要更新的知識庫ID</param>
/// <param name="oldFileId">需要更新的檔案的FileID</param>
/// <returns>如果成功,返回知識庫ID;否則返回 null</returns>
public static string UpdateKnowledgeBase(string filePath, string workspaceId, string indexId, string oldFileId)
{
// 設定預設值
string categoryId = "default";
string parser = "DASHSCOPE_DOCMIND";
string sourceType = "DATA_CENTER_FILE";
try
{
Console.WriteLine("步驟1:建立Client");
var client = CreateClient();
Console.WriteLine("步驟2:準備檔案資訊");
string fileName = Path.GetFileName(filePath);
string fileMd5 = CalculateMD5(filePath);
string fileSize = GetFileSize(filePath);
Console.WriteLine("步驟3:向阿里雲百鍊申請上傳租約");
Bailian20231229.Models.ApplyFileUploadLeaseResponse leaseResponse = ApplyLease(client, categoryId, fileName, fileMd5, fileSize, workspaceId);
string leaseId = leaseResponse.Body.Data.FileUploadLeaseId;
string uploadUrl = leaseResponse.Body.Data.Param.Url;
var uploadHeaders = leaseResponse.Body.Data.Param.Headers;
Console.WriteLine("步驟4:上傳檔案到臨時儲存");
// 請自行安裝Newtonsoft.Json
var uploadHeadersMap = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(uploadHeaders));
UploadFile(uploadUrl, uploadHeadersMap, filePath);
Console.WriteLine("步驟5:添加檔案到類目中");
Bailian20231229.Models.AddFileResponse addResponse = AddFile(client, leaseId, parser, categoryId, workspaceId);
string fileId = addResponse.Body.Data.FileId;
Console.WriteLine("步驟6:檢查阿里雲百鍊中的檔案狀態");
while (true)
{
Bailian20231229.Models.DescribeFileResponse describeResponse = DescribeFile(client, workspaceId, fileId);
string status = describeResponse.Body.Data.Status;
Console.WriteLine("當前檔案狀態:" + status);
if ("INIT".Equals(status))
{
Console.WriteLine("檔案待解析,請稍候...");
}
else if ("PARSING".Equals(status))
{
Console.WriteLine("檔案解析中,請稍候...");
}
else if ("PARSE_SUCCESS".Equals(status))
{
Console.WriteLine("檔案解析完成!");
break;
}
else
{
Console.WriteLine("未知的檔案狀態:" + status + ",請聯絡支援人員。");
return null;
}
Thread.Sleep(5000);
}
Console.WriteLine("步驟7:提交追加檔案任務");
Bailian20231229.Models.SubmitIndexAddDocumentsJobResponse indexAddResponse = SubmitIndexAddDocumentsJob(client, workspaceId, indexId, fileId, sourceType);
string jobId = indexAddResponse.Body.Data.Id;
Console.WriteLine("步驟8:等待追加任務完成");
while (true)
{
Bailian20231229.Models.GetIndexJobStatusResponse jobStatusResponse = GetIndexJobStatus(client, workspaceId, jobId, indexId);
string status = jobStatusResponse.Body.Data.Status;
Console.WriteLine("當前索引任務狀態:" + status);
if ("COMPLETED".Equals(status))
{
break;
}
Thread.Sleep(5000);
}
Console.WriteLine("步驟9:刪除舊檔案");
DeleteIndexDocument(client, workspaceId, indexId, oldFileId);
Console.WriteLine("阿里雲百鍊知識庫更新成功!");
return indexId;
}
catch (Exception e)
{
Console.WriteLine("發生錯誤:" + e.Message);
return null;
}
}
/// <summary>
/// 主函數。
/// </summary>
public static void Main(string[] args)
{
if (!CheckEnvironmentVariables())
{
Console.WriteLine("環境變數校正未通過。");
return;
}
Console.Write("請輸入您需要上傳檔案(更新後的)的實際本地路徑(以Linux為例:/xxx/xxx/阿里雲百鍊系列手機產品介紹.docx):");
string filePath = Console.ReadLine();
Console.Write("請輸入需要更新的知識庫ID:"); // 即 CreateIndex 介面返回的 Data.Id,您也可以在阿里雲百鍊控制台的知識庫頁面擷取。
string indexId = Console.ReadLine();
Console.Write("請輸入需要更新的檔案的 FileID:"); // 即 AddFile 介面返回的 FileId。您也可以在阿里雲百鍊控制台的應用資料頁面,單擊檔案名稱旁的 ID 表徵圖擷取。
string oldFileId = Console.ReadLine();
string workspaceId = Environment.GetEnvironmentVariable("WORKSPACE_ID");
string result = UpdateKnowledgeBase(filePath, workspaceId, indexId, oldFileId);
if (result != null)
{
Console.WriteLine("知識庫更新成功,返回知識庫ID: " + result);
}
else
{
Console.WriteLine("知識庫更新失敗。");
}
}
}
}
// 範例程式碼僅供參考,請勿在生產環境中直接使用
package main
import (
"bufio"
"crypto/md5"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"time"
bailian20231229 "github.com/alibabacloud-go/bailian-20231229/v2/client"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
"github.com/go-resty/resty/v2"
)
// CheckEnvironmentVariables 檢查並提示設定必要的環境變數。
func CheckEnvironmentVariables() bool {
// 必要的環境變數及其描述。
requiredVars := map[string]string{
"ALIBABA_CLOUD_ACCESS_KEY_ID": "阿里雲存取金鑰ID",
"ALIBABA_CLOUD_ACCESS_KEY_SECRET": "阿里雲存取金鑰密碼",
"WORKSPACE_ID": "阿里雲百鍊業務空間ID",
}
var missingVars []string
for varName, desc := range requiredVars {
if os.Getenv(varName) == "" {
fmt.Printf("錯誤:請設定 %s 環境變數 (%s)\n", varName, desc)
missingVars = append(missingVars, varName)
}
}
return len(missingVars) == 0
}
// CalculateMD5 計算檔案的MD5值。
//
// 參數:
// - filePath (string): 檔案本地路徑。
//
// 返回:
// - string: 檔案的MD5值。
// - error: 錯誤資訊。
func CalculateMD5(filePath string) (_result string, _err error) {
file, err := os.Open(filePath)
if err != nil {
return "", err
}
defer file.Close()
md5Hash := md5.New()
_, err = io.Copy(md5Hash, file)
if err != nil {
return "", err
}
return fmt.Sprintf("%x", md5Hash.Sum(nil)), nil
}
// GetFileSize 擷取檔案大小(以位元組為單位)。
//
// 參數:
// - filePath (string): 檔案本地路徑。
//
// 返回:
// - string: 檔案大小(以位元組為單位)。
// - error: 錯誤資訊。
func GetFileSize(filePath string) (_result string, _err error) {
info, err := os.Stat(filePath)
if err != nil {
return "", err
}
return fmt.Sprintf("%d", info.Size()), nil
}
// 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.ap-southeast-1.aliyuncs.com")
_result = &bailian20231229.Client{}
_result, _err = bailian20231229.NewClient(config)
return _result, _err
}
// 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)
}
// UploadFile 將檔案上傳到阿里雲百鍊服務。
//
// 參數:
// - preSignedUrl (string): 上傳租約中的 URL。
// - headers (map[string]string): 上傳請求的頭部。
// - filePath (string): 檔案本地路徑。
func UploadFile(preSignedUrl string, headers map[string]string, filePath string) error {
file, err := os.Open(filePath)
if err != nil {
return err
}
defer file.Close()
body, err := io.ReadAll(file)
if err != nil {
return err
}
client := resty.New()
uploadHeaders := map[string]string{
"X-bailian-extra": headers["X-bailian-extra"],
"Content-Type": headers["Content-Type"],
}
resp, err := client.R().
SetHeaders(uploadHeaders).
SetBody(body).
Put(preSignedUrl)
if err != nil {
return err
}
if resp.IsError() {
return fmt.Errorf("HTTP 錯誤: %d", resp.StatusCode())
}
return nil
}
// 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)
}
// DescribeFile 擷取檔案的基本資料。
//
// 參數:
// - client (bailian20231229.Client): 用戶端(Client)。
// - workspaceId (string): 業務空間ID。
// - fileId (string): 檔案ID。
//
// 返回:
// - *bailian20231229.DescribeFileResponse: 阿里雲百鍊服務的響應。
// - 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)
}
// SubmitIndexAddDocumentsJob 向一個文檔搜尋類知識庫追加匯入已解析的檔案。
//
// 參數:
// - client (bailian20231229.Client): 用戶端(Client)。
// - workspaceId (string): 業務空間ID。
// - indexId(string): 知識庫ID。
// - fileId(string): 檔案ID。
// - sourceType(string): 資料類型。
//
// 返回:
// - *bailian20231229.SubmitIndexAddDocumentsJobResponse: 阿里雲百鍊服務的響應。
// - error: 錯誤資訊。
func SubmitIndexAddDocumentsJob(client *bailian20231229.Client, workspaceId, indexId, fileId, sourceType string) (_result *bailian20231229.SubmitIndexAddDocumentsJobResponse, _err error) {
headers := make(map[string]*string)
submitIndexAddDocumentsJobRequest := &bailian20231229.SubmitIndexAddDocumentsJobRequest{
IndexId: tea.String(indexId),
SourceType: tea.String(sourceType),
DocumentIds: []*string{tea.String(fileId)},
}
runtime := &util.RuntimeOptions{}
return client.SubmitIndexAddDocumentsJobWithOptions(tea.String(workspaceId), submitIndexAddDocumentsJobRequest, headers, runtime)
}
// 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)
}
// DeleteIndexDocument 從指定的文檔搜尋類知識庫中永久刪除一個或多個檔案。
//
// 參數:
// - client (bailian20231229.Client): 用戶端(Client)。
// - workspaceId (string): 業務空間ID。
// - indexId (string): 知識庫ID。
// - fileId (string): 檔案ID。
//
// 返回:
// - *bailian20231229.DeleteIndexDocumentResponse: 阿里雲百鍊服務的響應。
// - error: 錯誤資訊。
func DeleteIndexDocument(client *bailian20231229.Client, workspaceId, indexId, fileId string) (*bailian20231229.DeleteIndexDocumentResponse, error) {
headers := make(map[string]*string)
deleteIndexDocumentRequest := &bailian20231229.DeleteIndexDocumentRequest{
IndexId: tea.String(indexId),
DocumentIds: []*string{tea.String(fileId)},
}
runtime := &util.RuntimeOptions{}
return client.DeleteIndexDocumentWithOptions(tea.String(workspaceId), deleteIndexDocumentRequest, headers, runtime)
}
// UpdateKnowledgeBase 使用阿里雲百鍊服務更新知識庫。
//
// 參數:
// - filePath (string): 檔案(更新後的)的實際本地路徑。
// - workspaceId (string): 業務空間ID。
// - indexId (string): 需要更新的知識庫ID。
// - oldFileId (string): 需要更新的檔案的FileID。
//
// 返回:
// - string: 如果成功,返回知識庫ID;否則返回Null 字元串。
// - error: 錯誤資訊。
func UpdateKnowledgeBase(filePath, workspaceId, indexId, oldFileId string) (_result string, _err error) {
// 設定預設值
categoryId := "default"
parser := "DASHSCOPE_DOCMIND"
sourceType := "DATA_CENTER_FILE"
fmt.Println("步驟1:建立Client")
client, err := CreateClient()
if err != nil {
return "", err
}
fmt.Println("步驟2:準備檔案資訊")
fileName := filepath.Base(filePath)
fileMD5, err := CalculateMD5(filePath)
if err != nil {
return "", err
}
fileSizeStr, err := GetFileSize(filePath)
if err != nil {
return "", err
}
fmt.Println("步驟3:向阿里雲百鍊申請上傳租約")
leaseResponse, err := ApplyLease(client, categoryId, fileName, fileMD5, fileSizeStr, workspaceId)
if err != nil {
return "", err
}
leaseId := tea.StringValue(leaseResponse.Body.Data.FileUploadLeaseId)
uploadURL := tea.StringValue(leaseResponse.Body.Data.Param.Url)
uploadHeaders := leaseResponse.Body.Data.Param.Headers
jsonData, err := json.Marshal(uploadHeaders)
if err != nil {
return "", err
}
var uploadHeadersMap map[string]string
err = json.Unmarshal(jsonData, &uploadHeadersMap)
if err != nil {
return "", err
}
fmt.Println("步驟4:上傳檔案到臨時儲存")
err = UploadFile(uploadURL, uploadHeadersMap, filePath)
if err != nil {
return "", err
}
fmt.Println("步驟5:添加檔案到類目中")
addResponse, err := AddFile(client, leaseId, parser, categoryId, workspaceId)
if err != nil {
return "", err
}
fileId := tea.StringValue(addResponse.Body.Data.FileId)
fmt.Println("步驟6:檢查阿里雲百鍊中的檔案狀態")
for {
describeResponse, err := DescribeFile(client, workspaceId, fileId)
if err != nil {
return "", err
}
status := tea.StringValue(describeResponse.Body.Data.Status)
fmt.Printf("當前檔案狀態:%s\n", status)
if status == "INIT" {
fmt.Println("檔案待解析,請稍候...")
} else if status == "PARSING" {
fmt.Println("檔案解析中,請稍候...")
} else if status == "PARSE_SUCCESS" {
fmt.Println("檔案解析完成!")
break
} else {
fmt.Printf("未知的檔案狀態:%s,請聯絡支援人員。\n", status)
return "", fmt.Errorf("unknown document status: %s", status)
}
time.Sleep(5 * time.Second)
}
// 提交追加檔案任務
fmt.Println("步驟7:提交追加檔案任務")
indexAddResponse, err := SubmitIndexAddDocumentsJob(client, workspaceId, indexId, fileId, sourceType)
if err != nil {
return "", err
}
jobId := tea.StringValue(indexAddResponse.Body.Data.Id)
// 等待任務完成
fmt.Println("步驟8:等待追加任務完成")
for {
getIndexJobStatusResponse, err := GetIndexJobStatus(client, workspaceId, jobId, indexId)
if err != nil {
return "", err
}
status := tea.StringValue(getIndexJobStatusResponse.Body.Data.Status)
fmt.Printf("當前索引任務狀態:%s\n", status)
if status == "COMPLETED" {
break
}
time.Sleep(5 * time.Second)
}
// 刪除舊檔案
fmt.Println("步驟9:刪除舊檔案")
_, err = DeleteIndexDocument(client, workspaceId, indexId, oldFileId)
if err != nil {
return "", err
}
fmt.Println("阿里雲百鍊知識庫更新成功!")
return indexId, nil
}
// 主函數。
func main() {
if !CheckEnvironmentVariables() {
fmt.Println("環境變數校正未通過。")
return
}
// 建立 scanner 用於讀取輸入
reader := bufio.NewReader(os.Stdin)
fmt.Print("請輸入您需要上傳檔案(更新後的)的實際本地路徑(以Linux為例:/xxx/xxx/阿里雲百鍊系列手機產品介紹.docx):")
filePath, _ := reader.ReadString('\n')
filePath = strings.TrimSpace(filePath)
fmt.Print("請輸入需要更新的知識庫ID:") // 即 CreateIndex 介面返回的 Data.Id,您也可以在阿里雲百鍊控制台的知識庫頁面擷取。
indexId, _ := reader.ReadString('\n')
indexId = strings.TrimSpace(indexId)
fmt.Print("請輸入需要更新的檔案的 FileID:") // 即 AddFile 介面返回的 FileId。您也可以在阿里雲百鍊控制台的應用資料頁面,單擊檔案名稱旁的 ID 表徵圖擷取。
oldFileId, _ := reader.ReadString('\n')
oldFileId = strings.TrimSpace(oldFileId)
workspaceId := os.Getenv("WORKSPACE_ID")
result, err := UpdateKnowledgeBase(filePath, workspaceId, indexId, oldFileId)
if err != nil {
fmt.Printf("發生錯誤:%v\n", err)
return
}
if result != "" {
fmt.Printf("知識庫更新成功,返回知識庫ID: %s\n", result)
} else {
fmt.Println("知識庫更新失敗。")
}
}
管理知識庫
重要
- 在調用本樣本之前,請務必完成上述所有前置步驟。子帳號調用本樣本前需擷取AliyunBailianDataFullAccess策略。
- 若您使用了 IDE 或其他輔助開發外掛程式,需將
ALIBABA_CLOUD_ACCESS_KEY_ID、ALIBABA_CLOUD_ACCESS_KEY_SECRET和WORKSPACE_ID變數配置到相應的開發環境中。
# 範例程式碼僅供參考,請勿在生產環境中直接使用
import os
from alibabacloud_bailian20231229 import models as bailian_20231229_models
from alibabacloud_bailian20231229.client import Client as bailian20231229Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient
def check_environment_variables():
"""檢查並提示設定必要的環境變數"""
required_vars = {
'ALIBABA_CLOUD_ACCESS_KEY_ID': '阿里雲存取金鑰ID',
'ALIBABA_CLOUD_ACCESS_KEY_SECRET': '阿里雲存取金鑰密碼',
'WORKSPACE_ID': '阿里雲百鍊業務空間ID'
}
missing_vars = []
for var, description in required_vars.items():
if not os.environ.get(var):
missing_vars.append(var)
print(f"錯誤:請設定 {var} 環境變數 ({description})")
return len(missing_vars) == 0
# 建立用戶端(Client)
def 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)
# 查看知識庫
def list_indices(client, workspace_id):
"""
擷取指定業務空間下一個或多個知識庫的詳細資料。
參數:
client (bailian20231229Client): 用戶端(Client)。
workspace_id (str): 業務空間ID。
返回:
阿里雲百鍊服務的響應。
"""
headers = {}
list_indices_request = bailian_20231229_models.ListIndicesRequest()
runtime = util_models.RuntimeOptions()
return client.list_indices_with_options(workspace_id, list_indices_request, headers, runtime)
# 刪除知識庫
def delete_index(client, workspace_id, index_id):
"""
永久性刪除指定的知識庫。
參數:
client (bailian20231229Client): 用戶端(Client)。
workspace_id (str): 業務空間ID。
index_id (str): 知識庫ID。
返回:
阿里雲百鍊服務的響應。
"""
headers = {}
delete_index_request = bailian_20231229_models.DeleteIndexRequest(
index_id=index_id
)
runtime = util_models.RuntimeOptions()
return client.delete_index_with_options(workspace_id, delete_index_request, headers, runtime)
def main():
if not check_environment_variables():
print("環境變數校正未通過。")
return
try:
start_option = input(
"請選擇要執行的操作:\n1. 查看知識庫\n2. 刪除知識庫\n請輸入選項(1或2):")
if start_option == '1':
# 查看知識庫
print("\n執行查看知識庫")
workspace_id = os.environ.get('WORKSPACE_ID')
client = create_client()
list_indices_response = list_indices(client, workspace_id)
print(UtilClient.to_jsonstring(list_indices_response.body.data))
elif start_option == '2':
print("\n執行刪除知識庫")
workspace_id = os.environ.get('WORKSPACE_ID')
index_id = input("請輸入知識庫ID:") # 即 CreateIndex 介面返回的 Data.Id,您也可以在阿里雲百鍊控制台的知識庫頁面擷取。
# 刪除前二次確認
while True:
confirm = input(f"您確定要永久性刪除該知識庫 {index_id} 嗎?(y/n): ").strip().lower()
if confirm == 'y':
break
elif confirm == 'n':
print("已取消刪除操作。")
return
else:
print("無效輸入,請輸入 y 或 n。")
client = create_client()
resp = delete_index(client, workspace_id, index_id)
if resp.body.status == 200:
print(f"知識庫{index_id}刪除成功!")
else:
err_info = UtilClient.to_jsonstring(resp.body)
print(f"發生錯誤:{err_info}")
else:
print("無效的選項,程式退出。")
return
except Exception as e:
print(f"發生錯誤:{e}")
return
if __name__ == '__main__':
main()
// 範例程式碼僅供參考,請勿在生產環境中直接使用
import com.aliyun.bailian20231229.models.DeleteIndexResponse;
import com.aliyun.bailian20231229.models.ListIndicesResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.*;
public class KnowledgeBaseManage {
/**
* 檢查並提示設定必要的環境變數。
*
* @return true 如果所有必需的環境變數都已設定,否則 false
*/
public static boolean checkEnvironmentVariables() {
Map<String, String> requiredVars = new HashMap<>();
requiredVars.put("ALIBABA_CLOUD_ACCESS_KEY_ID", "阿里雲存取金鑰ID");
requiredVars.put("ALIBABA_CLOUD_ACCESS_KEY_SECRET", "阿里雲存取金鑰密碼");
requiredVars.put("WORKSPACE_ID", "阿里雲百鍊業務空間ID");
List<String> missingVars = new ArrayList<>();
for (Map.Entry<String, String> entry : requiredVars.entrySet()) {
String value = System.getenv(entry.getKey());
if (value == null || value.isEmpty()) {
missingVars.add(entry.getKey());
System.out.println("錯誤:請設定 " + entry.getKey() + " 環境變數 (" + entry.getValue() + ")");
}
}
return missingVars.isEmpty();
}
/**
* 建立並配置用戶端(Client)
*
* @return 配置好的用戶端(Client)
*/
public static com.aliyun.bailian20231229.Client createClient() throws Exception {
com.aliyun.credentials.Client credential = new com.aliyun.credentials.Client();
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
.setCredential(credential);
// 下方接入地址以公用雲端的公網接入地址為例,可按需更換接入地址。
config.endpoint = "bailian.cn-beijing.aliyuncs.com";
return new com.aliyun.bailian20231229.Client(config);
}
/**
* 擷取指定業務空間下一個或多個知識庫的詳細資料
*
* @param client 用戶端(Client)
* @param workspaceId 業務空間ID
* @return 阿里雲百鍊服務的響應
*/
public static ListIndicesResponse listIndices(com.aliyun.bailian20231229.Client client, String workspaceId) throws Exception {
Map<String, String> headers = new HashMap<>();
com.aliyun.bailian20231229.models.ListIndicesRequest listIndicesRequest = new com.aliyun.bailian20231229.models.ListIndicesRequest();
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
return client.listIndicesWithOptions(workspaceId, listIndicesRequest, headers, runtime);
}
/**
* 永久性刪除指定的知識庫
*
* @param client 用戶端(Client)
* @param workspaceId 業務空間ID
* @param indexId 知識庫ID
* @return 阿里雲百鍊服務的響應
*/
public static DeleteIndexResponse deleteIndex(com.aliyun.bailian20231229.Client client, String workspaceId, String indexId) throws Exception {
Map<String, String> headers = new HashMap<>();
com.aliyun.bailian20231229.models.DeleteIndexRequest deleteIndexRequest = new com.aliyun.bailian20231229.models.DeleteIndexRequest();
deleteIndexRequest.setIndexId(indexId);
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
return client.deleteIndexWithOptions(workspaceId, deleteIndexRequest, headers, runtime);
}
/**
* 主函數
*/
public static void main(String[] args) {
if (!checkEnvironmentVariables()) {
System.out.println("環境變數校正未通過。");
return;
}
try {
Scanner scanner = new Scanner(System.in);
System.out.print("請選擇要執行的操作:\n1. 查看知識庫\n2. 刪除知識庫\n請輸入選項(1或2):");
String startOption = scanner.nextLine();
com.aliyun.bailian20231229.Client client = createClient();
if (startOption.equals("1")) {
// 查看知識庫
System.out.println("\n執行查看知識庫");
String workspaceId = System.getenv("WORKSPACE_ID");
ListIndicesResponse response = listIndices(client, workspaceId);
// 請自行安裝jackson-databind將響應轉換為 JSON 字串
ObjectMapper mapper = new ObjectMapper();
String result = mapper.writeValueAsString(response.getBody().getData());
System.out.println(result);
} else if (startOption.equals("2")) {
System.out.println("\n執行刪除知識庫");
String workspaceId = System.getenv("WORKSPACE_ID");
System.out.print("請輸入知識庫ID:"); // 即 CreateIndex 介面返回的 Data.Id,您也可以在阿里雲百鍊控制台的知識庫頁面擷取。
String indexId = scanner.nextLine();
// 刪除前二次確認
boolean confirm = false;
while (!confirm) {
System.out.print("您確定要永久性刪除該知識庫 " + indexId + " 嗎?(y/n): ");
String input = scanner.nextLine().trim().toLowerCase();
if (input.equals("y")) {
confirm = true;
} else if (input.equals("n")) {
System.out.println("已取消刪除操作。");
return;
} else {
System.out.println("無效輸入,請輸入 y 或 n。");
}
}
DeleteIndexResponse resp = deleteIndex(client, workspaceId, indexId);
if (resp.getBody().getStatus().equals("200")) {
System.out.println("知識庫" + indexId + "刪除成功!");
} else {
ObjectMapper mapper = new ObjectMapper();
System.out.println("發生錯誤:" + mapper.writeValueAsString(resp.getBody()));
}
} else {
System.out.println("無效的選項,程式退出。");
}
} catch (Exception e) {
System.out.println("發生錯誤:" + e.getMessage());
}
}
}
<?php
// 範例程式碼僅供參考,請勿在生產環境中直接使用
namespace AlibabaCloud\SDK\KnowledgeBase;
use AlibabaCloud\Dara\Models\RuntimeOptions;
use AlibabaCloud\SDK\Bailian\V20231229\Bailian;
use AlibabaCloud\SDK\Bailian\V20231229\Models\DeleteIndexRequest;
use AlibabaCloud\SDK\Bailian\V20231229\Models\ListIndexDocumentsRequest;
use \Exception;
use Darabonba\OpenApi\Models\Config;
class KnowledgeBaseManage {
/**
* 檢查並提示設定必要的環境變數。
*
* @return bool 返回 true 如果所有必需的環境變數都已設定,否則 false。
*/
public static function checkEnvironmentVariables() {
$requiredVars = [
'ALIBABA_CLOUD_ACCESS_KEY_ID' => '阿里雲存取金鑰ID',
'ALIBABA_CLOUD_ACCESS_KEY_SECRET' => '阿里雲存取金鑰密碼',
'WORKSPACE_ID' => '阿里雲百鍊業務空間ID'
];
$missingVars = [];
foreach ($requiredVars as $var => $description) {
if (!getenv($var)) {
$missingVars[] = $var;
echo "錯誤:請設定 $var 環境變數 ($description)\n";
}
}
return count($missingVars) === 0;
}
/**
* 初始化用戶端(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.ap-southeast-1.aliyuncs.com';
return new Bailian($config);
}
/**
* 擷取指定業務空間下一個或多個知識庫的詳細資料
*
* @param Bailian $client 用戶端對象(Client)
* @param string $workspaceId 業務空間ID
* @return ListIndicesResponse 阿里雲百鍊服務的響應
* @throws Exception
*/
public static function listIndices($client, $workspaceId) {
$headers = [];
$listIndexDocumentsRequest = new ListIndexDocumentsRequest([]);
$runtime = new RuntimeOptions([]);
// 調用用戶端方法
return $client->listIndicesWithOptions($workspaceId, $listIndexDocumentsRequest, $headers, $runtime);
}
/**
* 永久性刪除指定的知識庫
*
* @param Bailian $client 用戶端對象(Client)
* @param string $workspaceId 業務空間ID
* @param string $indexId 知識庫ID
* @return mixed 阿里雲百鍊服務的響應
* @throws Exception
*/
public static function deleteIndex($client, $workspaceId, $indexId) {
$headers = [];
$deleteIndexRequest = new DeleteIndexRequest([
"indexId" => $indexId
]);
$runtime = new RuntimeOptions([]);
return $client->deleteIndexWithOptions($workspaceId, $deleteIndexRequest, $headers, $runtime);
}
/**
* 主函數
*/
public static function main($args) {
if (!self::checkEnvironmentVariables()) {
echo "環境變數校正未通過。\n";
return;
}
try {
echo "請選擇要執行的操作:\n1. 查看知識庫\n2. 刪除知識庫\n請輸入選項(1或2):";
$startOption = trim(fgets(STDIN));
$client = self::createClient();
if ($startOption === "1") {
// 查看知識庫
echo "\n執行查看知識庫\n";
$workspaceId = getenv("WORKSPACE_ID");
$response = self::listIndices($client, $workspaceId);
// 將響應轉換為 JSON 字串
$result = json_encode($response->body->data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
echo $result . "\n";
} elseif ($startOption === "2") {
echo "\n執行刪除知識庫\n";
$workspaceId = getenv("WORKSPACE_ID");
$indexId = readline("請輸入知識庫ID:"); // 即 CreateIndex 介面返回的 Data.Id,您也可以在阿里雲百鍊控制台的知識庫頁面擷取。
// 刪除前二次確認
while (true) {
$confirm = strtolower(trim(readline("您確定要永久性刪除該知識庫 $indexId 嗎?(y/n): ")));
if ($confirm === 'y') {
break;
} elseif ($confirm === 'n') {
echo "已取消刪除操作。\n";
return;
} else {
echo "無效輸入,請輸入 y 或 n。\n";
}
}
$response = self::deleteIndex($client, $workspaceId, $indexId);
if ($response->body->status == "200")
echo "知識庫" . $indexId . "刪除成功!\n";
else
echo "發生錯誤:" . json_encode($response->body) . "\n";
} else {
echo "無效的選項,程式退出。\n";
}
} catch (Exception $e) {
echo "發生錯誤:" . $e->getMessage() . "\n";
}
}
}
// 假定autoload.php位於當前代碼檔案所在目錄的上一級目錄中,請根據您的專案實際結構調整。
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
require_once $path;
}
KnowledgeBaseManage::main(array_slice($argv, 1));
// 範例程式碼僅供參考,請勿在生產環境中直接使用
'use strict';
const bailian20231229 = require('@alicloud/bailian20231229');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Tea = require('@alicloud/tea-typescript');
class KbManage {
/**
* 檢查並提示設定必要的環境變數
* @returns {boolean} - 如果所有必需的環境變數都已設定,返回 true;否則返回 false
*/
static checkEnvironmentVariables() {
const requiredVars = {
'ALIBABA_CLOUD_ACCESS_KEY_ID': '阿里雲存取金鑰ID',
'ALIBABA_CLOUD_ACCESS_KEY_SECRET': '阿里雲存取金鑰密碼',
'WORKSPACE_ID': '阿里雲百鍊業務空間ID'
};
const missing = [];
for (const [varName, desc] of Object.entries(requiredVars)) {
if (!process.env[varName]) {
console.error(`錯誤:請設定 ${varName} 環境變數 (${desc})`);
missing.push(varName);
}
}
return missing.length === 0;
}
/**
* 建立並配置用戶端(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.ap-southeast-1.aliyuncs.com';
return new bailian20231229.default(config);
}
/**
* 擷取指定業務空間下一個或多個知識庫的詳細資料
* @param {bailian20231229.Client} client 用戶端(Client)
* @param {string} workspaceId 業務空間ID
* @returns {Promise<bailian20231229.ListIndicesResponse>} 阿里雲百鍊服務的響應
*/
static async listIndices(client, workspaceId) {
const headers = {};
const listIndicesRequest = new bailian20231229.ListIndicesRequest();
const runtime = new Util.RuntimeOptions({});
return await client.listIndicesWithOptions(workspaceId, listIndicesRequest, headers, runtime);
}
/**
* 永久性刪除指定的知識庫
* @param {bailian20231229.Client} client 用戶端(Client)
* @param {string} workspaceId 業務空間ID
* @param {string} indexId 知識庫ID
* @returns {Promise<bailian20231229.DeleteIndexResponse>} 阿里雲百鍊服務的響應
*/
static async deleteIndex(client, workspaceId, indexId) {
const headers = {};
const deleteIndexRequest = new bailian20231229.DeleteIndexRequest({
indexId
});
const runtime = new Util.RuntimeOptions({});
return await client.deleteIndexWithOptions(workspaceId, deleteIndexRequest, headers, runtime);
}
/**
* 使用阿里雲百鍊服務執行操作(查看或刪除知識庫)
*/
static async main(args) {
if (!this.checkEnvironmentVariables()) {
console.log("環境變數校正未通過。");
return;
}
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
try {
const startOption = await new Promise((resolve) => {
readline.question("請選擇要執行的操作:\n1. 查看知識庫\n2. 刪除知識庫\n請輸入選項(1或2):", (ans) => {
resolve(ans.trim());
});
});
if (startOption === '1') {
console.log("\n執行查看知識庫");
const workspaceId = process.env.WORKSPACE_ID;
const client = this.createClient();
const response = await this.listIndices(client, workspaceId);
console.log(JSON.stringify(response.body.data));
} else if (startOption === '2') {
console.log("\n執行刪除知識庫");
const workspaceId = process.env.WORKSPACE_ID;
const indexId = await new Promise((resolve) => {
readline.question("請輸入知識庫ID:", (ans) => { // 即 CreateIndex 介面返回的 Data.Id,您也可以在阿里雲百鍊控制台的知識庫頁面擷取。
resolve(ans.trim());
});
});
// 刪除前二次確認
let confirm = '';
while (confirm !== 'y' && confirm !== 'n') {
confirm = (await new Promise((resolve) => {
readline.question(`您確定要永久性刪除該知識庫 ${indexId} 嗎?(y/n): `, (ans) => {
resolve(ans.trim().toLowerCase());
});
})).toLowerCase();
if (confirm === 'n') {
console.log("已取消刪除操作。");
return;
} else if (confirm !== 'y') {
console.log("無效輸入,請輸入 y 或 n。");
}
}
const client = this.createClient();
const resp = await this.deleteIndex(client, workspaceId, indexId);
if (resp.body.status == '200')
console.log(`知識庫${indexId}刪除成功!`);
else {
const errInfo = JSON.stringify(resp.body);
console.error(`發生錯誤:${errInfo}`)
}
} else {
console.log("無效的選項,程式退出。");
}
} catch (err) {
console.error(`發生錯誤:${err.message}`);
} finally {
readline.close();
}
}
}
exports.KbManage = KbManage;
KbManage.main(process.argv.slice(2));
// 範例程式碼僅供參考,請勿在生產環境中直接使用
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using Tea;
using Tea.Utils;
namespace AlibabaCloud.SDK.KnowledgeBase
{
public class KnowledgeBaseManage
{
/// <summary>
/// 檢查並提示設定必要的環境變數。
/// </summary>
/// <returns>如果所有必需的環境變數都已設定,返回 true;否則返回 false。</returns>
public static bool CheckEnvironmentVariables()
{
var requiredVars = new Dictionary<string, string>
{
{ "ALIBABA_CLOUD_ACCESS_KEY_ID", "阿里雲存取金鑰ID" },
{ "ALIBABA_CLOUD_ACCESS_KEY_SECRET", "阿里雲存取金鑰密碼" },
{ "WORKSPACE_ID", "阿里雲百鍊業務空間ID" }
};
var missingVars = new List<string>();
foreach (var entry in requiredVars)
{
string value = Environment.GetEnvironmentVariable(entry.Key);
if (string.IsNullOrEmpty(value))
{
missingVars.Add(entry.Key);
Console.WriteLine($"錯誤:請設定 {entry.Key} 環境變數({entry.Value})");
}
}
return missingVars.Count == 0;
}
/// <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.ap-southeast-1.aliyuncs.com";
return new AlibabaCloud.SDK.Bailian20231229.Client(config);
}
/// <summary>
/// 擷取指定業務空間下一個或多個知識庫的詳細資料。
/// </summary>
/// <param name="client">用戶端(Client)</param>
/// <param name="workspaceId">業務空間ID</param>
/// <returns>阿里雲百鍊服務的響應</returns>
public static AlibabaCloud.SDK.Bailian20231229.Models.ListIndicesResponse ListIndices(AlibabaCloud.SDK.Bailian20231229.Client client, string workspaceId)
{
var headers = new Dictionary<string, string>() { };
var listIndicesRequest = new Bailian20231229.Models.ListIndicesRequest();
var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
return client.ListIndicesWithOptions(workspaceId, listIndicesRequest, headers, runtime);
}
/// <summary>
/// 永久性刪除指定的知識庫。
/// </summary>
/// <param name="client">用戶端(Client)</param>
/// <param name="workspaceId">業務空間ID</param>
/// <param name="indexId">知識庫ID</param>
/// <returns>阿里雲百鍊服務的響應</returns>
public static AlibabaCloud.SDK.Bailian20231229.Models.DeleteIndexResponse DeleteIndex(AlibabaCloud.SDK.Bailian20231229.Client client, string workspaceId, string indexId)
{
var headers = new Dictionary<string, string>() { };
var deleteIndexRequest = new Bailian20231229.Models.DeleteIndexRequest
{
IndexId = indexId
};
var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
return client.DeleteIndexWithOptions(workspaceId, deleteIndexRequest, headers, runtime);
}
/// <summary>
/// 主函數
/// </summary>
public static void Main(string[] args)
{
if (!CheckEnvironmentVariables())
{
Console.WriteLine("環境變數校正未通過。");
return;
}
try
{
Console.Write("請選擇要執行的操作:\n1. 查看知識庫\n2. 刪除知識庫\n請輸入選項(1或2):");
string startOption = Console.ReadLine();
if (startOption == "1")
{
Console.WriteLine("\n執行查看知識庫");
string workspaceId = Environment.GetEnvironmentVariable("WORKSPACE_ID");
Bailian20231229.Client client = CreateClient();
Bailian20231229.Models.ListIndicesResponse listIndicesResponse = ListIndices(client, workspaceId);
// 請自行安裝Newtonsoft.Json。將響應對象轉為 JSON 字串輸出
var json = JsonConvert.SerializeObject(listIndicesResponse.Body.Data, Formatting.Indented);
Console.WriteLine(json);
}
else if (startOption == "2")
{
Console.WriteLine("\n執行刪除知識庫");
string workspaceId = Environment.GetEnvironmentVariable("WORKSPACE_ID");
Console.Write("請輸入知識庫ID:"); // 即 CreateIndex 介面返回的 Data.Id,您也可以在阿里雲百鍊控制台的知識庫頁面擷取。
string indexId = Console.ReadLine();
// 刪除前二次確認
while (true)
{
Console.Write($"您確定要永久性刪除該知識庫 {indexId} 嗎?(y/n): ");
string confirm = Console.ReadLine()?.ToLower();
if (confirm == "y")
{
break;
}
else if (confirm == "n")
{
Console.WriteLine("已取消刪除操作。");
return;
}
else
{
Console.WriteLine("無效輸入,請輸入 y 或 n。");
}
}
Bailian20231229.Client client = CreateClient();
Bailian20231229.Models.DeleteIndexResponse resp = DeleteIndex(client, workspaceId, indexId);
if (resp.Body.Status == "200")
{
Console.WriteLine($"知識庫{indexId}刪除成功!");
}
else
{
var mapper = new JsonSerializerSettings { Formatting = Formatting.Indented };
string errInfo = JsonConvert.SerializeObject(resp.Body, mapper);
Console.WriteLine($"發生錯誤:{errInfo}");
}
}
else
{
Console.WriteLine("無效的選項,程式退出。");
return;
}
}
catch (Exception e)
{
Console.WriteLine("發生錯誤:" + e.Message);
}
}
}
}
// 範例程式碼僅供參考,請勿在生產環境中直接使用
package main
import (
"bufio"
"fmt"
"os"
"strings"
bailian20231229 "github.com/alibabacloud-go/bailian-20231229/v2/client"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
)
// checkEnvironmentVariables 檢查並提示設定必要的環境變數。
func checkEnvironmentVariables() bool {
// 必要的環境變數及其描述
requiredVars := map[string]string{
"ALIBABA_CLOUD_ACCESS_KEY_ID": "阿里雲存取金鑰ID",
"ALIBABA_CLOUD_ACCESS_KEY_SECRET": "阿里雲存取金鑰密碼",
"WORKSPACE_ID": "阿里雲百鍊業務空間ID",
}
var missingVars []string
for varName, desc := range requiredVars {
if os.Getenv(varName) == "" {
fmt.Printf("錯誤:請設定 %s 環境變數 (%s)\n", varName, desc)
missingVars = append(missingVars, varName)
}
}
return len(missingVars) == 0
}
// createClient 建立並配置用戶端(Client)。
//
// 返回:
// - *client.Bailian20231229Client: 配置好的用戶端(Client)。
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.ap-southeast-1.aliyuncs.com")
_result = &bailian20231229.Client{}
_result, _err = bailian20231229.NewClient(config)
return _result, _err
}
// listIndices 擷取指定業務空間下一個或多個知識庫的詳細資料。
//
// 參數:
// - client *bailian20231229.Client: 用戶端(Client)。
// - workspaceId string: 業務空間ID。
//
// 返回:
// - *bailian20231229.ListIndicesResponse: 阿里雲百鍊服務的響應。
// - error: 錯誤資訊。
func listIndices(client *bailian20231229.Client, workspaceId string) (_result *bailian20231229.ListIndicesResponse, _err error) {
headers := make(map[string]*string)
listIndicesRequest := &bailian20231229.ListIndicesRequest{}
runtime := &util.RuntimeOptions{}
return client.ListIndicesWithOptions(tea.String(workspaceId), listIndicesRequest, headers, runtime)
}
// deleteIndex 永久性刪除指定的知識庫。
//
// 參數:
// - client *bailian20231229.Client: 用戶端(Client)。
// - workspaceId string: 業務空間ID。
// - indexId string: 知識庫ID。
//
// 返回:
// - *bailian20231229.DeleteIndexResponse: 阿里雲百鍊服務的響應。
// - error: 錯誤資訊。
func deleteIndex(client *bailian20231229.Client, workspaceId, indexId string) (_result *bailian20231229.DeleteIndexResponse, _err error) {
headers := make(map[string]*string)
deleteIndexRequest := &bailian20231229.DeleteIndexRequest{
IndexId: tea.String(indexId),
}
runtime := &util.RuntimeOptions{}
return client.DeleteIndexWithOptions(tea.String(workspaceId), deleteIndexRequest, headers, runtime)
}
// 主函數。
func main() {
if !checkEnvironmentVariables() {
fmt.Println("環境變數校正未通過。")
return
}
scanner := bufio.NewScanner(os.Stdin)
fmt.Print("請選擇要執行的操作:\n1. 查看知識庫\n2. 刪除知識庫\n請輸入選項(1或2):")
// 確保讀取輸入
if !scanner.Scan() {
fmt.Println("無法讀取輸入。")
return
}
startOption := scanner.Text()
client, err := createClient()
if err != nil {
fmt.Println("建立用戶端失敗:", err)
return
}
if strings.TrimSpace(startOption) == "1" {
fmt.Println("\n執行查看知識庫")
workspaceId := os.Getenv("WORKSPACE_ID")
resp, err := listIndices(client, workspaceId)
if err != nil {
fmt.Println("擷取知識庫列表失敗:", err)
return
}
fmt.Printf("知識庫列表:\n%+v\n", resp.Body.Data)
} else if strings.TrimSpace(startOption) == "2" {
fmt.Println("\n執行刪除知識庫")
workspaceId := os.Getenv("WORKSPACE_ID")
fmt.Print("請輸入知識庫ID:")
if !scanner.Scan() {
fmt.Println("無法讀取知識庫ID。")
return
}
indexId := scanner.Text()
for {
fmt.Printf("您確定要永久性刪除該知識庫 %s 嗎?(y/n): ", indexId)
if !scanner.Scan() {
fmt.Println("無法讀取確認輸入。")
return
}
confirm := strings.ToLower(strings.TrimSpace(scanner.Text()))
if confirm == "y" {
break
} else if confirm == "n" {
fmt.Println("已取消刪除操作。")
return
} else {
fmt.Println("無效輸入,請輸入 y 或 n。")
}
}
resp, err := deleteIndex(client, workspaceId, indexId)
if err != nil {
fmt.Println("刪除知識庫失敗:", err)
} else {
if tea.StringValue(resp.Body.Status) == "200" {
fmt.Printf("知識庫 %s 刪除成功!\n", indexId)
} else {
fmt.Println(resp.Body)
}
}
} else {
fmt.Println("無效的選項,程式退出。")
}
}
建立知識庫
接下來通過樣本,引導您在給定的業務空間下建立一個文檔搜尋類知識庫。
1. 初始化用戶端在開始上傳檔案和建立知識庫之前,您需要使用配置好的AccessKey和AccessKey Secret初始化用戶端(Client),以完成身分識別驗證和存取點
建立完成後,您將得到一個Client對象,用於後續的 API 呼叫。 | |
2. 上傳知識庫檔案 | |
2.1. 申請檔案上傳租約在建立知識庫前,您需先將檔案上傳至同一業務空間,作為知識庫的知識來源。上傳檔案前,需調用ApplyFileUploadLease介面申請一個檔案上傳租約。該租約是一個臨時的授權,允許您在限定時間內(有效期間為分鐘級)上傳檔案。
申請臨時上傳租約成功後,您將獲得:
您將在下一步中用到它們。 | 請求樣本 響應樣本 |
2.2. 上傳檔案到臨時儲存取得上傳租約後,您即可使用租約中的臨時上傳參數和臨時上傳URL,將本機存放區或可通過公網訪問的檔案上傳至阿里雲百鍊伺服器。請注意,每個業務空間最多支援1萬個檔案。目前支援上傳的格式包括:PDF、DOCX、DOC、TXT、Markdown、PPTX、PPT、XLSX、XLS、HTML、PNG、JPG、JPEG、BMP 和 GIF。
| 重要本樣本不支援線上調試和多語言範例程式碼產生。 本地上傳URL地址上傳
|
2.3. 添加檔案到類目中阿里雲百鍊使用類目管理您上傳的檔案。因此,接下來您需要調用AddFile介面將已上傳的檔案添加到同一業務空間下的類目中。
完成添加後,阿里雲百鍊將返回該檔案的 | 請求樣本 響應樣本 |
2.4. 查詢檔案的解析狀態未解析完成的檔案無法用於知識庫,在請求高峰時段,該過程可能需要數小時。您可以調用DescribeFile介面查詢檔案的解析狀態。
當本介面返回的 | 請求樣本 響應樣本 |
3. 建立知識庫 | |
3.1. 初始化知識庫檔案解析完成後,您即可將其匯入同一業務空間下的知識庫。初始化(非最終提交)一個文檔搜尋類知識庫,可以調用CreateIndex介面。
本介面返回的
| 請求樣本 響應樣本 |
3.2. 提交索引任務初始化知識庫後,您需要調用SubmitIndexJob介面提交索引任務,以啟動知識庫的索引構建。
完成提交後,阿里雲百鍊隨即以非同步任務方式開始構建索引。本介面返回的 | 請求樣本 響應樣本 |
3.3. 等待索引任務完成索引任務的執行需要一定時間,在請求高峰時段,該過程可能需要數小時。查詢其執行狀態可以調用GetIndexJobStatus介面。
當本介面返回的 | 請求樣本 響應樣本 |
通過以上步驟,您已成功建立了一個知識庫,並包含了需要上傳的檔案。
檢索知識庫
目前,檢索知識庫支援兩種方式:
- 使用阿里雲百鍊應用:調用應用時,通過
rag_options傳入知識庫IDindex_id,為您的大模型應用補充私人知識和提供最新資訊。 - 使用阿里雲API:調用Retrieve介面在指定的知識庫中檢索資訊並返回原始文本切片。
二者的區別在於:前者先將檢索到的相關文本切片傳給您配置的大模型,模型再結合這些切片與使用者的原始查詢產生最終回答並返回;後者則是直接返迴文本切片。
接下來為您介紹使用阿里雲API的方式。
在指定的知識庫中檢索資訊,並返迴文本切片,可以通過調用Retrieve介面。
若本介面返回的結果包含較多幹擾資訊,您可以在請求時傳入SearchFilters設定檢索條件(比如設定標籤篩選),以排除幹擾資訊。 | 請求樣本 響應樣本 |
更新知識庫
接下來通過樣本,引導您更新文檔搜尋類知識庫。所有引用該知識庫的應用會即時生效您本次的更新(新增內容可用於檢索和召回,而已刪除內容將不再可用)。
資料查詢、圖片問答類知識庫不支援通過API更新。如何更新請參見知識庫:更新知識庫。
- 如何累加式更新知識庫:請您按照以下三步(先上傳更新後的檔案,再追加檔案至知識庫,最後刪除舊檔案)操作。此外暫無其他實現方式。
- 如何全量更新知識庫:對知識庫中的所有檔案,請您逐一執行以下三步完成更新。
- 如何?知識庫的自動更新/同步:請詳見如何?知識庫的自動更新/同步。
- 單次更新對檔案數量是否有限制:建議不超過1萬個,否則可能導致知識庫無法正常更新。
1. 上傳更新後的檔案按照建立知識庫:第二步操作,將更新後的檔案上傳至該知識庫所在的業務空間。
| |
2. 追加檔案至知識庫 | |
2.1. 提交追加檔案任務上傳檔案解析完成後,請調用SubmitIndexAddDocumentsJob介面將新檔案追加至知識庫,並重新構建知識庫索引。
完成提交後,阿里雲百鍊將以非同步任務方式開始重新構建知識庫。本介面返回的 重要
| 請求樣本 響應樣本 |
2.2. 等待追加任務完成索引任務的執行需要一定時間,在請求高峰時段,該過程可能需要數小時。查詢其執行狀態可以調用GetIndexJobStatus介面。
當本介面返回的
| 請求樣本 響應樣本 |
3. 刪除舊檔案最後,從指定知識庫中永久刪除舊版本的檔案(避免舊的知識被錯誤檢索),可以調用DeleteIndexDocument介面。
說明僅能刪除知識庫中狀態為匯入失敗(INSERT_ERROR)或匯入成功(FINISH)的檔案。如需查詢知識庫中的檔案狀態,可調用ListIndexDocuments介面。 | 請求樣本 響應樣本 |
管理知識庫
查看知識庫要查看給定業務空間下的一個或多個知識庫的資訊,可以調用ListIndices介面。
| 請求樣本 響應樣本 |
刪除知識庫要永久性刪除某個知識庫,可以調用DeleteIndex介面。刪除前,請解除該知識庫關聯的所有阿里雲百鍊應用(僅可通過阿里雲百鍊控制台操作),否則會刪除失敗。
請注意:本操作不會刪除您已添加至類目中的檔案。 | 請求樣本 響應樣本 |
API參考
請參閱API目錄(知識庫)擷取最新完整的知識庫API列表及輸入輸出參數。
常見問題
-
如何?知識庫的自動更新/同步?
文檔搜尋類知識庫
您可以通過整合阿里雲Object Storage Service、Function ComputeFC以及阿里雲百鍊知識庫相關的API實現。只需簡單幾步:
資料查詢/圖片問答類知識庫
不支援。
-
為什麼我建立的知識庫裡沒有內容?
一般是由於沒有執行或未能成功執行提交索引任務這一步導致。若調用CreateIndex介面後未成功調用SubmitIndexJob介面,您將得到一個空知識庫。此時,您只需重新執行提交索引任務並等待索引任務完成即可。
- 遇到報錯Access your uploaded file failed. Please check if your upload action was successful,應該如何處理?
-
遇到報錯Access denied: Either you are not authorized to access this workspace, or the workspace does not exist,應該如何處理?
一般是由於:
-
您請求的服務地址(服務存取點)有誤:以公網接入為例,如果您是中國站使用者,應訪問北京(公用雲端使用者)地區的接入地址;如果您是國際站使用者,應訪問新加坡地區的接入地址。如果您正在使用線上調試功能,請確認您選擇的服務地址正確無誤(如下圖所示)。
-
您傳入的WorkspaceId值不正確,或者您還不是該業務空間的成員導致:請確認
WorkspaceId值無誤且您是該業務空間的成員後,再調用介面。如何被添加為指定業務空間的成員
-
-
遇到報錯Specified access key is not found or invalid,應該如何處理?
一般是由於您傳入的
access_key_id或access_key_secret值不正確,或者該access_key_id已被禁用導致。請確認access_key_id值無誤且未被禁用後,再調用介面。 -
遇到報錯Category is mismatched,應該如何處理?
一般是由於在調用
ApplyFileUploadLease介面申請檔案上傳租約時使用的CategoryId,與後續調用AddFile介面時傳入的CategoryId不一致導致。請確保在整個檔案上傳流程中(從
ApplyFileUploadLease到AddFile),使用同一個CategoryId。您可以通過ListCategory介面擷取當前業務空間下的類目列表,確認所使用的CategoryId正確無誤。
計費說明
- 知識庫的所有功能及API調用均免費,詳見知識庫:計費說明。
- 檔案等資料匯入百鍊後,所需的儲存空間免費。
錯誤碼
如果調用本文中的API失敗並收到錯誤資訊,請參見錯誤中心進行解決。