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
-
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.
-
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 .
-
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_SECRETeWORKSPACE_IDem 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' Prepare o documento de conhecimento de exemplo Alibaba Cloud Model Studio Phone Introduction.docx para criar uma base de conhecimento.
Código de exemplo
Criar uma base de conhecimento
Crie uma base de conhecimento de busca de documentos em um workspace específico.
Instruções
Leia o conteúdo em inglês para entender O QUE precisa ser comunicado
Escreva o português brasileiro DO ZERO — esqueça a estrutura das frases em inglês
Preserve toda a formatação markdown, blocos de código, links e imagens exatamente como estão
Tags xref (
<a data-tag="xref" ...>texto</a>) — preserve A TAG INTEIRA com todos os atributos na ordem e caixa originais, traduza APENAS o texto visível entre > eAplique todas as regras específicas do idioma rigorosamente
Aplique as regras de stopwords com tolerância zero
Use o modo imperativo em passos numerados e listas de procedimentos
Garanta a consistência terminológica — o mesmo termo deve ter a mesma tradução em todo o documento
Varie os inícios de frase em listas e tabelas — nenhum início deve se repetir 3 ou mais vezes
-
Retorne APENAS o documento markdown em português brasileiro, sem explicações
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)Java
/** * Initialize a client. * * @return The configured client object. */ public static com.aliyun.bailian20231229.Client createClient() throws Exception { com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config() .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")) .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")); // The following endpoint is an example of a VPC endpoint for the public cloud. You can change the endpoint as needed. config.endpoint = "bailian-vpc.ap-southeast-1.aliyuncs.com"; return new com.aliyun.bailian20231229.Client(config); }PHP
/** * Initialize a client. * * @return Bailian The configured client object. */ public static function createClient(){ $config = new Config([ "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") ]); // The following endpoint is an example of a VPC endpoint for the public cloud. You can change the endpoint as needed. $config->endpoint = 'bailian-vpc.ap-southeast-1.aliyuncs.com'; return new Bailian($config); }Node.js
/** * Create and configure a client. * @return Client * @throws Exception */ static createClient() { const config = new OpenApi.Config({ accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID, accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET }); // The following endpoint is an example of a VPC endpoint for the public cloud. You can change the endpoint as needed. config.endpoint = `bailian-vpc.ap-southeast-1.aliyuncs.com`; return new bailian20231229.default(config); }C#
/// <summary> /// Initialize a client. /// </summary> /// <returns>The configured client object.</returns> /// <exception cref="Exception">Thrown when an error occurs during initialization.</exception> public static AlibabaCloud.SDK.Bailian20231229.Client CreateClient() { var config = new AlibabaCloud.OpenApiClient.Models.Config { AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"), AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), }; // The following endpoint is an example of a VPC endpoint for the public cloud. You can change the endpoint as needed. config.Endpoint = "bailian-vpc.ap-southeast-1.aliyuncs.com"; return new AlibabaCloud.SDK.Bailian20231229.Client(config); }Go
// CreateClient creates and configures a client. // // Returns: // - *client.Bailian20231229Client: The configured client. // - error: The error message. func CreateClient() (_result *bailian20231229.Client, _err error) { config := &openapi.Config{ AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")), AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")), } // The following endpoint is an example of a VPC endpoint for the public cloud. You can change the endpoint as needed. config.Endpoint = tea.String("bailian-vpc.ap-southeast-1.aliyuncs.com") _result = &bailian20231229.Client{} _result, _err = bailian20231229.NewClient(config) return _result, _err }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 ocategory_idcorrespondente. -
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.
-
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.
-
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.
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-extraemData.Param.Headers -
Content-TypeemData.Param.Headers
-
-
URL temporária de upload:
Data.Param.Url
Importante-
Antes de chamar esta operação, conceda as permissões de API necessárias (política AliyunBailianDataFullAccess) ao usuário RAM.
-
Esta operação suporta depuração online e geração de código de exemplo para várias linguagens.
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)Java
/** * Request a file upload lease. * * @param client The client object. * @param categoryId The category ID. * @param fileName The file name. * @param fileMd5 The MD5 hash of the file. * @param fileSize The file size in bytes. * @param workspaceId The workspace ID. * @return The response object from Alibaba Cloud Model Studio. */ public ApplyFileUploadLeaseResponse applyLease(com.aliyun.bailian20231229.Client client, String categoryId, String fileName, String fileMd5, String fileSize, String workspaceId) throws Exception { Map<String, String> headers = new HashMap<>(); com.aliyun.bailian20231229.models.ApplyFileUploadLeaseRequest applyFileUploadLeaseRequest = new com.aliyun.bailian20231229.models.ApplyFileUploadLeaseRequest(); applyFileUploadLeaseRequest.setFileName(fileName); applyFileUploadLeaseRequest.setMd5(fileMd5); applyFileUploadLeaseRequest.setSizeInBytes(fileSize); com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions(); ApplyFileUploadLeaseResponse applyFileUploadLeaseResponse = null; applyFileUploadLeaseResponse = client.applyFileUploadLeaseWithOptions(categoryId, workspaceId, applyFileUploadLeaseRequest, headers, runtime); return applyFileUploadLeaseResponse; }PHP
/** * Request a file upload lease. * * @param Bailian $client The client. * @param string $categoryId The category ID. * @param string $fileName The file name. * @param string $fileMd5 The MD5 hash of the file. * @param int $fileSize The file size in bytes. * @param string $workspaceId The workspace ID. * @return ApplyFileUploadLeaseResponse The response from Alibaba Cloud Model Studio. */ public function applyLease($client, $categoryId, $fileName, $fileMd5, $fileSize, $workspaceId) { $headers = []; $applyFileUploadLeaseRequest = new ApplyFileUploadLeaseRequest([ "fileName" => $fileName, "md5" => $fileMd5, "sizeInBytes" => $fileSize ]); $runtime = new RuntimeOptions([]); return $client->applyFileUploadLeaseWithOptions($categoryId, $workspaceId, $applyFileUploadLeaseRequest, $headers, $runtime); }Node.js
/** * Request a file upload lease. * @param {Bailian20231229Client} client - The client. * @param {string} categoryId - The category ID. * @param {string} fileName - The file name. * @param {string} fileMd5 - The MD5 hash of the file. * @param {string} fileSize - The file size in bytes. * @param {string} workspaceId - The workspace ID. * @returns {Promise<bailian20231229.ApplyFileUploadLeaseResponse>} - The response from Alibaba Cloud Model Studio. */ async function applyLease(client, categoryId, fileName, fileMd5, fileSize, workspaceId) { const headers = {}; const req = new bailian20231229.ApplyFileUploadLeaseRequest({ md5: fileMd5, fileName, sizeInBytes: fileSize }); const runtime = new Util.RuntimeOptions({}); return await client.applyFileUploadLeaseWithOptions( categoryId, workspaceId, req, headers, runtime ); }C#
/// <summary> /// Request a file upload lease. /// </summary> /// <param name="client">The client object.</param> /// <param name="categoryId">The category ID.</param> /// <param name="fileName">The file name.</param> /// <param name="fileMd5">The MD5 hash of the file.</param> /// <param name="fileSize">The file size in bytes.</param> /// <param name="workspaceId">The workspace ID.</param> /// <returns>The response object from Alibaba Cloud Model Studio.</returns> /// <exception cref="Exception">An exception is thrown if an error occurs during the call.</exception> public AlibabaCloud.SDK.Bailian20231229.Models.ApplyFileUploadLeaseResponse ApplyLease( AlibabaCloud.SDK.Bailian20231229.Client client, string categoryId, string fileName, string fileMd5, string fileSize, string workspaceId) { var headers = new Dictionary<string, string>() { }; var applyFileUploadLeaseRequest = new AlibabaCloud.SDK.Bailian20231229.Models.ApplyFileUploadLeaseRequest { FileName = fileName, Md5 = fileMd5, SizeInBytes = fileSize }; var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); return client.ApplyFileUploadLeaseWithOptions(categoryId, workspaceId, applyFileUploadLeaseRequest, headers, runtime); }Go
// ApplyLease requests a file upload lease from Alibaba Cloud Model Studio. // // Parameters: // - client (bailian20231229.Client): The client. // - categoryId (string): The category ID. // - fileName (string): The file name. // - fileMD5 (string): The MD5 hash of the file. // - fileSize (string): The file size in bytes. // - workspaceId (string): The workspace ID. // // Returns: // - *bailian20231229.ApplyFileUploadLeaseResponse: The response from Alibaba Cloud Model Studio. // - error: The error message. func ApplyLease(client *bailian20231229.Client, categoryId, fileName, fileMD5 string, fileSize string, workspaceId string) (_result *bailian20231229.ApplyFileUploadLeaseResponse, _err error) { headers := make(map[string]*string) applyFileUploadLeaseRequest := &bailian20231229.ApplyFileUploadLeaseRequest{ FileName: tea.String(fileName), Md5: tea.String(fileMD5), SizeInBytes: tea.String(fileSize), } runtime := &util.RuntimeOptions{} return client.ApplyFileUploadLeaseWithOptions(tea.String(categoryId), tea.String(workspaceId), applyFileUploadLeaseRequest, headers, runtime) }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.Urlretornado 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.
ImportanteEste exemplo não suporta depuração online nem geração automática de código de amostra.
Upload local
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)Java
import java.io.DataOutputStream; import java.io.FileInputStream; import java.net.HttpURLConnection; import java.net.URL; public class UploadFile { public static void uploadFile(String preSignedUrl, String filePath) { HttpURLConnection connection = null; try { // Create a URL object. URL url = new URL(preSignedUrl); connection = (HttpURLConnection) url.openConnection(); // 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. connection.setRequestMethod("PUT"); // Allow output to the connection because this connection is used to upload the file. connection.setDoOutput(true); connection.setRequestProperty("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."); connection.setRequestProperty("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 the file and upload it through the connection. try (DataOutputStream outStream = new DataOutputStream(connection.getOutputStream()); FileInputStream fileInputStream = new FileInputStream(filePath)) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = fileInputStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytesRead); } outStream.flush(); } // Check the response. int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // The file was uploaded successfully. System.out.println("File uploaded successfully."); } else { // The file failed to be uploaded. System.out.println("Failed to upload the file. ResponseCode: " + responseCode); } } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } } public static void main(String[] args) { String preSignedUrlOrHttpUrl = "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. String filePath = "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"; uploadFile(preSignedUrlOrHttpUrl, filePath); } }PHP
<?php /** * Upload a local file to temporary storage. * * @param string $preSignedUrl The pre-signed URL or HTTP address obtained from the ApplyFileUploadLease operation. * @param array $headers An array of request headers containing "X-bailian-extra" and "Content-Type". * @param string $filePath The local file path. * @throws Exception If the upload fails. */ function uploadFile($preSignedUrl, $headers, $filePath) { // Read the file content. $fileContent = file_get_contents($filePath); if ($fileContent === false) { throw new Exception("Cannot read the file: " . $filePath); } // Initialize a cURL session. $ch = curl_init(); // Set cURL options. curl_setopt($ch, CURLOPT_URL, $preSignedUrl); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); // Use the PUT method. curl_setopt($ch, CURLOPT_POSTFIELDS, $fileContent); // Set the request body to the file content. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response instead of outputting it directly. // Build the request headers. $uploadHeaders = [ "X-bailian-extra: " . $headers["X-bailian-extra"], "Content-Type: " . $headers["Content-Type"] ]; curl_setopt($ch, CURLOPT_HTTPHEADER, $uploadHeaders); // Execute the request. $response = curl_exec($ch); // Get the HTTP status code. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Close the cURL session. curl_close($ch); // Check the response code. if ($httpCode != 200) { throw new Exception("Upload failed. HTTP status code: " . $httpCode . ", error message: " . $response); } // The upload is successful. echo "File uploaded successfully.\n"; } /** * Main function: Upload a local file. */ function main() { // Replace this with the value of the Url field in Data.Param returned by the ApplyFileUploadLease operation in the previous step. $preSignedUrl = "Replace this with the value of the Url field in Data.Param returned by the ApplyFileUploadLease operation in the previous step."; // Replace these with the values of X-bailian-extra and Content-Type in Data.Param.Headers returned by the ApplyFileUploadLease operation in the previous step. $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." ]; // Upload a local file to temporary storage. $filePath = "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"; try { uploadFile($preSignedUrl, $headers, $filePath); } catch (Exception $e) { echo "Error: " . $e->getMessage() . "\n"; } } // Call the main function. main(); ?>Node.js
const fs = require('fs'); const axios = require('axios'); /** * Upload a local file to temporary storage. * * @param {string} preSignedUrl - The URL from the upload lease. * @param {Object} headers - The headers for the upload request. * @param {string} filePath - The local path of the file. * @throws {Error} If the upload fails. */ async function uploadFile(preSignedUrl, headers, filePath) { // Build the request headers required for the upload. const uploadHeaders = { "X-bailian-extra": headers["X-bailian-extra"], "Content-Type": headers["Content-Type"] }; // Create a file read stream. const fileStream = fs.createReadStream(filePath); try { // Use axios to send a PUT request. const response = await axios.put(preSignedUrl, fileStream, { headers: uploadHeaders }); // Check the response status code. if (response.status === 200) { console.log("File uploaded successfully."); } else { console.error(`Failed to upload the file. ResponseCode: ${response.status}`); throw new Error(`Upload failed with status code: ${response.status}`); } } catch (error) { // Handle errors. console.error("Error during upload:", error.message); throw new Error(`Upload failed: ${error.message}`); } } /** * Main function: Upload a local file. */ function main() { const preSignedUrl = "Replace this with the value of the Url field in Data.Param returned by the ApplyFileUploadLease operation in the previous step."; const 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." }; // Upload a local file to temporary storage. const filePath = "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"; uploadFile(preSignedUrl, headers, filePath) .then(() => { console.log("Upload completed."); }) .catch((err) => { console.error("Upload failed:", err.message); }); } // Call the main function. main();C#
using System; using System.IO; using System.Net; public class UploadFilExample { public static void UploadFile(string preSignedUrl, string filePath) { HttpWebRequest connection = null; try { // Create a URL object. Uri url = new Uri(preSignedUrl); connection = (HttpWebRequest)WebRequest.Create(url); // 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. connection.Method = "PUT"; // Allow output to the connection because this connection is used to upload the file. connection.AllowWriteStreamBuffering = false; connection.SendChunked = false; // Set the request headers to be the same as the field values in Data.Param.Headers returned by the ApplyFileUploadLease operation in the previous step. connection.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."; connection.ContentType = "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 the file and upload it through the connection. using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) using (var requestStream = connection.GetRequestStream()) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { requestStream.Write(buffer, 0, bytesRead); } requestStream.Flush(); } // Check the response. using (HttpWebResponse response = (HttpWebResponse)connection.GetResponse()) { if (response.StatusCode == HttpStatusCode.OK) { // The file was uploaded successfully. Console.WriteLine("File uploaded successfully."); } else { // The file failed to be uploaded. Console.WriteLine($"Failed to upload the file. ResponseCode: {response.StatusCode}"); } } } catch (Exception e) { Console.WriteLine(e.Message); e.StackTrace.ToString(); } finally { if (connection != null) { connection.Abort(); } } } public static void Main(string[] args) { string preSignedUrlOrHttpUrl = "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. string filePath = "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"; UploadFile(preSignedUrlOrHttpUrl, filePath); } }Go
package main import ( "fmt" "io" "os" "github.com/go-resty/resty/v2" ) // UploadFile uploads a local file to temporary storage. // // Parameters: // - preSignedUrl (string): The URL from the upload lease. // - headers (map[string]string): The headers for the upload request. // - filePath (string): The local path of the file. // // Returns: // - error: An error message if the upload fails, otherwise nil. func UploadFile(preSignedUrl string, headers map[string]string, filePath string) error { // Open the local file. file, err := os.Open(filePath) if err != nil { return fmt.Errorf("failed to open file: %w", err) } defer file.Close() // Read the content. body, err := io.ReadAll(file) if err != nil { return fmt.Errorf("failed to read file: %w", err) } // Create a REST client. client := resty.New() // Build the request headers required for the upload. uploadHeaders := map[string]string{ "X-bailian-extra": headers["X-bailian-extra"], "Content-Type": headers["Content-Type"], } // Send a PUT request. resp, err := client.R(). SetHeaders(uploadHeaders). SetBody(body). Put(preSignedUrl) if err != nil { return fmt.Errorf("failed to send request: %w", err) } // Check the HTTP response status code. if resp.IsError() { return fmt.Errorf("HTTP error: %d", resp.StatusCode()) } fmt.Println("File uploaded successfully.") return nil } // main function func main() { // Replace this with the value of the Url field in Data.Param returned by the ApplyFileUploadLease operation in the previous step. preSignedUrl := "Replace this with the value of the Url field in Data.Param returned by the ApplyFileUploadLease operation in the previous step." // Replace these with the values of X-bailian-extra and Content-Type in Data.Param.Headers returned by the ApplyFileUploadLease operation in the previous step. headers := map[string]string{ "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.", } // Upload a local file to temporary storage. filePath := "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" // Call the upload function. err := UploadFile(preSignedUrl, headers, filePath) if err != nil { fmt.Printf("Upload failed: %v\n", err) } }Upload via URL
A URL deve ser publicamente acessível e apontar para um arquivo válido.
Python
import requests from urllib.parse import urlparse def upload_file_link(pre_signed_url, source_url_string): """ Upload a file from a public URL to temporary storage. Args: pre_signed_url (str): The URL from the upload lease. source_url_string (str): The URL 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." } # Set the request method to GET to access the file URL. source_response = requests.get(source_url_string) if source_response.status_code != 200: raise RuntimeError("Failed to get source 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=source_response.content, 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." # The URL of the file. source_url = "Replace this with the URL of the file to upload." upload_file_link(pre_signed_url_or_http_url, source_url)Java
import java.io.BufferedInputStream; import java.io.DataOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class UploadFile { public static void uploadFileLink(String preSignedUrl, String sourceUrlString) { HttpURLConnection connection = null; try { // Create a URL object. URL url = new URL(preSignedUrl); connection = (HttpURLConnection) url.openConnection(); // 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. connection.setRequestMethod("PUT"); // Allow output to the connection because this connection is used to upload the file. connection.setDoOutput(true); connection.setRequestProperty("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."); connection.setRequestProperty("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."); URL sourceUrl = new URL(sourceUrlString); HttpURLConnection sourceConnection = (HttpURLConnection) sourceUrl.openConnection(); // Set the request method to GET to access the file URL. sourceConnection.setRequestMethod("GET"); // Get the response code. 200 indicates that the request was successful. int sourceFileResponseCode = sourceConnection.getResponseCode(); // Read the file from the URL and upload it through the connection. if (sourceFileResponseCode != HttpURLConnection.HTTP_OK) { throw new RuntimeException("Failed to get source file."); } try (DataOutputStream outStream = new DataOutputStream(connection.getOutputStream()); InputStream in = new BufferedInputStream(sourceConnection.getInputStream())) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { outStream.write(buffer, 0, bytesRead); } outStream.flush(); } // Check the response. int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // The file was uploaded successfully. System.out.println("File uploaded successfully."); } else { // The file failed to be uploaded. System.out.println("Failed to upload the file. ResponseCode: " + responseCode); } } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } } public static void main(String[] args) { String preSignedUrlOrHttpUrl = "Replace this with the value of the Url field in Data.Param returned by the ApplyFileUploadLease operation in the previous step."; String sourceUrl = "Replace this with the URL of the file to upload."; uploadFileLink(preSignedUrlOrHttpUrl, sourceUrl); } }PHP
<?php /** * Upload a file from a public URL to temporary storage. * * @param string $preSignedUrl The pre-signed URL or HTTP address obtained from the ApplyFileUploadLease operation. * @param array $headers An array of request headers containing "X-bailian-extra" and "Content-Type". * @param string $sourceUrl The URL of the file. * @throws Exception If the upload fails. */ function uploadFile($preSignedUrl, $headers, $sourceUrl) { $fileContent = file_get_contents($sourceUrl); if ($fileContent === false) { throw new Exception("Cannot download the file from the given URL: " . $sourceUrl); } // Initialize a cURL session. $ch = curl_init(); // Set cURL options. curl_setopt($ch, CURLOPT_URL, $preSignedUrl); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); // Use the PUT method. curl_setopt($ch, CURLOPT_POSTFIELDS, $fileContent); // Set the request body to the file content. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response instead of outputting it directly. // Build the request headers. $uploadHeaders = [ "X-bailian-extra: " . $headers["X-bailian-extra"], "Content-Type: " . $headers["Content-Type"] ]; curl_setopt($ch, CURLOPT_HTTPHEADER, $uploadHeaders); // Execute the request. $response = curl_exec($ch); // Get the HTTP status code. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Close the cURL session. curl_close($ch); // Check the response code. if ($httpCode != 200) { throw new Exception("Upload failed. HTTP status code: " . $httpCode . ", error message: " . $response); } // The upload is successful. echo "File uploaded successfully.\n"; } /** * Main function: Upload a file from a public URL to temporary storage. */ function main() { // Replace this with the value of the Url field in Data.Param returned by the ApplyFileUploadLease operation in the previous step. $preSignedUrl = "Replace this with the value of the Url field in Data.Param returned by the ApplyFileUploadLease operation in the previous step."; // Replace these with the values of X-bailian-extra and Content-Type in Data.Param.Headers returned by the ApplyFileUploadLease operation in the previous step. $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." ]; $sourceUrl = "Replace this with the URL of the file to upload."; try { uploadFile($preSignedUrl, $headers, $sourceUrl); } catch (Exception $e) { echo "Error: " . $e->getMessage() . "\n"; } } // Call the main function. main(); ?>Node.js
const axios = require('axios'); /** * Upload a file from a public URL to temporary storage. * * @param {string} preSignedUrl - The URL from the upload lease. * @param {Object} headers - The headers for the upload request. * @param {string} sourceUrl - The URL of the file. * @throws {Error} If the upload fails. */ async function uploadFileFromUrl(preSignedUrl, headers, sourceUrl) { // Build the request headers required for the upload. const uploadHeaders = { "X-bailian-extra": headers["X-bailian-extra"], "Content-Type": headers["Content-Type"] }; try { // Download the file from the given URL. const response = await axios.get(sourceUrl, { responseType: 'stream' }); // Use axios to send a PUT request. const uploadResponse = await axios.put(preSignedUrl, response.data, { headers: uploadHeaders }); // Check the response status code. if (uploadResponse.status === 200) { console.log("File uploaded successfully from URL."); } else { console.error(`Failed to upload the file. ResponseCode: ${uploadResponse.status}`); throw new Error(`Upload failed with status code: ${uploadResponse.status}`); } } catch (error) { // Handle errors. console.error("Error during upload:", error.message); throw new Error(`Upload failed: ${error.message}`); } } /** * Main function: Upload a publicly downloadable file to temporary storage. */ function main() { const preSignedUrl = "Replace this with the value of the Url field in Data.Param returned by the ApplyFileUploadLease operation in the previous step."; const 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." }; const sourceUrl = "Replace this with the URL of the file to upload."; uploadFileFromUrl(preSignedUrl, headers, sourceUrl) .then(() => { console.log("Upload completed."); }) .catch((err) => { console.error("Upload failed:", err.message); }); } // Call the main function. main();C#
using System; using System.IO; using System.Net; using System.Net.Http; using System.Threading.Tasks; public class UploadFileExample { public static async Task UploadFileFromUrl(string preSignedUrl, string url) { try { // Create an HTTP client to download the file from the given URL. using (HttpClient httpClient = new HttpClient()) { HttpResponseMessage response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead); response.EnsureSuccessStatusCode(); // Get the file stream. using (Stream fileStream = await response.Content.ReadAsStreamAsync()) { // Create a URL object. Uri urlObj = new Uri(preSignedUrl); HttpWebRequest connection = (HttpWebRequest)WebRequest.Create(urlObj); // Set the request method for file upload. connection.Method = "PUT"; connection.AllowWriteStreamBuffering = false; connection.SendChunked = false; // Set the request headers. Replace with actual values. connection.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."; connection.ContentType = "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."; // Get the request stream and write the file stream to it. using (Stream requestStream = connection.GetRequestStream()) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = await fileStream.ReadAsync(buffer, 0, buffer.Length)) > 0) { await requestStream.WriteAsync(buffer, 0, bytesRead); } await requestStream.FlushAsync(); } // Check the response. using (HttpWebResponse responseResult = (HttpWebResponse)connection.GetResponse()) { if (responseResult.StatusCode == HttpStatusCode.OK) { Console.WriteLine("File uploaded successfully from URL."); } else { Console.WriteLine($"Failed to upload the file. ResponseCode: {responseResult.StatusCode}"); } } } } } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); } } public static async Task Main(string[] args) { string preSignedUrlOrHttpUrl = "Replace this with the value of the Url field in Data.Param returned by the ApplyFileUploadLease operation in the previous step."; string url = "Replace this with the URL of the file to upload."; await UploadFileFromUrl(preSignedUrlOrHttpUrl, url); } }Go
package main import ( "fmt" "net/http" "github.com/go-resty/resty/v2" ) // UploadFileFromUrl uploads a file from a public URL to temporary storage. // // Parameters: // - preSignedUrl (string): The URL from the upload lease. // - headers (map[string]string): The headers for the upload request. // - sourceUrl (string): The URL of the file. // // Returns: // - error: An error message if the upload fails, otherwise nil. func UploadFileFromUrl(preSignedUrl string, headers map[string]string, sourceUrl string) error { // Download the file from the given URL. resp, err := http.Get(sourceUrl) if err != nil { return fmt.Errorf("failed to get file: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("failed to get file, status code: %d", resp.StatusCode) } // Create a REST client. client := resty.New() // Build the request headers required for the upload. uploadHeaders := map[string]string{ "X-bailian-extra": headers["X-bailian-extra"], "Content-Type": headers["Content-Type"], } // Send a PUT request. response, err := client.R(). SetHeaders(uploadHeaders). SetBody(resp.Body). Put(preSignedUrl) if err != nil { return fmt.Errorf("failed to send request: %w", err) } if err != nil { return fmt.Errorf("failed to send request: %w", err) } // Check the HTTP response status code. if response.IsError() { return fmt.Errorf("HTTP error: %d", response.StatusCode()) } fmt.Println("File uploaded successfully from URL.") return nil } // main function func main() { // Replace this with the value of the Url field in Data.Param returned by the ApplyFileUploadLease operation in the previous step. preSignedUrl := "Replace this with the value of the Url field in Data.Param returned by the ApplyFileUploadLease operation in the previous step." // Replace these with the values of X-bailian-extra and Content-Type in Data.Param.Headers returned by the ApplyFileUploadLease operation in the previous step. headers := map[string]string{ "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.", } sourceUrl := "Replace this with the URL of the file to upload." // Call the upload function. err := UploadFileFromUrl(preSignedUrl, headers, sourceUrl) if err != nil { fmt.Printf("Upload failed: %v\n", err) } }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.FileUploadLeaseIdretornado 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 ocategory_idcorrespondente.ImportanteO
CategoryIdinformado aqui deve corresponder aoCategoryIdusado na etapa de Solicitar um lease de upload de arquivo. Caso contrário, você receberá um erroCategory is mismatched.
Depois de adicionar um arquivo, o Model Studio retorna um
FileIdpara o arquivo e inicia automaticamente sua análise. Olease_idé invalidado imediatamente. Não reutilize o mesmo ID de lease para outro envio.Importante-
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)Java
/** * Add a file to a category. * * @param client The client object. * @param leaseId The lease ID. * @param parser The parser for the file. * @param categoryId The category ID. * @param workspaceId The workspace ID. * @return The response object from Alibaba Cloud Model Studio. */ public AddFileResponse addFile(com.aliyun.bailian20231229.Client client, String leaseId, String parser, String categoryId, String workspaceId) throws Exception { Map<String, String> headers = new HashMap<>(); com.aliyun.bailian20231229.models.AddFileRequest addFileRequest = new com.aliyun.bailian20231229.models.AddFileRequest(); addFileRequest.setLeaseId(leaseId); addFileRequest.setParser(parser); addFileRequest.setCategoryId(categoryId); com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions(); return client.addFileWithOptions(workspaceId, addFileRequest, headers, runtime); }PHP
/** * Add a file to a category. * * @param Bailian $client The client. * @param string $leaseId The lease ID. * @param string $parser The parser for the file. * @param string $categoryId The category ID. * @param string $workspaceId The workspace ID. * @return AddFileResponse The response from Alibaba Cloud Model Studio. */ public function addFile($client, $leaseId, $parser, $categoryId, $workspaceId) { $headers = []; $addFileRequest = new AddFileRequest([ "leaseId" => $leaseId, "parser" => $parser, "categoryId" => $categoryId ]); $runtime = new RuntimeOptions([]); return $client->addFileWithOptions($workspaceId, $addFileRequest, $headers, $runtime); }Node.js
/** * Add a file to a category. * @param {Bailian20231229Client} client - The client. * @param {string} leaseId - The lease ID. * @param {string} parser - The parser for the file. * @param {string} categoryId - The category ID. * @param {string} workspaceId - The workspace ID. * @returns {Promise<bailian20231229.AddFileResponse>} - The response from Alibaba Cloud Model Studio. */ async function addFile(client, leaseId, parser, categoryId, workspaceId) { const headers = {}; const req = new bailian20231229.AddFileRequest({ leaseId, parser, categoryId }); const runtime = new Util.RuntimeOptions({}); return await client.addFileWithOptions(workspaceId, req, headers, runtime); }C#
/// <summary> /// Add a file to a category. /// </summary> /// <param name="client">The client object.</param> /// <param name="leaseId">The lease ID.</param> /// <param name="parser">The parser for the file.</param> /// <param name="categoryId">The category ID.</param> /// <param name="workspaceId">The workspace ID.</param> /// <returns>The response object from Alibaba Cloud Model Studio.</returns> /// <exception cref="Exception">An exception is thrown if an error occurs during the call.</exception> public AlibabaCloud.SDK.Bailian20231229.Models.AddFileResponse AddFile( AlibabaCloud.SDK.Bailian20231229.Client client, string leaseId, string parser, string categoryId, string workspaceId) { var headers = new Dictionary<string, string>() { }; var addFileRequest = new AlibabaCloud.SDK.Bailian20231229.Models.AddFileRequest { LeaseId = leaseId, Parser = parser, CategoryId = categoryId }; var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); return client.AddFileWithOptions(workspaceId, addFileRequest, headers, runtime); }Go
// AddFile adds a file to a specified category in Alibaba Cloud Model Studio. // // Parameters: // - client (bailian20231229.Client): The client. // - leaseId (string): The lease ID. // - parser (string): The parser for the file. // - categoryId (string): The category ID. // - workspaceId (string): The workspace ID. // // Returns: // - *bailian20231229.AddFileResponse: The response from Alibaba Cloud Model Studio. // - error: The error message. func AddFile(client *bailian20231229.Client, leaseId, parser, categoryId, workspaceId string) (_result *bailian20231229.AddFileResponse, _err error) { headers := make(map[string]*string) addFileRequest := &bailian20231229.AddFileRequest{ LeaseId: tea.String(leaseId), Parser: tea.String(parser), CategoryId: tea.String(categoryId), } runtime := &util.RuntimeOptions{} return client.AddFileWithOptions(tea.String(workspaceId), addFileRequest, headers, runtime) }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.
-
file_id: Especifique o
FileIdretornado pela API quando você adiciona um arquivo a uma categoria.
Se o campo
Data.StatusforPARSE_SUCCESS, o arquivo foi analisado com sucesso e pode ser importado para a base de conhecimento.Importante-
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)Java
/** * Query the basic information of a file. * * @param client The client object. * @param workspaceId The workspace ID. * @param fileId The file ID. * @return The response object from Alibaba Cloud Model Studio. */ public DescribeFileResponse describeFile(com.aliyun.bailian20231229.Client client, String workspaceId, String fileId) throws Exception { Map<String, String> headers = new HashMap<>(); com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions(); return client.describeFileWithOptions(workspaceId, fileId, headers, runtime); }PHP
/** * Query the basic information of a file. * * @param Bailian $client The client. * @param string $workspaceId The workspace ID. * @param string $fileId The file ID. * @return DescribeFileResponse The response from Alibaba Cloud Model Studio. */ public function describeFile($client, $workspaceId, $fileId) { $headers = []; $runtime = new RuntimeOptions([]); return $client->describeFileWithOptions($workspaceId, $fileId, $headers, $runtime); }Node.js
/** * Query the parsing status of a file. * @param {Bailian20231229Client} client - The client. * @param {string} workspaceId - The workspace ID. * @param {string} fileId - The file ID. * @returns {Promise<bailian20231229.DescribeFileResponse>} - The response from Alibaba Cloud Model Studio. */ async function describeFile(client, workspaceId, fileId) { const headers = {}; const runtime = new Util.RuntimeOptions({}); return await client.describeFileWithOptions(workspaceId, fileId, headers, runtime); }C#
/// <summary> /// Query the basic information of a file. /// </summary> /// <param name="client">The client object.</param> /// <param name="workspaceId">The workspace ID.</param> /// <param name="fileId">The file ID.</param> /// <returns>The response object from Alibaba Cloud Model Studio.</returns> /// <exception cref="Exception">An exception is thrown if an error occurs during the call.</exception> public AlibabaCloud.SDK.Bailian20231229.Models.DescribeFileResponse DescribeFile( AlibabaCloud.SDK.Bailian20231229.Client client, string workspaceId, string fileId) { var headers = new Dictionary<string, string>() { }; var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); return client.describeFileWithOptions(workspaceId, fileId, headers, runtime); }Go
// DescribeFile gets the basic information of a file. // // Parameters: // - client (bailian20231229.Client): The client. // - workspaceId (string): The workspace ID. // - fileId (string): The file ID. // // Returns: // - *bailian20231229.DescribeFileResponse: The response from Alibaba Cloud Model Studio. // - error: The error message. func DescribeFile(client *bailian20231229.Client, workspaceId, fileId string) (_result *bailian20231229.DescribeFileResponse, _err error) { headers := make(map[string]*string) runtime := &util.RuntimeOptions{} return client.DescribeFileWithOptions(tea.String(workspaceId), tea.String(fileId), headers, runtime) }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
FileIdretornado pela API quando você adiciona um arquivo a uma categoria.Se
source_typeestiver definido comoDATA_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.Idretornado 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.
Importante-
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)Java
/** * Create (initialize) a knowledge base in Alibaba Cloud Model Studio. * * @param client The client object. * @param workspaceId The workspace ID. * @param fileId The file ID. * @param name The name of the knowledge base. * @param structureType The data structure type of the knowledge base. * @param sourceType The data source type. Category and file types are supported. * @param sinkType The vector storage type of the knowledge base. * @return The response object from Alibaba Cloud Model Studio. */ public CreateIndexResponse createIndex(com.aliyun.bailian20231229.Client client, String workspaceId, String fileId, String name, String structureType, String sourceType, String sinkType) throws Exception { Map<String, String> headers = new HashMap<>(); com.aliyun.bailian20231229.models.CreateIndexRequest createIndexRequest = new com.aliyun.bailian20231229.models.CreateIndexRequest(); createIndexRequest.setStructureType(structureType); createIndexRequest.setName(name); createIndexRequest.setSourceType(sourceType); createIndexRequest.setSinkType(sinkType); createIndexRequest.setDocumentIds(Collections.singletonList(fileId)); com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions(); return client.createIndexWithOptions(workspaceId, createIndexRequest, headers, runtime); }PHP
/** * Create (initialize) a knowledge base in Alibaba Cloud Model Studio. * * @param Bailian $client The client. * @param string $workspaceId The workspace ID. * @param string $fileId The file ID. * @param string $name The name of the knowledge base. * @param string $structureType The data structure type of the knowledge base. * @param string $sourceType The data source type. Category and file types are supported. * @param string $sinkType The vector storage type of the knowledge base. * @return CreateIndexResponse The response from Alibaba Cloud Model Studio. */ public function createIndex($client, $workspaceId, $fileId, $name, $structureType, $sourceType, $sinkType) { $headers = []; $createIndexRequest = new CreateIndexRequest([ "structureType" => $structureType, "name" => $name, "sourceType" => $sourceType, "documentIds" => [ $fileId ], "sinkType" => $sinkType ]); $runtime = new RuntimeOptions([]); return $client->createIndexWithOptions($workspaceId, $createIndexRequest, $headers, $runtime); }Node.js
/** * Initialize a knowledge base (index). * @param {Bailian20231229Client} client - The client. * @param {string} workspaceId - The workspace ID. * @param {string} fileId - The file ID. * @param {string} name - The name of the knowledge base. * @param {string} structureType - The data structure type of the knowledge base. * @param {string} sourceType - The data source type. Category and file types are supported. * @param {string} sinkType - The vector storage type of the knowledge base. * @returns {Promise<bailian20231229.CreateIndexResponse>} - The response from Alibaba Cloud Model Studio. */ async function createIndex(client, workspaceId, fileId, name, structureType, sourceType, sinkType) { const headers = {}; const req = new bailian20231229.CreateIndexRequest({ name, structureType, documentIds: [fileId], sourceType, sinkType }); const runtime = new Util.RuntimeOptions({}); return await client.createIndexWithOptions(workspaceId, req, headers, runtime); }C#
/// <summary> /// Create (initialize) a knowledge base in Alibaba Cloud Model Studio. /// </summary> /// <param name="client">The client object.</param> /// <param name="workspaceId">The workspace ID.</param> /// <param name="fileId">The file ID.</param> /// <param name="name">The name of the knowledge base.</param> /// <param name="structureType">The data structure type of the knowledge base.</param> /// <param name="sourceType">The data source type. Category and file types are supported.</param> /// <param name="sinkType">The vector storage type of the knowledge base.</param> /// <returns>The response object from Alibaba Cloud Model Studio.</returns> /// <exception cref="Exception">An exception is thrown if an error occurs during the call.</exception> public AlibabaCloud.SDK.Bailian20231229.Models.CreateIndexResponse CreateIndex( AlibabaCloud.SDK.Bailian20231229.Client client, string workspaceId, string fileId, string name, string structureType, string sourceType, string sinkType) { var headers = new Dictionary<string, string>() { }; var createIndexRequest = new AlibabaCloud.SDK.Bailian20231229.Models.CreateIndexRequest { StructureType = structureType, Name = name, SourceType = sourceType, SinkType = sinkType, DocumentIds = new List<string> { fileId } }; var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); return client.CreateIndexWithOptions(workspaceId, createIndexRequest, headers, runtime); }Go
// CreateIndex creates (initializes) a knowledge base in Alibaba Cloud Model Studio. // // Parameters: // - client (bailian20231229.Client): The client. // - workspaceId (string): The workspace ID. // - fileId (string): The file ID. // - name (string): The name of the knowledge base. // - structureType (string): The data structure type of the knowledge base. // - sourceType (string): The data source type. Category and file types are supported. // - sinkType (string): The vector storage type of the knowledge base. // // Returns: // - *bailian20231229.CreateIndexResponse: The response from Alibaba Cloud Model Studio. // - error: The error message. func CreateIndex(client *bailian20231229.Client, workspaceId, fileId, name, structureType, sourceType, sinkType string) (_result *bailian20231229.CreateIndexResponse, _err error) { headers := make(map[string]*string) createIndexRequest := &bailian20231229.CreateIndexRequest{ StructureType: tea.String(structureType), Name: tea.String(name), SourceType: tea.String(sourceType), SinkType: tea.String(sinkType), DocumentIds: []*string{tea.String(fileId)}, } runtime := &util.RuntimeOptions{} return client.CreateIndexWithOptions(tea.String(workspaceId), createIndexRequest, headers, runtime) }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.
-
index_id: Forneça o
Data.Idretornado pela API quando você inicializa a base de conhecimento.
Após a conclusão do envio, o Model Studio inicia imediatamente a construção do índice como uma tarefa assíncrona. O
Data.Idretornado 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.Importante-
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)Java
/** * Submit an index job to Alibaba Cloud Model Studio. * * @param client The client object. * @param workspaceId The workspace ID. * @param indexId The knowledge base ID. * @return The response object from Alibaba Cloud Model Studio. */ public SubmitIndexJobResponse submitIndex(com.aliyun.bailian20231229.Client client, String workspaceId, String indexId) throws Exception { Map<String, String> headers = new HashMap<>(); com.aliyun.bailian20231229.models.SubmitIndexJobRequest submitIndexJobRequest = new com.aliyun.bailian20231229.models.SubmitIndexJobRequest(); submitIndexJobRequest.setIndexId(indexId); com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions(); return client.submitIndexJobWithOptions(workspaceId, submitIndexJobRequest, headers, runtime); }PHP
/** * Submit an index job to Alibaba Cloud Model Studio. * * @param Bailian $client The client. * @param string $workspaceId The workspace ID. * @param string $indexId The knowledge base ID. * @return SubmitIndexJobResponse The response from Alibaba Cloud Model Studio. */ public static function submitIndex($client, $workspaceId, $indexId) { $headers = []; $submitIndexJobRequest = new SubmitIndexJobRequest([ 'indexId' => $indexId ]); $runtime = new RuntimeOptions([]); return $client->submitIndexJobWithOptions($workspaceId, $submitIndexJobRequest, $headers, $runtime); }Node.js
/** * Submit an index job. * @param {Bailian20231229Client} client - The client. * @param {string} workspaceId - The workspace ID. * @param {string} indexId - The knowledge base ID. * @returns {Promise<bailian20231229.SubmitIndexJobResponse>} - The response from Alibaba Cloud Model Studio. */ async function submitIndex(client, workspaceId, indexId) { const headers = {}; const req = new bailian20231229.SubmitIndexJobRequest({ indexId }); const runtime = new Util.RuntimeOptions({}); return await client.submitIndexJobWithOptions(workspaceId, req, headers, runtime); }C#
/// <summary> /// Submit an index job to Alibaba Cloud Model Studio. /// </summary> /// <param name="client">The client object.</param> /// <param name="workspaceId">The workspace ID.</param> /// <param name="indexId">The knowledge base ID.</param> /// <returns>The response object from Alibaba Cloud Model Studio.</returns> /// <exception cref="Exception">An exception is thrown if an error occurs during the call.</exception> public AlibabaCloud.SDK.Bailian20231229.Models.SubmitIndexJobResponse SubmitIndex( AlibabaCloud.SDK.Bailian20231229.Client client, string workspaceId, string indexId) { var headers = new Dictionary<string, string>() { }; var submitIndexJobRequest = new AlibabaCloud.SDK.Bailian20231229.Models.SubmitIndexJobRequest { IndexId = indexId }; var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); return client.SubmitIndexJobWithOptions(workspaceId, submitIndexJobRequest, headers, runtime); }Go
// SubmitIndex submits an index job. // // Parameters: // - client (bailian20231229.Client): The client. // - workspaceId (string): The workspace ID. // - indexId (string): The knowledge base ID. // // Returns: // - *bailian20231229.SubmitIndexJobResponse: The response from Alibaba Cloud Model Studio. // - error: The error message. func SubmitIndex(client *bailian20231229.Client, workspaceId, indexId string) (_result *bailian20231229.SubmitIndexJobResponse, _err error) { headers := make(map[string]*string) submitIndexJobRequest := &bailian20231229.SubmitIndexJobRequest{ IndexId: tea.String(indexId), } runtime := &util.RuntimeOptions{} return client.SubmitIndexJobWithOptions(tea.String(workspaceId), submitIndexJobRequest, headers, runtime) }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.
-
job_id: Informe o
Data.Idretornado pela API ao enviar um job de indexação.
Quando o campo
Data.StatusforCOMPLETED, a base de conhecimento terá sido criada.Importante-
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)Java
/** * Query the status of an index job. * * @param client The client object. * @param workspaceId The workspace ID. * @param jobId The job ID. * @param indexId The knowledge base ID. * @return The response object from Alibaba Cloud Model Studio. */ public GetIndexJobStatusResponse getIndexJobStatus(com.aliyun.bailian20231229.Client client, String workspaceId, String jobId, String indexId) throws Exception { Map<String, String> headers = new HashMap<>(); com.aliyun.bailian20231229.models.GetIndexJobStatusRequest getIndexJobStatusRequest = new com.aliyun.bailian20231229.models.GetIndexJobStatusRequest(); getIndexJobStatusRequest.setIndexId(indexId); getIndexJobStatusRequest.setJobId(jobId); com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions(); GetIndexJobStatusResponse getIndexJobStatusResponse = null; getIndexJobStatusResponse = client.getIndexJobStatusWithOptions(workspaceId, getIndexJobStatusRequest, headers, runtime); return getIndexJobStatusResponse; }PHP
/** * Query the status of an index job. * * @param Bailian $client The client. * @param string $workspaceId The workspace ID. * @param string $indexId The knowledge base ID. * @param string $jobId The job ID. * @return GetIndexJobStatusResponse The response from Alibaba Cloud Model Studio. */ public function getIndexJobStatus($client, $workspaceId, $jobId, $indexId) { $headers = []; $getIndexJobStatusRequest = new GetIndexJobStatusRequest([ 'indexId' => $indexId, 'jobId' => $jobId ]); $runtime = new RuntimeOptions([]); return $client->getIndexJobStatusWithOptions($workspaceId, $getIndexJobStatusRequest, $headers, $runtime); }Node.js
/** * Query the status of an index job. * @param {Bailian20231229Client} client - The client. * @param {string} workspaceId - The workspace ID. * @param {string} jobId - The job ID. * @param {string} indexId - The knowledge base ID. * @returns {Promise<bailian20231229.GetIndexJobStatusResponse>} - The response from Alibaba Cloud Model Studio. */ async function getIndexJobStatus(client, workspaceId, jobId, indexId) { const headers = {}; const req = new bailian20231229.GetIndexJobStatusRequest({ jobId, indexId }); const runtime = new Util.RuntimeOptions({}); return await client.getIndexJobStatusWithOptions(workspaceId, req, headers, runtime); }C#
/// <summary> /// Query the status of an index job. /// </summary> /// <param name="client">The client object.</param> /// <param name="workspaceId">The workspace ID.</param> /// <param name="jobId">The job ID.</param> /// <param name="indexId">The knowledge base ID.</param> /// <returns>The response object from Alibaba Cloud Model Studio.</returns> /// <exception cref="Exception">An exception is thrown if an error occurs during the call.</exception> public AlibabaCloud.SDK.Bailian20231229.Models.GetIndexJobStatusResponse GetIndexJobStatus( AlibabaCloud.SDK.Bailian20231229.Client client, string workspaceId, string jobId, string indexId) { var headers = new Dictionary<string, string>() { }; var getIndexJobStatusRequest = new AlibabaCloud.SDK.Bailian20231229.Models.GetIndexJobStatusRequest { IndexId = indexId, JobId = jobId }; var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); return client.GetIndexJobStatusWithOptions(workspaceId, getIndexJobStatusRequest, headers, runtime); }Go
// GetIndexJobStatus queries the status of an index job. // // Parameters: // - client (bailian20231229.Client): The client. // - workspaceId (string): The workspace ID. // - jobId (string): The job ID. // - indexId (string): The knowledge base ID. // // Returns: // - *bailian20231229.GetIndexJobStatusResponse: The response from Alibaba Cloud Model Studio. // - error: The error message. func GetIndexJobStatus(client *bailian20231229.Client, workspaceId, jobId, indexId string) (_result *bailian20231229.GetIndexJobStatusResponse, _err error) { headers := make(map[string]*string) getIndexJobStatusRequest := &bailian20231229.GetIndexJobStatusRequest{ JobId: tea.String(jobId), IndexId: tea.String(indexId), } runtime := &util.RuntimeOptions{} return client.GetIndexJobStatusWithOptions(tea.String(workspaceId), getIndexJobStatusRequest, headers, runtime) } -
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_optionspara transmitir o ID da base de conhecimentoindex_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.
Caso a resposta contenha excesso de informações irrelevantes, especifique SearchFilters na solicitação para filtrar os resultados por critérios como tags. |
Importante
Python
Java
PHP
Node.js
C#
Go
|
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 atualizadoSiga 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çãoApó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 Importante
|
Importante
Python
Java
PHP
Node.js
C#
Go
|
2.2. Aguardar a conclusão da tarefaA 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 A lista |
Importante
Python
Java
PHP
Node.js
C#
Go
|
3. Excluir o arquivo antigoPor 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.
Nota
É 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. |
Importante
Python
Java
PHP
Node.js
C#
Go
|
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 conhecimentoPara visualizar bases de conhecimento em um workspace específico, chame a operação ListIndices.
|
Importante
Python
Java
PHP
Node.js
C#
Go
|
Excluir uma base de conhecimentoPara 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. |
Importante
Python
Java
PHP
Node.js
C#
Go
|
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
-
Como automatizar atualizações e sincronização de bases de conhecimento?
Document search
Integre as APIs do Object Storage Service (OSS), Function Compute (FC) e bases de conhecimento do Model Studio. Siga estas etapas:
Criar um bucket: Acesse o console do OSS para criar um bucket do OSS destinado ao armazenamento dos seus arquivos de origem.
Criar uma base de conhecimento: Crie uma base de conhecimento de busca de documentos para armazenar seu conteúdo de conhecimento privado.
Criar uma função personalizada: Acesse o console do FC e crie uma função para eventos de alteração de arquivos, como operações de adição ou exclusão. Consulte Criar uma função. Essas funções sincronizam alterações de arquivos do OSS para sua base de conhecimento chamando as APIs relevantes descritas em Atualizar uma base de conhecimento.
Criar um gatilho do OSS: No FC, associe um gatilho do OSS à função personalizada criada na etapa anterior. Quando um evento de alteração de arquivo for detectado, como um novo upload de arquivo no OSS, o gatilho será ativado e o FC executará a função. Consulte Gatilhos.
Data query and image Q&A
Sem suporte.
-
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.
-
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.
-
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.

O valor WorkspaceId está incorreto ou você não é membro do workspace: Antes de chamar a API, verifique se o
WorkspaceIdestá correto e se você é membro do workspace. Como ser adicionado como membro de um workspace específico
-
-
O que devo fazer se receber o erro "Specified access key is not found or invalid"?
Esse erro geralmente ocorre porque o
access_key_idouaccess_key_secretfornecido está incorreto, ou oaccess_key_idfoi desativado. Certifique-se de que oaccess_key_idesteja correto e não desativado antes de chamar a API.
-
O que devo fazer se receber o erro "Category is mismatched"?
Esse erro normalmente ocorre quando o
CategoryIdusado na chamada da APIApplyFileUploadLeasedifere doCategoryIdpassado na chamada subsequente da APIAddFile.Certifique-se de usar o mesmo
CategoryIddurante todo o fluxo de upload de arquivos, desdeApplyFileUploadLeaseatéAddFile. Você pode chamar a APIListCategorypara recuperar a lista de categorias no workspace atual e verificar se oCategoryIdque 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.