全部產品
Search
文件中心

Alibaba Cloud Model Studio:知識庫API指南

更新時間:Oct 15, 2025

阿里雲百鍊知識庫提供開放的API介面,便於您快速接入現有業務系統,實現自動化操作,並應對複雜的檢索需求。

前置步驟

  1. 子帳號(主帳號不需要)需擷取API許可權(AliyunBailianDataFullAccess策略),並加入一個業務空間,然後才能通過阿里雲API操作知識庫。

    子帳號只能操作已加入業務空間中的知識庫;主帳號可操作所有業務空間下的知識庫。
  2. 安裝最新版阿里雲百鍊SDK,以調用知識庫相關的阿里雲API。如何安裝請參考阿里雲SDK開發參考目錄下文檔。

    如果SDK不能滿足需求,可以通過簽名機制(較為複雜)HTTP請求知識庫的相關介面。具體對接方式請參見API概覽
  3. 擷取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'
  4. 準備好樣本知識文檔阿里雲百鍊系列手機產品介紹.docx,用於建立知識庫。

完整範例程式碼

建立知識庫

重要
  • 在調用本樣本之前,請務必完成上述所有前置步驟。子帳號調用本樣本前需擷取AliyunBailianDataFullAccess策略

  • 若您使用了 IDE 或其他輔助開發外掛程式,需將ALIBABA_CLOUD_ACCESS_KEY_IDALIBABA_CLOUD_ACCESS_KEY_SECRETWORKSPACE_ID變數配置到相應的開發環境中。

Python

# 範例程式碼僅供參考,請勿在生產環境中直接使用
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()

Java

// 範例程式碼僅供參考,請勿在生產環境中直接使用
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

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

Node.js

// 範例程式碼僅供參考,請勿在生產環境中直接使用
'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));

C#

// 範例程式碼僅供參考,請勿在生產環境中直接使用
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}");
            }
        }
    }
}

Go

// 範例程式碼僅供參考,請勿在生產環境中直接使用
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_IDALIBABA_CLOUD_ACCESS_KEY_SECRETWORKSPACE_ID變數配置到相應的開發環境中。

Python

# 範例程式碼僅供參考,請勿在生產環境中直接使用
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()

Java

// 範例程式碼僅供參考,請勿在生產環境中直接使用
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

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

Node.js

// 範例程式碼僅供參考,請勿在生產環境中直接使用
'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));

C#

// 範例程式碼僅供參考,請勿在生產環境中直接使用
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);
            }
        }
    }
}

Go

// 範例程式碼僅供參考,請勿在生產環境中直接使用
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_IDALIBABA_CLOUD_ACCESS_KEY_SECRETWORKSPACE_ID變數配置到相應的開發環境中。

Python

# 範例程式碼僅供參考,請勿在生產環境中直接使用
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()

Java

// 範例程式碼僅供參考,請勿在生產環境中直接使用
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

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

Node.js

// 範例程式碼僅供參考,請勿在生產環境中直接使用
'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));

C#

// 範例程式碼僅供參考,請勿在生產環境中直接使用
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("知識庫更新失敗。");
            }
        }
    }
}

Go

// 範例程式碼僅供參考,請勿在生產環境中直接使用
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_IDALIBABA_CLOUD_ACCESS_KEY_SECRETWORKSPACE_ID變數配置到相應的開發環境中。

Python

# 範例程式碼僅供參考,請勿在生產環境中直接使用
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()

Java

// 範例程式碼僅供參考,請勿在生產環境中直接使用
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

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

Node.js

// 範例程式碼僅供參考,請勿在生產環境中直接使用
'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));

C#

// 範例程式碼僅供參考,請勿在生產環境中直接使用
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);
            }
        }
    }
}

Go

// 範例程式碼僅供參考,請勿在生產環境中直接使用
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("無效的選項,程式退出。")
	}
}

建立知識庫

接下來通過樣本,引導您在給定的業務空間下建立一個文檔搜尋類知識庫。

資料查詢、圖片問答類知識庫不支援通過API建立,請使用阿里雲百鍊控制台建立。

1. 初始化用戶端

在開始上傳檔案和建立知識庫之前,您需要使用配置好的AccessKey和AccessKey Secret初始化用戶端(Client),以完成身分識別驗證和存取點endpoint配置。

  • 公網接入地址:

    請確保您的用戶端可以訪問公網。
    • 公用雲端:bailian.ap-southeast-1.aliyuncs.com

  • VPC接入地址:

    若您的用戶端部署在阿里雲新加坡地區ap-southeast-1(公用雲端),且處於VPC網路環境中,可以使用以下VPC接入地址(不支援跨地區訪問)。
    • 公用雲端:bailian-vpc.ap-southeast-1.aliyuncs.com

建立完成後,您將得到一個Client對象,用於後續的 API 呼叫。

Python

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)

Java

/**
* 初始化用戶端(Client)。
*
* @return 配置好的用戶端對象
*/
public static com.aliyun.bailian20231229.Client createClient() throws Exception {
    com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
            .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
            .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
    // 下方接入地址以公用雲端的公網接入地址為例,可按需更換接入地址。
    config.endpoint = "bailian-vpc.ap-southeast-1.aliyuncs.com";
    return new com.aliyun.bailian20231229.Client(config);
}

PHP

/**
 * 初始化用戶端(Client)。
 *
 * @return Bailian 配置好的用戶端對象(Client)。
 */
public static function createClient(){
    $config = new Config([
        "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), 
        "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
    ]);
    // 下方接入地址以公用雲端的公網接入地址為例,可按需更換接入地址。
    $config->endpoint = 'bailian-vpc.ap-southeast-1.aliyuncs.com';
    return new Bailian($config);
}

Node.js

/**
 * 建立並配置用戶端(Client)
 * @return Client
 * @throws Exception
 */
static createClient() {
  const config = new OpenApi.Config({
    accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
    accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET
  });
  // 下方接入地址以公用雲端的公網接入地址為例,可按需更換接入地址
  config.endpoint = `bailian-vpc.ap-southeast-1.aliyuncs.com`;
  return new bailian20231229.default(config);
}

C#

/// <summary>
/// 初始化用戶端(Client)。
/// </summary>
/// <returns>配置好的用戶端對象</returns>
/// <exception cref="Exception">初始化過程中發生錯誤時拋出異常</exception>
public static AlibabaCloud.SDK.Bailian20231229.Client CreateClient()
{
    var config = new AlibabaCloud.OpenApiClient.Models.Config
    {
        AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
        AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
    };
    // 下方接入地址以公用雲端的公網接入地址為例,可按需更換接入地址.
    config.Endpoint = "bailian-vpc.ap-southeast-1.aliyuncs.com";
    return new AlibabaCloud.SDK.Bailian20231229.Client(config);
}

Go

// CreateClient 建立並配置用戶端(Client)。
//
// 返回:
//   - *client.Bailian20231229Client: 配置好的用戶端(Client)。
//   - error: 錯誤資訊。
func CreateClient() (_result *bailian20231229.Client, _err error) {
	config := &openapi.Config{
		AccessKeyId:     tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
		AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
	}
	// 下方接入地址以公用雲端的公網接入地址為例,可按需更換接入地址。
	config.Endpoint = tea.String("bailian-vpc.ap-southeast-1.aliyuncs.com")
	_result = &bailian20231229.Client{}
	_result, _err = bailian20231229.NewClient(config)
	return _result, _err
}

2. 上傳知識庫檔案

2.1. 申請檔案上傳租約

在建立知識庫前,您需先將檔案上傳至同一業務空間,作為知識庫的知識來源。上傳檔案前,需調用ApplyFileUploadLease介面申請一個檔案上傳租約。該租約是一個臨時的授權,允許您在限定時間內(有效期間為分鐘級)上傳檔案。

  • workspace_id:如何擷取業務空間ID

  • category_id:本樣本中,請傳入default。阿里雲百鍊使用類目管理您上傳的檔案,系統會自動建立一個預設類目。您亦可調用AddCategory介面建立新類目,並擷取對應的category_id

  • file_name:請傳入上傳檔案的名稱(包括尾碼)。其值必須與實際檔案名稱一致。例如,上傳圖中的檔案時,請傳入阿里雲百鍊系列手機產品介紹.docx

    image

  • file_md5:請傳入上傳檔案的MD5值(但當前阿里雲不對該值進行校正,便於您使用URL地址上傳檔案)。

    以Python為例,MD5值可使用hashlib模組擷取。其他語言請參見完整範例程式碼

    程式碼範例

    import hashlib
    
    
    def calculate_md5(file_path):
        """
        計算檔案的MD5值。
    
        參數:
            file_path (str): 檔案本地路徑。
    
        返回:
            str: 檔案的MD5值。
        """
        md5_hash = hashlib.md5()
    
        # 以二進位形式讀取檔案
        with open(file_path, "rb") as f:
            # 按塊讀取檔案,避免大檔案佔用過多記憶體
            for chunk in iter(lambda: f.read(4096), b""):
                md5_hash.update(chunk)
    
        return md5_hash.hexdigest()
    
    
    # 使用樣本
    file_path = "請替換為您需要上傳檔案的實際本地路徑,例如/xxx/xxx/xxx/阿里雲百鍊系列手機產品介紹.docx"
    md5_value = calculate_md5(file_path)
    print(f"檔案的MD5值為: {md5_value}")
    

    將代碼中的file_path變數替換為檔案的實際本地路徑後運行,即可擷取目標檔案的MD5值(下方為樣本值):

    檔案的MD5值為: 2ef7361ea907f3a1b91e3b9936f5643a
  • file_size:請傳入上傳檔案的位元組大小。

    以Python為例,該值可使用os模組擷取。其他語言請參見完整範例程式碼

    程式碼範例

    import os
    
    
    def get_file_size(file_path: str) -> int:
        """
        擷取檔案的位元組大小(以位元組為單位)。
    
        參數:
            file_path (str): 檔案的實際本地路徑。
    
        返回:
            int: 檔案大小(以位元組為單位)。
        """
        return os.path.getsize(file_path)
    
    
    # 使用樣本
    file_path = "請替換為您需要上傳檔案的實際本地路徑,例如/xxx/xxx/xxx/阿里雲百鍊系列手機產品介紹.docx"
    file_size = get_file_size(file_path)
    print(f"檔案的位元組大小為: {file_size}")
    

    將代碼中的file_path變數替換為檔案的實際本地路徑後運行,即可擷取目標檔案的位元組大小(下方為樣本值):

    檔案的位元組大小為: 14015

申請臨時上傳租約成功後,您將獲得:

  • 一組臨時上傳參數:

    • Data.FileUploadLeaseId

    • Data.Param.Method

    • Data.Param.Headers中的X-bailian-extra

    • Data.Param.Headers中的Content-Type

  • 一個臨時上傳URL:Data.Param.Url

您將在下一步中用到它們。

重要

Python

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)

Java

/**
 * 申請檔案上傳租約。
 *
 * @param client      用戶端對象
 * @param categoryId  類目ID
 * @param fileName    檔案名稱
 * @param fileMd5     檔案的MD5值
 * @param fileSize    檔案大小(以位元組為單位)
 * @param workspaceId 業務空間ID
 * @return 阿里雲百鍊服務的響應對象
 */
public ApplyFileUploadLeaseResponse applyLease(com.aliyun.bailian20231229.Client client, String categoryId, String fileName, String fileMd5, String fileSize, String workspaceId) throws Exception {
    Map<String, String> headers = new HashMap<>();
    com.aliyun.bailian20231229.models.ApplyFileUploadLeaseRequest applyFileUploadLeaseRequest = new com.aliyun.bailian20231229.models.ApplyFileUploadLeaseRequest();
    applyFileUploadLeaseRequest.setFileName(fileName);
    applyFileUploadLeaseRequest.setMd5(fileMd5);
    applyFileUploadLeaseRequest.setSizeInBytes(fileSize);
    com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
    ApplyFileUploadLeaseResponse applyFileUploadLeaseResponse = null;
    applyFileUploadLeaseResponse = client.applyFileUploadLeaseWithOptions(categoryId, workspaceId, applyFileUploadLeaseRequest, headers, runtime);
    return applyFileUploadLeaseResponse;
}

PHP

/**
 * 申請檔案上傳租約。
 *
 * @param Bailian $client 用戶端(Client)。
 * @param string $categoryId 類目ID。
 * @param string $fileName 檔案名稱。
 * @param string $fileMd5 檔案的MD5值。
 * @param int $fileSize 檔案大小(以位元組為單位)。
 * @param string $workspaceId 業務空間ID。
 * @return ApplyFileUploadLeaseResponse 阿里雲百鍊服務的響應。
 */
public function applyLease($client, $categoryId, $fileName, $fileMd5, $fileSize, $workspaceId) {
    $headers = [];
    $applyFileUploadLeaseRequest = new ApplyFileUploadLeaseRequest([
        "fileName" => $fileName,
        "md5" => $fileMd5,
        "sizeInBytes" => $fileSize
    ]);
    $runtime = new RuntimeOptions([]);
    return $client->applyFileUploadLeaseWithOptions($categoryId, $workspaceId, $applyFileUploadLeaseRequest, $headers, $runtime);
}

Node.js

/**
 * 申請檔案上傳租約
 * @param {Bailian20231229Client} client - 用戶端(Client)
 * @param {string} categoryId - 類目ID
 * @param {string} fileName - 檔案名稱
 * @param {string} fileMd5 - 檔案的MD5值
 * @param {string} fileSize - 檔案大小(以位元組為單位)
 * @param {string} workspaceId - 業務空間ID
 * @returns {Promise<bailian20231229.ApplyFileUploadLeaseResponse>} - 阿里雲百鍊服務的響應
 */
async function applyLease(client, categoryId, fileName, fileMd5, fileSize, workspaceId) {
  const headers = {};
  const req = new bailian20231229.ApplyFileUploadLeaseRequest({
    md5: fileMd5,
    fileName,
    sizeInBytes: fileSize
 });
 const runtime = new Util.RuntimeOptions({});
 return await client.applyFileUploadLeaseWithOptions(
    categoryId,
    workspaceId,
    req,
    headers,
    runtime
  );
}

C#

/// <summary>
/// 申請檔案上傳租約。
/// </summary>
/// <param name="client">用戶端對象</param>
/// <param name="categoryId">類目ID</param>
/// <param name="fileName">檔案名稱</param>
/// <param name="fileMd5">檔案的MD5值</param>
/// <param name="fileSize">檔案大小(以位元組為單位)</param>
/// <param name="workspaceId">業務空間ID</param>
/// <returns>阿里雲百鍊服務的響應對象</returns>
/// <exception cref="Exception">調用過程中發生錯誤時拋出異常</exception>
public AlibabaCloud.SDK.Bailian20231229.Models.ApplyFileUploadLeaseResponse ApplyLease(
    AlibabaCloud.SDK.Bailian20231229.Client client,
    string categoryId,
    string fileName,
    string fileMd5,
    string fileSize,
    string workspaceId)
{
    var headers = new Dictionary<string, string>() { };
    var applyFileUploadLeaseRequest = new AlibabaCloud.SDK.Bailian20231229.Models.ApplyFileUploadLeaseRequest
    {
        FileName = fileName,
        Md5 = fileMd5,
        SizeInBytes = fileSize
    };
    var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    return client.ApplyFileUploadLeaseWithOptions(categoryId, workspaceId, applyFileUploadLeaseRequest, headers, runtime);
}

Go

// ApplyLease 從阿里雲百鍊服務申請檔案上傳租約。
//
// 參數:
//   - client (bailian20231229.Client): 用戶端(Client)。
//   - categoryId (string): 類目ID。
//   - fileName (string): 檔案名稱。
//   - fileMD5 (string): 檔案的MD5值。
//   - fileSize (string): 檔案大小(以位元組為單位)。
//   - workspaceId (string): 業務空間ID。
//
// 返回:
//   - *bailian20231229.ApplyFileUploadLeaseResponse: 阿里雲百鍊服務的響應。
//   - error: 錯誤資訊。
func ApplyLease(client *bailian20231229.Client, categoryId, fileName, fileMD5 string, fileSize string, workspaceId string) (_result *bailian20231229.ApplyFileUploadLeaseResponse, _err error) {
	headers := make(map[string]*string)
	applyFileUploadLeaseRequest := &bailian20231229.ApplyFileUploadLeaseRequest{
		FileName:    tea.String(fileName),
		Md5:         tea.String(fileMD5),
		SizeInBytes: tea.String(fileSize),
	}
	runtime := &util.RuntimeOptions{}
	return client.ApplyFileUploadLeaseWithOptions(tea.String(categoryId), tea.String(workspaceId), applyFileUploadLeaseRequest, headers, runtime)
}

請求樣本

{
  "CategoryId": "default",
  "FileName": "阿里雲百鍊系列手機產品介紹.docx",
  "Md5": "2ef7361ea907f3a1b91e3b9936f5643a",
  "SizeInBytes": "14015",
  "WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}

響應樣本

{
  "RequestId": "778C0B3B-59C2-5FC1-A947-36EDD1XXXXXX",
  "Success": true,
  "Message": "",
  "Code": "success",
  "Status": "200",
  "Data": {
    "FileUploadLeaseId": "1e6a159107384782be5e45ac4759b247.1719325231035",
    "Type": "HTTP",
    "Param": {
      "Method": "PUT",
      "Url": "https://bailian-datahub-data-origin-prod.oss-cn-hangzhou.aliyuncs.com/1005426495169178/10024405/68abd1dea7b6404d8f7d7b9f7fbd332d.1716698936847.pdf?Expires=1716699536&OSSAccessKeyId=TestID&Signature=HfwPUZo4pR6DatSDym0zFKVh9Wg%3D",
      "Headers": "        \"X-bailian-extra\": \"MTAwNTQyNjQ5NTE2OTE3OA==\",\n        \"Content-Type\": \"application/pdf\""
    }
  }
}

2.2. 上傳檔案到臨時儲存

取得上傳租約後,您即可使用租約中的臨時上傳參數和臨時上傳URL,將本機存放區或可通過公網訪問的檔案上傳至阿里雲百鍊伺服器。請注意,每個業務空間最多支援1萬個檔案。目前支援上傳的格式包括:PDF、DOCX、DOC、TXT、Markdown、PPTX、PPT、XLSX、XLS、HTML、PNG、JPG、JPEG、BMP 和 GIF。

  • pre_signed_url:請傳入申請檔案上傳租約時介面返回的Data.Param.Url

    該 URL 為預簽名 URL,不支援 FormData 方式上傳,需使用二進位方式上傳(詳見範例程式碼)。
重要

本樣本不支援線上調試和多語言範例程式碼產生。

本地上傳

Python

import requests
from urllib.parse import urlparse

def upload_file(pre_signed_url, file_path):
    """
    將本地檔案上傳至臨時儲存。

    參數:
        pre_signed_url (str): 上傳租約中的URL。
        file_path (str): 檔案本地路徑。
    
    返回:
        阿里雲百鍊服務的響應。
    """
    try:
        # 佈建要求頭
        headers = {
            "X-bailian-extra": "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中X-bailian-extra欄位的值",
            "Content-Type": "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中Content-Type欄位的值(返回空值時,傳空值即可)"
        }

        # 讀取檔案並上傳
        with open(file_path, 'rb') as file:
            # 下方佈建要求方法用於檔案上傳,需與您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param中Method欄位的值一致
            response = requests.put(pre_signed_url, data=file, headers=headers)

        # 檢查響應狀態代碼
        if response.status_code == 200:
            print("File uploaded successfully.")
        else:
            print(f"Failed to upload the file. ResponseCode: {response.status_code}")

    except Exception as e:
        print(f"An error occurred: {str(e)}")

if __name__ == "__main__":

    pre_signed_url_or_http_url = "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param中Url欄位的值"

    # 將本地檔案上傳至臨時儲存
    file_path = "請替換為您需要上傳檔案的實際本地路徑(以Linux為例:/xxx/xxx/阿里雲百鍊系列手機產品介紹.docx)"
    upload_file(pre_signed_url_or_http_url, file_path)

Java

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class UploadFile {
    public static void uploadFile(String preSignedUrl, String filePath) {
        HttpURLConnection connection = null;
        try {
            // 建立URL對象
            URL url = new URL(preSignedUrl);
            connection = (HttpURLConnection) url.openConnection();
            // 佈建要求方法用於檔案上傳,需與您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param中Method欄位的值一致
            connection.setRequestMethod("PUT");
            // 允許向connection輸出,因為這個串連是用於上傳檔案的
            connection.setDoOutput(true);
            connection.setRequestProperty("X-bailian-extra", "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中X-bailian-extra欄位的值");
            connection.setRequestProperty("Content-Type", "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中Content-Type欄位的值(返回空值時,傳空值即可)");
            // 讀取檔案並通過串連上傳
            try (DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
                 FileInputStream fileInputStream = new FileInputStream(filePath)) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, bytesRead);
                }
                outStream.flush();
            }
            // 檢查響應
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 檔案上傳成功處理
                System.out.println("File uploaded successfully.");
            } else {
                // 檔案上傳失敗處理
                System.out.println("Failed to upload the file. ResponseCode: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    public static void main(String[] args) {
        String preSignedUrlOrHttpUrl = "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param中Url欄位的值";
        // 將本地檔案上傳至臨時儲存
        String filePath = "請替換為您需要上傳檔案的實際本地路徑(以Linux為例:/xxx/xxx/阿里雲百鍊系列手機產品介紹.docx)";
        uploadFile(preSignedUrlOrHttpUrl, filePath);
    }
}

PHP

<?php

/**
 * 將本地檔案上傳至臨時儲存
 *
 * @param string $preSignedUrl 從 ApplyFileUploadLease 介面擷取的預簽名 URL 或 HTTP 地址
 * @param array $headers 包含 "X-bailian-extra" 和 "Content-Type" 的要求標頭數組
 * @param string $filePath 本地檔案路徑
 * @throws Exception 如果上傳失敗
 */
function uploadFile($preSignedUrl, $headers, $filePath) {
    // 讀取檔案內容
    $fileContent = file_get_contents($filePath);
    if ($fileContent === false) {
        throw new Exception("無法讀取檔案: " . $filePath);
    }

    // 初始化 cURL 會話
    $ch = curl_init();

    // 設定 cURL 選項
    curl_setopt($ch, CURLOPT_URL, $preSignedUrl);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); // 使用 PUT 方法
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fileContent); // 佈建要求體為檔案內容
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返迴響應結果而不是直接輸出

    // 構建要求標頭
    $uploadHeaders = [
        "X-bailian-extra: " . $headers["X-bailian-extra"],
        "Content-Type: " . $headers["Content-Type"]
    ];
    curl_setopt($ch, CURLOPT_HTTPHEADER, $uploadHeaders);

    // 執行請求
    $response = curl_exec($ch);

    // 擷取 HTTP 響應碼
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    // 關閉 cURL 會話
    curl_close($ch);

    // 檢查響應碼
    if ($httpCode != 200) {
        throw new Exception("上傳失敗,HTTP 狀態代碼: " . $httpCode . ",錯誤資訊: " . $response);
    }

    // 上傳成功
    echo "File uploaded successfully.\n";
}

/**
 * 主函數:本地檔案上傳
 */
function main() {
    // 請替換為您在上一步中調用 ApplyFileUploadLease 介面實際返回的 Data.Param 中 Url 欄位的值
    $preSignedUrl = "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param中Url欄位的值";

    // 請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中的 X-bailian-extra 和 Content-Type
    $headers = [
        "X-bailian-extra" => "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中X-bailian-extra欄位的值",
        "Content-Type" => "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中Content-Type欄位的值(返回空值時,傳空值即可)"
    ];

    // 將本地檔案上傳至臨時儲存
    $filePath = "請替換為您需要上傳檔案的實際本地路徑(以Linux為例:/xxx/xxx/阿里雲百鍊系列手機產品介紹.docx)";

    try {
        uploadFile($preSignedUrl, $headers, $filePath);
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage() . "\n";
    }
}

// 調用主函數
main();

?>

Node.js

const fs = require('fs');
const axios = require('axios');

/**
 * 將本地檔案上傳至臨時儲存
 *
 * @param {string} preSignedUrl - 上傳租約中的URL
 * @param {Object} headers - 上傳請求的頭部
 * @param {string} filePath - 檔案本地路徑
 * @throws {Error} 如果上傳失敗
 */
async function uploadFile(preSignedUrl, headers, filePath) {
    // 構建上傳所需的要求標頭
    const uploadHeaders = {
        "X-bailian-extra": headers["X-bailian-extra"],
        "Content-Type": headers["Content-Type"]
    };

    // 建立檔案讀取流
    const fileStream = fs.createReadStream(filePath);

    try {
        // 使用 axios 發送 PUT 請求
        const response = await axios.put(preSignedUrl, fileStream, {
            headers: uploadHeaders
        });

        // 檢查響應狀態代碼
        if (response.status === 200) {
            console.log("File uploaded successfully.");
        } else {
            console.error(`Failed to upload the file. ResponseCode: ${response.status}`);
            throw new Error(`Upload failed with status code: ${response.status}`);
        }
    } catch (error) {
        // 處理錯誤
        console.error("Error during upload:", error.message);
        throw new Error(`上傳失敗: ${error.message}`);
    }
}

/**
 * 主函數:本地檔案上傳
 */
function main() {
    const preSignedUrl = "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param中Url欄位的值";

    const headers = {
        "X-bailian-extra": "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中X-bailian-extra欄位的值",
        "Content-Type": "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中Content-Type欄位的值(返回空值時,傳空值即可)"
    };

    // 將本地檔案上傳至臨時儲存
    const filePath = "請替換為您需要上傳檔案的實際本地路徑(以Linux為例:/xxx/xxx/阿里雲百鍊系列手機產品介紹.docx)";

    uploadFile(preSignedUrl, headers, filePath)
        .then(() => {
            console.log("Upload completed.");
        })
        .catch((err) => {
            console.error("Upload failed:", err.message);
        });
}

// 調用主函數
main();

C#

using System;
using System.IO;
using System.Net;

public class UploadFilExample
{
    public static void UploadFile(string preSignedUrl, string filePath)
    {
        HttpWebRequest connection = null;
        try
        {
            // 建立 URL 對象
            Uri url = new Uri(preSignedUrl);
            connection = (HttpWebRequest)WebRequest.Create(url);
            // 佈建要求方法用於檔案上傳,需與您在上一步中調用 ApplyFileUploadLease 介面實際返回的 Data.Param 中 Method 欄位的值一致
            connection.Method = "PUT";
            // 允許向 connection 輸出,因為這個串連是用於上傳檔案的
            connection.AllowWriteStreamBuffering = false;
            connection.SendChunked = false;
            // 佈建要求頭,需與您在上一步中調用 ApplyFileUploadLease 介面實際返回的 Data.Param.Headers 中的欄位值一致
            connection.Headers["X-bailian-extra"] = "請替換為您在上一步中調用 ApplyFileUploadLease 介面實際返回的 Data.Param.Headers 中 X-bailian-extra 欄位的值";
            connection.ContentType = "請替換為您在上一步中調用 ApplyFileUploadLease 介面實際返回的 Data.Param.Headers 中 Content-Type 欄位的值(返回空值時,傳空值即可)";
            // 讀取檔案並通過串連上傳
            using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            using (var requestStream = connection.GetRequestStream())
            {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    requestStream.Write(buffer, 0, bytesRead);
                }
                requestStream.Flush();
            }
            // 檢查響應
            using (HttpWebResponse response = (HttpWebResponse)connection.GetResponse())
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    // 檔案上傳成功處理
                    Console.WriteLine("File uploaded successfully.");
                }
                else
                {
                    // 檔案上傳失敗處理
                    Console.WriteLine($"Failed to upload the file. ResponseCode: {response.StatusCode}");
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            e.StackTrace.ToString();
        }
        finally
        {
            if (connection != null)
            {
                connection.Abort();
            }
        }
    }

    public static void Main(string[] args)
    {
        string preSignedUrlOrHttpUrl = "請替換為您在上一步中調用 ApplyFileUploadLease 介面實際返回的 Data.Param 中 Url 欄位的值";
        // 將本地檔案上傳至臨時儲存
        string filePath = "請替換為您需要上傳檔案的實際本地路徑(以Linux為例:/xxx/xxx/阿里雲百鍊系列手機產品介紹.docx)";
        UploadFile(preSignedUrlOrHttpUrl, filePath);
    }
}

Go

package main

import (
    "fmt"
    "io"
    "os"

    "github.com/go-resty/resty/v2"
)

// UploadFile 將本地檔案上傳至臨時儲存。
//
// 參數:
//   - preSignedUrl (string): 上傳租約中的 URL。
//   - headers (map[string]string): 上傳請求的頭部。
//   - filePath (string): 檔案本地路徑。
//
// 返回:
//   - error: 如果上傳失敗返回錯誤資訊,否則返回 nil
func UploadFile(preSignedUrl string, headers map[string]string, filePath string) error {
    // 開啟本地檔案
    file, err := os.Open(filePath)
    if err != nil {
        return fmt.Errorf("開啟檔案失敗: %w", err)
    }
    defer file.Close()

    // 讀取內容
    body, err := io.ReadAll(file)
    if err != nil {
        return fmt.Errorf("讀取檔案失敗: %w", err)
    }

    // 建立 REST 用戶端
    client := resty.New()

    // 構建上傳所需的要求標頭
    uploadHeaders := map[string]string{
        "X-bailian-extra": headers["X-bailian-extra"],
        "Content-Type":    headers["Content-Type"],
    }

    // 發送 PUT 請求
    resp, err := client.R().
        SetHeaders(uploadHeaders).
        SetBody(body).
        Put(preSignedUrl)

    if err != nil {
        return fmt.Errorf("發送請求失敗: %w", err)
    }

    // 檢查 HTTP 響應狀態代碼
    if resp.IsError() {
        return fmt.Errorf("HTTP 錯誤: %d", resp.StatusCode())
    }

    fmt.Println("File uploaded successfully.")
    return nil
}

// main 主函數
func main() {
    // 請替換為您在上一步中調用 ApplyFileUploadLease 介面實際返回的 Data.Param 中 Url 欄位的值
    preSignedUrl := "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param中Url欄位的值"

    // 請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中的 X-bailian-extra 和 Content-Type
    headers := map[string]string{
        "X-bailian-extra": "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中X-bailian-extra欄位的值",
        "Content-Type":    "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中Content-Type欄位的值(返回空值時,傳空值即可)",
    }

    // 將本地檔案上傳至臨時儲存
    filePath := "請替換為您需要上傳檔案的實際本地路徑(以Linux為例:/xxx/xxx/阿里雲百鍊系列手機產品介紹.docx)"

    // 調用上傳函數
    err := UploadFile(preSignedUrl, headers, filePath)
    if err != nil {
        fmt.Printf("上傳失敗: %v\n", err)
    }
}

URL地址上傳

請確保URL公開可訪問且指向一個有效檔案。

Python

import requests
from urllib.parse import urlparse

def upload_file_link(pre_signed_url, source_url_string):
    """
    將可通過公網訪問的檔案上傳至臨時儲存。

    參數:
        pre_signed_url (str): 上傳租約中的 URL。
        source_url_string (str): 檔案的URL地址。
    
    返回:
        阿里雲百鍊服務的響應。
    """
    try:
        # 佈建要求頭
        headers = {
            "X-bailian-extra": "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中X-bailian-extra欄位的值",
            "Content-Type": "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中Content-Type欄位的值(返回空值時,傳空值即可)"
        }

        # 設定訪問檔案URL地址的要求方法為GET
        source_response = requests.get(source_url_string)
        if source_response.status_code != 200:
            raise RuntimeError("Failed to get source file.")

        # 下方佈建要求方法用於檔案上傳,需與您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param中Method欄位的值一致
        response = requests.put(pre_signed_url, data=source_response.content, headers=headers)

        # 檢查響應狀態代碼
        if response.status_code == 200:
            print("File uploaded successfully.")
        else:
            print(f"Failed to upload the file. ResponseCode: {response.status_code}")

    except Exception as e:
        print(f"An error occurred: {str(e)}")

if __name__ == "__main__":

    pre_signed_url_or_http_url = "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param中Url欄位的值(返回空值時,傳空值即可)"

    # 檔案的URL地址
    source_url = "請替換為您需要上傳檔案的URL地址"
    upload_file_link(pre_signed_url_or_http_url, source_url)

Java

import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class UploadFile {
    public static void uploadFileLink(String preSignedUrl, String sourceUrlString) {
        HttpURLConnection connection = null;
        try {
            // 建立URL對象
            URL url = new URL(preSignedUrl);
            connection = (HttpURLConnection) url.openConnection();
            // 佈建要求方法用於檔案上傳,需與您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param中Method欄位的值一致
            connection.setRequestMethod("PUT");
            // 允許向connection輸出,因為這個串連是用於上傳檔案的
            connection.setDoOutput(true);
            connection.setRequestProperty("X-bailian-extra", "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中X-bailian-extra欄位的值");
            connection.setRequestProperty("Content-Type", "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中Content-Type欄位的值(返回空值時,傳空值即可)");
            URL sourceUrl = new URL(sourceUrlString);
            HttpURLConnection sourceConnection = (HttpURLConnection) sourceUrl.openConnection();
            // 設定訪問檔案URL地址的要求方法為GET
            sourceConnection.setRequestMethod("GET");
            // 擷取響應碼,200表示請求成功
            int sourceFileResponseCode = sourceConnection.getResponseCode();
            // 從URL地址讀取檔案並通過串連上傳
            if (sourceFileResponseCode != HttpURLConnection.HTTP_OK) {
                throw new RuntimeException("Failed to get source file.");
            }
            try (DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
                 InputStream in = new BufferedInputStream(sourceConnection.getInputStream())) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    outStream.write(buffer, 0, bytesRead);
                }
                outStream.flush();
            }
            // 檢查響應
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 檔案上傳成功
                System.out.println("File uploaded successfully.");
            } else {
                // 檔案上傳失敗
                System.out.println("Failed to upload the file. ResponseCode: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    public static void main(String[] args) {
        String preSignedUrlOrHttpUrl = "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param中Url欄位的值";
        
        String sourceUrl = "請替換為您需要上傳檔案的URL地址";
        uploadFileLink(preSignedUrlOrHttpUrl, sourceUrl);
    }
}

PHP

<?php

/**
 * 將可通過公網訪問的檔案上傳至臨時儲存
 *
 * @param string $preSignedUrl 從 ApplyFileUploadLease 介面擷取的預簽名 URL 或 HTTP 地址
 * @param array $headers 包含 "X-bailian-extra" 和 "Content-Type" 的要求標頭數組
 * @param string $sourceUrl 檔案的URL地址
 * @throws Exception 如果上傳失敗
 */
function uploadFile($preSignedUrl, $headers, $sourceUrl) {

    $fileContent = file_get_contents($sourceUrl);
    if ($fileContent === false) {
        throw new Exception("無法從給定的URL地址下載檔案: " . $sourceUrl);
    }
    // 初始化 cURL 會話
    $ch = curl_init();

    // 設定 cURL 選項
    curl_setopt($ch, CURLOPT_URL, $preSignedUrl);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); // 使用 PUT 方法
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fileContent); // 佈建要求體為檔案內容
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返迴響應結果而不是直接輸出

    // 構建要求標頭
    $uploadHeaders = [
        "X-bailian-extra: " . $headers["X-bailian-extra"],
        "Content-Type: " . $headers["Content-Type"]
    ];
    curl_setopt($ch, CURLOPT_HTTPHEADER, $uploadHeaders);

    // 執行請求
    $response = curl_exec($ch);

    // 擷取 HTTP 響應碼
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    // 關閉 cURL 會話
    curl_close($ch);

    // 檢查響應碼
    if ($httpCode != 200) {
        throw new Exception("上傳失敗,HTTP 狀態代碼: " . $httpCode . ",錯誤資訊: " . $response);
    }

    // 上傳成功
    echo "File uploaded successfully.\n";
}

/**
 * 主函數:將可通過公網訪問的檔案上傳至臨時儲存
 */
function main() {
    // 請替換為您在上一步中調用 ApplyFileUploadLease 介面實際返回的 Data.Param 中 Url 欄位的值
    $preSignedUrl = "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param中Url欄位的值";

    // 請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中的 X-bailian-extra 和 Content-Type
    $headers = [
        "X-bailian-extra" => "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中X-bailian-extra欄位的值",
        "Content-Type" => "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中Content-Type欄位的值(返回空值時,傳空值即可)"
    ];

    $sourceUrl = "請替換為您需要上傳檔案的URL地址";

    try {
        uploadFile($preSignedUrl, $headers, $sourceUrl);
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage() . "\n";
    }
}

// 調用主函數
main();

?>

Node.js

const axios = require('axios');

/**
 * 將可通過公網訪問的檔案上傳至臨時儲存
 *
 * @param {string} preSignedUrl - 上傳租約中的URL
 * @param {Object} headers - 上傳請求的頭部
 * @param {string} sourceUrl - 檔案的URL地址
 * @throws {Error} 如果上傳失敗
 */
async function uploadFileFromUrl(preSignedUrl, headers, sourceUrl) {
    // 構建上傳所需的要求標頭
    const uploadHeaders = {
        "X-bailian-extra": headers["X-bailian-extra"],
        "Content-Type": headers["Content-Type"]
    };

    try {
        // 從給定的URL地址下載檔案
        const response = await axios.get(sourceUrl, {
            responseType: 'stream'
        });

        // 使用 axios 發送 PUT 請求
        const uploadResponse = await axios.put(preSignedUrl, response.data, {
            headers: uploadHeaders
        });

        // 檢查響應狀態代碼
        if (uploadResponse.status === 200) {
            console.log("File uploaded successfully from URL.");
        } else {
            console.error(`Failed to upload the file. ResponseCode: ${uploadResponse.status}`);
            throw new Error(`Upload failed with status code: ${uploadResponse.status}`);
        }
    } catch (error) {
        // 處理錯誤
        console.error("Error during upload:", error.message);
        throw new Error(`上傳失敗: ${error.message}`);
    }
}

/**
 * 主函數:將一個可公開直接下載的檔案上傳到臨時儲存
 */
function main() {
    const preSignedUrl = "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param中Url欄位的值";

    const headers = {
        "X-bailian-extra": "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中X-bailian-extra欄位的值",
        "Content-Type": "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中Content-Type欄位的值(返回空值時,傳空值即可)"
    };

    const sourceUrl = "請替換為您需要上傳檔案的URL地址";

    uploadFileFromUrl(preSignedUrl, headers, sourceUrl)
        .then(() => {
            console.log("Upload completed.");
        })
        .catch((err) => {
            console.error("Upload failed:", err.message);
        });
}

// 調用主函數
main();

C#

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

public class UploadFileExample
{
    public static async Task UploadFileFromUrl(string preSignedUrl, string url)
    {
        try
        {
            // 建立 HTTP 用戶端從給定的URL地址下載檔案
            using (HttpClient httpClient = new HttpClient())
            {
                HttpResponseMessage response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
                response.EnsureSuccessStatusCode();

                // 擷取檔案流
                using (Stream fileStream = await response.Content.ReadAsStreamAsync())
                {
                    // 建立 URL 對象
                    Uri urlObj = new Uri(preSignedUrl);
                    HttpWebRequest connection = (HttpWebRequest)WebRequest.Create(urlObj);

                    // 佈建要求方法用於檔案上傳
                    connection.Method = "PUT";
                    connection.AllowWriteStreamBuffering = false;
                    connection.SendChunked = false;

                    // 佈建要求頭(請替換為實際值)
                    connection.Headers["X-bailian-extra"] = "請替換為您在上一步中調用 ApplyFileUploadLease 介面實際返回的 Data.Param.Headers 中 X-bailian-extra 欄位的值";
                    connection.ContentType = "請替換為您在上一步中調用 ApplyFileUploadLease 介面實際返回的 Data.Param.Headers 中 Content-Type 欄位的值(返回空值時,傳空值即可)";

                    // 擷取請求流並寫入檔案流
                    using (Stream requestStream = connection.GetRequestStream())
                    {
                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = await fileStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                        {
                            await requestStream.WriteAsync(buffer, 0, bytesRead);
                        }
                        await requestStream.FlushAsync();
                    }

                    // 檢查響應
                    using (HttpWebResponse responseResult = (HttpWebResponse)connection.GetResponse())
                    {
                        if (responseResult.StatusCode == HttpStatusCode.OK)
                        {
                            Console.WriteLine("File uploaded successfully from URL.");
                        }
                        else
                        {
                            Console.WriteLine($"Failed to upload the file. ResponseCode: {responseResult.StatusCode}");
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            Console.WriteLine(e.StackTrace);
        }
    }

    public static async Task Main(string[] args)
    {
        string preSignedUrlOrHttpUrl = "請替換為您在上一步中調用 ApplyFileUploadLease 介面實際返回的 Data.Param 中 Url 欄位的值";
        string url = "請替換為您需要上傳檔案的URL地址";   

        await UploadFileFromUrl(preSignedUrlOrHttpUrl, url);
    }
}

Go

package main
 
import (
    "fmt"
    "net/http"
 
    "github.com/go-resty/resty/v2"
)
 
// UploadFileFromUrl 將可通過公網訪問的檔案上傳至臨時儲存。
//
// 參數:
//   - preSignedUrl (string): 上傳租約中的 URL。
//   - headers (map[string]string): 上傳請求的頭部。
//   - sourceUrl (string): 檔案的URL地址。
//
// 返回:
//   - error: 如果上傳失敗返回錯誤資訊,否則返回 nil
func UploadFileFromUrl(preSignedUrl string, headers map[string]string, sourceUrl string) error {
    // 從給定的URL地址下載檔案
    resp, err := http.Get(sourceUrl)
    if err != nil {
        return fmt.Errorf("擷取檔案失敗: %w", err)
    }
    defer resp.Body.Close()
 
    if resp.StatusCode != http.StatusOK {
        return fmt.Errorf("擷取檔案失敗,狀態代碼: %d", resp.StatusCode)
    }
 
    // 建立 REST 用戶端
    client := resty.New()
 
    // 構建上傳所需的要求標頭
    uploadHeaders := map[string]string{
        "X-bailian-extra": headers["X-bailian-extra"],
        "Content-Type":    headers["Content-Type"],
    }
 
    // 發送 PUT 請求
    response, err := client.R().
        SetHeaders(uploadHeaders).
        SetBody(resp.Body).
        Put(preSignedUrl)
 
    if err != nil {
        return fmt.Errorf("發送請求失敗: %w", err)
    }
 
    if err != nil {
        return fmt.Errorf("發送請求失敗: %w", err)
    }
 
    // 檢查 HTTP 響應狀態代碼
    if response.IsError() {
        return fmt.Errorf("HTTP 錯誤: %d", response.StatusCode())
    }
 
    fmt.Println("File uploaded successfully from URL.")
    return nil
}
 
// main 主函數
func main() {
    // 請替換為您在上一步中調用 ApplyFileUploadLease 介面實際返回的 Data.Param 中 Url 欄位的值
    preSignedUrl := "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param中Url欄位的值"
 
    // 請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中的 X-bailian-extra 和 Content-Type
    headers := map[string]string{
        "X-bailian-extra": "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中X-bailian-extra欄位的值",
        "Content-Type":    "請替換為您在上一步中調用ApplyFileUploadLease介面實際返回的Data.Param.Headers中Content-Type欄位的值(返回空值時,傳空值即可)",
    }
 
    sourceUrl := "請替換為您需要上傳檔案的URL地址"
 
    // 調用上傳函數
    err := UploadFileFromUrl(preSignedUrl, headers, sourceUrl)
    if err != nil {
        fmt.Printf("上傳失敗: %v\n", err)
    }
}

2.3. 添加檔案到類目中

阿里雲百鍊使用類目管理您上傳的檔案。因此,接下來您需要調用AddFile介面將已上傳的檔案添加到同一業務空間下的類目中。

  • parser:請傳入DASHSCOPE_DOCMIND

  • lease_id:請傳入申請檔案上傳租約時介面返回的Data.FileUploadLeaseId

  • category_id:本樣本中,請傳入default。若您使用了自建類目上傳,則需傳入對應的category_id

完成添加後,阿里雲百鍊將返回該檔案的FileId,並自動開始解析您的檔案。同時lease_id(租約ID)隨即失效,請勿再使用相同的租約ID重複提交

重要

Python

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)

Java

/**
 * 將檔案添加到類目中。
 *
 * @param client      用戶端對象
 * @param leaseId     租約ID
 * @param parser      用於檔案的解析器
 * @param categoryId  類目ID
 * @param workspaceId 業務空間ID
 * @return 阿里雲百鍊服務的響應對象
 */
public AddFileResponse addFile(com.aliyun.bailian20231229.Client client, String leaseId, String parser, String categoryId, String workspaceId) throws Exception {
    Map<String, String> headers = new HashMap<>();
    com.aliyun.bailian20231229.models.AddFileRequest addFileRequest = new com.aliyun.bailian20231229.models.AddFileRequest();
    addFileRequest.setLeaseId(leaseId);
    addFileRequest.setParser(parser);
    addFileRequest.setCategoryId(categoryId);
    com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
    return client.addFileWithOptions(workspaceId, addFileRequest, headers, runtime);
}

PHP

/**
 * 將檔案添加到類目中。
 *
 * @param Bailian $client 用戶端(Client)。
 * @param string $leaseId 租約ID。
 * @param string $parser 用於檔案的解析器。
 * @param string $categoryId 類目ID。
 * @param string $workspaceId 業務空間ID。
 * @return AddFileResponse 阿里雲百鍊服務的響應。
 */
public function addFile($client, $leaseId, $parser, $categoryId, $workspaceId) {
    $headers = [];
    $addFileRequest = new AddFileRequest([
        "leaseId" => $leaseId,
        "parser" => $parser,
        "categoryId" => $categoryId
    ]);
    $runtime = new RuntimeOptions([]);
    return $client->addFileWithOptions($workspaceId, $addFileRequest, $headers, $runtime);
}

Node.js

/**
 * 添加檔案到類目中
 * @param {Bailian20231229Client} client - 用戶端(Client)
 * @param {string} leaseId - 租約ID
 * @param {string} parser - 用於檔案的解析器
 * @param {string} categoryId - 類目ID
 * @param {string} workspaceId - 業務空間ID
 * @returns {Promise<bailian20231229.AddFileResponse>} - 阿里雲百鍊服務的響應
 */
async function addFile(client, leaseId, parser, categoryId, workspaceId) {
 const headers = {};
 const req = new bailian20231229.AddFileRequest({
  leaseId,
  parser,
  categoryId
});
 const runtime = new Util.RuntimeOptions({});
 return await client.addFileWithOptions(workspaceId, req, headers, runtime);
}

C#

/// <summary>
/// 將檔案添加到類目中。
/// </summary>
/// <param name="client">用戶端對象</param>
/// <param name="leaseId">租約ID</param>
/// <param name="parser">用於檔案的解析器</param>
/// <param name="categoryId">類目ID</param>
/// <param name="workspaceId">業務空間ID</param>
/// <returns>阿里雲百鍊服務的響應對象</returns>
/// <exception cref="Exception">調用過程中發生錯誤時拋出異常</exception>
public AlibabaCloud.SDK.Bailian20231229.Models.AddFileResponse AddFile(
    AlibabaCloud.SDK.Bailian20231229.Client client,
    string leaseId,
    string parser,
    string categoryId,
    string workspaceId)
{
    var headers = new Dictionary<string, string>() { };
    var addFileRequest = new AlibabaCloud.SDK.Bailian20231229.Models.AddFileRequest
    {
        LeaseId = leaseId,
        Parser = parser,
        CategoryId = categoryId
    };
    var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    return client.AddFileWithOptions(workspaceId, addFileRequest, headers, runtime);
}

Go

// AddFile 將檔案添加到阿里雲百鍊服務的指定類目中。
//
// 參數:
//   - client (bailian20231229.Client): 用戶端(Client)。
//   - leaseId (string): 租約ID。
//   - parser (string): 用於檔案的解析器。
//   - categoryId (string): 類目ID。
//   - workspaceId (string): 業務空間ID。
//
// 返回:
//   - *bailian20231229.AddFileResponse: 阿里雲百鍊服務的響應。
//   - error: 錯誤資訊。
func AddFile(client *bailian20231229.Client, leaseId, parser, categoryId, workspaceId string) (_result *bailian20231229.AddFileResponse, _err error) {
	headers := make(map[string]*string)
	addFileRequest := &bailian20231229.AddFileRequest{
		LeaseId:    tea.String(leaseId),
		Parser:     tea.String(parser),
		CategoryId: tea.String(categoryId),
	}
	runtime := &util.RuntimeOptions{}
	return client.AddFileWithOptions(tea.String(workspaceId), addFileRequest, headers, runtime)
}

請求樣本

{
  "CategoryId": "default",
  "LeaseId": "d92bd94fa9b54326a2547415e100c9e2.1742195250069",
  "Parser": "DASHSCOPE_DOCMIND",
  "WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}

響應樣本

{
  "Status": "200",
  "Message": "",
  "RequestId": "5832A1F4-AF91-5242-8B75-35BDC9XXXXXX",
  "Data": {
    "FileId": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
    "Parser": "DASHSCOPE_DOCMIND"
  },
  "Code": "Success",
  "Success": "true"
}

2.4. 查詢檔案的解析狀態

未解析完成的檔案無法用於知識庫,在請求高峰時段,該過程可能需要數小時。您可以調用DescribeFile介面查詢檔案的解析狀態。

當本介面返回的Data.Status欄位值為PARSE_SUCCESS時,表示檔案已解析完成,可以將其匯入知識庫。

重要

Python

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)

Java

/**
 * 查詢檔案的基本資料。
 *
 * @param client      用戶端對象
 * @param workspaceId 業務空間ID
 * @param fileId      檔案ID
 * @return 阿里雲百鍊服務的響應對象
 */
public DescribeFileResponse describeFile(com.aliyun.bailian20231229.Client client, String workspaceId, String fileId) throws Exception {
    Map<String, String> headers = new HashMap<>();
    com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
    return client.describeFileWithOptions(workspaceId, fileId, headers, runtime);
}

PHP

/**
 * 查詢檔案的基本資料。
 *
 * @param Bailian $client 用戶端(Client)。
 * @param string $workspaceId 業務空間ID。
 * @param string $fileId 檔案ID。
 * @return DescribeFileResponse 阿里雲百鍊服務的響應。
 */
public function describeFile($client, $workspaceId, $fileId) {
    $headers = [];
    $runtime = new RuntimeOptions([]);
    return $client->describeFileWithOptions($workspaceId, $fileId, $headers, $runtime);
}

Node.js

/**
 * 查詢檔案的解析狀態
 * @param {Bailian20231229Client} client - 用戶端(Client)
 * @param {string} workspaceId - 業務空間ID
 * @param {string} fileId - 檔案ID
 * @returns {Promise<bailian20231229.DescribeFileResponse>} - 阿里雲百鍊服務的響應
 */
async function describeFile(client, workspaceId, fileId) {
 const headers = {};
 const runtime = new Util.RuntimeOptions({});
 return await client.describeFileWithOptions(workspaceId, fileId, headers, runtime);
}

C#

/// <summary>
/// 查詢檔案的基本資料。
/// </summary>
/// <param name="client">用戶端對象</param>
/// <param name="workspaceId">業務空間ID</param>
/// <param name="fileId">檔案ID</param>
/// <returns>阿里雲百鍊服務的響應對象</returns>
/// <exception cref="Exception">調用過程中發生錯誤時拋出異常</exception>
public AlibabaCloud.SDK.Bailian20231229.Models.DescribeFileResponse DescribeFile(
    AlibabaCloud.SDK.Bailian20231229.Client client,
    string workspaceId,
    string fileId)
{
    var headers = new Dictionary<string, string>() { };
    var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    return client.DescribeFileWithOptions(workspaceId, fileId, headers, runtime);
}

Go

// DescribeFile 擷取檔案的基本資料。
//
// 參數:
//   - client (bailian20231229.Client): 用戶端(Client)。
//   - workspaceId (string): 業務空間ID。
//   - fileId (string): 檔案ID。
//
// 返回:
//   - any: 阿里雲百鍊服務的響應。
//   - error: 錯誤資訊。
func DescribeFile(client *bailian20231229.Client, workspaceId, fileId string) (_result *bailian20231229.DescribeFileResponse, _err error) {
	headers := make(map[string]*string)
	runtime := &util.RuntimeOptions{}
	return client.DescribeFileWithOptions(tea.String(workspaceId), tea.String(fileId), headers, runtime)
}

請求樣本

{
  "FileId": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
  "WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}

響應樣本

{
  "Status": "200",
  "Message": "",
  "RequestId": "B9246251-987A-5628-8E1E-17BB39XXXXXX",
  "Data": {
    "CategoryId": "cate_206ea350f0014ea4a324adff1ca13011_10xxxxxx",
    "Status": "PARSE_SUCCESS",
    "FileType": "docx",
    "CreateTime": "2025-03-17 15:47:13",
    "FileName": "阿里雲百鍊系列手機產品介紹.docx",
    "FileId": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
    "SizeInBytes": "14015",
    "Parser": "DASHSCOPE_DOCMIND"
  },
  "Code": "Success",
  "Success": "true"
}

3. 建立知識庫

3.1. 初始化知識庫

檔案解析完成後,您即可將其匯入同一業務空間下的知識庫。初始化(非最終提交)一個文檔搜尋類知識庫,可以調用CreateIndex介面

  • workspace_id:如何擷取業務空間ID

  • file_id:請傳入添加檔案到類目中時介面返回的FileId

    若source_type為DATA_CENTER_FILE,則該參數為必傳,否則介面將報錯。
  • structure_type:本樣本中,請傳入unstructured

    資料查詢、圖片問答類知識庫不支援通過API建立,請使用阿里雲百鍊控制台建立。
  • source_type:本樣本中,請傳入DATA_CENTER_FILE

  • sink_type:本樣本中,請傳入BUILT_IN

本介面返回的Data.Id欄位值即為知識庫ID,用於後續的索引構建。

請您妥善保管知識庫ID,後續該知識庫所有相關API操作都將用到它。
重要

Python

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)

Java

/**
 * 在阿里雲百鍊服務中建立知識庫(初始化)。
 *
 * @param client        用戶端對象
 * @param workspaceId   業務空間ID
 * @param fileId        檔案ID
 * @param name          知識庫名稱
 * @param structureType 知識庫的資料類型
 * @param sourceType    應用資料的資料類型,支援類目類型和檔案類型
 * @param sinkType      知識庫的向量儲存類型
 * @return 阿里雲百鍊服務的響應對象
 */
public CreateIndexResponse createIndex(com.aliyun.bailian20231229.Client client, String workspaceId, String fileId, String name, String structureType, String sourceType, String sinkType) throws Exception {
    Map<String, String> headers = new HashMap<>();
    com.aliyun.bailian20231229.models.CreateIndexRequest createIndexRequest = new com.aliyun.bailian20231229.models.CreateIndexRequest();
    createIndexRequest.setStructureType(structureType);
    createIndexRequest.setName(name);
    createIndexRequest.setSourceType(sourceType);
    createIndexRequest.setSinkType(sinkType);
    createIndexRequest.setDocumentIds(Collections.singletonList(fileId));
    com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
    return client.createIndexWithOptions(workspaceId, createIndexRequest, headers, runtime);
}

PHP

/**
 * 在阿里雲百鍊服務中建立知識庫(初始化)。
 *
 * @param Bailian $client 用戶端(Client)。
 * @param string $workspaceId 業務空間ID。
 * @param string $fileId 檔案ID。
 * @param string $name 知識庫名稱。
 * @param string $structureType 知識庫的資料類型。
 * @param string $sourceType 應用資料的資料類型,支援類目類型和檔案類型。
 * @param string $sinkType 知識庫的向量儲存類型。
 * @return CreateIndexResponse 阿里雲百鍊服務的響應。
 */
public function createIndex($client, $workspaceId, $fileId, $name, $structureType, $sourceType, $sinkType) {
    $headers = [];
    $createIndexRequest = new CreateIndexRequest([
        "structureType" => $structureType,
        "name" => $name,
        "sourceType" => $sourceType,
        "documentIds" => [
            $fileId
        ],
        "sinkType" => $sinkType
    ]);
    $runtime = new RuntimeOptions([]);
    return $client->createIndexWithOptions($workspaceId, $createIndexRequest, $headers, $runtime);
}

Node.js

/**
 * 初始化知識庫(索引)
 * @param {Bailian20231229Client} client - 用戶端(Client)
 * @param {string} workspaceId - 業務空間ID
 * @param {string} fileId - 檔案ID
 * @param {string} name - 知識庫名稱
 * @param {string} structureType - 知識庫的資料類型
 * @param {string} sourceType - 應用資料的資料類型,支援類目類型和檔案類型
 * @param {string} sinkType - 知識庫的向量儲存類型
 * @returns {Promise<bailian20231229.CreateIndexResponse>} - 阿里雲百鍊服務的響應
 */
async function createIndex(client, workspaceId, fileId, name, structureType, sourceType, sinkType) {
 const headers = {};
 const req = new bailian20231229.CreateIndexRequest({
   name,
   structureType,
   documentIds: [fileId],
   sourceType,
   sinkType
 });
 const runtime = new Util.RuntimeOptions({});
 return await client.createIndexWithOptions(workspaceId, req, headers, runtime);
}

C#

/// <summary>
/// 在阿里雲百鍊服務中建立知識庫(初始化)。
/// </summary>
/// <param name="client">用戶端對象</param>
/// <param name="workspaceId">業務空間ID</param>
/// <param name="fileId">檔案ID</param>
/// <param name="name">知識庫名稱</param>
/// <param name="structureType">知識庫的資料類型</param>
/// <param name="sourceType">應用資料的資料類型,支援類目類型和檔案類型</param>
/// <param name="sinkType">知識庫的向量儲存類型</param>
/// <returns>阿里雲百鍊服務的響應對象</returns>
/// <exception cref="Exception">調用過程中發生錯誤時拋出異常</exception>
public AlibabaCloud.SDK.Bailian20231229.Models.CreateIndexResponse CreateIndex(
    AlibabaCloud.SDK.Bailian20231229.Client client,
    string workspaceId,
    string fileId,
    string name,
    string structureType,
    string sourceType,
    string sinkType)
{
    var headers = new Dictionary<string, string>() { };
    var createIndexRequest = new AlibabaCloud.SDK.Bailian20231229.Models.CreateIndexRequest
    {
        StructureType = structureType,
        Name = name,
        SourceType = sourceType,
        SinkType = sinkType,
        DocumentIds = new List<string> { fileId }
    };
    var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    return client.CreateIndexWithOptions(workspaceId, createIndexRequest, headers, runtime);
}

Go

// CreateIndex 在阿里雲百鍊服務中建立知識庫(初始化)。
//
// 參數:
//   - client (bailian20231229.Client): 用戶端(Client)。
//   - workspaceId (string): 業務空間ID。
//   - fileId (string): 檔案ID。
//   - name (string): 知識庫名稱。
//   - structureType (string): 知識庫的資料類型。
//   - sourceType (string): 應用資料的資料類型,支援類目類型和檔案類型。
//   - sinkType (string): 知識庫的向量儲存類型。
//
// 返回:
//   - *bailian20231229.CreateIndexResponse: 阿里雲百鍊服務的響應。
//   - error: 錯誤資訊。
func CreateIndex(client *bailian20231229.Client, workspaceId, fileId, name, structureType, sourceType, sinkType string) (_result *bailian20231229.CreateIndexResponse, _err error) {
	headers := make(map[string]*string)
	createIndexRequest := &bailian20231229.CreateIndexRequest{
		StructureType: tea.String(structureType),
		Name:          tea.String(name),
		SourceType:    tea.String(sourceType),
		SinkType:      tea.String(sinkType),
		DocumentIds:   []*string{tea.String(fileId)},
	}
	runtime := &util.RuntimeOptions{}
	return client.CreateIndexWithOptions(tea.String(workspaceId), createIndexRequest, headers, runtime)
}

請求樣本

{
  "Name": "阿里雲百鍊手機知識庫",
  "SinkType": "BUILT_IN",
  "SourceType": "DATA_CENTER_FILE",
  "StructureType": "unstructured",
  "WorkspaceId": "llm-4u5xpd1xdjqpxxxx",
  "DocumentIds": [
    "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx"
  ]
}

響應樣本

{
  "Status": "200",
  "Message": "success",
  "RequestId": "87CB0999-F1BB-5290-8C79-A875B2XXXXXX",
  "Data": {
    "Id": "mymxbdxxxx"
  },
  "Code": "Success",
  "Success": "true"
}

3.2. 提交索引任務

初始化知識庫後,您需要調用SubmitIndexJob介面提交索引任務,以啟動知識庫的索引構建。

完成提交後,阿里雲百鍊隨即以非同步任務方式開始構建索引。本介面返回的Data.Id為對應的任務ID。下一步中,您將用到此ID查詢任務的最新狀態。

重要

Python

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)

Java

/**
 * 向阿里雲百鍊服務提交索引任務。
 *
 * @param client      用戶端對象
 * @param workspaceId 業務空間ID
 * @param indexId     知識庫ID
 * @return 阿里雲百鍊服務的響應對象
 */
public SubmitIndexJobResponse submitIndex(com.aliyun.bailian20231229.Client client, String workspaceId, String indexId) throws Exception {
    Map<String, String> headers = new HashMap<>();
    com.aliyun.bailian20231229.models.SubmitIndexJobRequest submitIndexJobRequest = new com.aliyun.bailian20231229.models.SubmitIndexJobRequest();
    submitIndexJobRequest.setIndexId(indexId);
    com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
    return client.submitIndexJobWithOptions(workspaceId, submitIndexJobRequest, headers, runtime);
}

PHP

/**
 * 向阿里雲百鍊服務提交索引任務。
 *
 * @param Bailian $client 用戶端(Client)。
 * @param string $workspaceId 業務空間ID。
 * @param string $indexId 知識庫ID。
 * @return SubmitIndexJobResponse 阿里雲百鍊服務的響應。
 */
public static function submitIndex($client, $workspaceId, $indexId) {
    $headers = [];
    $submitIndexJobRequest = new SubmitIndexJobRequest([
        'indexId' => $indexId
    ]);
    $runtime = new RuntimeOptions([]);
    return $client->submitIndexJobWithOptions($workspaceId, $submitIndexJobRequest, $headers, $runtime);
}

Node.js

/**
 * 提交索引任務
 * @param {Bailian20231229Client} client - 用戶端(Client)
 * @param {string} workspaceId - 業務空間ID
 * @param {string} indexId - 知識庫ID
 * @returns {Promise<bailian20231229.SubmitIndexJobResponse>} - 阿里雲百鍊服務的響應
 */
async function submitIndex(client, workspaceId, indexId) {
  const headers = {};
  const req = new bailian20231229.SubmitIndexJobRequest({ indexId });
  const runtime = new Util.RuntimeOptions({});
  return await client.submitIndexJobWithOptions(workspaceId, req, headers, runtime);
}

C#

/// <summary>
/// 向阿里雲百鍊服務提交索引任務。
/// </summary>
/// <param name="client">用戶端對象</param>
/// <param name="workspaceId">業務空間ID</param>
/// <param name="indexId">知識庫ID</param>
/// <returns>阿里雲百鍊服務的響應對象</returns>
/// <exception cref="Exception">調用過程中發生錯誤時拋出異常</exception>
public AlibabaCloud.SDK.Bailian20231229.Models.SubmitIndexJobResponse SubmitIndex(
    AlibabaCloud.SDK.Bailian20231229.Client client,
    string workspaceId,
    string indexId)
{
    var headers = new Dictionary<string, string>() { };
    var submitIndexJobRequest = new AlibabaCloud.SDK.Bailian20231229.Models.SubmitIndexJobRequest
    {
           IndexId = indexId
    };
    var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    return client.SubmitIndexJobWithOptions(workspaceId, submitIndexJobRequest, headers, runtime);
}

Go

// SubmitIndex 提交索引任務。
//
// 參數:
//   - client (bailian20231229.Client): 用戶端(Client)。
//   - workspaceId (string): 業務空間ID。
//   - indexId (string): 知識庫ID。
//
// 返回:
//   - *bailian20231229.SubmitIndexJobResponse: 阿里雲百鍊服務的響應。
//   - error: 錯誤資訊。
func SubmitIndex(client *bailian20231229.Client, workspaceId, indexId string) (_result *bailian20231229.SubmitIndexJobResponse, _err error) {
	headers := make(map[string]*string)
	submitIndexJobRequest := &bailian20231229.SubmitIndexJobRequest{
		IndexId: tea.String(indexId),
	}
	runtime := &util.RuntimeOptions{}
	return client.SubmitIndexJobWithOptions(tea.String(workspaceId), submitIndexJobRequest, headers, runtime)
}

請求樣本

{
  "IndexId": "mymxbdxxxx",
  "WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}

響應樣本

{
  "Status": "200",
  "Message": "success",
  "RequestId": "7774575F-571D-5854-82C2-634AB8XXXXXX",
  "Data": {
    "IndexId": "mymxbdxxxx",
    "Id": "3cd6fb57aaf44cd0b4dd2ca584xxxxxx"
  },
  "Code": "Success",
  "Success": "true"
}

3.3. 等待索引任務完成

索引任務的執行需要一定時間,在請求高峰時段,該過程可能需要數小時。查詢其執行狀態可以調用GetIndexJobStatus介面

當本介面返回的Data.Status欄位值為COMPLETED時,表示知識庫已建立完成。

重要

Python

def get_index_job_status(client, workspace_id, index_id, job_id):
    """
    查詢索引任務狀態。

    參數:
        client (bailian20231229Client): 用戶端(Client)。
        workspace_id (str): 業務空間ID。
        index_id (str): 知識庫ID。
        job_id (str): 任務ID。

    返回:
        阿里雲百鍊服務的響應。
    """
    headers = {}
    get_index_job_status_request = bailian_20231229_models.GetIndexJobStatusRequest(
        index_id=index_id,
        job_id=job_id
    )
    runtime = util_models.RuntimeOptions()
    return client.get_index_job_status_with_options(workspace_id, get_index_job_status_request, headers, runtime)

Java

/**
 * 查詢索引任務狀態。
 *
 * @param client      用戶端對象
 * @param workspaceId 業務空間ID
 * @param jobId       任務ID
 * @param indexId     知識庫ID
 * @return 阿里雲百鍊服務的響應對象
 */
public GetIndexJobStatusResponse getIndexJobStatus(com.aliyun.bailian20231229.Client client, String workspaceId, String jobId, String indexId) throws Exception {
    Map<String, String> headers = new HashMap<>();
    com.aliyun.bailian20231229.models.GetIndexJobStatusRequest getIndexJobStatusRequest = new com.aliyun.bailian20231229.models.GetIndexJobStatusRequest();
    getIndexJobStatusRequest.setIndexId(indexId);
    getIndexJobStatusRequest.setJobId(jobId);
    com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
    GetIndexJobStatusResponse getIndexJobStatusResponse = null;
    getIndexJobStatusResponse = client.getIndexJobStatusWithOptions(workspaceId, getIndexJobStatusRequest, headers, runtime);
    return getIndexJobStatusResponse;
}

PHP

/**
 * 查詢索引任務狀態。
 *
 * @param Bailian $client 用戶端(Client)。
 * @param string $workspaceId 業務空間ID。
 * @param string $indexId 知識庫ID。
 * @param string $jobId 任務ID。
 * @return GetIndexJobStatusResponse 阿里雲百鍊服務的響應。
 */
public function getIndexJobStatus($client, $workspaceId, $jobId, $indexId) {
    $headers = [];
    $getIndexJobStatusRequest = new GetIndexJobStatusRequest([
        'indexId' => $indexId,
        'jobId' => $jobId
    ]);
    $runtime = new RuntimeOptions([]);
    return $client->getIndexJobStatusWithOptions($workspaceId, $getIndexJobStatusRequest, $headers, $runtime);
}

Node.js

/**
 * 查詢索引任務狀態
 * @param {Bailian20231229Client} client - 用戶端(Client)
 * @param {string} workspaceId - 業務空間ID
 * @param {string} jobId - 任務ID
 * @param {string} indexId - 知識庫ID
 * @returns {Promise<bailian20231229.GetIndexJobStatusResponse>} - 阿里雲百鍊服務的響應
 */
async function getIndexJobStatus(client, workspaceId, jobId, indexId) {
  const headers = {};
  const req = new bailian20231229.GetIndexJobStatusRequest({ jobId, indexId });
  const runtime = new Util.RuntimeOptions({});
  return await client.getIndexJobStatusWithOptions(workspaceId, req, headers, runtime);
}

C#

/// <summary>
/// 查詢索引任務狀態。
/// </summary>
/// <param name="client">用戶端對象</param>
/// <param name="workspaceId">業務空間ID</param>
/// <param name="jobId">任務ID</param>
/// <param name="indexId">知識庫ID</param>
/// <returns>阿里雲百鍊服務的響應對象</returns>
/// <exception cref="Exception">調用過程中發生錯誤時拋出異常</exception>
public AlibabaCloud.SDK.Bailian20231229.Models.GetIndexJobStatusResponse GetIndexJobStatus(
    AlibabaCloud.SDK.Bailian20231229.Client client,
    string workspaceId,
    string jobId,
    string indexId)
{
    var headers = new Dictionary<string, string>() { };
    var getIndexJobStatusRequest = new AlibabaCloud.SDK.Bailian20231229.Models.GetIndexJobStatusRequest
    {
        IndexId = indexId,
        JobId = jobId
    };
    var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    return client.GetIndexJobStatusWithOptions(workspaceId, getIndexJobStatusRequest, headers, runtime);
}

Go

// GetIndexJobStatus 查詢索引任務狀態。
//
// 參數:
//   - client (bailian20231229.Client): 用戶端(Client)。
//   - workspaceId (string): 業務空間ID。
//   - jobId (string): 任務ID。
//   - indexId (string): 知識庫ID。
//
// 返回:
//   - *bailian20231229.GetIndexJobStatusResponse: 阿里雲百鍊服務的響應。
//   - error: 錯誤資訊。
func GetIndexJobStatus(client *bailian20231229.Client, workspaceId, jobId, indexId string) (_result *bailian20231229.GetIndexJobStatusResponse, _err error) {
	headers := make(map[string]*string)
	getIndexJobStatusRequest := &bailian20231229.GetIndexJobStatusRequest{
		JobId:   tea.String(jobId),
		IndexId: tea.String(indexId),
	}
	runtime := &util.RuntimeOptions{}
	return client.GetIndexJobStatusWithOptions(tea.String(workspaceId), getIndexJobStatusRequest, headers, runtime)
}

請求樣本

{
  "IndexId": "mymxbdxxxx",
  "JobId": "3cd6fb57aaf44cd0b4dd2ca584xxxxxx",
  "WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}

響應樣本

{
  "Status": "200",
  "Message": "success",
  "RequestId": "E83423B9-7D6D-5283-836B-CF7EAEXXXXXX",
  "Data": {
    "Status": "COMPLETED",
    "Documents": [
      {
        "Status": "FINISH",
        "DocId": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
        "Message": "匯入成功",
        "DocName": "阿里雲百鍊系列手機產品介紹",
        "Code": "FINISH"
      }
    ],
    "JobId": "3cd6fb57aaf44cd0b4dd2ca584xxxxxx"
  },
  "Code": "Success",
  "Success": "true"
}

通過以上步驟,您已成功建立了一個知識庫,並包含了需要上傳的檔案。

檢索知識庫

目前,檢索知識庫支援兩種方式:

  • 使用阿里雲百鍊應用:調用應用時,通過rag_options傳入知識庫IDindex_id,為您的大模型應用補充私人知識和提供最新資訊。

  • 使用阿里雲API:調用Retrieve介面在指定的知識庫中檢索資訊並返回原始文本切片。

二者的區別在於:前者先將檢索到的相關文本切片傳給您配置的大模型,模型再結合這些切片與使用者的原始查詢產生最終回答並返回;後者則是直接返迴文本切片。

接下來為您介紹使用阿里雲API的方式。

在指定的知識庫中檢索資訊,並返迴文本切片,可以通過調用Retrieve介面

若本介面返回的結果包含較多幹擾資訊,您可以在請求時傳入SearchFilters設定檢索條件(比如設定標籤篩選),以排除幹擾資訊。

重要

Python

def retrieve_index(client, workspace_id, index_id, query):
    """
    在指定的知識庫中檢索資訊。
        
    參數:
        client (bailian20231229Client): 用戶端(Client)。
        workspace_id (str): 業務空間ID。
        index_id (str): 知識庫ID。
        query (str): 原始輸入prompt。

    返回:
        阿里雲百鍊服務的響應。
    """
    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)

Java

/**
 * 在指定的知識庫中檢索資訊。
 *
 * @param client         用戶端對象(bailian20231229Client)
 * @param workspaceId    業務空間ID
 * @param indexId        知識庫ID
 * @param query          檢索查詢語句
 * @return               阿里雲百鍊服務的響應
 */
public 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);
}

PHP

/**
 * 在指定的知識庫中檢索資訊。
 *
 * @param Bailian $client 用戶端對象(Client)。
 * @param string $workspaceId 業務空間ID
 * @param string $indexId 知識庫ID
 * @param string $query 檢索查詢語句
 * @return RetrieveResponse 阿里雲百鍊服務的響應
 * @throws Exception
 */
public function retrieveIndex($client, $workspaceId, $indexId, $query) {
    $headers = [];
    $retrieveRequest = new RetrieveRequest([
        "query" => $query,
        "indexId" => $indexId
    ]);
    $runtime = new RuntimeOptions([]);
    return $client->retrieveWithOptions($workspaceId, $retrieveRequest, $headers, $runtime);
}

Node.js

/**
 * 在指定的知識庫中檢索資訊
 * @param {bailian20231229.Client} client 用戶端(Client)
 * @param {string} workspaceId 業務空間ID
 * @param {string} indexId 知識庫ID
 * @param {string} query 檢索query
 * @returns {Promise<bailian20231229.RetrieveResponse>} 阿里雲百鍊服務的響應
 */
async function 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);
}

C#

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

Go

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

請求樣本

{
  "IndexId": "mymxbdxxxx",
  "WorkspaceId": "llm-4u5xpd1xdjqpxxxx",
  "Query": "請介紹一下阿里雲百鍊手機X1。"
}

響應樣本

{
  "Status": "200",
  "Message": "success",
  "RequestId": "17316EA2-1F4D-55AC-8872-53F6F1XXXXXX",
  "Data": {
    "Nodes": [
      {
        "Score": 0.6294550895690918,
        "Metadata": {
          "file_path": "https://bailian-datahub-data-prod.oss-cn-beijing.aliyuncs.com/10285263/multimodal/docJson/%E7%99%BE%E7%82%BC%E7%B3%BB%E5%88%97%E6%89%8B%E6%9C%BA%E4%BA%A7%E5%93%81%E4%BB%8B%E7%BB%8D_1742197778230.json?Expires=1742457465&OSSAccessKeyId=TestID&Signature=ptFkSObdnBrbJNEw8CnlOSP%2FTeI%3D",
          "is_displayed_chunk_content": "true",
          "_rc_v_score": 0.7449869735535081,
          "image_url": [],
          "nid": "9ad347d9e4d7465d2c1e693a08b0077c|d6f7fbf8403e0df796258e5ada1ee1c1|4772257e93ed64ea087ff4be0d5e4620|7ce1370e4a1958842c9268144a452cc7",
          "_q_score": 1,
          "source": "0",
          "_score": 0.6294550895690918,
          "title": "阿里雲百鍊手機產品介紹",
          "doc_id": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
          "content": "阿里雲百鍊手機產品介紹阿里雲百鍊 X1 ——暢享極致視界:搭載 6.7英寸 1440 x 3200像素超清螢幕,搭配 120Hz重新整理率,流暢視覺體驗躍然眼前。256GB海量儲存空間與 12GB RAM強強聯合,無論是大型遊戲還是多任務處理,都能輕鬆應對。5000mAh電池長續航,加上超感光四攝系統,記錄生活每一刻精彩。參考售價:4599- 4999通義 Vivid 7 ——智能攝影新體驗:擁有 6.5英寸 1080 x 2400像素全面屏,AI智能攝影功能讓每一張照片都能展現專業級色彩與細節。8GB RAM與 128GB儲存空間確保流暢操作,4500mAh電池滿足日常所需。側面指紋解鎖,便捷又安全。參考售價:2999- 3299星塵 S9 Pro ——創新視覺盛宴:突破性 6.9英寸 1440 x 3088像素屏下網路攝影機設計,帶來無界視覺享受。512GB儲存與 16GB RAM的頂級配置,配合 6000mAh電池與 100W快充技術,讓效能與續航並駕齊驅,引領科技潮流。參考售價:5999- 6499。",
          "_rc_score": 0,
          "workspace_id": "llm-4u5xpd1xdjqpxxxx",
          "hier_title": "阿里雲百鍊手機產品介紹",
          "_rc_t_score": 0.05215025693178177,
          "doc_name": "阿里雲百鍊系列手機產品介紹",
          "pipeline_id": "mymxbdxxxx",
          "_id": "llm-4u5xpd1xdjqp8itj_mymxbd6172_file_0b21e0a852cd40cd9741c54fefbb61cd_10285263_0_0"
        },
        "Text": "阿里雲百鍊手機產品介紹阿里雲百鍊 X1 ——暢享極致視界:搭載 6.7英寸 1440 x 3200像素超清螢幕,搭配 120Hz重新整理率,流暢視覺體驗躍然眼前。256GB海量儲存空間與 12GB RAM強強聯合,無論是大型遊戲還是多任務處理,都能輕鬆應對。5000mAh電池長續航,加上超感光四攝系統,記錄生活每一刻精彩。參考售價:4599- 4999通義 Vivid 7 ——智能攝影新體驗:擁有 6.5英寸 1080 x 2400像素全面屏,AI智能攝影功能讓每一張照片都能展現專業級色彩與細節。8GB RAM與 128GB儲存空間確保流暢操作,4500mAh電池滿足日常所需。側面指紋解鎖,便捷又安全。參考售價:2999- 3299星塵 S9 Pro ——創新視覺盛宴:突破性 6.9英寸 1440 x 3088像素屏下網路攝影機設計,帶來無界視覺享受。512GB儲存與 16GB RAM的頂級配置,配合 6000mAh電池與 100W快充技術,讓效能與續航並駕齊驅,引領科技潮流。參考售價:5999- 6499。"
      },
      {
        "Score": 0.5322970747947693,
        "Metadata": {
          "file_path": "https://bailian-datahub-data-prod.oss-cn-beijing.aliyuncs.com/10285263/multimodal/docJson/%E7%99%BE%E7%82%BC%E7%B3%BB%E5%88%97%E6%89%8B%E6%9C%BA%E4%BA%A7%E5%93%81%E4%BB%8B%E7%BB%8D_1742197778230.json?Expires=1742457465&OSSAccessKeyId=TestID&Signature=ptFkSObdnBrbJNEw8CnlOSP%2FTeI%3D",
          "is_displayed_chunk_content": "true",
          "_rc_v_score": 0.641660213470459,
          "image_url": [],
          "nid": "00be1864c18b4c39c59f83713af80092|4f2bfb02cc9fc4e85597b2e717699207",
          "_q_score": 0.9948930557644994,
          "source": "0",
          "_score": 0.5322970747947693,
          "title": "阿里雲百鍊手機產品介紹",
          "doc_id": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
          "content": "阿里雲百鍊 Flex Fold+ ——摺疊屏新紀元:集創新與奢華於一身,主屏 7.6英寸 1800 x 2400像素與外屏 4.7英寸 1080 x 2400像素,多角度自由懸停設計,滿足不同情境需求。阿里雲百鍊 Flex Fold+ ——摺疊屏新紀元:集創新與奢華於一身,主屏 7.6英寸 1800 x 2400像素與外屏 4.7英寸 1080 x 2400像素,多角度自由懸停設計,滿足不同情境需求。512GB儲存、12GB RAM,加之 4700mAh電池與 UTG超薄柔性玻璃,開啟摺疊屏時代新篇章。此外,這款手機還支援雙卡雙待、衛星通話,協助您在世界各地都能暢聯通話。參考零售價:9999- 10999。每一款手機都是匠心獨運,只為成就您手中的科技藝術品。選擇屬於您的智能夥伴,開啟未來科技生活的新篇章。",
          "_rc_score": 0,
          "workspace_id": "llm-4u5xpd1xdjqpxxxx",
          "hier_title": "阿里雲百鍊手機產品介紹",
          "_rc_t_score": 0.05188392847776413,
          "doc_name": "阿里雲百鍊系列手機產品介紹",
          "pipeline_id": "mymxbdxxxx",
          "_id": "llm-4u5xpd1xdjqp8itj_mymxbd6172_file_0b21e0a852cd40cd9741c54fefbb61cd_10285263_0_2"
        },
        "Text": "阿里雲百鍊 Flex Fold+ ——摺疊屏新紀元:集創新與奢華於一身,主屏 7.6英寸 1800 x 2400像素與外屏 4.7英寸 1080 x 2400像素,多角度自由懸停設計,滿足不同情境需求。阿里雲百鍊 Flex Fold+ ——摺疊屏新紀元:集創新與奢華於一身,主屏 7.6英寸 1800 x 2400像素與外屏 4.7英寸 1080 x 2400像素,多角度自由懸停設計,滿足不同情境需求。512GB儲存、12GB RAM,加之 4700mAh電池與 UTG超薄柔性玻璃,開啟摺疊屏時代新篇章。此外,這款手機還支援雙卡雙待、衛星通話,協助您在世界各地都能暢聯通話。參考零售價:9999- 10999。每一款手機都是匠心獨運,只為成就您手中的科技藝術品。選擇屬於您的智能夥伴,開啟未來科技生活的新篇章。"
      },
      {
        "Score": 0.5050643086433411,
        "Metadata": {
          "file_path": "https://bailian-datahub-data-prod.oss-cn-beijing.aliyuncs.com/10285263/multimodal/docJson/%E7%99%BE%E7%82%BC%E7%B3%BB%E5%88%97%E6%89%8B%E6%9C%BA%E4%BA%A7%E5%93%81%E4%BB%8B%E7%BB%8D_1742197778230.json?Expires=1742457465&OSSAccessKeyId=TestID&Signature=ptFkSObdnBrbJNEw8CnlOSP%2FTeI%3D",
          "is_displayed_chunk_content": "true",
          "_rc_v_score": 0.6757396459579468,
          "image_url": [],
          "nid": "f05d1b51eb6b033b32a162d90a9da71b|5cb6b848be8d11eb168c031025415cc5|4f2bfb02cc9fc4e85597b2e717699207",
          "_q_score": 0.9890713450653327,
          "source": "0",
          "_score": 0.5050643086433411,
          "title": "阿里雲百鍊手機產品介紹",
          "doc_id": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
          "content": "512GB儲存與 16GB RAM的頂級配置,配合 6000mAh電池與 100W快充技術,讓效能與續航並駕齊驅,引領科技潮流。參考售價:5999- 6499。阿里雲百鍊 Ace Ultra ——遊戲玩家之選:配備 6.67英寸 1080 x 2400像素螢幕,內建 10GB RAM與 256GB儲存,確保遊戲運行絲滑無阻。5500mAh電池搭配液冷散熱系統,長時間遊戲也能保持冷靜。高動態雙擴音器,沈浸式音效升級遊戲體驗。參考售價:3999- 4299。阿里雲百鍊 Zephyr Z9 ——輕薄便攜的藝術:輕巧的 6.4英寸 1080 x 2340像素設計,搭配 128GB儲存與 6GB RAM,日常使用遊刃有餘。4000mAh電池確保一天無憂,30倍數字變焦鏡頭捕捉遠處細節,輕薄而不失強大。參考售價:2499- 2799。阿里雲百鍊 Flex Fold+ ——摺疊屏新紀元:集創新與奢華於一身,主屏 7.6英寸 1800 x 2400像素與外屏 4.7英寸 1080 x 2400像素,多角度自由懸停設計,滿足不同情境需求。",
          "_rc_score": 0,
          "workspace_id": "llm-4u5xpd1xdjqpxxxx",
          "hier_title": "阿里雲百鍊手機產品介紹",
          "_rc_t_score": 0.05158032476902008,
          "doc_name": "阿里雲百鍊系列手機產品介紹",
          "pipeline_id": "mymxbdxxxx",
          "_id": "llm-4u5xpd1xdjqp8itj_mymxbd6172_file_0b21e0a852cd40cd9741c54fefbb61cd_10285263_0_1"
        },
        "Text": "512GB儲存與 16GB RAM的頂級配置,配合 6000mAh電池與 100W快充技術,讓效能與續航並駕齊驅,引領科技潮流。參考售價:5999- 6499。阿里雲百鍊 Ace Ultra ——遊戲玩家之選:配備 6.67英寸 1080 x 2400像素螢幕,內建 10GB RAM與 256GB儲存,確保遊戲運行絲滑無阻。5500mAh電池搭配液冷散熱系統,長時間遊戲也能保持冷靜。高動態雙擴音器,沈浸式音效升級遊戲體驗。參考售價:3999- 4299。阿里雲百鍊 Zephyr Z9 ——輕薄便攜的藝術:輕巧的 6.4英寸 1080 x 2340像素設計,搭配 128GB儲存與 6GB RAM,日常使用遊刃有餘。4000mAh電池確保一天無憂,30倍數字變焦鏡頭捕捉遠處細節,輕薄而不失強大。參考售價:2499- 2799。阿里雲百鍊 Flex Fold+ ——摺疊屏新紀元:集創新與奢華於一身,主屏 7.6英寸 1800 x 2400像素與外屏 4.7英寸 1080 x 2400像素,多角度自由懸停設計,滿足不同情境需求。"
      }
    ]
  },
  "Code": "Success",
  "Success": "true"
}

更新知識庫

接下來通過樣本,引導您更新文檔搜尋類知識庫。所有引用該知識庫的應用會即時生效您本次的更新(新增內容可用於檢索和召回,而已刪除內容將不再可用)。

資料查詢、圖片問答類知識庫不支援通過API更新。如何更新請參見知識庫:更新知識庫
  • 如何累加式更新知識庫:請您按照以下三步(先上傳更新後的檔案,再追加檔案至知識庫,最後刪除舊檔案)操作。此外暫無其他實現方式。

  • 如何全量更新知識庫:對知識庫中的所有檔案,請您逐一執行以下三步完成更新。

  • 如何?知識庫的自動更新/同步:請詳見如何?知識庫的自動更新/同步

  • 單次更新對檔案數量是否有限制:建議不超過1萬個,否則可能導致知識庫無法正常更新。

1. 上傳更新後的檔案

按照建立知識庫:第二步操作,將更新後的檔案上傳至該知識庫所在的業務空間。

您需要重新申請檔案上傳租約,為更新後的檔案產生一組新的上傳參數。

2. 追加檔案至知識庫

2.1. 提交追加檔案任務

上傳檔案解析完成後,請調用SubmitIndexAddDocumentsJob介面將新檔案追加至知識庫,並重新構建知識庫索引。

完成提交後,阿里雲百鍊將以非同步任務方式開始重新構建知識庫。本介面返回的Data.Id為對應的任務ID(job_id)。下一步中,您將用到此ID查詢任務的最新狀態。

重要
  • SubmitIndexAddDocumentsJob介面調用成功後,將執行一段時間,您可通過job_id查詢任務的最新狀態。在任務完成前,請勿重複提交。

重要

Python

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)

Java

/**
 * 向一個文檔搜尋類知識庫追加匯入已解析的檔案
 *
 * @param client      用戶端(Client)
 * @param workspaceId 業務空間ID
 * @param indexId     知識庫ID
 * @param fileId      檔案ID
 * @param sourceType  資料類型
 * @return 阿里雲百鍊服務的響應
 */
public 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);
}

PHP

/**
 * 向一個文檔搜尋類知識庫追加匯入已解析的檔案
 *
 * @param Bailian $client 用戶端對象
 * @param string $workspaceId 業務空間ID
 * @param string $indexId 知識庫ID
 * @param string $fileId 檔案ID
 * @param string $sourceType 資料類型
 * @return SubmitIndexAddDocumentsJobResponse 阿里雲百鍊服務的響應
 * @throws Exception
 */
public 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);
}

Node.js

/**
 * 提交追加檔案任務
 * @param {Bailian20231229Client} client - 用戶端(Client)
 * @param {string} workspaceId - 業務空間ID
 * @param {string} indexId - 知識庫ID
 * @param {string} fileId - 檔案ID
 * @param {string} sourceType - 資料類型
 * @returns {Promise<bailian20231229.SubmitIndexAddDocumentsJobResponse>} - 阿里雲百鍊服務的響應
 */
async function 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);
}

C#

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

Go

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

請求樣本

{
  "IndexId": "mymxbdxxxx",
  "SourceType": "DATA_CENTER_FILE",
  "WorkspaceId": "llm-4u5xpd1xdjqpxxxx",
  "DocumentIds": [
    "file_247a2fd456a349ee87d071404840109b_10xxxxxx"
  ]
}

響應樣本

{
  "Status": "200",
  "RequestId": "F693EB60-FEFC-559A-BF56-A41F52XXXXXX",
  "Message": "success",
  "Data": {
    "Id": "d8d189a36a3248438dca23c078xxxxxx"
  },
  "Code": "Success",
  "Success": "true"
}

2.2. 等待追加任務完成

索引任務的執行需要一定時間,在請求高峰時段,該過程可能需要數小時。查詢其執行狀態可以調用GetIndexJobStatus介面

當本介面返回的Data.Status欄位值為COMPLETED,表示本次更新的檔案已全部成功追加至知識庫。

本介面返回的檔案清單Documents為本次追加(由您提供的job_id唯一確定)的所有檔案。

重要

Python

def get_index_job_status(client, workspace_id, index_id, job_id):
    """
    查詢索引任務狀態。

    參數:
        client (bailian20231229Client): 用戶端(Client)。
        workspace_id (str): 業務空間ID。
        index_id (str): 知識庫ID。
        job_id (str): 任務ID。

    返回:
        阿里雲百鍊服務的響應。
    """
    headers = {}
    get_index_job_status_request = bailian_20231229_models.GetIndexJobStatusRequest(
        index_id=index_id,
        job_id=job_id
    )
    runtime = util_models.RuntimeOptions()
    return client.get_index_job_status_with_options(workspace_id, get_index_job_status_request, headers, runtime)

Java

/**
 * 查詢索引任務狀態。
 *
 * @param client      用戶端對象
 * @param workspaceId 業務空間ID
 * @param jobId       任務ID
 * @param indexId     知識庫ID
 * @return 阿里雲百鍊服務的響應對象
 */
public GetIndexJobStatusResponse getIndexJobStatus(com.aliyun.bailian20231229.Client client, String workspaceId, String jobId, String indexId) throws Exception {
    Map<String, String> headers = new HashMap<>();
    com.aliyun.bailian20231229.models.GetIndexJobStatusRequest getIndexJobStatusRequest = new com.aliyun.bailian20231229.models.GetIndexJobStatusRequest();
    getIndexJobStatusRequest.setIndexId(indexId);
    getIndexJobStatusRequest.setJobId(jobId);
    com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
    GetIndexJobStatusResponse getIndexJobStatusResponse = null;
    getIndexJobStatusResponse = client.getIndexJobStatusWithOptions(workspaceId, getIndexJobStatusRequest, headers, runtime);
    return getIndexJobStatusResponse;
}

PHP

/**
 * 查詢索引任務狀態。
 *
 * @param Bailian $client 用戶端(Client)。
 * @param string $workspaceId 業務空間ID。
 * @param string $indexId 知識庫ID。
 * @param string $jobId 任務ID。
 * @return GetIndexJobStatusResponse 阿里雲百鍊服務的響應。
 */
public function getIndexJobStatus($client, $workspaceId, $jobId, $indexId) {
    $headers = [];
    $getIndexJobStatusRequest = new GetIndexJobStatusRequest([
        'indexId' => $indexId,
        'jobId' => $jobId
    ]);
    $runtime = new RuntimeOptions([]);
    return $client->getIndexJobStatusWithOptions($workspaceId, $getIndexJobStatusRequest, $headers, $runtime);
}

Node.js

/**
 * 查詢索引任務狀態
 * @param {Bailian20231229Client} client - 用戶端(Client)
 * @param {string} workspaceId - 業務空間ID
 * @param {string} jobId - 任務ID
 * @param {string} indexId - 知識庫ID
 * @returns {Promise<bailian20231229.GetIndexJobStatusResponse>} - 阿里雲百鍊服務的響應
 */
static getIndexJobStatus(client, workspaceId, jobId, indexId) {
    const headers = {};
    const req = new bailian20231229.GetIndexJobStatusRequest({ jobId, indexId });
    const runtime = new Util.RuntimeOptions({});
    return await client.getIndexJobStatusWithOptions(workspaceId, req, headers, runtime);
}

C#

/// <summary>
/// 查詢索引任務狀態。
/// </summary>
/// <param name="client">用戶端對象</param>
/// <param name="workspaceId">業務空間ID</param>
/// <param name="jobId">任務ID</param>
/// <param name="indexId">知識庫ID</param>
/// <returns>阿里雲百鍊服務的響應對象</returns>
/// <exception cref="Exception">調用過程中發生錯誤時拋出異常</exception>
public AlibabaCloud.SDK.Bailian20231229.Models.GetIndexJobStatusResponse GetIndexJobStatus(
    AlibabaCloud.SDK.Bailian20231229.Client client,
    string workspaceId,
    string jobId,
    string indexId)
{
    var headers = new Dictionary<string, string>() { };
    var getIndexJobStatusRequest = new AlibabaCloud.SDK.Bailian20231229.Models.GetIndexJobStatusRequest
    {
        IndexId = indexId,
        JobId = jobId
    };
    var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    return client.GetIndexJobStatusWithOptions(workspaceId, getIndexJobStatusRequest, headers, runtime);
}

Go

// GetIndexJobStatus 查詢索引任務狀態。
//
// 參數:
//   - client (bailian20231229.Client): 用戶端(Client)。
//   - workspaceId (string): 業務空間ID。
//   - jobId (string): 任務ID。
//   - indexId (string): 知識庫ID。
//
// 返回:
//   - *bailian20231229.GetIndexJobStatusResponse: 阿里雲百鍊服務的響應。
//   - error: 錯誤資訊。
func GetIndexJobStatus(client *bailian20231229.Client, workspaceId, jobId, indexId string) (_result *bailian20231229.GetIndexJobStatusResponse, _err error) {
	headers := make(map[string]*string)
	getIndexJobStatusRequest := &bailian20231229.GetIndexJobStatusRequest{
		JobId:   tea.String(jobId),
		IndexId: tea.String(indexId),
	}
	runtime := &util.RuntimeOptions{}
	return client.GetIndexJobStatusWithOptions(tea.String(workspaceId), getIndexJobStatusRequest, headers, runtime)
}

請求樣本

{
  "IndexId": "mymxbdxxxx",
  "JobId": "76f243b9ee534d59a61f156ff0xxxxxx",
  "WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}

響應樣本

{
  "Status": 200,
  "Message": "success",
  "RequestId": "7F727D58-D90E-51E7-B56E-985A42XXXXXX",
  "Data": {
    "Status": "COMPLETED",
    "Documents": [
      {
        "Status": "FINISH",
        "DocId": "file_247a2fd456a349ee87d071404840109b_10xxxxxx",
        "Message": "匯入成功",
        "DocName": "阿里雲百鍊系列手機產品介紹",
        "Code": "FINISH"
      }
    ],
    "JobId": "76f243b9ee534d59a61f156ff0xxxxxx"
  },
  "Code": "Success",
  "Success": true
}

3. 刪除舊檔案

最後,從指定知識庫中永久刪除舊版本的檔案(避免舊的知識被錯誤檢索),可以調用DeleteIndexDocument介面

  • file_id:請傳入舊版本檔案的FileId

說明

僅能刪除知識庫中狀態為匯入失敗(INSERT_ERROR)或匯入成功(FINISH)的檔案。如需查詢知識庫中的檔案狀態,可調用ListIndexDocuments介面

重要

Python

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)

Java

/**
 * 從指定的文檔搜尋類知識庫中永久刪除一個或多個檔案
 *
 * @param client      用戶端(Client)
 * @param workspaceId 業務空間ID
 * @param indexId     知識庫ID
 * @param fileId      檔案ID
 * @return 阿里雲百鍊服務的響應
 */
public 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);
}

PHP

/**
 * 從指定的文檔搜尋類知識庫中永久刪除檔案
 *
 * @param Bailian $client 用戶端對象
 * @param string $workspaceId 業務空間ID
 * @param string $indexId 知識庫ID
 * @param string $fileId 檔案ID
 * @return mixed 阿里雲百鍊服務的響應
 * @throws Exception
 */
public function deleteIndexDocument($client, $workspaceId, $indexId, $fileId) {
    $headers = [];
    $deleteIndexDocumentRequest = new DeleteIndexDocumentRequest([
        "indexId" => $indexId,
        "documentIds" => [
            $fileId
        ]
    ]);
    $runtime = new RuntimeOptions([]);
    return $client->deleteIndexDocumentWithOptions($workspaceId, $deleteIndexDocumentRequest, $headers, $runtime);
}

Node.js

/**
 * 刪除舊檔案
 * @param {Bailian20231229Client} client - 用戶端(Client)
 * @param {string} workspaceId - 業務空間ID
 * @param {string} indexId - 知識庫ID
 * @param {string} fileId - 檔案ID
 * @returns {Promise<bailian20231229.DeleteIndexDocumentResponse>} - 阿里雲百鍊服務的響應
 */
async function 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);
}

C#

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

Go

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

請求樣本

{
  "DocumentIds": [
    "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx"
  ],
  "IndexId": "mymxbdxxxx",
  "WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}

響應樣本

{
  "Status": "200",
  "RequestId": "2D8505EC-C667-5102-9154-00B6FEXXXXXX",
  "Message": "success",
  "Data": {
    "DeletedDocument": [
      "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx"
    ]
  },
  "Code": "Success",
  "Success": "true"
}

管理知識庫

建立和使用知識庫不支援通過API操作,請使用阿里雲百鍊控制台操作。

查看知識庫

要查看給定業務空間下的一個或多個知識庫的資訊,可以調用ListIndices介面

重要

Python

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)

Java

/**
 * 擷取指定業務空間下一個或多個知識庫的詳細資料
 *
 * @param client      用戶端(Client)
 * @param workspaceId 業務空間ID
 * @return 阿里雲百鍊服務的響應
 */
public 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);
}

PHP

/**
 * 擷取指定業務空間下一個或多個知識庫的詳細資料
 *
 * @param Bailian $client 用戶端對象(Client)
 * @param string $workspaceId 業務空間ID
 * @return ListIndicesResponse 阿里雲百鍊服務的響應
 * @throws Exception
 */
public function listIndices($client, $workspaceId) {
    $headers = [];
    $listIndexDocumentsRequest = new ListIndexDocumentsRequest([]);
    $runtime = new RuntimeOptions([]);
    return $client->listIndicesWithOptions($workspaceId, $listIndexDocumentsRequest, $headers, $runtime);
}

Node.js

/**
 * 擷取指定業務空間下一個或多個知識庫的詳細資料
 * @param {bailian20231229.Client} client 用戶端(Client)
 * @param {string} workspaceId 業務空間ID
 * @returns {Promise<bailian20231229.ListIndicesResponse>} 阿里雲百鍊服務的響應
 */
async function listIndices(client, workspaceId) {
    const headers = {};
    const listIndicesRequest = new bailian20231229.ListIndicesRequest();
    const runtime = new Util.RuntimeOptions({});
    return await client.listIndicesWithOptions(workspaceId, listIndicesRequest, headers, runtime);
}

C#

/// <summary>
/// 擷取指定業務空間下一個或多個知識庫的詳細資料。
/// </summary>
/// <param name="client">用戶端(Client)</param>
/// <param name="workspaceId">業務空間ID</param>
/// <returns>阿里雲百鍊服務的響應</returns>
public 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);
}

Go

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

請求樣本

{
  "WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}

響應樣本

{
  "Status": "200",
  "RequestId": "5ACB2EB3-6C9A-5B0F-8E60-3FBE7EXXXXXX",
  "Message": "success",
  "Data": {
    "TotalCount": "1",
    "PageSize": "10",
    "PageNumber": "1",
    "Indices": [
      {
        "DocumentIds": [
          "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx"
        ],
        "Description": "",
        "OverlapSize": 100,
        "SinkInstanceId": "gp-2zegk3i6ca4xxxxxx",
        "SourceType": "DATA_CENTER_FILE",
        "RerankModelName": "gte-rerank-hybrid",
        "SinkRegion": "cn-beijing",
        "Name": "百鍊手機知識庫",
        "ChunkSize": 500,
        "EmbeddingModelName": "text-embedding-v2",
        "RerankMinScore": 0.01,
        "Id": "mymxbdxxxx",
        "SinkType": "BUILT_IN",
        "Separator": " |,|,|。|?|!|\n|\\?|\\!"
      }
    ]
  },
  "Code": "Success",
  "Success": "true"
}

刪除知識庫

要永久性刪除某個知識庫,可以調用DeleteIndex介面。刪除前,請解除該知識庫關聯的所有阿里雲百鍊應用(僅可通過阿里雲百鍊控制台操作),否則會刪除失敗。

請注意:本操作不會刪除您已添加至類目中的檔案。

重要

Python

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)

Java

/**
 * 永久性刪除指定的知識庫
 *
 * @param client      用戶端(Client)
 * @param workspaceId 業務空間ID
 * @param indexId     知識庫ID
 * @return 阿里雲百鍊服務的響應
 */
public 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);
}

PHP

/**
 * 永久性刪除指定的知識庫
 *
 * @param Bailian $client 用戶端對象(Client)
 * @param string $workspaceId 業務空間ID
 * @param string $indexId 知識庫ID
 * @return mixed 阿里雲百鍊服務的響應
 * @throws Exception
 */
public function deleteIndex($client, $workspaceId, $indexId) {
    $headers = [];
    $deleteIndexRequest = new DeleteIndexRequest([
        "indexId" => $indexId
    ]);
    $runtime = new RuntimeOptions([]);
    return $client->deleteIndexWithOptions($workspaceId, $deleteIndexRequest, $headers, $runtime);
}

Node.js

/**
 * 永久性刪除指定的知識庫
 * @param {bailian20231229.Client} client 用戶端(Client)
 * @param {string} workspaceId 業務空間ID
 * @param {string} indexId 知識庫ID
 * @returns {Promise<bailian20231229.DeleteIndexResponse>} 阿里雲百鍊服務的響應
 */
async function 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);
}

C#

/// <summary>
/// 永久性刪除指定的知識庫。
/// </summary>
/// <param name="client">用戶端(Client)</param>
/// <param name="workspaceId">業務空間ID</param>
/// <param name="indexId">知識庫ID</param>
/// <returns>阿里雲百鍊服務的響應</returns>
public 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);
}

Go

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

}

請求樣本

{
  "IndexId": "mymxbdxxxx",
  "WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}

響應樣本

{
  "Status": "200",
  "Message": "success",
  "RequestId": "118CB681-75AA-583B-8D84-25440CXXXXXX",
  "Code": "Success",
  "Success": "true"
}

API參考

請參閱API目錄(知識庫)擷取最新完整的知識庫API列表及輸入輸出參數。

常見問題

  1. 如何?知識庫的自動更新/同步?

    文檔搜尋類知識庫

    您可以通過整合阿里雲Object Storage Service、Function ComputeFC以及阿里雲百鍊知識庫相關的API實現。只需簡單幾步:

    1. 建立Bucket:前往OSS控制台,建立一個OSS Bucket用於儲存您的原始檔案。

    2. 建立知識庫建立一個文檔搜尋類知識庫,用於儲存您的私人知識內容。

    3. 建立自訂函數:前往FC控制台,針對檔案變更類事件(例如新增、刪除等操作)建立函數,具體操作請參見建立函數。這些函數通過調用上文中更新知識庫的相關API,將OSS上發生的檔案變更同步至已建立的知識庫中。

    4. 建立OSS觸發器:在FC中,為上一步建立的自訂函數關聯OSS觸發器。當捕獲到檔案變更類的事件後(例如有新檔案上傳至OSS時),相應的觸發器會被啟用,觸發FC執行相應的函數。具體操作請參見觸發器

    資料查詢/圖片問答類知識庫

    不支援。

  1. 為什麼我建立的知識庫裡沒有內容?

    一般是由於沒有執行或未能成功執行提交索引任務這一步導致。若調用CreateIndex介面後未成功調用SubmitIndexJob介面,您將得到一個空知識庫。此時,您只需重新執行提交索引任務等待索引任務完成即可。

  1. 遇到報錯Access your uploaded file failed. Please check if your upload action was successful,應該如何處理?

    一般是由於沒有執行或未能成功執行上傳檔案到臨時儲存這一步導致。請在確認該步驟成功執行後,再調用AddFile介面。

  1. 遇到報錯Access denied: Either you are not authorized to access this workspace, or the workspace does not exist,應該如何處理?

    一般是由於:

    • 您請求的服務地址(服務存取點)有誤:以公網接入為例,如果您是中國站使用者,應訪問北京(公用雲端使用者)或上海(金融雲使用者)地區的接入地址;如果您是國際站使用者,應訪問新加坡地區的接入地址。如果您正在使用線上調試功能,請確認您選擇的服務地址正確無誤(如下圖所示)。

      image

    • 您傳入的WorkspaceId值不正確,或者您還不是該業務空間的成員導致:請確認WorkspaceId值無誤且您是該業務空間的成員後,再調用介面。如何被添加為指定業務空間的成員

  1. 遇到報錯Specified access key is not found or invalid,應該如何處理?

    一般是由於您傳入的access_key_idaccess_key_secret值不正確,或者該access_key_id已被禁用導致。請確認access_key_id值無誤且未被禁用後,再調用介面。

計費說明

  • 知識庫的所有功能及API調用均免費,詳見知識庫:計費說明

  • 檔案等資料匯入百鍊後,所需的儲存空間免費。

錯誤碼

如果調用本文中的API失敗並收到錯誤資訊,請參見錯誤中心進行解決。