Skip to main content
Knowledge Base (RAG)

Knowledge base API

The Alibaba Cloud Model Studio knowledge base provides open APIs that enable you to integrate with your existing business systems, automate operations, and address complex retrieval needs.

Prerequisites

  1. To manage a knowledge base with APIs, a RAM user must get API permissions (the AliyunBailianDataFullAccess policy) and join a workspace. This is not required for an Alibaba Cloud account.
    A RAM user can manage knowledge bases only in workspaces they have joined. An Alibaba Cloud account can manage knowledge bases in all workspaces.
  2. Install the latest version of the Alibaba Cloud Model Studio SDK to call the knowledge base APIs. For installation instructions, see the Alibaba Cloud SDK Development Reference.
    If the SDK does not meet your requirements, you can call the knowledge base APIs via HTTP requests using the signature mechanism. For connection details, see API Overview.
  3. Get an AccessKey ID and an AccessKey Secret, and a workspace ID. Configure them as system environment variables to run the sample code. The following example shows how to set these variables in Linux:
    If you use an IDE or other development plugins, configure the ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET, and WORKSPACE_ID variables in your development environment.
export ALIBABA_CLOUD_ACCESS_KEY_ID='Your AccessKey ID'
export ALIBABA_CLOUD_ACCESS_KEY_SECRET='Your AccessKey Secret'
export WORKSPACE_ID='Your Alibaba Cloud Model Studio workspace ID'
  1. Prepare the sample knowledge document Alibaba Cloud Model Studio Phone Introduction.docx to create a knowledge base.
  • Create a knowledge base
  • Retrieve from a knowledge base
  • Update a knowledge base
  • Manage knowledge bases
  • Before calling this example, complete the prerequisites and ensure the RAM user has the AliyunBailianDataFullAccess policy.
  • If you use an IDE or other development plugins, set the ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET, and WORKSPACE_ID environment variables in your development environment.
Python
# This sample code is for reference only. Do not use it in a production environment.
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():
    """Verifies that the required environment variables are set."""
    required_vars = {
        'ALIBABA_CLOUD_ACCESS_KEY_ID': 'Alibaba Cloud AccessKey ID',
        'ALIBABA_CLOUD_ACCESS_KEY_SECRET': 'Alibaba Cloud AccessKey Secret',
        'WORKSPACE_ID': 'Alibaba Cloud Model Studio workspace ID'
    }
    missing_vars = []
    for var, description in required_vars.items():
        if not os.environ.get(var):
            missing_vars.append(var)
            print(f"Error: Please set the {var} environment variable ({description}).")

    return len(missing_vars) == 0

def calculate_md5(file_path: str) -> str:
    """
    Calculates the MD5 hash of a file.

    Args:
        file_path (str): The local path of the file.

    Returns:
        str: The MD5 hash of the file.
    """
    md5_hash = hashlib.md5()

    # Read the file in binary mode.
    with open(file_path, "rb") as f:
        # Read the file in chunks to conserve memory when processing large files.
        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:
    """
    Returns the size of a file in bytes.
    Args:
        file_path (str): The local path of the file.
    Returns:
        int: The file size in bytes.
    """
    return os.path.getsize(file_path)

# Initialize the client.
def create_client() -> bailian20231229Client:
    """
    Creates and configures a client.

    Returns:
        bailian20231229Client: The configured 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')
    )
    # This endpoint is for the Asia Pacific SE 1 (Singapore) region. Modify it if you use a different region.
    config.endpoint = 'bailian.ap-southeast-1.aliyuncs.com'
    return bailian20231229Client(config)

# Request a file upload lease.
def apply_lease(client, category_id, file_name, file_md5, file_size, workspace_id):
    """
    Requests a file upload lease from the Model Studio service.

    Args:
        client (bailian20231229Client): The client.
        category_id (str): The category ID.
        file_name (str): The file name.
        file_md5 (str): The MD5 hash of the file.
        file_size (int): The file size in bytes.
        workspace_id (str): The workspace ID.

    Returns:
        The response from the Model Studio service.
    """
    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)

# Upload the file to temporary storage.
def upload_file(pre_signed_url, headers, file_path):
    """
    Uploads the file to the presigned URL from the upload lease.
    Args:
        pre_signed_url (str): The URL from the upload lease.
        headers (dict): The request headers for the upload.
        file_path (str): The local path of the file.
    """
    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()

# Add the file to a category.
def add_file(client: bailian20231229Client, lease_id: str, parser: str, category_id: str, workspace_id: str):
    """
    Adds the file to a specified category in the Model Studio service.

    Args:
        client (bailian20231229Client): The client.
        lease_id (str): The lease ID.
        parser (str): The parser for the file.
        category_id (str): The category ID.
        workspace_id (str): The workspace ID.

    Returns:
        The response from the Model Studio service.
    """
    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)

# Query the parsing status of the file.
def describe_file(client, workspace_id, file_id):
    """
    Gets the basic information about a file.

    Args:
        client (bailian20231229Client): The client.
        workspace_id (str): The workspace ID.
        file_id (str): The file ID.

    Returns:
        The response from the Model Studio service.
    """
    headers = {}
    runtime = util_models.RuntimeOptions()
    return client.describe_file_with_options(workspace_id, file_id, headers, runtime)

# Initialize the knowledge base (index).
def create_index(client, workspace_id, file_id, name, structure_type, source_type, sink_type):
    """
    Creates a knowledge base (initializes an index) in the Model Studio service.

    Args:
        client (bailian20231229Client): The client.
        workspace_id (str): The workspace ID.
        file_id (str): The file ID.
        name (str): The name of the knowledge base.
        structure_type (str): The data type of the knowledge base.
        source_type (str): The data source type. For example, the script uses 'DATA_CENTER_FILE'.
        sink_type (str): The vector storage type for the knowledge base.

    Returns:
        The response from the Model Studio service.
    """
    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)

# Submit an indexing task.
def submit_index(client, workspace_id, index_id):
    """
    Submits an indexing task to the Model Studio service.

    Args:
        client (bailian20231229Client): The client.
        workspace_id (str): The workspace ID.
        index_id (str): The knowledge base ID.

    Returns:
        The response from the Model Studio service.
    """
    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)

# Get the status of an indexing task.
def get_index_job_status(client, workspace_id, job_id, index_id):
    """
    Queries the status of an indexing task.

    Args:
        client (bailian20231229Client): The client.
        workspace_id (str): The workspace ID.
        index_id (str): The knowledge base ID.
        job_id (str): The ID of the indexing task.

    Returns:
        The response from the Model Studio service.
    """
    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
):
    """
    Creates a knowledge base in Model Studio.
    Args:
        file_path (str): The local path of the file.
        workspace_id (str): The workspace ID.
        name (str): The name of the knowledge base.
    Returns:
        str or None: The knowledge base ID on success, or None on failure.
    """
    # Set default values.
    category_id = 'default'
    parser = 'DASHSCOPE_DOCMIND'
    source_type = 'DATA_CENTER_FILE'
    structure_type = 'unstructured'
    sink_type = 'DEFAULT'
    try:
        # Step 1: Initialize the client.
        print("Step 1: Initializing the client...")
        client = create_client()
        # Step 2: Prepare file information.
        print("Step 2: Preparing file information...")
        file_name = os.path.basename(file_path)
        file_md5 = calculate_md5(file_path)
        file_size = get_file_size(file_path)
        # Step 3: Request an upload lease.
        print("Step 3: Requesting an upload lease from Model Studio...")
        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
        # Step 4: Upload the file.
        print("Step 4: Uploading the file to Model Studio...")
        upload_file(upload_url, upload_headers, file_path)
        # Step 5: Add the file to the server.
        print("Step 5: Adding the file to Model Studio...")
        add_response = add_file(client, lease_id, parser, category_id, workspace_id)
        file_id = add_response.body.data.file_id
        # Step 6: Check the file status.
        print("Step 6: Checking the file status in Model Studio...")
        while True:
            describe_response = describe_file(client, workspace_id, file_id)
            status = describe_response.body.data.status
            print(f"Current file status: {status}")
            if status == 'INIT':
                print("File is pending parsing. Please wait...")
            elif status == 'PARSING':
                print("File is parsing. Please wait...")
            elif status == 'PARSE_SUCCESS':
                print("File parsed successfully!")
                break
            else:
                print(f"Unknown file status: {status}. Please contact technical support.")
                return None
            time.sleep(5)
        # Step 7: Initialize the knowledge base.
        print("Step 7: Initializing the knowledge base in Model Studio...")
        index_response = create_index(client, workspace_id, file_id, name, structure_type, source_type, sink_type)
        index_id = index_response.body.data.id
        # Step 8: Submit an indexing task.
        print("Step 8: Submitting the indexing task to Model Studio...")
        submit_response = submit_index(client, workspace_id, index_id)
        job_id = submit_response.body.data.id
        # Step 9: Get the status of the indexing task.
        print("Step 9: Getting the indexing task status from Model Studio...")
        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"Current indexing task status: {status}")
            if status == 'COMPLETED':
                break
            time.sleep(5)
        print("Model Studio knowledge base created successfully!")
        return index_id
    except Exception as e:
        print(f"An error occurred: {e}")
        return None

def main():
    if not check_environment_variables():
        print("Environment variable check failed.")
        return
    file_path = input("Enter the local path of the file to upload (e.g., /path/to/file.docx): ")
    kb_name = input("Enter a name for your knowledge base: ")
    workspace_id = os.environ.get('WORKSPACE_ID')
    create_knowledge_base(file_path, workspace_id, kb_name)

if __name__ == '__main__':
    main()

Create a knowledge base

Create a document search knowledge base in a specified workspace.

1. Initialize client

To upload files and create a knowledge base, first initialize a client. Use your AccessKey and AccessKey Secret to verify your identity and configure the endpoint.
  • Public endpoints
    Your client must have internet access.
    • Public cloud: bailian.ap-southeast-1.aliyuncs.com
  • VPC endpoints
    If your client is deployed on the public cloud in the Alibaba Cloud Singapore region (ap-southeast-1) and is within a VPC, you can use the following VPC endpoint. Cross-region access is not supported.
    • Public cloud: bailian-vpc.ap-southeast-1.aliyuncs.com
Creating the client returns a Client object for subsequent API calls.
Python
def create_client() -> bailian20231229Client:
    """
    Create and configure a client.

    Returns:
        bailian20231229Client: The configured 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')
    )
    # The following endpoint is an example of a public endpoint for the public cloud. You can change the endpoint as needed.
    config.endpoint = 'bailian.ap-southeast-1.aliyuncs.com'
    return bailian20231229Client(config)

2. Upload knowledge base files

2.1. Request a file upload lease

Before creating a knowledge base, upload its source files to the same workspace. To do this, call the ApplyFileUploadLease operation to request a file upload lease. A lease is a temporary authorization to upload a file and is valid for several minutes.
  • workspace_id: See How to obtain a workspace ID.
  • category_id: In this example, pass default. Model Studio uses categories to manage your uploaded files. The system automatically creates a default category. You can also call the AddCategory API to create a new category and obtain the corresponding category_id.
  • file_name: Pass the name of the uploaded file, including its extension. The value must match the actual filename. For example, when you upload the file shown in the figure, pass Alibaba_Cloud_Model_Studio_Mobile_Phone_Series_Introduction.docx.
    image
  • file_md5: Pass the MD5 hash of the file to upload. Alibaba Cloud does not currently verify this value, which facilitates uploading files from a URL.
    In Python, you can get the MD5 hash by using the hashlib module. For other languages, see the complete sample code.
    import hashlib
    
    def calculate_md5(file_path):
        """
        Calculate the MD5 hash of a file.
    
        Args:
            file_path (str): The local path of the file.
    
        Returns:
            str: The MD5 hash of the file.
        """
        md5_hash = hashlib.md5()
    
        # Read the file in binary mode.
        with open(file_path, "rb") as f:
            # Read the file in chunks to avoid high memory usage for large files.
            for chunk in iter(lambda: f.read(4096), b""):
                md5_hash.update(chunk)
    
        return md5_hash.hexdigest()
    
    # Example usage
    file_path = "Replace this with the actual local path of the file to upload, for example, /path/to/your/Alibaba Cloud Model Studio Product Overview.docx"
    md5_value = calculate_md5(file_path)
    print(f"The MD5 hash of the file is: {md5_value}")
    
    Replace the file_path variable in the code with the actual local path of the file and run the code to get the MD5 hash of the target file. The following is an example value:
    The MD5 hash of the file is: 2ef7361ea907f3a1b91e3b9936f5643a
    
  • file_size: Pass the size of the file to upload in bytes.
    In Python, you can get this value by using the os module. For other languages, see the complete sample code.
    import os
    
    def get_file_size(file_path: str) -> int:
        """
        Get the size of a file in bytes.
    
        Args:
            file_path (str): The actual local path of the file.
    
        Returns:
            int: The file size in bytes.
        """
        return os.path.getsize(file_path)
    
    # Example usage
    file_path = "Replace this with the actual local path of the file to upload, for example, /path/to/your/Alibaba Cloud Model Studio Product Overview.docx"
    file_size = get_file_size(file_path)
    print(f"The size of the file in bytes is: {file_size}")
    
    Replace the file_path variable with the actual local path of the file and run the code to get the size of the target file in bytes. The following is an example value:
    The size of the file in bytes is: 14015
    
A successful request for a temporary upload lease returns the following:
  • A set of temporary upload parameters:
    • Data.FileUploadLeaseId
    • Data.Param.Method
    • X-bailian-extra in Data.Param.Headers
    • Content-Type in Data.Param.Headers
  • Temporary upload URL:Data.Param.Url
Python
def apply_lease(client, category_id, file_name, file_md5, file_size, workspace_id):
    """
    Request a file upload lease from Alibaba Cloud Model Studio.

    Args:
        client (bailian20231229Client): The client.
        category_id (str): The category ID.
        file_name (str): The file name.
        file_md5 (str): The MD5 hash of the file.
        file_size (int): The file size in bytes.
        workspace_id (str): The workspace ID.

    Returns:
        The response from Alibaba Cloud Model Studio.
    """
    headers = {}
    request = bailian_20231229_models.ApplyFileUploadLeaseRequest(
        file_name=file_name,
        md_5=file_md5,
        size_in_bytes=file_size,
    )
    runtime = util_models.RuntimeOptions()
    return client.apply_file_upload_lease_with_options(category_id, workspace_id, request, headers, runtime)
{
  "CategoryId": "default",
  "FileName": "Alibaba Cloud Model Studio Product Overview.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=YOUR_ACCESS_KEY_ID&Signature=YOUR_SIGNATURE",
      "Headers": "        \"X-bailian-extra\": \"MTAwNTQyNjQ5NTE2OTE3OA==\",\n        \"Content-Type\": \"application/pdf\""
    }
  }
}

2.2. Upload file to temporary storage

With the upload lease, use the temporary upload parameters and URL to upload files from your local storage or a publicly accessible URL to the Model Studio server. Each workspace supports up to 10,000 files. The supported formats include PDF, DOCX, DOC, TXT, Markdown, PPTX, PPT, XLSX, XLS, HTML, PNG, JPG, JPEG, BMP, and GIF.
  • pre_signed_url: Specify the Request a file upload lease API response's Data.Param.Url.
    This is a pre-signed URL and does not support FormData uploads. You must upload the file in binary format. For details, see the sample code.
This example does not support online debugging or sample code generation.
  • Local upload
  • URL upload
Python
import requests
from urllib.parse import urlparse

def upload_file(pre_signed_url, file_path):
    """
    Upload a local file to temporary storage.

    Args:
        pre_signed_url (str): The URL from the upload lease.
        file_path (str): The local path of the file.

    Returns:
        The response from Alibaba Cloud Model Studio.
    """
    try:
        # Set the request headers.
        headers = {
            "X-bailian-extra": "Replace this with the value of the X-bailian-extra field in Data.Param.Headers returned by the ApplyFileUploadLease operation in the previous step.",
            "Content-Type": "Replace this with the value of the Content-Type field in Data.Param.Headers returned by the ApplyFileUploadLease operation in the previous step. If a null value is returned, pass a null value."
        }

        # Read and upload the file.
        with open(file_path, 'rb') as file:
            # The request method for the file upload must be the same as the value of the Method field in Data.Param returned by the ApplyFileUploadLease operation in the previous step.
            response = requests.put(pre_signed_url, data=file, headers=headers)

        # Check the response status code.
        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 = "Replace this with the value of the Url field in Data.Param returned by the ApplyFileUploadLease operation in the previous step."

    # Upload a local file to temporary storage.
    file_path = "Replace this with the actual local path of the file to upload, for example, on Linux: /path/to/your/Alibaba Cloud Model Studio Product Overview.docx"
    upload_file(pre_signed_url_or_http_url, file_path)

2.3. Add file to a category

After uploading the file, add it to a category in the same workspace by calling the AddFile operation.
  • parser: Specify DASHSCOPE_DOCMIND.
  • lease_id: Set this parameter to the Data.FileUploadLeaseId that is returned when you request a file upload lease.
  • category_id: In this example, pass default. If you use a custom category for uploads, you must pass the corresponding category_id.
    The CategoryId passed here must match the CategoryId used in the Apply for a file upload lease step. Otherwise, you will receive a Category is mismatched error.
After you add a file, Model Studio returns a FileId for the file and automatically starts parsing it. The lease_id is immediately invalidated. Do not reuse the same lease ID for another submission.
Python
def add_file(client: bailian20231229Client, lease_id: str, parser: str, category_id: str, workspace_id: str):
    """
    Add a file to a specified category in Alibaba Cloud Model Studio.

    Args:
        client (bailian20231229Client): The client.
        lease_id (str): The lease ID.
        parser (str): The parser for the file.
        category_id (str): The category ID.
        workspace_id (str): The workspace ID.

    Returns:
        The response from Alibaba Cloud Model Studio.
    """
    headers = {}
    request = bailian_20231229_models.AddFileRequest(
        lease_id=lease_id,
        parser=parser,
        category_id=category_id,
    )
    runtime = util_models.RuntimeOptions()
    return client.add_file_with_options(workspace_id, request, headers, runtime)
{
  "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. Query file parsing status

A file cannot be used in a knowledge base until it is parsed. During peak hours, this process can take several hours. You can call the DescribeFile operation to query its parsing status.If the Data.Status field is PARSE_SUCCESS, the file has been successfully parsed and you can import it into the knowledge base.
  • Before calling this operation, a RAM user must be granted the required API permissions (the AliyunBailianDataFullAccess or AliyunBailianDataReadOnlyAccess policy).
  • This operation supports online debugging and sample code generation for multiple languages.
Python
def describe_file(client, workspace_id, file_id):
    """
    Get the basic information of a file.

    Args:
        client (bailian20231229Client): The client.
        workspace_id (str): The workspace ID.
        file_id (str): The file ID.

    Returns:
        The response from Alibaba Cloud Model Studio.
    """
    headers = {}
    runtime = util_models.RuntimeOptions()
    return client.describe_file_with_options(workspace_id, file_id, headers, runtime)
{
  "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": "Alibaba Cloud Model Studio Product Overview.docx",
    "FileId": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
    "SizeInBytes": "14015",
    "Parser": "DASHSCOPE_DOCMIND"
  },
  "Code": "Success",
  "Success": "true"
}

3. Create a knowledge base

3.1. Initialize knowledge base

Once a file is parsed, you can create a knowledge base from it in the same workspace. To begin, call the CreateIndex operation to initialize (but not finalize) a document retrieval knowledge base.
  • workspace_id: See How to obtain a workspace ID.
  • file_id: Specify the FileId returned by the API when you add a file to a category.
    If source_type is set to DATA_CENTER_FILE, this parameter is required, and the API returns an error if it is not specified.
  • structure_type: In this example, pass unstructured.
  • source_type: In this example, pass DATA_CENTER_FILE.
  • sink_type: In this example, specify BUILT_IN.
The value of the Data.Id field returned by this API is the knowledge base ID, which is used for subsequent index building.
Keep the knowledge base ID secure, as it is required for all subsequent API operations related to this knowledge base.
Python
def create_index(client, workspace_id, file_id, name, structure_type, source_type, sink_type):
    """
    Create (initialize) a knowledge base in Alibaba Cloud Model Studio.

    Args:
        client (bailian20231229Client): The client.
        workspace_id (str): The workspace ID.
        file_id (str): The file ID.
        name (str): The name of the knowledge base.
        structure_type (str): The data structure type of the knowledge base.
        source_type (str): The data source type. Category and file types are supported.
        sink_type (str): The vector storage type of the knowledge base.

    Returns:
        The response from Alibaba Cloud Model Studio.
    """
    headers = {}
    request = bailian_20231229_models.CreateIndexRequest(
        structure_type=structure_type,
        name=name,
        source_type=source_type,
        sink_type=sink_type,
        document_ids=[file_id]
    )
    runtime = util_models.RuntimeOptions()
    return client.create_index_with_options(workspace_id, request, headers, runtime)
{
  "Name": "Alibaba Cloud Model Studio Phone Knowledge Base",
  "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. Submit an index job

After initializing the knowledge base, call the SubmitIndexJob operation to start the index building process.After the submission is complete, Model Studio immediately starts building the index as an asynchronous task. The Data.Id returned by this API call is the corresponding task ID. You will use this ID in the next step to query the latest status of the task.
Python
def submit_index(client, workspace_id, index_id):
    """
    Submit an index job to Alibaba Cloud Model Studio.

    Args:
        client (bailian20231229Client): The client.
        workspace_id (str): The workspace ID.
        index_id (str): The knowledge base ID.

    Returns:
        The response from Alibaba Cloud Model Studio.
    """
    headers = {}
    submit_index_job_request = bailian_20231229_models.SubmitIndexJobRequest(
        index_id=index_id
    )
    runtime = util_models.RuntimeOptions()
    return client.submit_index_job_with_options(workspace_id, submit_index_job_request, headers, runtime)
{
  "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. Query index job status

The index job takes some time to complete. During peak hours, this process can take several hours. Call the GetIndexJobStatus operation to query its execution status.When the Data.Status field is COMPLETED, the knowledge base has been created.
Python
def get_index_job_status(client, workspace_id, index_id, job_id):
    """
    Query the status of an index job.

    Args:
        client (bailian20231229Client): The client.
        workspace_id (str): The workspace ID.
        index_id (str): The knowledge base ID.
        job_id (str): The job ID.

    Returns:
        The response from Alibaba Cloud Model Studio.
    """
    headers = {}
    get_index_job_status_request = bailian_20231229_models.GetIndexJobStatusRequest(
        index_id=index_id,
        job_id=job_id
    )
    runtime = util_models.RuntimeOptions()
    return client.get_index_job_status_with_options(workspace_id, get_index_job_status_request, headers, runtime)
{
  "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": "Imported successfully.",
        "DocName": "Alibaba Cloud Model Studio Product Overview",
        "Code": "FINISH"
      }
    ],
    "JobId": "3cd6fb57aaf44cd0b4dd2ca584xxxxxx"
  },
  "Code": "Success",
  "Success": "true"
}
You have created a knowledge base from the uploaded files.

Retrieve from a knowledge base

You can retrieve information from a knowledge base in two ways:
  • Using an Alibaba Cloud Model Studio application: When you call an application, use the rag_options parameter to pass the knowledge base ID index_id. This supplements your model with private knowledge and provides the latest information.
  • Using an Alibaba Cloud API: Call the Retrieve API to retrieve information from a specified knowledge base and return the original text segments.
The first method sends the retrieved text segments to your configured model to generate a final answer, while the second method directly returns the text segments. This section covers how to use an Alibaba Cloud API.
To retrieve information and return text segments from a specified knowledge base, call the Retrieve API.If a response contains excessive irrelevant information, specify SearchFilters in the request to filter results by criteria such as tags.
Python
def retrieve_index(client, workspace_id, index_id, query):
    """
    Retrieves information from a specified knowledge base.

    Args:
        client (bailian20231229Client): The client object.
        workspace_id (str): The workspace ID.
        index_id (str): The knowledge base ID.
        query (str): The search query.

    Returns:
        The response from the Model Studio service.
    """
    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)
{
  "IndexId": "mymxbdxxxx",
  "WorkspaceId": "llm-4u5xpd1xdjqpxxxx",
  "Query": "Please introduce the Alibaba Cloud Model Studio X1 phone."
}
{
  "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/Model_Studio_Series_Phone_Product_Introduction_1742197778230.json?Expires=1742457465&OSSAccessKeyId=YOUR_ACCESS_KEY_ID&Signature=YOUR_SIGNATURE",
          "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": "Alibaba Cloud Model Studio Phone Product Introduction",
          "doc_id": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
          "content": "Alibaba Cloud Model Studio Phone Product Introduction\nAlibaba Cloud Model Studio X1 — Enjoy the ultimate visual experience: Features a 6.7-inch 1440 x 3200 pixel ultra-clear screen with a 120 Hz refresh rate for a smooth and vivid visual experience. The powerful combination of 256 GB of mass storage and 12 GB of RAM handles large games and multitasking with ease. A long-lasting 5000 mAh battery and an ultra-sensitive quad-camera system capture every wonderful moment of your life. Reference price: 4,599–4,999\nTongyi Vivid 7 — A new experience in smart photography: Features a 6.5-inch 1080 x 2400 pixel full screen. The AI smart photography feature ensures every photo shows professional-grade color and detail. 8 GB of RAM and 128 GB of storage ensure smooth operation, and the 4,500 mAh battery meets daily needs. Side fingerprint unlock is convenient and secure. Reference price: 2,999–3,299\nStardust S9 Pro — An innovative visual feast: A groundbreaking 6.9-inch 1440 x 3088 pixel under-screen camera design provides a borderless visual experience. Top-tier configuration with 512 GB of storage and 16 GB of RAM, combined with a 6,000 mAh battery and 100 W fast charging technology, delivers both performance and endurance, leading the tech trend. Reference price: 5,999–6,499.",
          "_rc_score": 0,
          "workspace_id": "llm-4u5xpd1xdjqpxxxx",
          "hier_title": "Alibaba Cloud Model Studio Phone Product Introduction",
          "_rc_t_score": 0.05215025693178177,
          "doc_name": "Alibaba Cloud Model Studio Series Phone Product Introduction",
          "pipeline_id": "mymxbdxxxx",
          "_id": "llm-4u5xpd1xdjqp8itj_mymxbd6172_file_0b21e0a852cd40cd9741c54fefbb61cd_10285263_0_0"
        },
        "Text": "Alibaba Cloud Model Studio Phone Product Introduction\nAlibaba Cloud Model Studio X1 — Enjoy the ultimate visual experience: Features a 6.7-inch 1440 x 3200 pixel ultra-clear screen with a 120 Hz refresh rate for a smooth and vivid visual experience. The powerful combination of 256 GB of mass storage and 12 GB of RAM handles large games and multitasking with ease. A long-lasting 5000 mAh battery and an ultra-sensitive quad-camera system capture every wonderful moment of your life. Reference price: 4,599–4,999\nTongyi Vivid 7 — A new experience in smart photography: Features a 6.5-inch 1080 x 2400 pixel full screen. The AI smart photography feature ensures every photo shows professional-grade color and detail. 8 GB of RAM and 128 GB of storage ensure smooth operation, and the 4,500 mAh battery meets daily needs. Side fingerprint unlock is convenient and secure. Reference price: 2,999–3,299\nStardust S9 Pro — An innovative visual feast: A groundbreaking 6.9-inch 1440 x 3088 pixel under-screen camera design provides a borderless visual experience. Top-tier configuration with 512 GB of storage and 16 GB of RAM, combined with a 6,000 mAh battery and 100 W fast charging technology, delivers both performance and endurance, leading the tech trend. Reference price: 5,999–6,499."
      },
      {
        "Score": 0.5322970747947693,
        "Metadata": {
          "file_path": "https://bailian-datahub-data-prod.oss-cn-beijing.aliyuncs.com/10285263/multimodal/docJson/Model_Studio_Series_Phone_Product_Introduction_1742197778230.json?Expires=1742457465&OSSAccessKeyId=YOUR_ACCESS_KEY_ID&Signature=YOUR_SIGNATURE",
          "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": "Alibaba Cloud Model Studio Phone Product Introduction",
          "doc_id": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
          "content": "Alibaba Cloud Model Studio Flex Fold+ — A new era of foldable screens: Combining innovation and luxury, it features a 7.6-inch 1800 x 2400 pixel main screen and a 4.7-inch 1080 x 2400 pixel external screen. The multi-angle free-stop hinge design meets the needs of different scenarios. Alibaba Cloud Model Studio Flex Fold+ — A new era of foldable screens: Combining innovation and luxury, it features a 7.6-inch 1800 x 2400 pixel main screen and a 4.7-inch 1080 x 2400 pixel external screen. The multi-angle free-stop hinge design meets the needs of different scenarios. 512 GB of storage, 12 GB of RAM, a 4700 mAh battery, and UTG ultra-thin flexible glass open a new chapter in the era of foldable screens. In addition, this phone supports Dual SIM Dual Standby and satellite calls, helping you stay connected anywhere in the world. Reference retail price: 9,999–10,999. Each phone is a masterpiece of craftsmanship, designed to be a work of technological art in your hands. Choose your smart companion and start a new chapter of future tech life.",
          "_rc_score": 0,
          "workspace_id": "llm-4u5xpd1xdjqpxxxx",
          "hier_title": "Alibaba Cloud Model Studio Phone Product Introduction",
          "_rc_t_score": 0.05188392847776413,
          "doc_name": "Alibaba Cloud Model Studio Series Phone Product Introduction",
          "pipeline_id": "mymxbdxxxx",
          "_id": "llm-4u5xpd1xdjqp8itj_mymxbd6172_file_0b21e0a852cd40cd9741c54fefbb61cd_10285263_0_2"
        },
        "Text": "Alibaba Cloud Model Studio Flex Fold+ — A new era of foldable screens: Combining innovation and luxury, it features a 7.6-inch 1800 x 2400 pixel main screen and a 4.7-inch 1080 x 2400 pixel external screen. The multi-angle free-stop hinge design meets the needs of different scenarios. Alibaba Cloud Model Studio Flex Fold+ — A new era of foldable screens: Combining innovation and luxury, it features a 7.6-inch 1800 x 2400 pixel main screen and a 4.7-inch 1080 x 2400 pixel external screen. The multi-angle free-stop hinge design meets the needs of different scenarios. 512 GB of storage, 12 GB of RAM, a 4700 mAh battery, and UTG ultra-thin flexible glass open a new chapter in the era of foldable screens. In addition, this phone supports Dual SIM Dual Standby and satellite calls, helping you stay connected anywhere in the world. Reference retail price: 9,999–10,999. Each phone is a masterpiece of craftsmanship, designed to be a work of technological art in your hands. Choose your smart companion and start a new chapter of future tech life."
      },
      {
        "Score": 0.5050643086433411,
        "Metadata": {
          "file_path": "https://bailian-datahub-data-prod.oss-cn-beijing.aliyuncs.com/10285263/multimodal/docJson/Model_Studio_Series_Phone_Product_Introduction_1742197778230.json?Expires=1742457465&OSSAccessKeyId=YOUR_ACCESS_KEY_ID&Signature=YOUR_SIGNATURE",
          "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": "Alibaba Cloud Model Studio Phone Product Introduction",
          "doc_id": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
          "content": "Top-tier configuration with 512 GB of storage and 16 GB of RAM, combined with a 6,000 mAh battery and 100 W fast charging technology, delivers both performance and endurance, leading the tech trend. Reference price: 5,999–6,499. Alibaba Cloud Model Studio Ace Ultra — The gamer's choice: Equipped with a 6.67-inch 1080 x 2400 pixel screen, 10 GB of RAM, and 256 GB of storage to ensure silky-smooth gameplay. The 5,500 mAh battery with a liquid cooling system stays cool even during long gaming sessions. High-dynamic dual speakers upgrade the gaming experience with immersive sound effects. Reference price: 3,999–4,299. Alibaba Cloud Model Studio Zephyr Z9 — The art of being thin and portable: A lightweight 6.4-inch 1080 x 2340 pixel design, with 128 GB of storage and 6 GB of RAM, is more than enough for daily use. The 4,000 mAh battery ensures a full day of use without worry. The 30x digital zoom lens captures distant details. It is thin but powerful. Reference price: 2,499–2,799. Alibaba Cloud Model Studio Flex Fold+ — A new era of foldable screens: Combining innovation and luxury, it features a 7.6-inch 1800 x 2400 pixel main screen and a 4.7-inch 1080 x 2400 pixel external screen. The multi-angle free-stop hinge design meets the needs of different scenarios.",
          "_rc_score": 0,
          "workspace_id": "llm-4u5xpd1xdjqpxxxx",
          "hier_title": "Alibaba Cloud Model Studio Phone Product Introduction",
          "_rc_t_score": 0.05158032476902008,
          "doc_name": "Alibaba Cloud Model Studio Series Phone Product Introduction",
          "pipeline_id": "mymxbdxxxx",
          "_id": "llm-4u5xpd1xdjqp8itj_mymxbd6172_file_0b21e0a852cd40cd9741c54fefbb61cd_10285263_0_1"
        },
        "Text": "Top-tier configuration with 512 GB of storage and 16 GB of RAM, combined with a 6,000 mAh battery and 100 W fast charging technology, delivers both performance and endurance, leading the tech trend. Reference price: 5,999–6,499. Alibaba Cloud Model Studio Ace Ultra — The gamer's choice: Equipped with a 6.67-inch 1080 x 2400 pixel screen, 10 GB of RAM, and 256 GB of storage to ensure silky-smooth gameplay. The 5,500 mAh battery with a liquid cooling system stays cool even during long gaming sessions. High-dynamic dual speakers upgrade the gaming experience with immersive sound effects. Reference price: 3,999–4,299. Alibaba Cloud Model Studio Zephyr Z9 — The art of being thin and portable: A lightweight 6.4-inch 1080 x 2340 pixel design, with 128 GB of storage and 6 GB of RAM, is more than enough for daily use. The 4,000 mAh battery ensures a full day of use without worry. The 30x digital zoom lens captures distant details. It is thin but powerful. Reference price: 2,499–2,799. Alibaba Cloud Model Studio Flex Fold+ — A new era of foldable screens: Combining innovation and luxury, it features a 7.6-inch 1800 x 2400 pixel main screen and a 4.7-inch 1080 x 2400 pixel external screen. The multi-angle free-stop hinge design meets the needs of different scenarios."
      }
    ]
  },
  "Code": "Success",
  "Success": "true"
}

Update a knowledge base

The following example shows how to update a document search knowledge base. Applications that use the knowledge base reflect your updates in real time. New content becomes available for retrieval, while deleted content is no longer accessible.
You cannot update data query or image Q&A knowledge bases using an API. For more information, see Update a knowledge base.
  • Incremental update: The only supported method is a three-step process: upload the updated file, append the file to the knowledge base, and then delete the old file.
  • Full update: For each file in the knowledge base, perform the three steps to complete the update.
  • Automatic update or synchronization: For more information, see How to automatically update or synchronize a knowledge base.
  • File limit for a single update: We recommend updating no more than 10,000 files at a time. Exceeding this limit might prevent the knowledge base from updating correctly.

1. Upload the updated file

Follow the procedure in Create a knowledge base: Step 2 to upload the updated file to the workspace that contains the knowledge base.
Request a new file upload lease to generate a new set of upload parameters for the updated file.

2. Append file to the knowledge base

2.1. Submit an append task

After the uploaded file is parsed, call the SubmitIndexAddDocumentsJob operation to append the new file to the knowledge base and rebuild the knowledge base index.After you submit the task, Model Studio rebuilds the knowledge base asynchronously. This operation returns Data.Id, which is the task ID (job_id). Use this ID in the next step to query the task status.
  • After you call the SubmitIndexAddDocumentsJob operation, the task takes some time to complete. You can use the job_id to query the task status. Do not resubmit the task before it is complete.
Python
def submit_index_add_documents_job(client, workspace_id, index_id, file_id, source_type):
    """
    Appends and imports a parsed file to a document search knowledge base.

    Args:
        client (bailian20231229Client): The client.
        workspace_id (str): The workspace ID.
        index_id (str): The knowledge base ID.
        file_id (str): The file ID.
        source_type(str): The data type.

    Returns:
        The response from the Alibaba Cloud Model Studio service.
    """
    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)
{
  "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. Wait for task completion

The indexing task takes some time to complete. During peak hours, this process can take several hours. You can call the GetIndexJobStatus operation to query its execution status.A value of COMPLETED for the Data.Status field in the response indicates that all updated files have been successfully appended to the knowledge base.
The Documents list in the response contains all files for the append task corresponding to the job_id you provided.
Python
def get_index_job_status(client, workspace_id, index_id, job_id):
    """
    Queries the status of an indexing task.

    Args:
        client (bailian20231229Client): The client.
        workspace_id (str): The workspace ID.
        index_id (str): The knowledge base ID.
        job_id (str): The task ID.

    Returns:
        The response from the Alibaba Cloud Model Studio service.
    """
    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)
{
  "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": "Import successful",
        "DocName": "Alibaba Cloud Model Studio Phone Product Introduction",
        "Code": "FINISH"
      }
    ],
    "JobId": "76f243b9ee534d59a61f156ff0xxxxxx"
  },
  "Code": "Success",
  "Success": true
}

3. Delete the old file

Finally, call the DeleteIndexDocument operation to permanently delete the old version of the file from the knowledge base. This prevents outdated information from being retrieved accidentally.
  • file_id: Enter the FileId of the old file.
You can only delete files with a status of import failed (INSERT_ERROR) or import successful (FINISH). To query the status of files in the knowledge base, you can call the ListIndexDocuments operation.
Python
def delete_index_document(client, workspace_id, index_id, file_id):
    """
    Permanently deletes one or more files from a specified document search knowledge base.

    Args:
        client (bailian20231229Client): The client.
        workspace_id (str): The workspace ID.
        index_id (str): The knowledge base ID.
        file_id (str): The file ID.

    Returns:
        The response from the Alibaba Cloud Model Studio service.
    """
    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)
{
  "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"
}

Manage knowledge bases

Creating and using knowledge bases are not supported through the API. You must perform these tasks in the Model Studio console.

View a knowledge base

To view knowledge bases in a specified workspace, call the ListIndices operation.
Python
def list_indices(client, workspace_id):
    """
    Gets the details of knowledge bases in a specified workspace.

    Args:
        client (bailian20231229Client): The client.
        workspace_id (str): The workspace ID.

    Returns:
        The response from the Alibaba Cloud Model Studio service.
    """
    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)
{
  "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": "Model Studio Mobile Phone Knowledge Base",
        "ChunkSize": 500,
        "EmbeddingModelName": "text-embedding-v2",
        "RerankMinScore": 0.01,
        "Id": "mymxbdxxxx",
        "SinkType": "BUILT_IN",
        "Separator": " |,|,|。|?|!|\n|\\?|\\!"
      }
    ]
  },
  "Code": "Success",
  "Success": "true"
}

Delete a knowledge base

To permanently delete a knowledge base, call the DeleteIndex operation. Before you delete the knowledge base, you must disassociate it from all linked Alibaba Cloud Model Studio applications in the Model Studio console. Otherwise, the deletion fails.Note: This operation does not delete the files you have added to a category.
Python
def delete_index(client, workspace_id, index_id):
    """
    Permanently deletes the specified knowledge base.

    Args:
        client (bailian20231229Client): The client.
        workspace_id (str): The workspace ID.
        index_id (str): The knowledge base ID.

    Returns:
        The response from the Alibaba Cloud Model Studio service.
    """
    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)
{
  "IndexId": "mymxbdxxxx",
  "WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}
{
  "Status": "200",
  "Message": "success",
  "RequestId": "118CB681-75AA-583B-8D84-25440CXXXXXX",
  "Code": "Success",
  "Success": "true"
}

API

See the API Catalog (Knowledge Base) for a complete list of knowledge base APIs and their request and response parameters.

FAQ

  1. How do I automate knowledge base updates and synchronization?
    • Data query and image Q&A
  2. Why is my new knowledge base empty? This typically occurs if the Submit an index job step fails to run. If you call the CreateIndex API but the SubmitIndexJob API call fails, the knowledge base will be empty. To resolve this, Submit an index job again and wait for the index job to complete.
  3. What should I do if I receive the error "Access your uploaded file failed. Please check if your upload action was successful"? This error usually occurs because the Upload the file to temporary storage step did not run successfully. Confirm that this step runs successfully before you call the AddFile API operation.
  4. What should I do if I receive the error "Access denied: Either you are not authorized to access this workspace, or the workspace does not exist"? This error usually occurs for the following reasons:
    • The requested service endpoint (service endpoint) is incorrect: For access over the Internet, users of the China site (public cloud) should use the service endpoint in China (Beijing), whereas users of the international site should use the service endpoint in Singapore. If you are using the online debugging feature, make sure that you select the correct service endpoint, as shown in the following figure.
      image
    • TheWorkspaceIdvalue is incorrect, or you are not a member of the workspace: Before you call the API, verify that the WorkspaceId is correct and that you are a member of the workspace. How to be added as a member of a specified workspace
  5. What should I do if I receive the error "Specified access key is not found or invalid"? This error usually occurs because the provided access_key_id or access_key_secret is incorrect, or the access_key_id has been disabled. Ensure that the access_key_id is correct and not disabled before you call the API.
  6. What should I do if I receive the error "Category is mismatched"? This error typically occurs when the CategoryId used in the ApplyFileUploadLease API call differs from the CategoryId passed in the subsequent AddFile API call. Ensure that you use the same CategoryId throughout the entire file upload flow, from ApplyFileUploadLease to AddFile. You can call the ListCategory API to retrieve the list of categories in the current workspace and verify that the CategoryId you are using is correct.

Billing

  • All knowledge base features and API calls are free. See Knowledge Base: Billing.
  • Storage space for data, such as files, imported into Model Studio is free.

Error codes

If a call to an API operation described in this topic fails, see Error Center.