Skip to main content

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.

This document is for knowledge bases for document search only.
Knowledge base features are only supported in the China (Beijing) region on the China site and the Singapore region on the International site. Other regions, such as Germany (Frankfurt), do not support knowledge base features.

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
  • Manage chunks
  • 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 China (Beijing) region. Modify it if you use a different region.
    config.endpoint = 'bailian.cn-beijing.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.cn-beijing.aliyuncs.com
  • VPC endpoints
    If your client is deployed on the public cloud in the Alibaba Cloud China (Beijing) region (cn-beijing) and is within a VPC, you can use the following VPC endpoint. Cross-region access is not supported.
    • Public cloud: bailian-vpc.cn-beijing.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.cn-beijing.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, if the actual file name is Alibaba_Cloud_Model_Studio_Mobile_Phone_Series_Introduction.docx, pass that as file_name.
  • 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 100,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

Currently, you can retrieve information from a knowledge base in the following ways:
  • Using an Alibaba Cloud Model Studio application: When you call an application, pass the knowledge base ID index_id through rag_options to supplement your model application with private knowledge and provide 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.
  • Using the Knowledge Search service (recommended): Call the Search API to perform joint semantic retrieval across multiple knowledge bases and return text segments ranked by relevance. Retrieval strategies are configured and published in the console in advance, and callers only need to pass the search intent (query/images) and agent_id.
The differences among the three are as follows: the first method first sends the retrieved relevant text segments to your configured model, which then combines these segments with the user's original query to generate and return a final answer; the latter two methods directly return text segments. Among them, the Knowledge Search service (Search API) is the recommended method, which supports joint retrieval across multiple knowledge bases and multimodal retrieval, and whose retrieval strategies are centrally configured and managed in the console without being maintained in requests. The following describes how to use the Knowledge Search service (Search API).
To perform joint semantic retrieval across multiple knowledge bases and return text segments ranked by relevance, call the Search API.
  • agent_id: The ID of the Knowledge Search service (agent) instance. Obtain it after creating and publishing the service on the Knowledge Search page in the console.
  • API Key: The Alibaba Cloud Model Studio API Key. Obtain it on the API Key page in the console.
  • workspace_id: The workspace that contains the knowledge base, used to construct the Base URL (https://{workspaceId}.cn-beijing.maas.aliyuncs.com). Obtain it in workspace management in the console.
    A RAM user can only retrieve knowledge bases in a workspace they have joined.
Retrieval strategies (weights across knowledge bases, knowledge routing, reranking models, etc.) are configured in the service instance and published in the console in advance. Callers only need to pass the search intent (query/images) and agent_id, without maintaining retrieval strategy parameters in the request.
  • Before calling, you must create and publish a Knowledge Search service (agent) on the Knowledge Search page in the Model Studio console and obtain the service ID (agent_id). If the service is not published, an "agent not published" error is returned.
  • The default rate limit is 25 QPS per user. If you are rate-limited, retry later.
cURL
curl -X POST "https://{workspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/indices/knowledge/search" \
  -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "agent_id": "aid-xxxxxxxxxxxxxxxx",
    "query": "请介绍一下阿里云百炼手机X1。",
    "images": []
  }'
{
  "agent_id": "aid-xxxxxxxxxxxxxxxx",
  "query": "请介绍一下阿里云百炼手机X1。",
  "images": []
}
{
  "code": "Success",
  "status_code": 200,
  "status": "SUCCESS",
  "success": true,
  "message": "success",
  "request_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "data": {
    "total": 3,
    "nodes": [
      {
        "score": 0.9201,
        "text": "阿里云百炼手机产品介绍阿里云百炼 X1 ——畅享极致视界:搭载 6.7英寸 1440 x 3200像素超清屏幕,搭配 120Hz刷新率,流畅视觉体验跃然眼前。256GB海量存储空间与 12GB RAM强强联合,无论是大型游戏还是多任务处理,都能轻松应对。5000mAh电池长续航,加上超感光四摄系统,记录生活每一刻精彩。参考售价:4599- 4999",
        "metadata": {
          "doc_id": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
          "doc_name": "阿里云百炼系列手机产品介绍",
          "title": "阿里云百炼手机产品介绍",
          "content": "阿里云百炼手机产品介绍阿里云百炼 X1 ——畅享极致视界:搭载 6.7英寸 1440 x 3200像素超清屏幕,搭配 120Hz刷新率,流畅视觉体验跃然眼前。256GB海量存储空间与 12GB RAM强强联合,无论是大型游戏还是多任务处理,都能轻松应对。5000mAh电池长续航,加上超感光四摄系统,记录生活每一刻精彩。参考售价:4599- 4999",
          "pipeline_id": "mymxbdxxxx",
          "workspace_id": "llm-4u5xpd1xdjqpxxxx",
          "_id": "llm-4u5xpd1xdjqpxxxx_mymxbd6172_file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx_0_0",
          "_knowledge_type": "document",
          "_knowledge_scene": "basic_document_qa"
        }
      }
    ],
    "cost_time": 2629
  }
}

Structured output

The Knowledge Base retrieval API does not support the response_format parameter. To get JSON-formatted output, set response_format at the model invocation layer. Take Python SDK alibabacloud_bailian20231229 2.14.3 as an example: RetrieveRequest has 15 fields: index_id, query, dense_similarity_top_k, enable_reranking, enable_rewrite, extra, images, query_history, rerank, rerank_min_score, rerank_top_n, rewrite, save_retriever_history, search_filters, sparse_similarity_top_k, among which response_format is not included. For the Agent API, you can use the instructions field to specify the JSON output format through a prompt, that is, include "Please output in JSON format" in instructions when creating the application. Alibaba Cloud Model Studio does not directly generate JSON files; you need to write the returned JSON content to a file yourself.

Knowledge Base retrieval + JSON output

First call the retrieval interface to obtain text chunks from the knowledge base, then use the chunks as context to call a DashScope model interface with response_format={"type": "json_object"} set, and you will get structured output.
import os
import dashscope
from alibabacloud_bailian20231229.client import Client
from alibabacloud_bailian20231229 import models
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions

# 0. Initialize the client
client = Client(Config(
    access_key_id=os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_ID"),
    access_key_secret=os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
    endpoint="bailian.cn-beijing.aliyuncs.com"
))
dashscope_client = dashscope.Client(api_key=os.getenv("DASHSCOPE_API_KEY"))
workspace_id = "llm-xxx"  # Workspace ID
runtime = RuntimeOptions()

# 1. Retrieve from the knowledge base
retrieve_req = models.RetrieveRequest(index_id="xxx", query="产品信息")
retrieve_resp = client.retrieve_with_options(workspace_id, retrieve_req, {}, runtime)
context = "\n".join([n.text for n in retrieve_resp.body.data.nodes])

# 2. Call the model with JSON output
resp = dashscope_client.chat.completions.create(
    model="qwen-plus",
    messages=[
        {"role": "system", "content": f"根据以下知识库内容回答,输出JSON格式:\n{context}"},
        {"role": "user", "content": "列出所有产品型号及价格"}
    ],
    response_format={"type": "json_object"}
)
print(resp.output_text)
For more parameters of the model invocation interface, see DashScope API reference.

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.
Data query and image Q&A knowledge bases can also be created and managed through the RAG API. For more information, see RAG API Reference.
  • 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 100,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

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"
}

Manage chunks

Query, edit, and delete chunks in a knowledge base. Editing chunks is supported by all knowledge base types; for deletion, document search, data query, and image Q&A knowledge bases are all supported, while audio/video search knowledge bases only support deletion.

Query the chunk list

Call the ListChunks API to query the chunk list of a knowledge base.
  • client: How to obtain a client
  • workspace_id: How to obtain a workspace ID
  • index_id: The knowledge base ID, i.e. the Data.Id returned when the knowledge base was created.
  • page_num: Page number, starting from 1 (optional, default 1).
  • page_size: Number of items per page (optional, default 10).
  • file_id: Document ID (optional; when not specified, chunks of the entire knowledge base are returned).
Python
def list_chunks(client, workspace_id, index_id, page_num=1, page_size=10, file_id=None):
    """查询切片列表"""
    headers = {}
    request = bailian_20231229_models.ListChunksRequest(
        index_id=index_id,
        page_num=page_num,
        page_size=page_size,
        file_id=file_id
    )
    runtime = util_models.RuntimeOptions()
    return client.list_chunks_with_options(workspace_id, request, headers, runtime)

Edit a chunk

Call the UpdateChunk API to modify the content of a specified chunk. This operation is supported by all knowledge base types.
  • client: How to obtain a client
  • workspace_id: How to obtain a workspace ID
  • pipeline_id: The knowledge base ID, i.e. the Data.Id returned when the knowledge base was created.
  • data_id: Document ID (the document the chunk belongs to; can be obtained from metadata.doc_id in the ListChunks response).
  • chunk_id: The complete _id value of the chunk (can be obtained from metadata._id in the ListChunks response).
  • content: The new chunk content (10-6000 characters).
  • is_displayed_chunk_content: Whether to display the chunk content (set to true).
Python
def update_chunk(client, workspace_id, pipeline_id, data_id, chunk_id, content):
    """编辑切片"""
    headers = {}
    request = bailian_20231229_models.UpdateChunkRequest(
        pipeline_id=pipeline_id,
        data_id=data_id,
        chunk_id=chunk_id,
        is_displayed_chunk_content=True,
        content=content
    )
    runtime = util_models.RuntimeOptions()
    return client.update_chunk_with_options(workspace_id, request, headers, runtime)

Delete chunks

Call the DeleteChunk API to delete one or more chunks. A maximum of 10 chunks can be deleted per call.
  • client: How to obtain a client
  • workspace_id: How to obtain a workspace ID
  • pipeline_id: The knowledge base ID, i.e. the Data.Id returned when the knowledge base was created.
  • chunk_ids: The list of chunk _id values to delete (obtained from metadata._id in the ListChunks response).
Python
def delete_chunk(client, workspace_id, pipeline_id, chunk_ids):
    """删除切片"""
    headers = {}
    request = bailian_20231229_models.DeleteChunkRequest(
        pipeline_id=pipeline_id,
        chunk_ids=chunk_ids
    )
    runtime = util_models.RuntimeOptions()
    return client.delete_chunk_with_options(workspace_id, request, headers, runtime)

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 because the Submit an index job step was not performed or did not complete successfully. If you call the CreateIndex API but do not successfully call the SubmitIndexJob API, you will get an empty knowledge base. To resolve this, simply 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 was not performed or did not complete 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, if you are a user of the China site (public cloud), you should use the service endpoint in the China (Beijing) region; if you are a user of the international site, you should use the service endpoint in the Singapore region. If you are using the online debugging feature, make sure the service endpoint dropdown is set correctly (China site: China (Beijing)).
    • 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 to apply for a file upload lease 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.
  7. Why do the API results differ from the console debug window when I call a knowledge base application? Troubleshoot this issue from the following perspectives:
    • Multi-turn conversation context: The console debug window retains multi-turn conversation history by default. If your API call does not pass session_id, each call is a standalone call without context. Follow-up questions that rely on previous context will lose their referents, which may produce answers completely different from those in the debug window. To enable multi-turn conversation, retrieve session_id from the response of the first call and pass the same session_id in subsequent calls to maintain session continuity.
    • Application release status: After the application configuration is modified, you must click Publish for the changes to take effect, and API calls always use the published version. If you are verifying unpublished changes in the debug window, the API responses will not reflect those changes. Make sure the application status is Published.
    • Parameter alignment: When you call through the application (App API), the default parameters configured in the application (such as temperature and top_p) are used, which is consistent with the debug window. If you directly call the DashScope model service API, you must explicitly specify these parameters, and their values may differ from those in the debug environment, resulting in differences in answer style and content.
    • Knowledge base association: When you call through the application (App API), the knowledge bases configured in the application are automatically associated, so you do not need to specify them manually. If you directly call the knowledge base retrieval API, you must explicitly pass in knowledgebase_id; omitting it or passing an incorrect value will prevent the expected knowledge from being retrieved.

Billing

Knowledge bases use a pay-as-you-go model. Usage for each billable item is calculated hourly, and fees are automatically deducted from your Alibaba Cloud account. To prevent service interruptions from an overdue payment, ensure you maintain a sufficient account balance. You can add funds in Billing and Costs.

Billable item

Description

Specification fee

The fee for the actual runtime of a Standard or Enterprise knowledge base. For pricing details, see Knowledge base billing. Configuration changes trigger segmented billing based on the time of the change.

Embedding and rerank model call fees

You are charged for calling embedding and rerank models when creating, updating, or retrieving from a knowledge base. Billing is based on input token usage. For pricing, see the Model Call Billing page.

To view your bill, see Bill Details.

Error codes

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