> For the complete documentation index, see [llms.txt](https://docs.maiagent.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.maiagent.ai/tech/en/api-integration/api_knowledge.md).

# Presigned File Upload Mode

Upload files to MaiAgent in two stages using a Presigned URL：obtain a presigned URL to send the file directly to storage, then register it as a knowledge base file or conversation attachment.

MaiAgent currently requires file uploads in two places

1. Knowledge base document uploads
2. Uploads of attachments used in messages

## Presigned Upload Mode

MaiAgent supports **Presigned upload mode**, which lets clients upload files directly to cloud storage (such as S3) without routing them through the server. In this mode, the server only generates a secure, time-limited Presigned URL, which the client uses to upload the file directly.

#### Differences from traditional uploads：

1. **Data flow**
   * Traditional mode：Files pass through the server, which then uploads them to cloud storage.
   * Presigned mode：Clients upload files directly to the cloud, avoiding the burden of file handling on the server.
2. **Performance and cost**
   * Traditional mode may consume excessive server resources and increase data transfer costs.
   * Presigned mode reduces server load, improves performance, and lowers transfer costs.
3. **Security**
   * Presigned URLs include a signature and an expiration time, ensuring that only authorized users can make upload requests within the specified period.

This mode is especially suitable for large files or frequent uploads, improving efficiency while maintaining strong security.

#### Presigned upload flow diagram

```mermaid
sequenceDiagram
    participant Client as Client
    participant Server as Sever
    participant S3 as Storage(S3)

    Note over Client,S3: Presigned upload flow
    
    Client->>+Server: 1. Request a presigned URL
    Note right of Client: POST /api/v1/upload-presigned-url/<br/>Include filename, type, and size
    
    Server->>Server: 2. Validate request parameters
    Server->>Server: 3. Generate presigned parameters
    Note right of Server: Set expiration, permissions, etc.
    Server-->>-Client: 4. Return the presigned URL and parameters
    
    Client->>+S3: 5. Upload directly using the presigned URL
    Note right of Client: POST to the presigned URL<br/>Include every entry in fields + the file binary
    S3-->>-Client: 6. Upload completion response (HTTP 204)
    
    opt Knowledge base scenario：Register the file in the knowledge base
        Client->>+Server: 7. Register using fields.key
        Note right of Client: POST /api/v1/knowledge-bases/{KB_ID}/files/<br/>Include file = fields.key in the body
        Server->>Server: 8. Create KnowledgeBaseFile and schedule parsing
        Server-->>-Client: 9. Return the file record
    end
```

#### Traditional upload flow diagram

Traditional uploads are available only for message attachments：`POST /api/v1/attachments-upload/`. Place the file in the `file` field of a multipart form; the response is an attachment object. Knowledge base files can only be uploaded using Presigned mode.

```mermaid
sequenceDiagram
    participant Client as Client
    participant Server as Server
    participant S3 as Storage(S3)

    Note over Client,S3: Traditional upload flow
    
    Client->>+Server: 1. File upload request
    Note right of Client: POST /api/v1/attachments-upload/<br/>Multipart form with the file in the file field
    
    Server->>Server: 2. Validate the file<br/>(size, type, format)
    Server->>Server: 3. Save a temporary file
    
    Server->>+S3: 4. Upload the file to S3
    Note right of Server: Use the AWS SDK<br/>Upload the temporary file
    S3-->>-Server: 5. Upload success response
    
    Server->>Server: 6. Clean up the temporary file
    Server-->>-Client: 7. Return the upload result
    Note left of Server: Return the attachment object (id, file, etc.)
```

***

#### Uploading files with Presigned URLs

The following describes how to upload files using the Presigned upload APIs provided by MaiAgent. **For knowledge bases**, follow Step 1 → 2 → 3. **For message attachments**, follow Step 1 → 2, then obtain an attachment object as described in [Creating message attachments](#message-attachments) before including it in a message.

#### 1. **Obtain a Presigned URL**

**Endpoint**

`POST https://api.maiagent.ai/api/v1/upload-presigned-url/`

**Description**

The client sends a request to the server to obtain a Presigned URL for uploading the file directly to cloud storage.

**Request parameters**

| Parameter   | Type      | Required | Description                                                                                                                                                                                      |
| ----------- | --------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `filename`  | `string`  | Yes      | Name of the file to upload                                                                                                                                                                       |
| `modelName` | `string`  | Yes      | <p>Module name used to classify the purpose of the uploaded file<br></p><p>For knowledge bases, enter <code>chatbot-file</code></p><p>For message attachments, enter <code>attachment</code></p> |
| `fieldName` | `string`  | Yes      | File field name. Enter `file` for both knowledge bases (`chatbot-file`) and message attachments (`attachment`)                                                                                   |
| `fileSize`  | `integer` | Yes      | File size in bytes. It must match the actual binary size exactly, or S3 will reject Step 2                                                                                                       |

**Example request**

```bash
curl --location 'https://api.maiagent.ai/api/v1/upload-presigned-url/' \
--header 'Authorization: Api-Key YOUR_API_KEY' \
--header 'Content-Type: application/json' \
--data '{
    "filename": "document.pdf",
    "modelName": "chatbot-file",
    "fieldName": "file",
    "fileSize": 178329
}'
```

**Example response**

```json
{
    "url": "https://s3.ap-northeast-1.amazonaws.com/whizchat-media-prod-django.playma.app",
    "fields": {
        "key": "media/chatbots/chatbot-file/86572e41-16ba-45dd-b049-28c69f77ffb0.pdf",
        "x-amz-algorithm": "AWS4-HMAC-SHA256",
        "x-amz-credential": "ASIATIVCN4X5XXXXXXXX/20260522/ap-northeast-1/s3/aws4_request",
        "x-amz-date": "20260522T020727Z",
        "x-amz-security-token": "IQoJb3JpZ2luX2VjEEoa...（a very long STS token）",
        "policy": "eyJleHBpcmF0aW9uIjog...（base64 policy）",
        "x-amz-signature": "617e10d1db034ab351d3735de5c56287ecc926dbfe5b5884d2ce67deed363004"
    }
}
```

{% hint style="warning" %}
**Production environments use temporary AWS STS credentials** (`x-amz-credential` starts with `ASIA`), so the response's `fields` object \*\*includes the \*\***`x-amz-security-token`** field. When uploading in Step 2, include every `fields` entry exactly as returned (including `x-amz-security-token`). S3 will reject the upload if any are missing.

Presigned URLs **expire after approximately 1 hour**. Use them as soon as possible after obtaining them.
{% endhint %}

***

#### 2. **Upload the file to cloud storage**

**Description**

Use the `url` and `fields` obtained above to upload the file directly to cloud storage. **Every entry in the `fields` object must be included** (including `x-amz-security-token`). Do not hardcode the field list; dynamic assembly prevents omissions if AWS adds fields later.

**S3 responds with HTTP 204 No Content (an empty body) on a successful upload**.

{% hint style="info" %}
For deployments using Azure Blob storage, the Step 1 response also includes `method: "PUT"` and `headers`：use PUT to send the file body directly to `url`, including every header in `headers`. Success returns HTTP 201. In this case, `fields` contains only `key`; subsequent steps still use `fields.key`. If the response has no `method`, always upload using POST as shown below.
{% endhint %}

**Example request (curl, including the STS token)**

```bash
curl --location 'https://s3.ap-northeast-1.amazonaws.com/whizchat-media-prod-django.playma.app' \
--form 'key="media/chatbots/chatbot-file/86572e41-16ba-45dd-b049-28c69f77ffb0.pdf"' \
--form 'x-amz-algorithm="AWS4-HMAC-SHA256"' \
--form 'x-amz-credential="ASIATIVCN4X5XXXXXXXX/20260522/ap-northeast-1/s3/aws4_request"' \
--form 'x-amz-date="20260522T020727Z"' \
--form 'x-amz-security-token="IQoJb3JpZ2luX2VjEEoa..."' \
--form 'policy="eyJleHBpcmF0aW9uIjog..."' \
--form 'x-amz-signature="617e10d1db034ab351d3735de5c56287ecc926dbfe5b5884d2ce67deed363004"' \
--form 'file=@"/path/to/document.pdf"'
```

**Example request (Python, dynamic assembly, recommended)**

```python
import requests

# Step 1: Obtain a Presigned URL
presign = requests.post(
    'https://api.maiagent.ai/api/v1/upload-presigned-url/',
    headers={'Authorization': 'Api-Key YOUR_API_KEY'},
    json={
        'modelName': 'chatbot-file',
        'fieldName': 'file',
        'filename': 'document.pdf',
        'fileSize': 178329,
    },
).json()

# Step 2: Pass the entire fields object to automatically include every entry (including x-amz-security-token)
with open('/path/to/document.pdf', 'rb') as f:
    s3_response = requests.post(
        presign['url'],
        data=presign['fields'],
        files={'file': f},
    )
assert s3_response.status_code == 204, s3_response.text

file_key = presign['fields']['key']  # Value used in Step 3
```

***

#### 3. **Register the file in the knowledge base (knowledge base scenarios only)**

**Endpoint**

`POST https://api.maiagent.ai/api/v1/knowledge-bases/{knowledgeBasePk}/files/`

**Description**

After Step 2, the file binary is in S3, but **it is not yet in the knowledge base**. Call this API to register the upload as a `KnowledgeBaseFile` so the system can begin parsing, chunking, and indexing.

{% hint style="warning" %}
**The `file` field must contain `fields.key` from the Step 1 response (the internal relative path in MaiAgent S3), not an arbitrary external URL**. If you have an external URL (such as a download link from a partner system), first download the file using `GET`, then follow Step 1 → 2 → 3.
{% endhint %}

**Path parameters**

| Parameter         | Type     | Description                                    |
| ----------------- | -------- | ---------------------------------------------- |
| `knowledgeBasePk` | `string` | Unique identifier of the knowledge base (UUID) |

**Request parameters**

| Parameter                       | Type     | Required | Description                                                                                                                                                                                                                                                    |
| ------------------------------- | -------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `files`                         | `array`  | Yes      | List of files to create; multiple files can be created in one batch                                                                                                                                                                                            |
| `files[].filename`              | `string` | Yes      | Original filename                                                                                                                                                                                                                                              |
| `files[].file`                  | `string` | Yes      | `fields.key` from the Step 1 response (a relative path, **not a URL**)                                                                                                                                                                                         |
| `files[].parser`                | `string` | No       | UUID of the parser to use. If omitted, the parser is automatically detected for PDF, Word (.docx), and PowerPoint (.pptx) (see [Parser tools](/tech/en/quickstart/parser.md#auto-detect-and-billing)); other formats use the default parser for that file type |
| `files[].labels`                | `array`  | No       | File labels (an array of {id, name} objects)                                                                                                                                                                                                                   |
| `files[].rawUserDefineMetadata` | `object` | No       | User-defined metadata                                                                                                                                                                                                                                          |

**Example request**

```bash
curl --location 'https://api.maiagent.ai/api/v1/knowledge-bases/86401a64-ad89-4847-a709-f4ccfa0af7b9/files/' \
--header 'Authorization: Api-Key YOUR_API_KEY' \
--header 'Content-Type: application/json' \
--data '{
    "files": [
        {
            "filename": "document.pdf",
            "file": "media/chatbots/chatbot-file/86572e41-16ba-45dd-b049-28c69f77ffb0.pdf"
        }
    ]
}'
```

**Example response**

```json
[
    {
        "id": "86572e41-16ba-45dd-b049-28c69f77ffb0",
        "filename": "document.pdf",
        "file": "https://media.maiagent.ai/media/chatbots/chatbot-file/86572e41-16ba-45dd-b049-28c69f77ffb0.pdf",
        "fileType": "pdf",
        "knowledgeBase": {
            "id": "86401a64-ad89-4847-a709-f4ccfa0af7b9",
            "name": "My knowledge base"
        },
        "size": 178329,
        "status": "initial",
        "parser": {
            "id": "535c5b86-0534-4d0a-abfe-82f3d37e769a",
            "name": "MaiAgent Parser",
            "provider": "maiagent",
            "order": 0,
            "supportsDiarization": false
        },
        "labels": [],
        "rawUserDefineMetadata": {},
        "createdAt": "1779425272000"
    }
]
```

**File status (`status`)**

| Value        | Description                                  |
| ------------ | -------------------------------------------- |
| `initial`    | Newly created, awaiting processing           |
| `processing` | Parsing, chunking, and indexing in progress  |
| `done`       | Processing complete, available for retrieval |
| `failed`     | Processing failed                            |

#### Creating message attachments (message attachment scenarios only) <a href="#message-attachments" id="message-attachments"></a>

For message attachments, enter `"modelName": "attachment"` and `"fieldName": "file"` in Step 1. After uploading in Step 2, register the file as a conversation attachment to obtain an attachment object.

**Endpoint**

`POST https://api.maiagent.ai/api/v1/conversations/{conversationId}/attachments/`

**Request parameters**

| Parameter  | Type     | Required | Description                                                             |
| ---------- | -------- | -------- | ----------------------------------------------------------------------- |
| `file`     | `string` | Yes      | `fields.key` from the Step 1 response                                   |
| `filename` | `string` | Yes      | Original filename                                                       |
| `type`     | `string` | No       | `image` (image), `audio` (audio), or `other` (other files, the default) |

**Example request**

```bash
curl --location 'https://api.maiagent.ai/api/v1/conversations/8e44604a-8278-4c96-96b5-3e5a0548d738/attachments/' \
--header 'Authorization: Api-Key YOUR_API_KEY' \
--header 'Content-Type: application/json' \
--data '{
    "file": "media/chat/attachment/0b6f3c2e-6a51-4f43-9d3f-6e2f1c9a7b10.pdf",
    "filename": "document.pdf",
    "type": "other"
}'
```

**Example response** (HTTP 201)

```json
{
    "id": "5d1f2a7c-3b8e-4c19-9a62-1e4b7f0c8d35",
    "type": "other",
    "filename": "document.pdf",
    "file": "https://…/document.pdf",
    "expiresAt": null
}
```

When sending a message, include the response's `id`, `type`, `filename`, and `file` in the attachment array：`attachments` in [Creating conversations and messages](/tech/en/api-integration/conversations-and-messages.md), or `message.attachments` in [completions](/tech/en/api-integration/dui-hua-yu-xun-xi-hui-fu-chuan-liu-tong-bu.md). If you do not yet have a conversation ID (for example, when using completions to start a conversation), you can use the traditional upload endpoint above, `POST /api/v1/attachments-upload/`, to obtain an attachment object.

#### How message attachments are processed <a href="#attachment-processing" id="attachment-processing"></a>

An attachment object is simply an uploaded file; the message it belongs to and its `type` determine how the model reads it. `POST /conversations/{conversationId}/attachments/` and `POST /attachments-upload/` create the same kind of object. The former binds it to a conversation in advance, while the latter binds it when the message is sent. Subsequent processing is identical; an attachment belongs to only one message.

| `type`                                                       | How the model reads it                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | When it is available                                                                                                                                                                                                                                                                                                                   |
| ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `image`（`.png`、`.jpg`、`.jpeg`、`.gif`、`.webp`、`.bmp`、`.tiff`） | Sent directly as an image to the Agent's language model, without parsing or indexing. The Agent must use a multimodal model; otherwise, it replies “The LLM you selected does not support multimodal input.” The platform configures the number of images sent to the model per request (20 by default); excess images are not sent                                                                                                                                                                                                                                                                                                                                                                                                                                                                         | When the message is sent                                                                                                                                                                                                                                                                                                               |
| `other`（PDF、Word、PowerPoint、Excel／CSV、HTML、TXT／Markdown）     | Depends on the Agent's reply mode. **Non-Agent modes, such as conversation mode**：Upon upload, a file scoped to this conversation is created, parsed, chunked, and vectorized using a knowledge base parser. When answering, it is retrieved together with the knowledge base (using the Agent's maximum retrieval chunk count); the full content is not inserted into the prompt. **Agent mode**：No automatic parsing occurs. When answering, the Agent uses attachment tools according to the question—`parse_attachment_content` parses and reads chunks, `read_attachment_full_text` reads the entire text of plain text files, and `ingest_attachment` indexes the file for retrieval (these tools can each be disabled in the Agent's advanced settings). Excel／CSV files are converted to table text | Non-Agent modes：After parsing completes; `waitForAttachments` (completions, `true` by default) waits for parsing before answering. If set to `false`, the attachment may not be readable for this response. Agent mode：The Agent processes the attachment when answering after the message is sent; `waitForAttachments` has no effect |
| `audio`（`.wav`、`.mp3`、`.m4a`、`.aac`）                         | Converted into a transcript by a speech-to-text parser, then handled in the same way as `other`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             | Same as above                                                                                                                                                                                                                                                                                                                          |

Differences from knowledge base files：

|                                  | Message attachments                                                                                                                                                                                                                     | Knowledge base files                                        |
| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- |
| Scope                            | Only subsequent messages in the same conversation can retrieve them; other conversations cannot access them                                                                                                                             | All Agents and conversations using the knowledge base       |
| Reuse                            | No need to upload again within the same conversation; a new conversation requires another upload                                                                                                                                        | Upload once for permanent availability                      |
| Labels, metadata, query metadata | None                                                                                                                                                                                                                                    | Available; labels and query metadata can restrict the scope |
| Parser                           | Non-Agent modes use the default parser for the extension (an image-capable parser is used when OCR is enabled on the conversation platform); in Agent mode, the Agent selects a parser in `parse_attachment_content`                    | Can be specified at upload                                  |
| Retention                        | Automatically deleted on expiration according to the platform's attachment cleanup settings (including parsed copies); see [Credits billing](https://docs.maiagent.ai/others/credits#attachment-and-derived-storage) in the user manual | Until deleted                                               |
| Deletion                         | Through the [Conversation attachment management API](/tech/en/api-integration/endpoint-behaviors/conversation-attachments.md) (requires the file library to be enabled), or upon expiration                                             | Knowledge base file API                                     |
| Billing                          | Parsing and vectorization follow knowledge base billing rules; storage counts toward “conversation attachment storage”                                                                                                                  | Parsing, vectorization, file storage, and vector storage    |

To query the same set of documents across multiple conversations, upload them to a knowledge base. Use attachments for one-time files, such as a user's quotation.

***

## Common errors and troubleshooting

**Q：S3 returns `The AWS Access Key Id you provided does not exist in our records`**

A：Step 2 is missing `x-amz-security-token`, or an expired access key / S3 endpoint was hardcoded. Always use the `url` and `fields` freshly returned by Step 1, and pass the entire `fields` object unchanged to Step 2.

**Q：S3 returns `Policy Condition failed`**

A：Usually, `fileSize` in Step 1 does not match the actual binary size. Recalculate the actual file size and repeat Step 1.

**Q：Step 3 returns 400, reporting an issue with the `file` field**

A：`file` must contain `fields.key` from the Step 1 response (for example, `media/chatbots/chatbot-file/xxx.pdf`), not the full URL returned by Step 3 or an arbitrary external URL.

**Q：I already have an external URL (such as a download link from a partner system). Can I pass it directly to Step 3?**

A：No. The `file` field in Step 3 is a relative key in MaiAgent's own S3. First download the file from the external URL using `GET`, then follow Step 1 → 2 → 3.

**Q：The file remains at `status: processing` after Step 3**

A：Parsing time depends on file size and type; large files may take several minutes. Poll the status using `GET /api/v1/knowledge-bases/{KB_ID}/files/{file_id}/`. The Agent can retrieve the file once it reaches `done`.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.maiagent.ai/tech/en/api-integration/api_knowledge.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
