The Alibaba Cloud Model Studio knowledge base provides open APIs that enable you to integrate with your existing business systems, automate operations, and address complex retrieval needs.
Prerequisites
-
To manage a knowledge base with APIs, a RAM user must get API permissions (the AliyunBailianDataFullAccess policy) and join a workspace. This is not required for an Alibaba Cloud account.
A RAM user can manage knowledge bases only in workspaces they have joined. An Alibaba Cloud account can manage knowledge bases in all workspaces.
-
Install the latest version of the Alibaba Cloud Model Studio SDK to call the knowledge base APIs. For installation instructions, see the Alibaba Cloud SDK Development Reference.
If the SDK does not meet your requirements, you can call the knowledge base APIs via HTTP requests using the signature mechanism. For connection details, see API Overview.
-
Get an AccessKey ID and an AccessKey Secret, and a workspace ID. Configure them as system environment variables to run the sample code. The following example shows how to set these variables in Linux:
If you use an IDE or other development plugins, configure the
ALIBABA_CLOUD_ACCESS_KEY_ID,ALIBABA_CLOUD_ACCESS_KEY_SECRET, andWORKSPACE_IDvariables in your development environment.
- Prepare the sample knowledge document Alibaba Cloud Model Studio Phone Introduction.docx to create a knowledge base.
Sample code
Sample code
- Create a knowledge base
- Retrieve from a knowledge base
- Update a knowledge base
- Manage knowledge bases
Python
Create a knowledge base
Create a document search knowledge base in a specified workspace.
1. Initialize clientTo upload files and create a knowledge base, first initialize a client. Use your AccessKey and AccessKey Secret to verify your identity and configure theendpoint.
| Python |
2. Upload knowledge base files | |
2.1. Request a file upload leaseBefore creating a knowledge base, upload its source files to the same workspace. To do this, call the ApplyFileUploadLease operation to request a file upload lease. A lease is a temporary authorization to upload a file and is valid for several minutes.
| Python
Request example
Response example |
2.2. Upload file to temporary storageWith the upload lease, use the temporary upload parameters and URL to upload files from your local storage or a publicly accessible URL to the Model Studio server. Each workspace supports up to 10,000 files. The supported formats include PDF, DOCX, DOC, TXT, Markdown, PPTX, PPT, XLSX, XLS, HTML, PNG, JPG, JPEG, BMP, and GIF.
|
Python |
2.3. Add file to a categoryAfter uploading the file, add it to a category in the same workspace by calling the AddFile operation.
FileId for the file and automatically starts parsing it. The lease_id is immediately invalidated. Do not reuse the same lease ID for another submission. | Python
Request example
Response example |
2.4. Query file parsing statusA file cannot be used in a knowledge base until it is parsed. During peak hours, this process can take several hours. You can call the DescribeFile operation to query its parsing status.
Data.Status field is PARSE_SUCCESS, the file has been successfully parsed and you can import it into the knowledge base. | Python
Request example
Response example |
3. Create a knowledge base | |
3.1. Initialize knowledge baseOnce a file is parsed, you can create a knowledge base from it in the same workspace. To begin, call the CreateIndex operation to initialize (but not finalize) a document retrieval knowledge base.
Data.Id field returned by this API is the knowledge base ID, which is used for subsequent index building.Keep the knowledge base ID secure, as it is required for all subsequent API operations related to this knowledge base. | Python
Request example
Response example |
3.2. Submit an index jobAfter initializing the knowledge base, call the SubmitIndexJob operation to start the index building process.
Data.Id returned by this API call is the corresponding task ID. You will use this ID in the next step to query the latest status of the task. | Python
Request example
Response example |
3.3. Query index job statusThe index job takes some time to complete. During peak hours, this process can take several hours. Call the GetIndexJobStatus operation to query its execution status.
Data.Status field is COMPLETED, the knowledge base has been created. | Python
Request example
Response example |
Retrieve from a knowledge base
You can retrieve information from a knowledge base in two ways:
- Using an Alibaba Cloud Model Studio application: When you call an application, use the
rag_optionsparameter to pass the knowledge base IDindex_id. This supplements your model with private knowledge and provides the latest information. - Using an Alibaba Cloud API: Call the Retrieve API to retrieve information from a specified knowledge base and return the original text segments.
To retrieve information and return text segments from a specified knowledge base, call the Retrieve API.
| Python
Sample request
Sample response |
Update a knowledge base
The following example shows how to update a document search knowledge base. Applications that use the knowledge base reflect your updates in real time. New content becomes available for retrieval, while deleted content is no longer accessible.
You cannot update data query or image Q&A knowledge bases using an API. For more information, see Update a knowledge base.
- Incremental update: The only supported method is a three-step process: upload the updated file, append the file to the knowledge base, and then delete the old file.
- Full update: For each file in the knowledge base, perform the three steps to complete the update.
- Automatic update or synchronization: For more information, see How to automatically update or synchronize a knowledge base.
- File limit for a single update: We recommend updating no more than 10,000 files at a time. Exceeding this limit might prevent the knowledge base from updating correctly.
1. Upload the updated fileFollow the procedure in Create a knowledge base: Step 2 to upload the updated file to the workspace that contains the knowledge base.Request a new file upload lease to generate a new set of upload parameters for the updated file. | |
2. Append file to the knowledge base | |
2.1. Submit an append taskAfter the uploaded file is parsed, call the SubmitIndexAddDocumentsJob operation to append the new file to the knowledge base and rebuild the knowledge base index.
Data.Id, which is the task ID (job_id). Use this ID in the next step to query the task status. | Python
Request example
Response example |
2.2. Wait for task completionThe indexing task takes some time to complete. During peak hours, this process can take several hours. You can call the GetIndexJobStatus operation to query its execution status.
COMPLETED for the Data.Status field in the response indicates that all updated files have been successfully appended to the knowledge base.The | Python
Request example
Response example |
3. Delete the old fileFinally, call the DeleteIndexDocument operation to permanently delete the old version of the file from the knowledge base. This prevents outdated information from being retrieved accidentally.
You can only delete files with a status of import failed (INSERT_ERROR) or import successful (FINISH). To query the status of files in the knowledge base, you can call the ListIndexDocuments operation. | Python
Sample request
Sample response |
Manage knowledge bases
Creating and using knowledge bases are not supported through the API. You must perform these tasks in the Model Studio console.
View a knowledge baseTo view knowledge bases in a specified workspace, call the ListIndices operation.
| Python
Sample request
Sample response |
Delete a knowledge baseTo permanently delete a knowledge base, call the DeleteIndex operation. Before you delete the knowledge base, you must disassociate it from all linked Alibaba Cloud Model Studio applications in the Model Studio console. Otherwise, the deletion fails.
| Python
Sample request
Sample response |
API
See the API Catalog (Knowledge Base) for a complete list of knowledge base APIs and their request and response parameters.
FAQ
-
How do I automate knowledge base updates and synchronization?
- Document search
- Data query and image Q&A
Integrate the APIs for Object Storage Service (OSS), Function Compute (FC), and Model Studio knowledge bases. Follow these steps:- Create a bucket: Go to the OSS console to create an OSS bucket for storing your source files.
- Create a knowledge base: Create a document search knowledge base to store your private knowledge content.
- Create a custom function: Go to the FC console and create a function for file change events, such as add or delete operations. See Create a function. These functions synchronize file changes from OSS to your knowledge base by calling the relevant APIs described in Update a knowledge base.
- Create an OSS trigger: In FC, associate an OSS trigger with the custom function that you created in the previous step. When a file change event is detected, such as a new file upload to OSS, the trigger activates and FC executes the function. See Triggers.
- Why is my new knowledge base empty? This typically occurs if the Submit an index job step fails to run. If you call the CreateIndex API but the SubmitIndexJob API call fails, the knowledge base will be empty. To resolve this, Submit an index job again and wait for the index job to complete.
- What should I do if I receive the error "Access your uploaded file failed. Please check if your upload action was successful"? This error usually occurs because the Upload the file to temporary storage step did not run successfully. Confirm that this step runs successfully before you call the AddFile API operation.
-
What should I do if I receive the error "Access denied: Either you are not authorized to access this workspace, or the workspace does not exist"?
This error usually occurs for the following reasons:
-
The requested service endpoint (service endpoint) is incorrect: For access over the Internet, users of the China site (public cloud) should use the service endpoint in China (Beijing), whereas users of the international site should use the service endpoint in Singapore. If you are using the online debugging feature, make sure that you select the correct service endpoint, as shown in the following figure.

-
The
WorkspaceIdvalue is incorrect, or you are not a member of the workspace: Before you call the API, verify that theWorkspaceIdis correct and that you are a member of the workspace. How to be added as a member of a specified workspace
-
The requested service endpoint (service endpoint) is incorrect: For access over the Internet, users of the China site (public cloud) should use the service endpoint in China (Beijing), whereas users of the international site should use the service endpoint in Singapore. If you are using the online debugging feature, make sure that you select the correct service endpoint, as shown in the following figure.
-
What should I do if I receive the error "Specified access key is not found or invalid"?
This error usually occurs because the provided
access_key_idoraccess_key_secretis incorrect, or theaccess_key_idhas been disabled. Ensure that theaccess_key_idis correct and not disabled before you call the API. -
What should I do if I receive the error "Category is mismatched"?
This error typically occurs when the
CategoryIdused in theApplyFileUploadLeaseAPI call differs from theCategoryIdpassed in the subsequentAddFileAPI call. Ensure that you use the sameCategoryIdthroughout the entire file upload flow, fromApplyFileUploadLeasetoAddFile. You can call theListCategoryAPI to retrieve the list of categories in the current workspace and verify that theCategoryIdyou are using is correct.
Billing
- All knowledge base features and API calls are free. See Knowledge Base: Billing.
- Storage space for data, such as files, imported into Model Studio is free.
