# Using Knowledge Base—Creation and Interaction

## Overview

MaiAgent provides developers with the ability to manage knowledge base files through the API. Developers can perform the following operations on knowledge bases within their workspace:

* Upload new files to a knowledge base
* Query all files in a knowledge base
* Update existing file information
* Delete individual or batch files

{% hint style="info" %}
**Important Reminder**

When using the API, all operations require a valid API Key for authentication. Make sure your API Key has the appropriate permissions.
{% endhint %}

***

## Knowledge Base Operations

### Creating a Knowledge Base

Before using a knowledge base, you must first create at least **one** knowledge base. When creating a knowledge base, you must specify the Embedding Model, Reranker Model, knowledge base name, and the AI assistants that can use this knowledge base.

You can specify the above configuration via scripts. Here is an example request for creating a knowledge base:

{% code overflow="wrap" %}

```json
{
  "embeddingModel": "550e8400-e29b-41d4-a716-446655440000", // Embedding Model ID
  "rerankerModel": "550e8400-e29b-41d4-a716-446655440000", // Reranker Model ID
  "name": "Internal Training Manual",
  "description": "This knowledge base is for internal training use, containing user manuals, product manuals, and troubleshooting guides, for new employee onboarding only",
  "numberOfRetrievedChunks": 12, //  Number of retrieved chunks
  "enableRerank": true,
  "chatbots": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000"
    }
  ],
  "groups": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000"
    }
  ]
}
```

{% endcode %}

After submitting and receiving an HTTPS response, the creation is successful and you can begin operating on this knowledge base.

### Using an ID to Operate on a Single Knowledge Base

Before you start managing files in a single knowledge base, you need to obtain the knowledge base's unique identifier (`id`).

{% hint style="warning" %}
How to obtain the knowledge base id?

1. Get the `id` of a newly created knowledge base

For a knowledge base just created via script, the HTTPS response returned after creation will contain the `id` among other fields. The `id` in the response represents the knowledge base's `id` value.

2. Get the `id` of an existing knowledge base

You can obtain the corresponding knowledge base `id` from the response of the "list all knowledge bases" endpoint. See the API documentation: [Knowledge Bases (New)](https://docs.maiagent.ai/api/api-reference/zhi-shi-ku-xin-ban#lie-chu-suo-you-zhi-shi-ku)
{% endhint %}

### Querying Knowledge Base Files

The `Query Files` endpoint can be used to list all files in a knowledge base. You can use query parameters to filter by specific type, status, or search for specific keywords. Place the knowledge base `id` you want to query into the `{knowledgeBasePK}` position in the endpoint to query a specific knowledge base.

#### Endpoint

```
GET /api/knowledge-bases/{knowledgeBasePk}/files/
```

#### File Status Values (key: Status)

You can check the processing status of each file from the endpoint response. The possible statuses are listed below. A status of `done` indicates the file has been processed and is available for LLM retrieval:

* `initial` - Initialized
* `processing` - Processing
* `done` - Complete
* `deleting` - Deleting
* `deleted` - Deleted
* `failed` - Failed

This endpoint allows filtering by file type using the `fileType` parameter, such as `pdf`, `docx`, `txt`, `xlsx`, etc.

#### Example: Query All PDF Files

{% tabs %}
{% tab title="Shell/Bash" %}
{% code overflow="wrap" %}

```bash
# API call example (Shell)
curl -X GET "https://api.maiagent.ai/api/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/?fileType=example&knowledgeBase=550e8400-e29b-41d4-a716-446655440000&page=1&pageSize=1&query=example&status=deleted" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# Make sure to replace YOUR_API_KEY and verify the request data before running.
```

{% endcode %}
{% endtab %}
{% endtabs %}

***

## File Operations

### Uploading Files to a Knowledge Base

#### Endpoint

```
POST /api/knowledge-bases/{knowledgeBasePk}/files/
```

You can use this endpoint to upload files directly to a knowledge base. During upload, you can specify file information through parameters such as:

* `rawUserDefineMetadata`: Document metadata
* `labels`: Document classification labels

#### Example: Upload a Single Document -- Product Manual

**Request structure example**

You can specify the file content and target knowledge base.

{% code overflow="wrap" %}

```json
{
  "files": [
    {
      "filename": "Product Manual.pdf",
      "file": "https://my-product-bucket.s3.ap-northeast-1.amazonaws.com/products/laptop-dell-xps-15.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20251030%2Fap-northeast-1%2Fs3%2Faws4_request&X-Amz-Date=20251030T143000Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890",
      "knowledgeBase": {
        "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
        "name": "Internal Training Knowledge Base"
      },
      "parser": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      "labels": [
        {
          "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
          "name": "New Employee Training"
        }
      ],
    },
  ]
}
```

{% endcode %}

The response will contain the newly created file object, including the system-generated file ID.

You can also upload multiple files to different knowledge bases.

#### Example: Upload Multiple Documents to Different Knowledge Bases

{% code overflow="wrap" %}

```json
{
  "files": [
    {
      "filename": "New Employee Onboarding Manual.pdf",
      "file": "https://my-product-bucket.s3.ap-northeast-1.amazonaws.com/products/laptop-dell-xps-15.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20251030%2Fap-northeast-1%2Fs3%2Faws4_request&X-Amz-Date=20251030T143000Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567891",
      "knowledgeBase": {
        "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
        "name": "Internal Training Knowledge Base"
      },
    },
    {
      "filename": "D256 Product Documentation.pdf",
      "file": "https://my-product-bucket.s3.ap-northeast-1.amazonaws.com/products/laptop-dell-xps-15.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20251030%2Fap-northeast-1%2Fs3%2Faws4_request&X-Amz-Date=20251030T143000Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=abcdef1234567890abcdef1234567890abcdef123456",
      "knowledgeBase": {
        "id": "3fa85f64-5717-4562-b3fc-2c963f655o2l1",
        "name": "Customer Service Knowledge Base"
      },
    }
  ]
}
```

{% endcode %}

{% hint style="danger" %}
Please note: Individual files must not exceed 100MB, otherwise they cannot be processed correctly and the HTTP response will return an error message.
{% endhint %}

### Updating Existing File Information

You can use the `Update File Information` endpoint to modify information for an uploaded file, such as the filename, labels, or custom metadata. If a file has been updated, you do not need to re-upload it -- you can modify the information directly via script.

#### Endpoint <a href="#duan-dian" id="duan-dian"></a>

```
PUT /api/knowledge-bases/{knowledgeBasePk}/files/{id}/
```

**Request example**

{% code overflow="wrap" %}

```json
{
  "filename": "Product Manual Revised.pdf",
  "file": "https://ecommerce-products.s3.us-west-2.amazonaws.com/images/electronics/smartphones/iphone-15-pro-max-256gb-natural-titanium.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAI44QH8DHBEXAMPLE%2F20251030%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20251030T120000Z&X-Amz-Expires=7200&X-Amz-SignedHeaders=host&X-Amz-Security-Token=FwoGZXIvYXdzEBYaDH...truncated...&X-Amz-Signature=8c9d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d",
  "knowledgeBase": {
    "id": "550e8400-e29b-41d4-a716-446655440000"
  },
  "labels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
    }
  ],
  "rawUserDefineMetadata": {
    "editDate": "2025/10/30",
    "lastEditBy": "Wang",
    "version": "online"
  }
}
```

{% endcode %}

### Deleting Files

#### Deleting a Single File

**Endpoint**

```
DELETE /api/knowledge-bases/{knowledgeBasePk}/files/{id}
```

Use this endpoint to remove a single file from a knowledge base. Specify the file `id` to delete in the `{id}` position of the endpoint.

**Example**

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API call example (Shell)
curl -X DELETE "https://api.maiagent.ai/api/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# Make sure to replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}
{% endtabs %}

After successful deletion, the API will return a `204` status code. The file will no longer be available for LLM reference in responses.

#### Batch Deleting Files

To delete multiple files at once, use the `Batch Delete Files` endpoint for improved management efficiency.

**Endpoint**

```
POST /api/knowledge-bases/{knowledgeBasePk}/files/batch-delete/
```

Request example

```json
{
  "ids": [
    "550e8400-e29b-41d4-a716-446655440000",
    "550e8400-e29b-41d4-a716-446655449198",
    "kdlkjf029-e2b-41d4-adk06-dklwie091874"
  ]
}
```

You can pass in multiple file `id` values to have the system delete multiple files at once.

{% hint style="warning" %}
This endpoint can only batch delete files within a single knowledge base. Cross-knowledge-base batch deletion is not supported.
{% endhint %}

***

## Use Cases

The Knowledge Base File Management API has many practical use cases, such as:

### 1. Automated Document Updates

When your product documentation is updated in a Git repository, you can use a CI/CD pipeline to automatically upload the latest version to the knowledge base. This ensures the AI assistant always has access to the most current product information.

#### **Example Workflow**

{% stepper %}
{% step %}
**Detect a document update commit**
{% endstep %}

{% step %}
**Check if the file already exists**

Use the MaiAgent API to query whether a matching file exists in the knowledge base.
{% endstep %}

{% step %}
**Update/Upload file**

If the file exists, use the <mark style="color:blue;">partial update endpoint</mark> to update it; if it does not exist, use the <mark style="color:blue;">upload file endpoint</mark> to upload the new file.
{% endstep %}
{% endstepper %}

### 2. Content Management System Integration

If you use MaiAgent as a Content Management System (CMS), you can build a management interface that allows content editors to:

* Upload new content files
* Organize content using labels
* Search and filter specific types of content
* Batch delete expired content

***

## Summary

MaiAgent's public REST API enables you to manage knowledge base files more efficiently, including:

* Creating knowledge bases
* Querying and filtering files
* Uploading new files
* Updating file information
* Deleting individual or batch files

## Next Steps

* Check the complete [API Reference Documentation](https://docs.maiagent.ai/api) to start using the MaiAgent API services
* Explore the [MaiAgent WebChat SDK](https://docs.maiagent.ai/tech/api-integration/web-chat-sdk) to simplify API integration


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.maiagent.ai/tech/maiagent-tech-en/api-integration/shi-yong-zhi-shi-ku-jian-li-yu-hu-dong.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
