Skip to main content

API de base de conocimientos

La base de conocimientos de Alibaba Cloud Model Studio proporciona APIs abiertas que le permiten integrarse con sus sistemas empresariales existentes, automatizar operaciones y satisfacer necesidades complejas de recuperación.

Requisitos previos

  1. Para gestionar una base de conocimientos con API, un usuario RAM debe obtener permisos de API (la política AliyunBailianDataFullAccess) y unirse a un espacio de trabajo. Esto no es necesario para una cuenta de Alibaba Cloud.
    Un usuario RAM solo puede gestionar bases de conocimientos en espacios de trabajo a los que se ha unido. Una cuenta de Alibaba Cloud puede gestionar bases de conocimientos en todos los espacios de trabajo.
  2. Instale la versión más reciente del SDK de Alibaba Cloud Model Studio para llamar a las API de la base de conocimientos. Para obtener instrucciones de instalación, consulte la Referencia de desarrollo del SDK de Alibaba Cloud.
    Si el SDK no cumple con sus requisitos, puede llamar a las API de la base de conocimientos mediante solicitudes HTTP utilizando el mecanismo de firma. Para obtener detalles sobre la conexión, consulte la Descripción general de la API.
  3. Obtenga un AccessKey ID y un AccessKey Secret, y un ID de espacio de trabajo. Configúrelos como variables de entorno del sistema para ejecutar el código de ejemplo. El siguiente ejemplo muestra cómo establecer estas variables en Linux:
    Si utiliza un IDE u otros complementos de desarrollo, configure las variables ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET y WORKSPACE_ID en su entorno de desarrollo.
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 el documento de conocimiento de ejemplo Alibaba Cloud Model Studio Phone Introduction.docx para crear una base de conocimientos.
  • Crear una base de conocimientos
  • Recuperar desde una base de conocimientos
  • Actualizar una base de conocimientos
  • Gestionar bases de conocimientos
  • Antes de ejecutar este ejemplo, complete los requisitos previos y asegúrese de que el usuario RAM tenga asignada la política AliyunBailianDataFullAccess.
  • Si utiliza un IDE u otros complementos de desarrollo, establezca las variables de entorno ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET y WORKSPACE_ID en su entorno de desarrollo.
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()

Crear una base de conocimientos

Crear una base de conocimientos de búsqueda de documentos en un espacio de trabajo especificado.

1. Inicializar cliente

Para cargar archivos y crear una base de conocimientos, primero inicialice un cliente. Utilice su AccessKey y AccessKey Secret para verificar su identidad y configurar el endpoint.
  • Endpoints públicos
    Su cliente debe tener acceso a Internet.
    • Nube pública: bailian.ap-southeast-1.aliyuncs.com
  • Endpoints de VPC
    Si su cliente está implementado en la nube pública en la región de Singapur de Alibaba Cloud (ap-southeast-1) y se encuentra dentro de una VPC, puede utilizar el siguiente punto de conexión de VPC. No se admite el acceso entre regiones.
    • Nube pública: bailian-vpc.ap-southeast-1.aliyuncs.com
La creación del cliente devuelve un objeto Client para llamadas API posteriores.
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. Cargar archivos de la base de conocimientos

2.1. Solicitar una concesión de carga de archivo

Antes de crear una base de conocimientos, cargue sus archivos de origen en el mismo espacio de trabajo. Para ello, llame a la operación ApplyFileUploadLease para solicitar un permiso de carga de archivo. Un permiso es una autorización temporal para cargar un archivo y es válido durante varios minutos.
  • workspace_id: Consulte Cómo obtener un ID de espacio de trabajo.
  • category_id: En este ejemplo, pase default. Model Studio utiliza categorías para gestionar sus archivos cargados. El sistema crea automáticamente una categoría predeterminada. También puede llamar a la API AddCategory para crear una nueva categoría y obtener el category_id correspondiente.
  • file_name: Pase el nombre del archivo cargado, incluida su extensión. El valor debe coincidir con el nombre de archivo real. Por ejemplo, cuando cargue el archivo que se muestra en la figura, pase Alibaba_Cloud_Model_Studio_Mobile_Phone_Series_Introduction.docx.
    imagen
  • file_md5: Pase el hash MD5 del archivo a cargar. Actualmente, Alibaba Cloud no verifica este valor, lo que facilita la carga de archivos desde una URL.
    En Python, puede obtener el hash MD5 utilizando el módulo hashlib. Para otros lenguajes, consulte el código de muestra completo.
    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}")
    
    Reemplace la variable file_path en el código con la ruta local real del archivo y ejecute el código para obtener el hash MD5 del archivo objetivo. El siguiente es un valor de ejemplo:
    The MD5 hash of the file is: 2ef7361ea907f3a1b91e3b9936f5643a
    
  • file_size: Pase el tamaño del archivo a cargar en bytes.
    En Python, puede obtener este valor utilizando el módulo os. Para otros lenguajes, consulte el código de muestra completo.
    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}")
    
    Reemplace la variable file_path con la ruta local real del archivo y ejecute el código para obtener el tamaño del archivo objetivo en bytes. El siguiente es un valor de ejemplo:
    The size of the file in bytes is: 14015
    
Una solicitud exitosa de concesión de carga temporal devuelve lo siguiente:
  • Un conjunto de parámetros de carga temporal:
    • Data.FileUploadLeaseId
    • Data.Param.Method
    • X-bailian-extra en Data.Param.Headers
    • Content-Type en Data.Param.Headers
  • URL de carga temporal: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. Cargar archivo al almacenamiento temporal

Con el permiso de carga, utilice los parámetros de carga temporal y la URL para cargar archivos desde su almacenamiento local o una URL de acceso público al servidor de Model Studio. Cada espacio de trabajo admite hasta 10,000 archivos. Los formatos admitidos incluyen PDF, DOCX, DOC, TXT, Markdown, PPTX, PPT, XLSX, XLS, HTML, PNG, JPG, JPEG, BMP y GIF.
  • pre_signed_url: Especifique el Data.Param.Url de la respuesta de la API Solicitar una concesión de carga de archivo.
    Esta es una URL prefirmada y no admite cargas FormData. Debe cargar el archivo en formato binario. Para más detalles, consulte el código de muestra.
Este ejemplo no admite depuración en línea ni generación de código de muestra.
  • Carga local
  • Carga por URL
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. Agregar archivo a una categoría

Después de cargar el archivo, agréguelo a una categoría en el mismo espacio de trabajo llamando a la operación AddFile.
  • parser: Especifique DASHSCOPE_DOCMIND.
  • lease_id: Establezca este parámetro en el valor de Data.FileUploadLeaseId que se devuelve cuando usted solicita un permiso de carga de archivo.
  • category_id: En este ejemplo, pase default. Si utiliza una categoría personalizada para las cargas, debe pasar el category_id correspondiente.
    El valor de CategoryId pasado aquí debe coincidir con el CategoryId utilizado en el paso Solicitar un permiso de carga de archivo. De lo contrario, recibirá un error de Category is mismatched.
Después de agregar un archivo, Model Studio devuelve un FileId para el archivo e inicia automáticamente su análisis. El lease_id se invalida inmediatamente. No reutilice el mismo ID de permiso para otro envío.
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. Consultar estado de análisis del archivo

Un archivo no se puede utilizar en una base de conocimientos hasta que se haya analizado. Durante las horas pico, este proceso puede tardar varias horas. Puede llamar a la operación DescribeFile para consultar su estado de análisis.Si el campo Data.Status es PARSE_SUCCESS, el archivo se ha analizado correctamente y puede importarlo a la base de conocimientos.
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. Crear una base de conocimientos

3.1. Inicializar base de conocimientos

Una vez analizado un archivo, puede crear una base de conocimientos a partir de él en el mismo espacio de trabajo. Para comenzar, llame a la operación CreateIndex para inicializar (pero no finalizar) una base de conocimientos de recuperación de documentos.
  • workspace_id: Consulte Cómo obtener un ID de espacio de trabajo.
  • file_id: Especifique el FileId devuelto por la API cuando agrega un archivo a una categoría.
    Si source_type está configurado como DATA_CENTER_FILE, este parámetro es obligatorio y la API devuelve un error si no se especifica.
  • structure_type: En este ejemplo, pase unstructured.
  • source_type: En este ejemplo, pase DATA_CENTER_FILE.
  • sink_type: En este ejemplo, especifique BUILT_IN.
El valor del campo Data.Id devuelto por esta API es el ID de la base de conocimientos, que se utiliza para la construcción posterior del índice.
Mantenga seguro el ID de la base de conocimientos, ya que es necesario para todas las operaciones API posteriores relacionadas con esta base de conocimientos.
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. Enviar un trabajo de indexación

Después de inicializar la base de conocimientos, llame a la operación SubmitIndexJob para iniciar el proceso de construcción del índice.Una vez completado el envío, Model Studio comienza inmediatamente a construir el índice como una tarea asíncrona. El valor de Data.Id devuelto por esta llamada a la API es el ID de la tarea correspondiente. Utilizará este ID en el siguiente paso para consultar el estado más reciente de la tarea.
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. Consultar estado del trabajo de indexación

El trabajo de indexación tarda algún tiempo en completarse. Durante las horas pico, este proceso puede tardar varias horas. Llame a la operación GetIndexJobStatus para consultar su estado de ejecución.Cuando el campo Data.Status es COMPLETED, la base de conocimientos se ha creado.
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"
}
Ha creado una base de conocimientos a partir de los archivos cargados.

Recuperar desde una base de conocimientos

Puede recuperar información de una base de conocimientos de dos maneras:
  • Mediante una aplicación de Alibaba Cloud Model Studio: Cuando usted llama a una aplicación, utilice el parámetro rag_options para pasar el ID de la base de conocimientos index_id. Esto complementa su modelo con conocimiento privado y proporciona la información más reciente.
  • Mediante una API de Alibaba Cloud: Llame a la API Retrieve para recuperar información de una base de conocimientos específica y devolver los segmentos de texto originales.
El primer método envía los segmentos de texto recuperados a su modelo configurado para generar una respuesta final, mientras que el segundo método devuelve directamente los segmentos de texto. Esta sección explica cómo utilizar una API de Alibaba Cloud.
Para recuperar información y devolver segmentos de texto de una base de conocimientos especificada, llame a la API Retrieve.Si una respuesta contiene demasiada información irrelevante, especifique SearchFilters en la solicitud para filtrar los resultados según criterios como etiquetas.
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"
}

Actualizar una base de conocimientos

El siguiente ejemplo muestra cómo actualizar una base de conocimientos de búsqueda de documentos. Las aplicaciones que utilizan la base de conocimientos reflejan sus actualizaciones en tiempo real. El contenido nuevo estará disponible para su recuperación, mientras que el contenido eliminado ya no será accesible.
No puede actualizar bases de conocimientos de consulta de datos o preguntas y respuestas sobre imágenes mediante una API. Para más información, consulte Actualizar una base de conocimientos.
  • Actualización incremental: El único método admitido es un proceso de tres pasos: cargar el archivo actualizado, agregar el archivo a la base de conocimientos y luego eliminar el archivo antiguo.
  • Actualización completa: Para cada archivo en la base de conocimientos, realice los tres pasos para completar la actualización.
  • Actualización o sincronización automática: Para obtener más información, consulte Cómo actualizar o sincronizar automáticamente una base de conocimientos.
  • Límite de archivos por actualización individual: Se recomienda no actualizar más de 10,000 archivos a la vez. Superar este límite podría impedir que la base de conocimientos se actualice correctamente.

1. Cargar el archivo actualizado

Siga el procedimiento descrito en Crear una base de conocimientos: Paso 2 para cargar el archivo actualizado en el espacio de trabajo que contiene la base de conocimientos.
Solicite una nueva concesión de carga de archivo para generar un nuevo conjunto de parámetros de carga para el archivo actualizado.

2. Agregar archivo a la base de conocimientos

2.1. Enviar una tarea de adición

Una vez analizado el archivo cargado, llame a la operación SubmitIndexAddDocumentsJob para anexar el nuevo archivo a la base de conocimientos y reconstruir el índice de la misma.Después de enviar la tarea, Model Studio reconstruye la base de conocimientos de forma asíncrona. Esta operación devuelve Data.Id, que es el ID de la tarea (job_id). Utilice este ID en el siguiente paso para consultar el estado de la tarea.
  • Después de llamar a la operación SubmitIndexAddDocumentsJob, la tarea tarda algún tiempo en completarse. Puede utilizar el job_id para consultar el estado de la tarea. No vuelva a enviar la tarea antes de que se 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. Esperar finalización de la tarea

La tarea de indexación tarda algún tiempo en completarse. Durante las horas pico, este proceso puede tardar varias horas. Puede llamar a la operación GetIndexJobStatus para consultar su estado de ejecución.Un valor de COMPLETED para el campo Data.Status en la respuesta indica que todos los archivos actualizados se han agregado correctamente a la base de conocimientos.
La lista Documents en la respuesta contiene todos los archivos para la tarea de adición correspondiente al job_id que proporcionó.
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. Eliminar el archivo antiguo

Finalmente, llame a la operación DeleteIndexDocument para eliminar permanentemente la versión antigua del archivo de la base de conocimientos. Esto evita que se recupere información obsoleta accidentalmente.
  • file_id: Introduzca el FileId del archivo antiguo.
Solo puede eliminar archivos con un estado de importación fallida (INSERT_ERROR) o importación exitosa (FINISH). Para consultar el estado de los archivos en la base de conocimientos, puede llamar a la operación ListIndexDocuments.
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"
}

Gestionar bases de conocimientos

La creación y el uso de bases de conocimientos no son compatibles a través de la API. Debe realizar estas tareas en la consola de Model Studio.

Ver una base de conocimientos

Para ver las bases de conocimientos en un espacio de trabajo especificado, llame a la operación ListIndices.
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"
}

Eliminar una base de conocimientos

Para eliminar permanentemente una base de conocimientos, llame a la operación DeleteIndex. Antes de eliminar la base de conocimientos, debe desvincularla de todas las aplicaciones vinculadas de Alibaba Cloud Model Studio en la consola de Model Studio. De lo contrario, la eliminación fallará.Nota: Esta operación no elimina los archivos que ha agregado a una categoría.
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

Consulte el Catálogo de API (Base de conocimientos) para obtener una lista completa de las API de la base de conocimientos y sus parámetros de solicitud y respuesta.

FAQ

  1. ¿Cómo automatizo las actualizaciones y la sincronización de la base de conocimientos?
    • Búsqueda de documentos
    • Consulta de datos y preguntas y respuestas con imágenes
    Integre las API de Object Storage Service (OSS), Function Compute (FC) y las bases de conocimientos de Model Studio. Siga estos pasos:
    1. Crear un bucket: Vaya a la consola de OSS para crear un bucket de OSS para almacenar sus archivos fuente.
    2. Crear una base de conocimientos: Cree una base de conocimientos de búsqueda de documentos para almacenar su contenido de conocimiento privado.
    3. Crear una función personalizada: Vaya a la consola de FC y cree una función para eventos de cambio de archivo, como operaciones de adición o eliminación. Consulte Crear una función. Estas funciones sincronizan los cambios de archivos desde OSS hacia su base de conocimientos llamando a las API relevantes descritas en Actualizar una base de conocimientos.
    4. Crear un activador de OSS: En FC, asocie un activador de OSS con la función personalizada que creó en el paso anterior. Cuando se detecta un evento de cambio de archivo, como una nueva carga de archivo en OSS, el activador se activa y FC ejecuta la función. Consulte Activadores.
  2. ¿Por qué mi nueva base de conocimientos está vacía? Esto suele ocurrir si el paso Enviar un trabajo de indexación no se ejecuta correctamente. Si llama a la API CreateIndex pero la llamada a la API SubmitIndexJob falla, la base de conocimientos quedará vacía. Para resolverlo, envíe un trabajo de indexación nuevamente y espere a que el trabajo de indexación finalice.
  3. ¿Qué debo hacer si recibo el error "Access your uploaded file failed. Please check if your upload action was successful"? Este error suele ocurrir porque el paso Cargar el archivo en el almacenamiento temporal no se ejecutó correctamente. Confirme que este paso se ejecute correctamente antes de llamar a la operación de API AddFile.
  4. ¿Qué debo hacer si recibo el error "Access denied: Either you are not authorized to access this workspace, or the workspace does not exist"? Este error suele ocurrir por las siguientes razones:
    • El endpoint de servicio solicitado (endpoint de servicio) es incorrecto: Para el acceso a través de Internet, los usuarios del sitio de China (nube pública) deben usar el endpoint de servicio en China (Beijing), mientras que los usuarios del sitio internacional deben usar el endpoint de servicio en Singapore. Si está utilizando la función de depuración en línea, asegúrese de seleccionar el endpoint de servicio correcto, como se muestra en la siguiente figura.
      imagen
    • ElWorkspaceIdvalor es incorrecto o usted no es miembro del espacio de trabajo: Antes de llamar a la API, verifique que el WorkspaceId sea correcto y que usted sea miembro del espacio de trabajo. Cómo ser agregado como miembro de un espacio de trabajo específico
  5. ¿Qué debo hacer si recibo el error "Specified access key is not found or invalid"? Este error suele ocurrir porque el access_key_id o el access_key_secret proporcionados son incorrectos, o porque el access_key_id ha sido deshabilitado. Asegúrese de que el access_key_id sea correcto y no esté deshabilitado antes de llamar a la API.
  6. ¿Qué debo hacer si recibo el error "Category is mismatched"? Este error suele ocurrir cuando el CategoryId utilizado en la llamada a la API ApplyFileUploadLease difiere del CategoryId pasado en la llamada posterior a la API AddFile. Asegúrese de utilizar el mismo CategoryId durante todo el flujo de carga de archivos, desde ApplyFileUploadLease hasta AddFile. Puede llamar a la API ListCategory para recuperar la lista de categorías en el espacio de trabajo actual y verificar que el CategoryId que está utilizando sea correcto.

Facturación

  • Todas las funciones de la base de conocimientos y las llamadas a la API son gratuitas. Consulte Base de conocimientos: Facturación.
  • El espacio de almacenamiento para datos, como archivos, importados a Model Studio es gratuito.

Códigos de error

Si falla una llamada a una operación API descrita en este tema, consulte el Centro de errores.