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
- Manage chunks
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 100,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
Currently, you can retrieve information from a knowledge base in the following ways:
- Using an Alibaba Cloud Model Studio application: When you call an application, pass the knowledge base ID
index_idthroughrag_optionsto supplement your model application with private knowledge and provide the latest information. - Using an Alibaba Cloud API: Call the Retrieve API to retrieve information from a specified knowledge base and return the original text segments.
- Using the Knowledge Search service (recommended): Call the Search API to perform joint semantic retrieval across multiple knowledge bases and return text segments ranked by relevance. Retrieval strategies are configured and published in the console in advance, and callers only need to pass the search intent (
query/images) andagent_id.
To perform joint semantic retrieval across multiple knowledge bases and return text segments ranked by relevance, call the Search API.
query/images) and agent_id, without maintaining retrieval strategy parameters in the request. | cURL
Sample request
Sample response |
Structured output
The Knowledge Base retrieval API does not support the response_format parameter. To get JSON-formatted output, set response_format at the model invocation layer.
Take Python SDK alibabacloud_bailian20231229 2.14.3 as an example: RetrieveRequest has 15 fields: index_id, query, dense_similarity_top_k, enable_reranking, enable_rewrite, extra, images, query_history, rerank, rerank_min_score, rerank_top_n, rewrite, save_retriever_history, search_filters, sparse_similarity_top_k, among which response_format is not included.
For the Agent API, you can use the instructions field to specify the JSON output format through a prompt, that is, include "Please output in JSON format" in instructions when creating the application.
Alibaba Cloud Model Studio does not directly generate JSON files; you need to write the returned JSON content to a file yourself.
Knowledge Base retrieval + JSON output
First call the retrieval interface to obtain text chunks from the knowledge base, then use the chunks as context to call a DashScope model interface with response_format={"type": "json_object"} set, and you will get structured output.
Update a knowledge base
The following example shows how to update a document search knowledge base. Applications that use the knowledge base reflect your updates in real time. New content becomes available for retrieval, while deleted content is no longer accessible.
Data query and image Q&A knowledge bases can also be created and managed through the RAG API. For more information, see RAG API Reference.
- Incremental update: The only supported method is a three-step process: upload the updated file, append the file to the knowledge base, and then delete the old file.
- Full update: For each file in the knowledge base, perform the three steps to complete the update.
- Automatic update or synchronization: For more information, see How to automatically update or synchronize a knowledge base.
- File limit for a single update: We recommend updating no more than 100,000 files at a time. Exceeding this limit might prevent the knowledge base from updating correctly.
1. Upload the updated 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
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 |
Manage chunks
Query, edit, and delete chunks in a knowledge base. Editing chunks is supported by all knowledge base types; for deletion, document search, data query, and image Q&A knowledge bases are all supported, while audio/video search knowledge bases only support deletion.
Query the chunk listCall the ListChunks API to query the chunk list of a knowledge base.
| Python |
Edit a chunkCall the UpdateChunk API to modify the content of a specified chunk. This operation is supported by all knowledge base types.
| Python |
Delete chunksCall the DeleteChunk API to delete one or more chunks. A maximum of 10 chunks can be deleted per call.
| Python |
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
- Audio and video search
Use Object Storage Service (OSS) to manage files and Function Compute (FC) to listen for file change events. This setup automatically synchronizes updates to your knowledge base in real time. See Automate AI knowledge base updates. - Why is my new knowledge base empty? This typically occurs because the Submit an index job step was not performed or did not complete successfully. If you call the CreateIndex API but do not successfully call the SubmitIndexJob API, you will get an empty knowledge base. To resolve this, simply Submit an index job again and wait for the index job to complete.
- What should I do if I receive the error "Access your uploaded file failed. Please check if your upload action was successful"? This error usually occurs because the Upload the file to temporary storage step was not performed or did not complete successfully. Confirm that this step runs successfully before you call the AddFile API operation.
-
What should I do if I receive the error "Access denied: Either you are not authorized to access this workspace, or the workspace does not exist"?
This error usually occurs for the following reasons:
- The requested service endpoint (service endpoint) is incorrect: For access over the Internet, if you are a user of the China site (public cloud), you should use the service endpoint in the China (Beijing) region; if you are a user of the international site, you should use the service endpoint in the Singapore region. If you are using the online debugging feature, make sure the service endpoint dropdown is set correctly (China site: China (Beijing)).
-
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
-
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 to apply for a file upload lease 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. -
Why do the API results differ from the console debug window when I call a knowledge base application?
Troubleshoot this issue from the following perspectives:
- Multi-turn conversation context: The console debug window retains multi-turn conversation history by default. If your API call does not pass
session_id, each call is a standalone call without context. Follow-up questions that rely on previous context will lose their referents, which may produce answers completely different from those in the debug window. To enable multi-turn conversation, retrievesession_idfrom the response of the first call and pass the samesession_idin subsequent calls to maintain session continuity. - Application release status: After the application configuration is modified, you must click Publish for the changes to take effect, and API calls always use the published version. If you are verifying unpublished changes in the debug window, the API responses will not reflect those changes. Make sure the application status is Published.
- Parameter alignment: When you call through the application (App API), the default parameters configured in the application (such as
temperatureandtop_p) are used, which is consistent with the debug window. If you directly call the DashScope model service API, you must explicitly specify these parameters, and their values may differ from those in the debug environment, resulting in differences in answer style and content. - Knowledge base association: When you call through the application (App API), the knowledge bases configured in the application are automatically associated, so you do not need to specify them manually. If you directly call the knowledge base retrieval API, you must explicitly pass in
knowledgebase_id; omitting it or passing an incorrect value will prevent the expected knowledge from being retrieved.
- Multi-turn conversation context: The console debug window retains multi-turn conversation history by default. If your API call does not pass
Billing
Knowledge bases use a pay-as-you-go model. Usage for each billable item is calculated hourly, and fees are automatically deducted from your Alibaba Cloud account. To prevent service interruptions from an overdue payment, ensure you maintain a sufficient account balance. You can add funds in Billing and Costs.
Billable item | Description |
|---|---|
Specification fee | The fee for the actual runtime of a |
Embedding and rerank model call fees | You are charged for calling embedding and rerank models when creating, updating, or retrieving from a knowledge base. Billing is based on input token usage. For pricing, see the Model Call Billing page. |