Skip to main content
Base de Conhecimento (RAG)

API da base de conhecimento

A base de conhecimento do Alibaba Cloud Model Studio oferece APIs abertas que permitem a integração com seus sistemas de negócios existentes, a automação de operações e o atendimento a necessidades complexas de recuperação.

Pré-requisitos

  1. Para gerenciar uma base de conhecimento por meio de APIs, um usuário RAM deve obter permissões de API (a política AliyunBailianDataFullAccess) e ingressar em um workspace. Essa exigência não se aplica a uma conta Alibaba Cloud.
    Um usuário RAM só pode gerenciar bases de conhecimento nos workspaces aos quais ingressou. Já uma conta Alibaba Cloud tem permissão para gerenciar bases de conhecimento em todos os workspaces.
  2. Instale a versão mais recente do SDK do Alibaba Cloud Model Studio para chamar as APIs da base de conhecimento. Para obter instruções de instalação, consulte a Referência de Desenvolvimento do SDK da Alibaba Cloud.
    Caso o SDK não atenda aos seus requisitos, chame as APIs da base de conhecimento via solicitações HTTP utilizando o mecanismo de assinatura . Para detalhes sobre a conexão, consulte a Visão Geral da API .
  3. Obtenha um AccessKey ID e um AccessKey Secret, além de um ID de workspace. Configure-os como variáveis de ambiente do sistema para executar o código de exemplo. O exemplo a seguir demonstra como definir essas variáveis no Linux:
    Ao utilizar uma IDE ou outros plugins de desenvolvimento, configure as variáveis ALIBABA_CLOUD_ACCESS_KEY_ID , ALIBABA_CLOUD_ACCESS_KEY_SECRET e WORKSPACE_ID em seu ambiente de desenvolvimento.
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 o documento de conhecimento de exemplo Alibaba Cloud Model Studio Phone Introduction.docx para criar uma base de conhecimento.
  • Criar uma base de conhecimento
  • Recuperar dados de uma base de conhecimento
  • Atualizar uma base de conhecimento
  • Gerenciar bases de conhecimento
  • Antes de executar este exemplo, conclua os pré-requisitos e verifique se o usuário RAM possui a política AliyunBailianDataFullAccess.
  • Caso utilize uma IDE ou outros plugins de desenvolvimento, defina as variáveis de ambiente ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET e WORKSPACE_ID no seu ambiente de desenvolvimento.
  • Python
  • Java
  • PHP
  • Node.js
  • C#
  • Go
# 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()
# 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()

Criar uma base de conhecimento

Crie uma base de conhecimento de busca de documentos em um workspace específico.

1. Inicializar o client

Para fazer upload de arquivos e criar uma base de conhecimento, primeiro inicialize um client. Utilize seu AccessKey e AccessKey Secret para verificar sua identidade e configurar o endpoint.
  • Endpoints públicos
    Seu client precisa ter acesso à internet.
    • Cloud pública: bailian.ap-southeast-1.aliyuncs.com
  • Endpoints de VPC
    Se o seu client estiver implantado na cloud pública, na região Singapore do Alibaba Cloud (ap-southeast-1) e dentro de uma VPC, utilize o seguinte endpoint de VPC. O acesso entre regiões não é suportado.
    • Cloud pública: bailian-vpc.ap-southeast-1.aliyuncs.com
A criação do client retorna um objeto Client para chamadas de API subsequentes.
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. Fazer upload dos arquivos da base de conhecimento

2.1. Solicitar uma concessão de upload de arquivo

Antes de criar uma base de conhecimento, faça o upload dos arquivos de origem para o mesmo workspace. Para isso, chame a operação ApplyFileUploadLease para solicitar uma concessão de upload. Essa concessão é uma autorização temporária, válida por alguns minutos, para realizar o upload do arquivo.
  • workspace_id: Consulte Como obter um ID de workspace.
  • category_id: Neste exemplo, passe default. O Model Studio utiliza categorias para gerenciar seus arquivos enviados. O sistema cria automaticamente uma categoria padrão. Também é possível chamar a API AddCategory para criar uma nova categoria e obter o category_id correspondente.
  • file_name: Informe o nome do arquivo a ser enviado, incluindo sua extensão. O valor deve corresponder exatamente ao nome real do arquivo. Por exemplo, ao enviar o arquivo mostrado na figura, utilize Alibaba_Cloud_Model_Studio_Mobile_Phone_Series_Introduction.docx.
    image
  • file_md5: Forneça o hash MD5 do arquivo a ser enviado. Atualmente, o Alibaba Cloud não valida esse valor, o que facilita o upload de arquivos a partir de uma URL.
    Em Python, obtenha o hash MD5 usando o módulo hashlib. Para outras linguagens, consulte o código de exemplo 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}")
    
    Substitua a variável file_path no código pelo caminho local real do arquivo e execute o código para obter o hash MD5 do arquivo desejado. Veja abaixo um exemplo de valor:
    The MD5 hash of the file is: 2ef7361ea907f3a1b91e3b9936f5643a
    
  • file_size: Informe o tamanho do arquivo a ser enviado, em bytes.
    Em Python, obtenha esse valor usando o módulo os. Para outras linguagens, consulte o código de exemplo 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}")
    
    Substitua a variável file_path pelo caminho local real do arquivo e execute o código para obter o tamanho do arquivo desejado em bytes. Veja abaixo um exemplo de valor:
    The size of the file in bytes is: 14015
    
Uma solicitação bem-sucedida de concessão temporária de upload retorna os seguintes dados:
  • Um conjunto de parâmetros temporários de upload:
    • Data.FileUploadLeaseId
    • Data.Param.Method
    • X-bailian-extra em Data.Param.Headers
    • Content-Type em Data.Param.Headers
  • URL temporária de upload: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 de arquivo para armazenamento temporário

Com a concessão de upload, utilize os parâmetros temporários e a URL para enviar arquivos do seu armazenamento local ou de uma URL publicamente acessível para o servidor do Model Studio. Cada workspace suporta até 10.000 arquivos. Os formatos suportados incluem PDF, DOCX, DOC, TXT, Markdown, PPTX, PPT, XLSX, XLS, HTML, PNG, JPG, JPEG, BMP e GIF.
  • pre_signed_url: Especifique o valor de Data.Param.Url retornado na resposta da API Solicitar uma concessão de upload de arquivo.
    Esta é uma URL pré-assinada e não suporta uploads via FormData. O arquivo deve ser enviado em formato binário. Para mais detalhes, consulte o código de exemplo.
Este exemplo não suporta depuração online nem geração automática de código de amostra.
  • Upload local
  • Upload via 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. Adicionar arquivo a uma categoria

Após fazer upload do arquivo, adicione-o a uma categoria no mesmo workspace chamando a operação AddFile.
  • parser: Especifique DASHSCOPE_DOCMIND.
  • lease_id: Defina este parâmetro como o Data.FileUploadLeaseId retornado quando você solicita um lease de upload de arquivo.
  • category_id: Neste exemplo, passe default. Caso utilize uma categoria personalizada para uploads, é necessário passar o category_id correspondente.
    O CategoryId informado aqui deve corresponder ao CategoryId usado na etapa de Solicitar um lease de upload de arquivo. Caso contrário, você receberá um erro Category is mismatched.
Depois de adicionar um arquivo, o Model Studio retorna um FileId para o arquivo e inicia automaticamente sua análise. O lease_id é invalidado imediatamente. Não reutilize o mesmo ID de lease para outro envio.
  • Antes de chamar esta operação, um usuário RAM deve ter as permissões de API necessárias concedidas (a política AliyunBailianDataFullAccess).
  • Esta operação oferece suporte a depuração online e geração de código de exemplo para várias linguagens.
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 status de análise do arquivo

Um arquivo só pode ser utilizado em uma base de conhecimento após ser analisado. Em horários de pico, esse processo pode levar várias horas. Chame a operação DescribeFile para consultar o status da análise.Se o campo Data.Status for PARSE_SUCCESS, o arquivo foi analisado com sucesso e pode ser importado para a base de conhecimento.
  • Antes de chamar esta operação, um usuário RAM deve ter as permissões de API necessárias concedidas (a política AliyunBailianDataFullAccess ou AliyunBailianDataReadOnlyAccess).
  • Esta operação oferece suporte a depuração online e geração de código de exemplo para várias linguagens.
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. Criar uma base de conhecimento

3.1. Inicializar base de conhecimento

Depois que um arquivo é analisado, é possível criar uma base de conhecimento a partir dele no mesmo workspace. Para começar, chame a operação CreateIndex para inicializar (mas não finalizar) uma base de conhecimento de recuperação de documentos.
  • workspace_id: Consulte Como obter um ID de workspace.
  • file_id: Especifique o FileId retornado pela API quando você adiciona um arquivo a uma categoria.
    Se source_type estiver definido como DATA_CENTER_FILE, este parâmetro é obrigatório e a API retornará um erro caso não seja especificado.
  • structure_type: Neste exemplo, passe unstructured.
  • source_type: Neste exemplo, passe DATA_CENTER_FILE.
  • sink_type: Neste exemplo, especifique BUILT_IN.
O valor do campo Data.Id retornado por esta API é o ID da base de conhecimento, utilizado posteriormente na construção do índice.
Mantenha o ID da base de conhecimento seguro, pois ele é necessário para todas as operações de API subsequentes relacionadas a esta base.
  • Antes de chamar esta operação, um usuário RAM deve ter as permissões de API necessárias concedidas (a política AliyunBailianDataFullAccess).
  • Esta operação oferece suporte a depuração online e geração de código de exemplo para várias linguagens.
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 um job de indexação

Após inicializar a base de conhecimento, chame a operação SubmitIndexJob para iniciar o processo de construção do índice.Após a conclusão do envio, o Model Studio inicia imediatamente a construção do índice como uma tarefa assíncrona. O Data.Id retornado por esta chamada de API é o ID da tarefa correspondente. Você usará esse ID na próxima etapa para consultar o status mais recente da tarefa.
  • Antes de chamar esta operação, um usuário RAM deve ter as permissões de API necessárias concedidas (a política AliyunBailianDataFullAccess).
  • Esta operação oferece suporte a depuração online e geração de código de exemplo para várias linguagens.
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 o status do job de indexação

O job de indexação leva algum tempo para ser concluído. Em horários de pico, esse processo pode durar várias horas. Chame a operação GetIndexJobStatus para consultar o status de execução.Quando o campo Data.Status for COMPLETED, a base de conhecimento terá sido criada.
  • Antes de chamar esta operação, conceda as permissões de API necessárias (política AliyunBailianDataFullAccess) ao usuário RAM.
  • Esta operação oferece suporte a depuração online e geração de código de exemplo para várias linguagens.
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"
}
Você criou uma base de conhecimento a partir dos arquivos enviados.

Recuperar informações de uma base de conhecimento

Existem duas formas de recuperar informações de uma base de conhecimento:
  • Por meio de um aplicativo do Alibaba Cloud Model Studio: Ao chamar um aplicativo, utilize o parâmetro rag_options para transmitir o ID da base de conhecimento index_id. Essa abordagem complementa seu modelo com conhecimento privado e fornece as informações mais recentes.
  • Por meio de uma API do Alibaba Cloud: Chame a API Retrieve para buscar dados em uma base de conhecimento específica e obter os segmentos de texto originais.
No primeiro método, os segmentos de texto recuperados são enviados ao modelo configurado para gerar uma resposta final. Já o segundo método retorna diretamente os segmentos de texto. Esta seção aborda como utilizar uma API do Alibaba Cloud.
Para recuperar informações e retornar segmentos de texto de uma base de conhecimento específica, chame a API Retrieve.
  • client: Como obter o client
  • workspace_id: O ID do workspace que contém a base de conhecimento. Como obter o ID do workspace
    Um usuário RAM só pode recuperar informações de uma base de conhecimento em um workspace ao qual tenha ingressado.
Caso a resposta contenha excesso de informações irrelevantes, especifique SearchFilters na solicitação para filtrar os resultados por critérios como tags.
  • O usuário RAM precisa ter as permissões de API necessárias (política AliyunBailianDataFullAccess) para executar esta operação.
  • Esta operação oferece suporte a depuração online e geração de código de exemplo para diversas linguagens.
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"
}

Atualizar uma base de conhecimento

O exemplo a seguir demonstra como atualizar uma base de conhecimento de busca de documentos. As aplicações que utilizam a base de conhecimento refletem suas atualizações em tempo real. O novo conteúdo fica disponível para recuperação, enquanto o conteúdo excluído deixa de ser acessível.
Não é possível atualizar bases de conhecimento de consulta de dados ou de perguntas e respostas por imagem usando uma API. Para mais informações, consulte Atualizar uma base de conhecimento .
  • Atualização incremental: O único método suportado consiste em um processo de três etapas: faça upload do arquivo atualizado, anexe o arquivo à base de conhecimento e, em seguida, exclua o arquivo antigo.
  • Atualização completa: Para cada arquivo na base de conhecimento, execute as três etapas para concluir a atualização.
  • Atualização ou sincronização automática: Para mais informações, consulte Como atualizar ou sincronizar automaticamente uma base de conhecimento.
  • Limite de arquivos por atualização única: Recomendamos atualizar no máximo 10.000 arquivos por vez. Exceder esse limite pode impedir que a base de conhecimento seja atualizada corretamente.

1. Fazer upload do arquivo atualizado

Siga o procedimento em Criar uma base de conhecimento: Etapa 2 para fazer upload do arquivo atualizado no workspace que contém a base de conhecimento.
Solicite uma nova concessão de upload de arquivo para gerar um novo conjunto de parâmetros de upload para o arquivo atualizado.

2. Anexar o arquivo à base de conhecimento

2.1. Enviar uma tarefa de anexação

Após a análise do arquivo carregado, chame a operação SubmitIndexAddDocumentsJob para anexar o novo arquivo à base de conhecimento e reconstruir seu índice.Após o envio da tarefa, o Alibaba Cloud Model Studio reconstrói a base de conhecimento de forma assíncrona. Esta operação retorna Data.Id, que corresponde ao ID da tarefa (job_id). Utilize este ID na próxima etapa para consultar o status da tarefa.
  • Após chamar a operação SubmitIndexAddDocumentsJob, a tarefa leva algum tempo para ser concluída. Use o job_id para consultar o status da tarefa. Não reenvie a tarefa antes que ela seja concluída.
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. Aguardar a conclusão da tarefa

A tarefa de indexação leva algum tempo para ser concluída. Durante horários de pico, esse processo pode levar várias horas. Chame a operação GetIndexJobStatus para consultar o status de execução.O valor COMPLETED no campo Data.Status da resposta indica que todos os arquivos atualizados foram anexados com sucesso à base de conhecimento.
A lista Documents na resposta contém todos os arquivos da tarefa de anexação correspondente ao job_id fornecido.
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. Excluir o arquivo antigo

Por fim, chame a operação DeleteIndexDocument para excluir permanentemente a versão antiga do arquivo da base de conhecimento. Isso evita que informações desatualizadas sejam recuperadas acidentalmente.
  • file_id: Insira o FileId do arquivo antigo.
É possível excluir apenas arquivos com status de falha na importação (INSERT_ERROR) ou importação bem-sucedida (FINISH). Para consultar o status dos arquivos na base de conhecimento, chame a operação 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"
}

Gerenciar bases de conhecimento

Não há suporte para a Criação e uso de bases de conhecimento por meio da API. Execute essas tarefas no console do Model Studio .

Visualizar uma base de conhecimento

Para visualizar bases de conhecimento em um workspace específico, chame a operação ListIndices.
  • client: Como obter o client
  • workspace_id: Como obter o ID do workspace
    Um usuário RAM só pode visualizar bases de conhecimento nos workspaces dos quais participa.
  • Antes de chamar esta operação, o usuário RAM deve ter as permissões de API necessárias, anexando a política AliyunBailianDataFullAccess.
  • Esta operação oferece suporte a depuração online e geração de código de exemplo para várias linguagens.
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"
}

Excluir uma base de conhecimento

Para excluir permanentemente uma base de conhecimento, chame a operação DeleteIndex. Antes de excluir a base de conhecimento, você deve desassociá-la de todos os aplicativos do Alibaba Cloud Model Studio vinculados no console do Model Studio. Caso contrário, a exclusão falhará.Observação: Esta operação não exclui os arquivos que você adicionou a uma categoria.
  • Antes de chamar esta operação, o usuário RAM deve ter as permissões de API necessárias, anexando a política AliyunBailianDataFullAccess.
  • Esta operação oferece suporte a depuração online e geração de código de exemplo para várias linguagens.
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 o Catálogo de APIs (Base de Conhecimento) para obter uma lista completa das APIs de base de conhecimento e seus parâmetros de solicitação e resposta.

Perguntas frequentes

  1. Como automatizar atualizações e sincronização de bases de conhecimento?
    • Data query and image Q&A
  2. Por que minha nova base de conhecimento está vazia? Isso geralmente ocorre se a etapa Enviar um trabalho de índice falhar ao ser executada. Se você chamar a API CreateIndex, mas a chamada da API SubmitIndexJob falhar, a base de conhecimento ficará vazia. Para resolver isso, envie um trabalho de índice novamente e aguarde a conclusão do trabalho de índice.
  3. O que devo fazer se receber o erro "Access your uploaded file failed. Please check if your upload action was successful"? Esse erro geralmente ocorre porque a etapa Carregar o arquivo no armazenamento temporário não foi executada com êxito. Confirme se essa etapa é executada com sucesso antes de chamar a operação da API AddFile.
  4. O que devo fazer se receber o erro "Access denied: Either you are not authorized to access this workspace, or the workspace does not exist"? Esse erro geralmente ocorre pelos seguintes motivos:
    • O endpoint de serviço solicitado (endpoint de serviço) está incorreto: Para acesso pela Internet, usuários do site da China (nuvem pública) devem usar o endpoint de serviço em China (Beijing), enquanto usuários do site internacional devem usar o endpoint de serviço em Singapore. Se estiver usando o recurso de depuração online, certifique-se de selecionar o endpoint de serviço correto, conforme mostrado na figura a seguir.
      image
    • O valorWorkspaceIdestá incorreto ou você não é membro do workspace: Antes de chamar a API, verifique se o WorkspaceId está correto e se você é membro do workspace. Como ser adicionado como membro de um workspace específico
  5. O que devo fazer se receber o erro "Specified access key is not found or invalid"? Esse erro geralmente ocorre porque o access_key_id ou access_key_secret fornecido está incorreto, ou o access_key_id foi desativado. Certifique-se de que o access_key_id esteja correto e não desativado antes de chamar a API.
  6. O que devo fazer se receber o erro "Category is mismatched"? Esse erro normalmente ocorre quando o CategoryId usado na chamada da API ApplyFileUploadLease difere do CategoryId passado na chamada subsequente da API AddFile. Certifique-se de usar o mesmo CategoryId durante todo o fluxo de upload de arquivos, desde ApplyFileUploadLease até AddFile. Você pode chamar a API ListCategory para recuperar a lista de categorias no workspace atual e verificar se o CategoryId que você está usando está correto.

Faturamento

  • Todos os recursos da base de conhecimento e chamadas de API são gratuitos. Consulte Base de Conhecimento: Faturamento.
  • O espaço de armazenamento para dados, como arquivos, importados para o Model Studio é gratuito.

Códigos de erro

Se uma chamada para uma operação de API descrita neste tópico falhar, consulte o Centro de Erros.