> 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/api/api-reference/zhi-shi-ku-xin-ban.md).

# 知識庫（新版）

### 建立知識庫 <a href="#knowledge-bases-create" id="knowledge-bases-create"></a>

POST `/api/v1/knowledge-bases/`

#### 請求內容

**請求參數**

| 欄位                      | 類型              | 必填 | 說明                                                                                                                                                                                                          |
| ----------------------- | --------------- | -- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| embeddingModel          | string (uuid)   | 是  |                                                                                                                                                                                                             |
| rerankerModel           | string (uuid)   | 是  |                                                                                                                                                                                                             |
| name                    | string          | 是  |                                                                                                                                                                                                             |
| description             | string          | 否  |                                                                                                                                                                                                             |
| numberOfRetrievedChunks | integer         | 否  | 提取的參考資料數量，預設為 12，最小值為 1                                                                                                                                                                                     |
| enableHyde              | boolean         | 否  | 啟用 HyDE，預設為 False                                                                                                                                                                                           |
| similarityCutoff        | number (double) | 否  | 相似度門檻，預設為 0.0，範圍為 0.0-1.0                                                                                                                                                                                   |
| enableRerank            | boolean         | 否  | 是否啟用重新排序，預設為 True                                                                                                                                                                                           |
| enableRrf               | boolean         | 否  | Enable Reciprocal Rank Fusion for hybrid search. Disable this if using a custom Elasticsearch without enterprise license. If not provided, uses system default.                                             |
| vectorDatabaseType      | object          | 否  | Type of vector database: elasticsearch, opensearch, oracle or synxdb. Defaults to the platform-managed engine. `elasticsearch`: Elasticsearch ; `opensearch`: OpenSearch ; `oracle`: Oracle AI Database ... |
| vectorDatabaseUrl       | string          | 否  | Custom vector database endpoint URL or Oracle DSN. For Elasticsearch/OpenSearch: URL format (e.g., "<https://host:9200>"). For Oracle: DSN format (e.g., "host:1521/service\_name").                        |
| vectorDatabaseApiKey    | string          | 否  | API Key for Elasticsearch. Not used for OpenSearch.                                                                                                                                                         |
| opensearchUsername      | string          | 否  | Username for OpenSearch Basic Auth.                                                                                                                                                                         |
| opensearchPassword      | string          | 否  | Password for OpenSearch Basic Auth.                                                                                                                                                                         |
| oracleUser              | string          | 否  | Oracle database username.                                                                                                                                                                                   |
| oraclePassword          | string          | 否  | Oracle database password.                                                                                                                                                                                   |
| synxdbUser              | string          | 否  | SynxDB database username.                                                                                                                                                                                   |
| synxdbPassword          | string          | 否  | SynxDB database password.                                                                                                                                                                                   |
| chatbots                | array\[IdName]  | 否  |                                                                                                                                                                                                             |
| groups                  | array\[IdName]  | 否  |                                                                                                                                                                                                             |

**請求結構範例**

```typescript
{
  "embeddingModel": string (uuid)
  "rerankerModel": string (uuid)
  "name": string
  "description"?: string // 非必填
  "numberOfRetrievedChunks"?: integer // 提取的參考資料數量，預設為 12，最小值為 1 (非必填)
  "enableHyde"?: boolean // 啟用 HyDE，預設為 False (非必填)
  "similarityCutoff"?: number (double) // 相似度門檻，預設為 0.0，範圍為 0.0-1.0 (非必填)
  "enableRerank"?: boolean // 是否啟用重新排序，預設為 True (非必填)
  "enableRrf"?: boolean // Enable Reciprocal Rank Fusion for hybrid search. Disable this if using a custom Elasticsearch without enterprise license. If not provided, uses system default. (非必填)
  "vectorDatabaseType"?:  // Type of vector database: elasticsearch, opensearch, oracle or synxdb. Defaults to the platform-managed engine.

* `elasticsearch` - Elasticsearch
* `opensearch` - OpenSearch
* `oracle` - Oracle AI Database 26ai
* `synxdb` - SynxDB (非必填)
  {
  }
  "vectorDatabaseUrl"?: string // Custom vector database endpoint URL or Oracle DSN. For Elasticsearch/OpenSearch: URL format (e.g., "https://host:9200"). For Oracle: DSN format (e.g., "host:1521/service_name"). (非必填)
  "vectorDatabaseApiKey"?: string // API Key for Elasticsearch. Not used for OpenSearch. (非必填)
  "opensearchUsername"?: string // Username for OpenSearch Basic Auth. (非必填)
  "opensearchPassword"?: string // Password for OpenSearch Basic Auth. (非必填)
  "oracleUser"?: string // Oracle database username. (非必填)
  "oraclePassword"?: string // Oracle database password. (非必填)
  "synxdbUser"?: string // SynxDB database username. (非必填)
  "synxdbPassword"?: string // SynxDB database password. (非必填)
  "chatbots"?: [ // 非必填
    {
      "id": string (uuid)
    }
  ]
  "groups"?: [ // 非必填
    {
      "id": string (uuid)
    }
  ]
}
```

**請求範例值**

```json
{
  "embeddingModel": "550e8400-e29b-41d4-a716-446655440000",
  "rerankerModel": "550e8400-e29b-41d4-a716-446655440000",
  "name": "範例名稱",
  "description": "範例字串",
  "numberOfRetrievedChunks": 123,
  "enableHyde": true,
  "similarityCutoff": 123,
  "enableRerank": true,
  "enableRrf": true,
  "vectorDatabaseType": {},
  "vectorDatabaseUrl": "範例字串",
  "vectorDatabaseApiKey": "範例字串",
  "opensearchUsername": "範例字串",
  "opensearchPassword": "範例字串",
  "oracleUser": "範例字串",
  "oraclePassword": "範例字串",
  "synxdbUser": "範例字串",
  "synxdbPassword": "範例字串",
  "chatbots": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000"
    }
  ],
  "groups": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000"
    }
  ]
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/knowledge-bases/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "embeddingModel": "550e8400-e29b-41d4-a716-446655440000",
    "rerankerModel": "550e8400-e29b-41d4-a716-446655440000",
    "name": "範例名稱",
    "description": "範例字串",
    "numberOfRetrievedChunks": 123,
    "enableHyde": true,
    "similarityCutoff": 123,
    "enableRerank": true,
    "enableRrf": true,
    "vectorDatabaseType": {},
    "vectorDatabaseUrl": "範例字串",
    "vectorDatabaseApiKey": "範例字串",
    "opensearchUsername": "範例字串",
    "opensearchPassword": "範例字串",
    "oracleUser": "範例字串",
    "oraclePassword": "範例字串",
    "synxdbUser": "範例字串",
    "synxdbPassword": "範例字串",
    "chatbots": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000"
      }
    ],
    "groups": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000"
      }
    ]
  }'

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// 請求內容 (payload)
const data = {
    "embeddingModel": "550e8400-e29b-41d4-a716-446655440000",
    "rerankerModel": "550e8400-e29b-41d4-a716-446655440000",
    "name": "範例名稱",
    "description": "範例字串",
    "numberOfRetrievedChunks": 123,
    "enableHyde": true,
    "similarityCutoff": 123,
    "enableRerank": true,
    "enableRrf": true,
    "vectorDatabaseType": {},
    "vectorDatabaseUrl": "範例字串",
    "vectorDatabaseApiKey": "範例字串",
    "opensearchUsername": "範例字串",
    "opensearchPassword": "範例字串",
    "oracleUser": "範例字串",
    "oraclePassword": "範例字串",
    "synxdbUser": "範例字串",
    "synxdbPassword": "範例字串",
    "chatbots": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000"
      }
    ],
    "groups": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000"
      }
    ]
  };

axios.post("https://api.maiagent.ai/api/v1/knowledge-bases/", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "embeddingModel": "550e8400-e29b-41d4-a716-446655440000",
    "rerankerModel": "550e8400-e29b-41d4-a716-446655440000",
    "name": "範例名稱",
    "description": "範例字串",
    "numberOfRetrievedChunks": 123,
    "enableHyde": True,
    "similarityCutoff": 123,
    "enableRerank": True,
    "enableRrf": True,
    "vectorDatabaseType": {},
    "vectorDatabaseUrl": "範例字串",
    "vectorDatabaseApiKey": "範例字串",
    "opensearchUsername": "範例字串",
    "opensearchPassword": "範例字串",
    "oracleUser": "範例字串",
    "oraclePassword": "範例字串",
    "synxdbUser": "範例字串",
    "synxdbPassword": "範例字串",
    "chatbots": [
        {
            "id": "550e8400-e29b-41d4-a716-446655440000"
        }
    ],
    "groups": [
        {
            "id": "550e8400-e29b-41d4-a716-446655440000"
        }
    ]
}

response = requests.post(url, json=data, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/knowledge-bases/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'embeddingModel' => '550e8400-e29b-41d4-a716-446655440000',
            'rerankerModel' => '550e8400-e29b-41d4-a716-446655440000',
            'name' => '範例名稱',
            'description' => '範例字串',
            'numberOfRetrievedChunks' => 123,
            'enableHyde' => true,
            'similarityCutoff' => 123,
            'enableRerank' => true,
            'enableRrf' => true,
            'vectorDatabaseType' => new \stdClass(),
            'vectorDatabaseUrl' => '範例字串',
            'vectorDatabaseApiKey' => '範例字串',
            'opensearchUsername' => '範例字串',
            'opensearchPassword' => '範例字串',
            'oracleUser' => '範例字串',
            'oraclePassword' => '範例字串',
            'synxdbUser' => '範例字串',
            'synxdbPassword' => '範例字串',
            'chatbots' => [
                [
                    'id' => '550e8400-e29b-41d4-a716-446655440000'
                ]
            ],
            'groups' => [
                [
                    'id' => '550e8400-e29b-41d4-a716-446655440000'
                ]
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 201**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "createdBy": 
  {
    "id": string (uuid)
    "name": string
  }
  "organization"?: string (uuid) // 非必填
  "embeddingModel": string (uuid)
  "rerankerModel": string (uuid)
  "name": string
  "description"?: string // 非必填
  "numberOfRetrievedChunks"?: integer // 提取的參考資料數量，預設為 12，最小值為 1 (非必填)
  "enableHyde"?: boolean // 啟用 HyDE，預設為 False (非必填)
  "similarityCutoff"?: number (double) // 相似度門檻，預設為 0.0，範圍為 0.0-1.0 (非必填)
  "enableRerank"?: boolean // 是否啟用重新排序，預設為 True (非必填)
  "enableRrf"?: boolean // Enable Reciprocal Rank Fusion for hybrid search. Disable this if using a custom Elasticsearch without enterprise license. (非必填)
  "vectorDatabaseType"?:  // Type of vector database: elasticsearch or opensearch.

* `elasticsearch` - Elasticsearch
* `opensearch` - OpenSearch
* `oracle` - Oracle AI Database 26ai
* `synxdb` - SynxDB (非必填)
  {
  }
  "vectorDatabaseUrl"?: string // Custom vector database endpoint URL or Oracle DSN. For Elasticsearch/OpenSearch: URL format (e.g., "https://host:9200"). For Oracle: DSN format (e.g., "host:1521/service_name"). (非必填)
  "vectorDatabaseApiKey"?: string // API Key for Elasticsearch. Not used for OpenSearch. (非必填)
  "opensearchUsername"?: string // Username for OpenSearch Basic Auth. (非必填)
  "opensearchPassword"?: string // Password for OpenSearch Basic Auth. (非必填)
  "oracleUser"?: string // Oracle database username. (非必填)
  "oraclePassword"?: string // Oracle database password. (非必填)
  "synxdbUser"?: string // SynxDB database username. (非必填)
  "synxdbPassword"?: string // SynxDB database password. (非必填)
  "labels": [
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "chatbots"?: [ // 非必填
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "groups"?: [ // 知識庫可存取的群組列表 (非必填)
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "filesCount": integer // Return count of KnowledgeBaseFile excluding processed files, conversation attachments, and soft-deleted.
  "vectorStorageSize": integer
  "chunksCount": integer
  "canUpdate": boolean // Return whether the current user can update this resource.
  "canDelete": boolean // Return whether the current user can delete this resource.
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應字串"
  },
  "organization": "550e8400-e29b-41d4-a716-446655440000",
  "embeddingModel": "550e8400-e29b-41d4-a716-446655440000",
  "rerankerModel": "550e8400-e29b-41d4-a716-446655440000",
  "name": "回應字串",
  "description": "回應字串",
  "numberOfRetrievedChunks": 456,
  "enableHyde": false,
  "similarityCutoff": 456,
  "enableRerank": false,
  "enableRrf": false,
  "vectorDatabaseType": {},
  "vectorDatabaseUrl": "回應字串",
  "vectorDatabaseApiKey": "回應字串",
  "opensearchUsername": "回應字串",
  "opensearchPassword": "回應字串",
  "oracleUser": "回應字串",
  "oraclePassword": "回應字串",
  "synxdbUser": "回應字串",
  "synxdbPassword": "回應字串",
  "labels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ],
  "chatbots": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ],
  "groups": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ],
  "filesCount": 456,
  "vectorStorageSize": 456,
  "chunksCount": 456,
  "canUpdate": false,
  "canDelete": false,
  "createdAt": "回應字串",
  "updatedAt": "回應字串"
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 列出所有知識庫 <a href="#knowledge-bases-list" id="knowledge-bases-list"></a>

GET `/api/v1/knowledge-bases/`

#### 參數

| 參數名稱             | 必填 | 類型      | 說明                                             |
| ---------------- | -- | ------- | ---------------------------------------------- |
| `embeddingModel` | ❌  | string  |                                                |
| `page`           | ❌  | integer | A page number within the paginated result set. |
| `pageSize`       | ❌  | integer | Number of results to return per page.          |
| `query`          | ❌  | string  |                                                |
| `rerankerModel`  | ❌  | string  |                                                |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/knowledge-bases/?embeddingModel=550e8400-e29b-41d4-a716-446655440000&page=1&pageSize=1&query=example&rerankerModel=550e8400-e29b-41d4-a716-446655440000" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/knowledge-bases/?embeddingModel=550e8400-e29b-41d4-a716-446655440000&page=1&pageSize=1&query=example&rerankerModel=550e8400-e29b-41d4-a716-446655440000", config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/?embeddingModel=550e8400-e29b-41d4-a716-446655440000&page=1&pageSize=1&query=example&rerankerModel=550e8400-e29b-41d4-a716-446655440000"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/knowledge-bases/?embeddingModel=550e8400-e29b-41d4-a716-446655440000&page=1&pageSize=1&query=example&rerankerModel=550e8400-e29b-41d4-a716-446655440000", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "count": integer
  "next"?: string (uri) // 非必填
  "previous"?: string (uri) // 非必填
  "results": [
    {
      "id": string (uuid)
      "createdBy": 
      {
        "id": string (uuid)
        "name": string
      }
      "organization"?: string (uuid) // 非必填
      "embeddingModel": string (uuid)
      "rerankerModel": string (uuid)
      "name": string
      "description"?: string // 非必填
      "numberOfRetrievedChunks"?: integer // 提取的參考資料數量，預設為 12，最小值為 1 (非必填)
      "enableHyde"?: boolean // 啟用 HyDE，預設為 False (非必填)
      "similarityCutoff"?: number (double) // 相似度門檻，預設為 0.0，範圍為 0.0-1.0 (非必填)
      "enableRerank"?: boolean // 是否啟用重新排序，預設為 True (非必填)
      "enableRrf"?: boolean // Enable Reciprocal Rank Fusion for hybrid search. Disable this if using a custom Elasticsearch without enterprise license. (非必填)
      "vectorDatabaseType"?:  // Type of vector database: elasticsearch or opensearch.

* `elasticsearch` - Elasticsearch
* `opensearch` - OpenSearch
* `oracle` - Oracle AI Database 26ai
* `synxdb` - SynxDB (非必填)
      {
      }
      "vectorDatabaseUrl"?: string // Custom vector database endpoint URL or Oracle DSN. For Elasticsearch/OpenSearch: URL format (e.g., "https://host:9200"). For Oracle: DSN format (e.g., "host:1521/service_name"). (非必填)
      "vectorDatabaseApiKey"?: string // API Key for Elasticsearch. Not used for OpenSearch. (非必填)
      "opensearchUsername"?: string // Username for OpenSearch Basic Auth. (非必填)
      "opensearchPassword"?: string // Password for OpenSearch Basic Auth. (非必填)
      "oracleUser"?: string // Oracle database username. (非必填)
      "oraclePassword"?: string // Oracle database password. (非必填)
      "synxdbUser"?: string // SynxDB database username. (非必填)
      "synxdbPassword"?: string // SynxDB database password. (非必填)
      "labels": [
        {
          "id": string (uuid)
          "name": string
        }
      ]
      "chatbots"?: [ // 非必填
        {
          "id": string (uuid)
          "name": string
        }
      ]
      "groups"?: [ // 知識庫可存取的群組列表 (非必填)
        {
          "id": string (uuid)
          "name": string
        }
      ]
      "filesCount": integer // Return count of KnowledgeBaseFile excluding processed files, conversation attachments, and soft-deleted.
      "vectorStorageSize": integer
      "chunksCount": integer
      "canUpdate": boolean // Return whether the current user can update this resource.
      "canDelete": boolean // Return whether the current user can delete this resource.
      "createdAt": string (timestamp)
      "updatedAt": string (timestamp)
    }
  ]
}
```

**回應範例值**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "createdBy": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應字串"
      },
      "organization": "550e8400-e29b-41d4-a716-446655440000",
      "embeddingModel": "550e8400-e29b-41d4-a716-446655440000",
      "rerankerModel": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串",
      "description": "回應字串",
      "numberOfRetrievedChunks": 456,
      "enableHyde": false,
      "similarityCutoff": 456,
      "enableRerank": false,
      "enableRrf": false,
      "vectorDatabaseType": {},
      "vectorDatabaseUrl": "回應字串",
      "vectorDatabaseApiKey": "回應字串",
      "opensearchUsername": "回應字串",
      "opensearchPassword": "回應字串",
      "oracleUser": "回應字串",
      "oraclePassword": "回應字串",
      "synxdbUser": "回應字串",
      "synxdbPassword": "回應字串",
      "labels": [
        {
          "id": "550e8400-e29b-41d4-a716-446655440000",
          "name": "回應字串"
        }
      ],
      "chatbots": [
        {
          "id": "550e8400-e29b-41d4-a716-446655440000",
          "name": "回應字串"
        }
      ],
      "groups": [
        {
          "id": "550e8400-e29b-41d4-a716-446655440000",
          "name": "回應字串"
        }
      ],
      "filesCount": 456,
      "vectorStorageSize": 456,
      "chunksCount": 456,
      "canUpdate": false,
      "canDelete": false,
      "createdAt": "回應字串",
      "updatedAt": "回應字串"
    }
  ]
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 取得特定知識庫詳情 <a href="#knowledge-bases-retrieve" id="knowledge-bases-retrieve"></a>

GET `/api/v1/knowledge-bases/{id}/`

#### 參數

| 參數名稱 | 必填 | 類型     | 說明                                             |
| ---- | -- | ------ | ---------------------------------------------- |
| `id` | ✅  | string | A UUID string identifying this Knowledge Base. |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/", config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "createdBy": 
  {
    "id": string (uuid)
    "name": string
  }
  "organization"?: string (uuid) // 非必填
  "embeddingModel": string (uuid)
  "rerankerModel": string (uuid)
  "name": string
  "description"?: string // 非必填
  "numberOfRetrievedChunks"?: integer // 提取的參考資料數量，預設為 12，最小值為 1 (非必填)
  "enableHyde"?: boolean // 啟用 HyDE，預設為 False (非必填)
  "similarityCutoff"?: number (double) // 相似度門檻，預設為 0.0，範圍為 0.0-1.0 (非必填)
  "enableRerank"?: boolean // 是否啟用重新排序，預設為 True (非必填)
  "enableRrf"?: boolean // Enable Reciprocal Rank Fusion for hybrid search. Disable this if using a custom Elasticsearch without enterprise license. (非必填)
  "vectorDatabaseType"?:  // Type of vector database: elasticsearch or opensearch.

* `elasticsearch` - Elasticsearch
* `opensearch` - OpenSearch
* `oracle` - Oracle AI Database 26ai
* `synxdb` - SynxDB (非必填)
  {
  }
  "vectorDatabaseUrl"?: string // Custom vector database endpoint URL or Oracle DSN. For Elasticsearch/OpenSearch: URL format (e.g., "https://host:9200"). For Oracle: DSN format (e.g., "host:1521/service_name"). (非必填)
  "vectorDatabaseApiKey"?: string // API Key for Elasticsearch. Not used for OpenSearch. (非必填)
  "opensearchUsername"?: string // Username for OpenSearch Basic Auth. (非必填)
  "opensearchPassword"?: string // Password for OpenSearch Basic Auth. (非必填)
  "oracleUser"?: string // Oracle database username. (非必填)
  "oraclePassword"?: string // Oracle database password. (非必填)
  "synxdbUser"?: string // SynxDB database username. (非必填)
  "synxdbPassword"?: string // SynxDB database password. (非必填)
  "labels": [
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "chatbots"?: [ // 非必填
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "groups"?: [ // 知識庫可存取的群組列表 (非必填)
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "filesCount": integer // Return count of KnowledgeBaseFile excluding processed files, conversation attachments, and soft-deleted.
  "vectorStorageSize": integer
  "chunksCount": integer
  "canUpdate": boolean // Return whether the current user can update this resource.
  "canDelete": boolean // Return whether the current user can delete this resource.
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應字串"
  },
  "organization": "550e8400-e29b-41d4-a716-446655440000",
  "embeddingModel": "550e8400-e29b-41d4-a716-446655440000",
  "rerankerModel": "550e8400-e29b-41d4-a716-446655440000",
  "name": "回應字串",
  "description": "回應字串",
  "numberOfRetrievedChunks": 456,
  "enableHyde": false,
  "similarityCutoff": 456,
  "enableRerank": false,
  "enableRrf": false,
  "vectorDatabaseType": {},
  "vectorDatabaseUrl": "回應字串",
  "vectorDatabaseApiKey": "回應字串",
  "opensearchUsername": "回應字串",
  "opensearchPassword": "回應字串",
  "oracleUser": "回應字串",
  "oraclePassword": "回應字串",
  "synxdbUser": "回應字串",
  "synxdbPassword": "回應字串",
  "labels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ],
  "chatbots": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ],
  "groups": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ],
  "filesCount": 456,
  "vectorStorageSize": 456,
  "chunksCount": 456,
  "canUpdate": false,
  "canDelete": false,
  "createdAt": "回應字串",
  "updatedAt": "回應字串"
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 搜尋特定知識庫的內容 <a href="#knowledge-bases-search-create" id="knowledge-bases-search-create"></a>

POST `/api/v1/knowledge-bases/{id}/search/`

#### 參數

| 參數名稱             | 必填 | 類型      | 說明                                             |
| ---------------- | -- | ------- | ---------------------------------------------- |
| `id`             | ✅  | string  | A UUID string identifying this Knowledge Base. |
| `embeddingModel` | ❌  | string  |                                                |
| `page`           | ❌  | integer | A page number within the paginated result set. |
| `pageSize`       | ❌  | integer | Number of results to return per page.          |
| `query`          | ❌  | string  |                                                |
| `rerankerModel`  | ❌  | string  |                                                |

#### 請求內容

**請求參數**

| 欄位            | 類型     | 必填 | 說明                                                                                                                                                                                                |
| ------------- | ------ | -- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| searchMode    | object | 否  | Search mode: hybrid (default, vector + BM25), semantic (vector only), keyword (BM25 only) `hybrid`: Hybrid (vector + BM25) ; `semantic`: Semantic (vector only) ; `keyword`: Keyword (BM25 only); |
| queryMetadata | object | 否  | 查詢元數據，用於控制搜尋範圍和方式                                                                                                                                                                                 |

**請求結構範例**

```typescript
{
  "searchMode"?:  // Search mode: hybrid (default, vector + BM25), semantic (vector only), keyword (BM25 only)

* `hybrid` - Hybrid (vector + BM25)
* `semantic` - Semantic (vector only)
* `keyword` - Keyword (BM25 only) (非必填)
  {
  }
  "queryMetadata"?: object // 查詢元數據，用於控制搜尋範圍和方式 (非必填)
}
```

**請求範例值**

```json
{
  "query": "如何使用API"
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/search/?embeddingModel=550e8400-e29b-41d4-a716-446655440000&page=1&pageSize=1&query=example&rerankerModel=550e8400-e29b-41d4-a716-446655440000" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "如何使用API"
  }'

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// 請求內容 (payload)
const data = {
    "query": "如何使用API"
  };

axios.post("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/search/?embeddingModel=550e8400-e29b-41d4-a716-446655440000&page=1&pageSize=1&query=example&rerankerModel=550e8400-e29b-41d4-a716-446655440000", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/search/?embeddingModel=550e8400-e29b-41d4-a716-446655440000&page=1&pageSize=1&query=example&rerankerModel=550e8400-e29b-41d4-a716-446655440000"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "query": "如何使用API"
}

response = requests.post(url, json=data, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/search/?embeddingModel=550e8400-e29b-41d4-a716-446655440000&page=1&pageSize=1&query=example&rerankerModel=550e8400-e29b-41d4-a716-446655440000", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'query' => '如何使用API'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "count": integer
  "next"?: string (uri) // 非必填
  "previous"?: string (uri) // 非必填
  "results": [
    {
      "id": string (uuid)
      "charactersCount": integer
      "hitsCount": integer
      "text": string
      "updatedAt": string (timestamp)
      "filename": string
      "chatbotFile": object // 返回 ChatbotFile 的完整資訊，包含檔案 URL 和類型，以支援前端圖片預覽
      "knowledgeBaseFile": object // 與 get_chatbot_file 相同，提供向後兼容
      "pageNumber": integer // Backward-compatible alias of ``page_start``.
      "pageStart": integer
      "pageEnd": integer
      "citationTitle": string // Source title shown on the inline citation hover card.
      "citationDescription": string // Source description shown on the inline citation hover card.
      "citationQuote": string // Quoted text snippet shown on the inline citation hover card.
      "hasImage": boolean // 判斷是否包含圖片（檢查檔案類型或 text 中的 Markdown 圖片）
      "imageUrl": string // 提取圖片 URL（優先使用檔案 URL，否則從 Markdown 提取）
      "displayText": string // 返回移除圖片 Markdown 標記的完整文字
      "displayTitle": string // 返回顯示標題（fallback: citation_title -> filename）
      "highlightedText": string // Return text with matched terms wrapped in ``<mark>`` tags.

Priority:
1. ES/OpenSearch native highlight (set by retrieve_api via ``_es_highlighted_text``)
2. Python regex fallback (keyword-based, works for all backends)
      "labels": [
        {
          "id": string (uuid)
          "name": string
        }
      ]
      "rawUserDefineMetadata"?: object // Metadata keys and values defined by the user. (非必填)
      "metadataEnabledForSearch": object // Map each user-defined metadata key on this node to whether it was sent into the LLM.

A key reaches the LLM only when its ``MetadataKey.enabled_for_search`` is True *and*
the node carries a value for it. Since this maps over ``raw_user_define_metadata``
(the keys the cited-documents block displays, all of which have a value),
``enabled_for_search`` alone decides the flag. The source of truth is the node's
knowledge base ``MetadataKey`` current setting, matching the AI Search indicator.
      "startCharIdx": integer // Character offset where this paragraph starts in its file's assembled text. Null inside message citations; a knowledge base file's text-node pages and search results carry a value.
      "endCharIdx": integer // Character offset where this paragraph ends in its file's assembled text. Null inside message citations; a knowledge base file's text-node pages and search results carry a value.
    }
  ]
}
```

**回應範例值**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "charactersCount": 456,
      "hitsCount": 456,
      "text": "回應字串",
      "updatedAt": "回應字串",
      "filename": "回應字串",
      "chatbotFile": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應範例名稱",
        "description": "回應範例描述"
      },
      "knowledgeBaseFile": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應範例名稱",
        "description": "回應範例描述"
      },
      "pageNumber": 456,
      "pageStart": 456,
      "pageEnd": 456,
      "citationTitle": "回應字串",
      "citationDescription": "回應字串",
      "citationQuote": "回應字串",
      "hasImage": false,
      "imageUrl": "回應字串",
      "displayText": "回應字串",
      "displayTitle": "回應字串",
      "highlightedText": "回應字串",
      "labels": [
        {
          "id": "550e8400-e29b-41d4-a716-446655440000",
          "name": "回應字串"
        }
      ],
      "rawUserDefineMetadata": null,
      "metadataEnabledForSearch": {
        "key1": "value1",
        "key2": "value2",
        "createdAt": "2025-01-01T00:00:00.000Z"
      },
      "startCharIdx": 456,
      "endCharIdx": 456
    }
  ]
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 更新知識庫 <a href="#knowledge-bases-update" id="knowledge-bases-update"></a>

PUT `/api/v1/knowledge-bases/{id}/`

#### 參數

| 參數名稱 | 必填 | 類型     | 說明                                             |
| ---- | -- | ------ | ---------------------------------------------- |
| `id` | ✅  | string | A UUID string identifying this Knowledge Base. |

#### 請求內容

**請求參數**

| 欄位                      | 類型              | 必填 | 說明                                                                                                                                                                                   |
| ----------------------- | --------------- | -- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| organization            | string (uuid)   | 否  |                                                                                                                                                                                      |
| embeddingModel          | string (uuid)   | 是  |                                                                                                                                                                                      |
| rerankerModel           | string (uuid)   | 是  |                                                                                                                                                                                      |
| name                    | string          | 是  |                                                                                                                                                                                      |
| description             | string          | 否  |                                                                                                                                                                                      |
| numberOfRetrievedChunks | integer         | 否  | 提取的參考資料數量，預設為 12，最小值為 1                                                                                                                                                              |
| enableHyde              | boolean         | 否  | 啟用 HyDE，預設為 False                                                                                                                                                                    |
| similarityCutoff        | number (double) | 否  | 相似度門檻，預設為 0.0，範圍為 0.0-1.0                                                                                                                                                            |
| enableRerank            | boolean         | 否  | 是否啟用重新排序，預設為 True                                                                                                                                                                    |
| enableRrf               | boolean         | 否  | Enable Reciprocal Rank Fusion for hybrid search. Disable this if using a custom Elasticsearch without enterprise license.                                                            |
| vectorDatabaseType      | object          | 否  | Type of vector database: elasticsearch or opensearch. `elasticsearch`: Elasticsearch ; `opensearch`: OpenSearch ; `oracle`: Oracle AI Database 26ai ; `synxdb`: SynxDB;              |
| vectorDatabaseUrl       | string          | 否  | Custom vector database endpoint URL or Oracle DSN. For Elasticsearch/OpenSearch: URL format (e.g., "<https://host:9200>"). For Oracle: DSN format (e.g., "host:1521/service\_name"). |
| vectorDatabaseApiKey    | string          | 否  | API Key for Elasticsearch. Not used for OpenSearch.                                                                                                                                  |
| opensearchUsername      | string          | 否  | Username for OpenSearch Basic Auth.                                                                                                                                                  |
| opensearchPassword      | string          | 否  | Password for OpenSearch Basic Auth.                                                                                                                                                  |
| oracleUser              | string          | 否  | Oracle database username.                                                                                                                                                            |
| oraclePassword          | string          | 否  | Oracle database password.                                                                                                                                                            |
| synxdbUser              | string          | 否  | SynxDB database username.                                                                                                                                                            |
| synxdbPassword          | string          | 否  | SynxDB database password.                                                                                                                                                            |
| chatbots                | array\[IdName]  | 否  |                                                                                                                                                                                      |
| groups                  | array\[IdName]  | 否  | 知識庫可存取的群組列表                                                                                                                                                                          |

**請求結構範例**

```typescript
{
  "organization"?: string (uuid) // 非必填
  "embeddingModel": string (uuid)
  "rerankerModel": string (uuid)
  "name": string
  "description"?: string // 非必填
  "numberOfRetrievedChunks"?: integer // 提取的參考資料數量，預設為 12，最小值為 1 (非必填)
  "enableHyde"?: boolean // 啟用 HyDE，預設為 False (非必填)
  "similarityCutoff"?: number (double) // 相似度門檻，預設為 0.0，範圍為 0.0-1.0 (非必填)
  "enableRerank"?: boolean // 是否啟用重新排序，預設為 True (非必填)
  "enableRrf"?: boolean // Enable Reciprocal Rank Fusion for hybrid search. Disable this if using a custom Elasticsearch without enterprise license. (非必填)
  "vectorDatabaseType"?:  // Type of vector database: elasticsearch or opensearch.

* `elasticsearch` - Elasticsearch
* `opensearch` - OpenSearch
* `oracle` - Oracle AI Database 26ai
* `synxdb` - SynxDB (非必填)
  {
  }
  "vectorDatabaseUrl"?: string // Custom vector database endpoint URL or Oracle DSN. For Elasticsearch/OpenSearch: URL format (e.g., "https://host:9200"). For Oracle: DSN format (e.g., "host:1521/service_name"). (非必填)
  "vectorDatabaseApiKey"?: string // API Key for Elasticsearch. Not used for OpenSearch. (非必填)
  "opensearchUsername"?: string // Username for OpenSearch Basic Auth. (非必填)
  "opensearchPassword"?: string // Password for OpenSearch Basic Auth. (非必填)
  "oracleUser"?: string // Oracle database username. (非必填)
  "oraclePassword"?: string // Oracle database password. (非必填)
  "synxdbUser"?: string // SynxDB database username. (非必填)
  "synxdbPassword"?: string // SynxDB database password. (非必填)
  "chatbots"?: [ // 非必填
    {
      "id": string (uuid)
    }
  ]
  "groups"?: [ // 知識庫可存取的群組列表 (非必填)
    {
      "id": string (uuid)
    }
  ]
}
```

**請求範例值**

```json
{
  "organization": "550e8400-e29b-41d4-a716-446655440000",
  "embeddingModel": "550e8400-e29b-41d4-a716-446655440000",
  "rerankerModel": "550e8400-e29b-41d4-a716-446655440000",
  "name": "範例名稱",
  "description": "範例字串",
  "numberOfRetrievedChunks": 123,
  "enableHyde": true,
  "similarityCutoff": 123,
  "enableRerank": true,
  "enableRrf": true,
  "vectorDatabaseType": {},
  "vectorDatabaseUrl": "範例字串",
  "vectorDatabaseApiKey": "範例字串",
  "opensearchUsername": "範例字串",
  "opensearchPassword": "範例字串",
  "oracleUser": "範例字串",
  "oraclePassword": "範例字串",
  "synxdbUser": "範例字串",
  "synxdbPassword": "範例字串",
  "chatbots": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000"
    }
  ],
  "groups": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000"
    }
  ]
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X PUT "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "organization": "550e8400-e29b-41d4-a716-446655440000",
    "embeddingModel": "550e8400-e29b-41d4-a716-446655440000",
    "rerankerModel": "550e8400-e29b-41d4-a716-446655440000",
    "name": "範例名稱",
    "description": "範例字串",
    "numberOfRetrievedChunks": 123,
    "enableHyde": true,
    "similarityCutoff": 123,
    "enableRerank": true,
    "enableRrf": true,
    "vectorDatabaseType": {},
    "vectorDatabaseUrl": "範例字串",
    "vectorDatabaseApiKey": "範例字串",
    "opensearchUsername": "範例字串",
    "opensearchPassword": "範例字串",
    "oracleUser": "範例字串",
    "oraclePassword": "範例字串",
    "synxdbUser": "範例字串",
    "synxdbPassword": "範例字串",
    "chatbots": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000"
      }
    ],
    "groups": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000"
      }
    ]
  }'

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// 請求內容 (payload)
const data = {
    "organization": "550e8400-e29b-41d4-a716-446655440000",
    "embeddingModel": "550e8400-e29b-41d4-a716-446655440000",
    "rerankerModel": "550e8400-e29b-41d4-a716-446655440000",
    "name": "範例名稱",
    "description": "範例字串",
    "numberOfRetrievedChunks": 123,
    "enableHyde": true,
    "similarityCutoff": 123,
    "enableRerank": true,
    "enableRrf": true,
    "vectorDatabaseType": {},
    "vectorDatabaseUrl": "範例字串",
    "vectorDatabaseApiKey": "範例字串",
    "opensearchUsername": "範例字串",
    "opensearchPassword": "範例字串",
    "oracleUser": "範例字串",
    "oraclePassword": "範例字串",
    "synxdbUser": "範例字串",
    "synxdbPassword": "範例字串",
    "chatbots": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000"
      }
    ],
    "groups": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000"
      }
    ]
  };

axios.put("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "organization": "550e8400-e29b-41d4-a716-446655440000",
    "embeddingModel": "550e8400-e29b-41d4-a716-446655440000",
    "rerankerModel": "550e8400-e29b-41d4-a716-446655440000",
    "name": "範例名稱",
    "description": "範例字串",
    "numberOfRetrievedChunks": 123,
    "enableHyde": True,
    "similarityCutoff": 123,
    "enableRerank": True,
    "enableRrf": True,
    "vectorDatabaseType": {},
    "vectorDatabaseUrl": "範例字串",
    "vectorDatabaseApiKey": "範例字串",
    "opensearchUsername": "範例字串",
    "opensearchPassword": "範例字串",
    "oracleUser": "範例字串",
    "oraclePassword": "範例字串",
    "synxdbUser": "範例字串",
    "synxdbPassword": "範例字串",
    "chatbots": [
        {
            "id": "550e8400-e29b-41d4-a716-446655440000"
        }
    ],
    "groups": [
        {
            "id": "550e8400-e29b-41d4-a716-446655440000"
        }
    ]
}

response = requests.put(url, json=data, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->put("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'organization' => '550e8400-e29b-41d4-a716-446655440000',
            'embeddingModel' => '550e8400-e29b-41d4-a716-446655440000',
            'rerankerModel' => '550e8400-e29b-41d4-a716-446655440000',
            'name' => '範例名稱',
            'description' => '範例字串',
            'numberOfRetrievedChunks' => 123,
            'enableHyde' => true,
            'similarityCutoff' => 123,
            'enableRerank' => true,
            'enableRrf' => true,
            'vectorDatabaseType' => new \stdClass(),
            'vectorDatabaseUrl' => '範例字串',
            'vectorDatabaseApiKey' => '範例字串',
            'opensearchUsername' => '範例字串',
            'opensearchPassword' => '範例字串',
            'oracleUser' => '範例字串',
            'oraclePassword' => '範例字串',
            'synxdbUser' => '範例字串',
            'synxdbPassword' => '範例字串',
            'chatbots' => [
                [
                    'id' => '550e8400-e29b-41d4-a716-446655440000'
                ]
            ],
            'groups' => [
                [
                    'id' => '550e8400-e29b-41d4-a716-446655440000'
                ]
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "createdBy": 
  {
    "id": string (uuid)
    "name": string
  }
  "organization"?: string (uuid) // 非必填
  "embeddingModel": string (uuid)
  "rerankerModel": string (uuid)
  "name": string
  "description"?: string // 非必填
  "numberOfRetrievedChunks"?: integer // 提取的參考資料數量，預設為 12，最小值為 1 (非必填)
  "enableHyde"?: boolean // 啟用 HyDE，預設為 False (非必填)
  "similarityCutoff"?: number (double) // 相似度門檻，預設為 0.0，範圍為 0.0-1.0 (非必填)
  "enableRerank"?: boolean // 是否啟用重新排序，預設為 True (非必填)
  "enableRrf"?: boolean // Enable Reciprocal Rank Fusion for hybrid search. Disable this if using a custom Elasticsearch without enterprise license. (非必填)
  "vectorDatabaseType"?:  // Type of vector database: elasticsearch or opensearch.

* `elasticsearch` - Elasticsearch
* `opensearch` - OpenSearch
* `oracle` - Oracle AI Database 26ai
* `synxdb` - SynxDB (非必填)
  {
  }
  "vectorDatabaseUrl"?: string // Custom vector database endpoint URL or Oracle DSN. For Elasticsearch/OpenSearch: URL format (e.g., "https://host:9200"). For Oracle: DSN format (e.g., "host:1521/service_name"). (非必填)
  "vectorDatabaseApiKey"?: string // API Key for Elasticsearch. Not used for OpenSearch. (非必填)
  "opensearchUsername"?: string // Username for OpenSearch Basic Auth. (非必填)
  "opensearchPassword"?: string // Password for OpenSearch Basic Auth. (非必填)
  "oracleUser"?: string // Oracle database username. (非必填)
  "oraclePassword"?: string // Oracle database password. (非必填)
  "synxdbUser"?: string // SynxDB database username. (非必填)
  "synxdbPassword"?: string // SynxDB database password. (非必填)
  "labels": [
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "chatbots"?: [ // 非必填
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "groups"?: [ // 知識庫可存取的群組列表 (非必填)
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "filesCount": integer // Return count of KnowledgeBaseFile excluding processed files, conversation attachments, and soft-deleted.
  "vectorStorageSize": integer
  "chunksCount": integer
  "canUpdate": boolean // Return whether the current user can update this resource.
  "canDelete": boolean // Return whether the current user can delete this resource.
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應字串"
  },
  "organization": "550e8400-e29b-41d4-a716-446655440000",
  "embeddingModel": "550e8400-e29b-41d4-a716-446655440000",
  "rerankerModel": "550e8400-e29b-41d4-a716-446655440000",
  "name": "回應字串",
  "description": "回應字串",
  "numberOfRetrievedChunks": 456,
  "enableHyde": false,
  "similarityCutoff": 456,
  "enableRerank": false,
  "enableRrf": false,
  "vectorDatabaseType": {},
  "vectorDatabaseUrl": "回應字串",
  "vectorDatabaseApiKey": "回應字串",
  "opensearchUsername": "回應字串",
  "opensearchPassword": "回應字串",
  "oracleUser": "回應字串",
  "oraclePassword": "回應字串",
  "synxdbUser": "回應字串",
  "synxdbPassword": "回應字串",
  "labels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ],
  "chatbots": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ],
  "groups": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ],
  "filesCount": 456,
  "vectorStorageSize": 456,
  "chunksCount": 456,
  "canUpdate": false,
  "canDelete": false,
  "createdAt": "回應字串",
  "updatedAt": "回應字串"
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 部分更新知識庫 <a href="#knowledge-bases-partial-update" id="knowledge-bases-partial-update"></a>

PATCH `/api/v1/knowledge-bases/{id}/`

#### 參數

| 參數名稱 | 必填 | 類型     | 說明                                             |
| ---- | -- | ------ | ---------------------------------------------- |
| `id` | ✅  | string | A UUID string identifying this Knowledge Base. |

#### 請求內容

**請求參數**

| 欄位                      | 類型              | 必填 | 說明                                                                                                                                                                                   |
| ----------------------- | --------------- | -- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| organization            | string (uuid)   | 否  |                                                                                                                                                                                      |
| embeddingModel          | string (uuid)   | 否  |                                                                                                                                                                                      |
| rerankerModel           | string (uuid)   | 否  |                                                                                                                                                                                      |
| name                    | string          | 否  |                                                                                                                                                                                      |
| description             | string          | 否  |                                                                                                                                                                                      |
| numberOfRetrievedChunks | integer         | 否  | 提取的參考資料數量，預設為 12，最小值為 1                                                                                                                                                              |
| enableHyde              | boolean         | 否  | 啟用 HyDE，預設為 False                                                                                                                                                                    |
| similarityCutoff        | number (double) | 否  | 相似度門檻，預設為 0.0，範圍為 0.0-1.0                                                                                                                                                            |
| enableRerank            | boolean         | 否  | 是否啟用重新排序，預設為 True                                                                                                                                                                    |
| enableRrf               | boolean         | 否  | Enable Reciprocal Rank Fusion for hybrid search. Disable this if using a custom Elasticsearch without enterprise license.                                                            |
| vectorDatabaseType      | object          | 否  | Type of vector database: elasticsearch or opensearch. `elasticsearch`: Elasticsearch ; `opensearch`: OpenSearch ; `oracle`: Oracle AI Database 26ai ; `synxdb`: SynxDB;              |
| vectorDatabaseUrl       | string          | 否  | Custom vector database endpoint URL or Oracle DSN. For Elasticsearch/OpenSearch: URL format (e.g., "<https://host:9200>"). For Oracle: DSN format (e.g., "host:1521/service\_name"). |
| vectorDatabaseApiKey    | string          | 否  | API Key for Elasticsearch. Not used for OpenSearch.                                                                                                                                  |
| opensearchUsername      | string          | 否  | Username for OpenSearch Basic Auth.                                                                                                                                                  |
| opensearchPassword      | string          | 否  | Password for OpenSearch Basic Auth.                                                                                                                                                  |
| oracleUser              | string          | 否  | Oracle database username.                                                                                                                                                            |
| oraclePassword          | string          | 否  | Oracle database password.                                                                                                                                                            |
| synxdbUser              | string          | 否  | SynxDB database username.                                                                                                                                                            |
| synxdbPassword          | string          | 否  | SynxDB database password.                                                                                                                                                            |
| chatbots                | array\[IdName]  | 否  |                                                                                                                                                                                      |
| groups                  | array\[IdName]  | 否  | 知識庫可存取的群組列表                                                                                                                                                                          |

**請求結構範例**

```typescript
{
  "organization"?: string (uuid) // 非必填
  "embeddingModel"?: string (uuid) // 非必填
  "rerankerModel"?: string (uuid) // 非必填
  "name"?: string // 非必填
  "description"?: string // 非必填
  "numberOfRetrievedChunks"?: integer // 提取的參考資料數量，預設為 12，最小值為 1 (非必填)
  "enableHyde"?: boolean // 啟用 HyDE，預設為 False (非必填)
  "similarityCutoff"?: number (double) // 相似度門檻，預設為 0.0，範圍為 0.0-1.0 (非必填)
  "enableRerank"?: boolean // 是否啟用重新排序，預設為 True (非必填)
  "enableRrf"?: boolean // Enable Reciprocal Rank Fusion for hybrid search. Disable this if using a custom Elasticsearch without enterprise license. (非必填)
  "vectorDatabaseType"?:  // Type of vector database: elasticsearch or opensearch.

* `elasticsearch` - Elasticsearch
* `opensearch` - OpenSearch
* `oracle` - Oracle AI Database 26ai
* `synxdb` - SynxDB (非必填)
  {
  }
  "vectorDatabaseUrl"?: string // Custom vector database endpoint URL or Oracle DSN. For Elasticsearch/OpenSearch: URL format (e.g., "https://host:9200"). For Oracle: DSN format (e.g., "host:1521/service_name"). (非必填)
  "vectorDatabaseApiKey"?: string // API Key for Elasticsearch. Not used for OpenSearch. (非必填)
  "opensearchUsername"?: string // Username for OpenSearch Basic Auth. (非必填)
  "opensearchPassword"?: string // Password for OpenSearch Basic Auth. (非必填)
  "oracleUser"?: string // Oracle database username. (非必填)
  "oraclePassword"?: string // Oracle database password. (非必填)
  "synxdbUser"?: string // SynxDB database username. (非必填)
  "synxdbPassword"?: string // SynxDB database password. (非必填)
  "chatbots"?: [ // 非必填
    {
      "id": string (uuid)
    }
  ]
  "groups"?: [ // 知識庫可存取的群組列表 (非必填)
    {
      "id": string (uuid)
    }
  ]
}
```

**請求範例值**

```json
{
  "organization": "550e8400-e29b-41d4-a716-446655440000",
  "embeddingModel": "550e8400-e29b-41d4-a716-446655440000",
  "rerankerModel": "550e8400-e29b-41d4-a716-446655440000",
  "name": "範例名稱",
  "description": "範例字串",
  "numberOfRetrievedChunks": 123,
  "enableHyde": true,
  "similarityCutoff": 123,
  "enableRerank": true,
  "enableRrf": true,
  "vectorDatabaseType": {},
  "vectorDatabaseUrl": "範例字串",
  "vectorDatabaseApiKey": "範例字串",
  "opensearchUsername": "範例字串",
  "opensearchPassword": "範例字串",
  "oracleUser": "範例字串",
  "oraclePassword": "範例字串",
  "synxdbUser": "範例字串",
  "synxdbPassword": "範例字串",
  "chatbots": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000"
    }
  ],
  "groups": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000"
    }
  ]
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X PATCH "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "organization": "550e8400-e29b-41d4-a716-446655440000",
    "embeddingModel": "550e8400-e29b-41d4-a716-446655440000",
    "rerankerModel": "550e8400-e29b-41d4-a716-446655440000",
    "name": "範例名稱",
    "description": "範例字串",
    "numberOfRetrievedChunks": 123,
    "enableHyde": true,
    "similarityCutoff": 123,
    "enableRerank": true,
    "enableRrf": true,
    "vectorDatabaseType": {},
    "vectorDatabaseUrl": "範例字串",
    "vectorDatabaseApiKey": "範例字串",
    "opensearchUsername": "範例字串",
    "opensearchPassword": "範例字串",
    "oracleUser": "範例字串",
    "oraclePassword": "範例字串",
    "synxdbUser": "範例字串",
    "synxdbPassword": "範例字串",
    "chatbots": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000"
      }
    ],
    "groups": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000"
      }
    ]
  }'

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// 請求內容 (payload)
const data = {
    "organization": "550e8400-e29b-41d4-a716-446655440000",
    "embeddingModel": "550e8400-e29b-41d4-a716-446655440000",
    "rerankerModel": "550e8400-e29b-41d4-a716-446655440000",
    "name": "範例名稱",
    "description": "範例字串",
    "numberOfRetrievedChunks": 123,
    "enableHyde": true,
    "similarityCutoff": 123,
    "enableRerank": true,
    "enableRrf": true,
    "vectorDatabaseType": {},
    "vectorDatabaseUrl": "範例字串",
    "vectorDatabaseApiKey": "範例字串",
    "opensearchUsername": "範例字串",
    "opensearchPassword": "範例字串",
    "oracleUser": "範例字串",
    "oraclePassword": "範例字串",
    "synxdbUser": "範例字串",
    "synxdbPassword": "範例字串",
    "chatbots": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000"
      }
    ],
    "groups": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000"
      }
    ]
  };

axios.patch("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "organization": "550e8400-e29b-41d4-a716-446655440000",
    "embeddingModel": "550e8400-e29b-41d4-a716-446655440000",
    "rerankerModel": "550e8400-e29b-41d4-a716-446655440000",
    "name": "範例名稱",
    "description": "範例字串",
    "numberOfRetrievedChunks": 123,
    "enableHyde": True,
    "similarityCutoff": 123,
    "enableRerank": True,
    "enableRrf": True,
    "vectorDatabaseType": {},
    "vectorDatabaseUrl": "範例字串",
    "vectorDatabaseApiKey": "範例字串",
    "opensearchUsername": "範例字串",
    "opensearchPassword": "範例字串",
    "oracleUser": "範例字串",
    "oraclePassword": "範例字串",
    "synxdbUser": "範例字串",
    "synxdbPassword": "範例字串",
    "chatbots": [
        {
            "id": "550e8400-e29b-41d4-a716-446655440000"
        }
    ],
    "groups": [
        {
            "id": "550e8400-e29b-41d4-a716-446655440000"
        }
    ]
}

response = requests.patch(url, json=data, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->patch("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'organization' => '550e8400-e29b-41d4-a716-446655440000',
            'embeddingModel' => '550e8400-e29b-41d4-a716-446655440000',
            'rerankerModel' => '550e8400-e29b-41d4-a716-446655440000',
            'name' => '範例名稱',
            'description' => '範例字串',
            'numberOfRetrievedChunks' => 123,
            'enableHyde' => true,
            'similarityCutoff' => 123,
            'enableRerank' => true,
            'enableRrf' => true,
            'vectorDatabaseType' => new \stdClass(),
            'vectorDatabaseUrl' => '範例字串',
            'vectorDatabaseApiKey' => '範例字串',
            'opensearchUsername' => '範例字串',
            'opensearchPassword' => '範例字串',
            'oracleUser' => '範例字串',
            'oraclePassword' => '範例字串',
            'synxdbUser' => '範例字串',
            'synxdbPassword' => '範例字串',
            'chatbots' => [
                [
                    'id' => '550e8400-e29b-41d4-a716-446655440000'
                ]
            ],
            'groups' => [
                [
                    'id' => '550e8400-e29b-41d4-a716-446655440000'
                ]
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "createdBy": 
  {
    "id": string (uuid)
    "name": string
  }
  "organization"?: string (uuid) // 非必填
  "embeddingModel": string (uuid)
  "rerankerModel": string (uuid)
  "name": string
  "description"?: string // 非必填
  "numberOfRetrievedChunks"?: integer // 提取的參考資料數量，預設為 12，最小值為 1 (非必填)
  "enableHyde"?: boolean // 啟用 HyDE，預設為 False (非必填)
  "similarityCutoff"?: number (double) // 相似度門檻，預設為 0.0，範圍為 0.0-1.0 (非必填)
  "enableRerank"?: boolean // 是否啟用重新排序，預設為 True (非必填)
  "enableRrf"?: boolean // Enable Reciprocal Rank Fusion for hybrid search. Disable this if using a custom Elasticsearch without enterprise license. (非必填)
  "vectorDatabaseType"?:  // Type of vector database: elasticsearch or opensearch.

* `elasticsearch` - Elasticsearch
* `opensearch` - OpenSearch
* `oracle` - Oracle AI Database 26ai
* `synxdb` - SynxDB (非必填)
  {
  }
  "vectorDatabaseUrl"?: string // Custom vector database endpoint URL or Oracle DSN. For Elasticsearch/OpenSearch: URL format (e.g., "https://host:9200"). For Oracle: DSN format (e.g., "host:1521/service_name"). (非必填)
  "vectorDatabaseApiKey"?: string // API Key for Elasticsearch. Not used for OpenSearch. (非必填)
  "opensearchUsername"?: string // Username for OpenSearch Basic Auth. (非必填)
  "opensearchPassword"?: string // Password for OpenSearch Basic Auth. (非必填)
  "oracleUser"?: string // Oracle database username. (非必填)
  "oraclePassword"?: string // Oracle database password. (非必填)
  "synxdbUser"?: string // SynxDB database username. (非必填)
  "synxdbPassword"?: string // SynxDB database password. (非必填)
  "labels": [
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "chatbots"?: [ // 非必填
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "groups"?: [ // 知識庫可存取的群組列表 (非必填)
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "filesCount": integer // Return count of KnowledgeBaseFile excluding processed files, conversation attachments, and soft-deleted.
  "vectorStorageSize": integer
  "chunksCount": integer
  "canUpdate": boolean // Return whether the current user can update this resource.
  "canDelete": boolean // Return whether the current user can delete this resource.
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應字串"
  },
  "organization": "550e8400-e29b-41d4-a716-446655440000",
  "embeddingModel": "550e8400-e29b-41d4-a716-446655440000",
  "rerankerModel": "550e8400-e29b-41d4-a716-446655440000",
  "name": "回應字串",
  "description": "回應字串",
  "numberOfRetrievedChunks": 456,
  "enableHyde": false,
  "similarityCutoff": 456,
  "enableRerank": false,
  "enableRrf": false,
  "vectorDatabaseType": {},
  "vectorDatabaseUrl": "回應字串",
  "vectorDatabaseApiKey": "回應字串",
  "opensearchUsername": "回應字串",
  "opensearchPassword": "回應字串",
  "oracleUser": "回應字串",
  "oraclePassword": "回應字串",
  "synxdbUser": "回應字串",
  "synxdbPassword": "回應字串",
  "labels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ],
  "chatbots": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ],
  "groups": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ],
  "filesCount": 456,
  "vectorStorageSize": 456,
  "chunksCount": 456,
  "canUpdate": false,
  "canDelete": false,
  "createdAt": "回應字串",
  "updatedAt": "回應字串"
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 刪除知識庫 <a href="#knowledge-bases-destroy" id="knowledge-bases-destroy"></a>

DELETE `/api/v1/knowledge-bases/{id}/`

#### 參數

| 參數名稱 | 必填 | 類型     | 說明                                             |
| ---- | -- | ------ | ---------------------------------------------- |
| `id` | ✅  | string | A UUID string identifying this Knowledge Base. |

#### 程式碼範例

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

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

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

// 請求內容 (payload)
const data = null;

axios.delete("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.delete(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->delete("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

| 狀態碼 | 說明                                                                 |
| --- | ------------------------------------------------------------------ |
| 204 | No response body                                                   |
| 4XX | Error response; X-Error-Code carries its code (see "Error codes"). |

***

### 檢查 RRF 可用性 <a href="#knowledge-bases-check-rrf-availability-retrieve" id="knowledge-bases-check-rrf-availability-retrieve"></a>

GET `/api/v1/knowledge-bases/{id}/check-rrf-availability/`

#### 參數

| 參數名稱 | 必填 | 類型     | 說明                                             |
| ---- | -- | ------ | ---------------------------------------------- |
| `id` | ✅  | string | A UUID string identifying this Knowledge Base. |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/check-rrf-availability/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/check-rrf-availability/", config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/check-rrf-availability/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/check-rrf-availability/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "createdBy": 
  {
    "id": string (uuid)
    "name": string
  }
  "organization"?: string (uuid) // 非必填
  "embeddingModel": string (uuid)
  "rerankerModel": string (uuid)
  "name": string
  "description"?: string // 非必填
  "numberOfRetrievedChunks"?: integer // 提取的參考資料數量，預設為 12，最小值為 1 (非必填)
  "enableHyde"?: boolean // 啟用 HyDE，預設為 False (非必填)
  "similarityCutoff"?: number (double) // 相似度門檻，預設為 0.0，範圍為 0.0-1.0 (非必填)
  "enableRerank"?: boolean // 是否啟用重新排序，預設為 True (非必填)
  "enableRrf"?: boolean // Enable Reciprocal Rank Fusion for hybrid search. Disable this if using a custom Elasticsearch without enterprise license. (非必填)
  "vectorDatabaseType"?:  // Type of vector database: elasticsearch or opensearch.

* `elasticsearch` - Elasticsearch
* `opensearch` - OpenSearch
* `oracle` - Oracle AI Database 26ai
* `synxdb` - SynxDB (非必填)
  {
  }
  "vectorDatabaseUrl"?: string // Custom vector database endpoint URL or Oracle DSN. For Elasticsearch/OpenSearch: URL format (e.g., "https://host:9200"). For Oracle: DSN format (e.g., "host:1521/service_name"). (非必填)
  "vectorDatabaseApiKey"?: string // API Key for Elasticsearch. Not used for OpenSearch. (非必填)
  "opensearchUsername"?: string // Username for OpenSearch Basic Auth. (非必填)
  "opensearchPassword"?: string // Password for OpenSearch Basic Auth. (非必填)
  "oracleUser"?: string // Oracle database username. (非必填)
  "oraclePassword"?: string // Oracle database password. (非必填)
  "synxdbUser"?: string // SynxDB database username. (非必填)
  "synxdbPassword"?: string // SynxDB database password. (非必填)
  "labels": [
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "chatbots"?: [ // 非必填
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "groups"?: [ // 知識庫可存取的群組列表 (非必填)
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "filesCount": integer // Return count of KnowledgeBaseFile excluding processed files, conversation attachments, and soft-deleted.
  "vectorStorageSize": integer
  "chunksCount": integer
  "canUpdate": boolean // Return whether the current user can update this resource.
  "canDelete": boolean // Return whether the current user can delete this resource.
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應字串"
  },
  "organization": "550e8400-e29b-41d4-a716-446655440000",
  "embeddingModel": "550e8400-e29b-41d4-a716-446655440000",
  "rerankerModel": "550e8400-e29b-41d4-a716-446655440000",
  "name": "回應字串",
  "description": "回應字串",
  "numberOfRetrievedChunks": 456,
  "enableHyde": false,
  "similarityCutoff": 456,
  "enableRerank": false,
  "enableRrf": false,
  "vectorDatabaseType": {},
  "vectorDatabaseUrl": "回應字串",
  "vectorDatabaseApiKey": "回應字串",
  "opensearchUsername": "回應字串",
  "opensearchPassword": "回應字串",
  "oracleUser": "回應字串",
  "oraclePassword": "回應字串",
  "synxdbUser": "回應字串",
  "synxdbPassword": "回應字串",
  "labels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ],
  "chatbots": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ],
  "groups": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ],
  "filesCount": 456,
  "vectorStorageSize": 456,
  "chunksCount": 456,
  "canUpdate": false,
  "canDelete": false,
  "createdAt": "回應字串",
  "updatedAt": "回應字串"
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 匯出標籤 Excel <a href="#knowledge-bases-export-labels-excel-retrieve" id="knowledge-bases-export-labels-excel-retrieve"></a>

GET `/api/v1/knowledge-bases/{id}/export-labels-excel/`

#### 參數

| 參數名稱 | 必填 | 類型     | 說明                                             |
| ---- | -- | ------ | ---------------------------------------------- |
| `id` | ✅  | string | A UUID string identifying this Knowledge Base. |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/export-labels-excel/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/export-labels-excel/", config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/export-labels-excel/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/export-labels-excel/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

| 狀態碼 | 說明                                                                 |
| --- | ------------------------------------------------------------------ |
| 200 | Excel file download                                                |
| 4XX | Error response; X-Error-Code carries its code (see "Error codes"). |

***

### 匯入標籤 Excel <a href="#knowledge-bases-import-labels-excel-create" id="knowledge-bases-import-labels-excel-create"></a>

POST `/api/v1/knowledge-bases/{id}/import-labels-excel/`

#### 參數

| 參數名稱 | 必填 | 類型     | 說明                                             |
| ---- | -- | ------ | ---------------------------------------------- |
| `id` | ✅  | string | A UUID string identifying this Knowledge Base. |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/import-labels-excel/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -F "excelFile=@example_file.txt"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');
const FormData = require('form-data');

// 建立FormData對象
const formData = new FormData();
// 請用實際檔案替換
formData.append('excelFile', /* 實際檔案物件 */, 'example_file.txt');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    ...formData.getHeaders()
  }
};

axios.post("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/import-labels-excel/", formData, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/import-labels-excel/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}

# 建立檔案和表單資料
files = {
    'excelFile': ('example_file.txt', open('example_file.txt', 'rb'), 'text/plain')
}

response = requests.post(url, files=files, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/import-labels-excel/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ],
        'multipart' => [
            [
                'name' => 'excelFile',
                'contents' => fopen('example_file.txt', 'r'),
                'filename' => 'example_file.txt'
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "success"?: boolean // 非必填
  "updated_count"?: integer // 非必填
  "total_rows"?: integer // 非必填
  "errors"?: [ // 非必填
    {
      "row"?: integer // 非必填
      "file_id"?: string // 非必填
      "error"?: string // 非必填
    }
  ]
}
```

**回應範例值**

```json
{
  "success": false,
  "updated_count": 456,
  "total_rows": 456,
  "errors": [
    {
      "row": 456,
      "file_id": "回應字串",
      "error": "回應字串"
    }
  ]
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 匯出元資料 Excel <a href="#knowledge-bases-export-metadata-excel-retrieve" id="knowledge-bases-export-metadata-excel-retrieve"></a>

GET `/api/v1/knowledge-bases/{id}/export-metadata-excel/`

#### 參數

| 參數名稱 | 必填 | 類型     | 說明                                             |
| ---- | -- | ------ | ---------------------------------------------- |
| `id` | ✅  | string | A UUID string identifying this Knowledge Base. |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/export-metadata-excel/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/export-metadata-excel/", config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/export-metadata-excel/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/export-metadata-excel/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

| 狀態碼 | 說明                                                                 |
| --- | ------------------------------------------------------------------ |
| 200 | Excel 檔案下載                                                         |
| 4XX | Error response; X-Error-Code carries its code (see "Error codes"). |

***

### 匯入元資料 Excel <a href="#knowledge-bases-import-metadata-excel-create" id="knowledge-bases-import-metadata-excel-create"></a>

POST `/api/v1/knowledge-bases/{id}/import-metadata-excel/`

#### 參數

| 參數名稱 | 必填 | 類型     | 說明                                             |
| ---- | -- | ------ | ---------------------------------------------- |
| `id` | ✅  | string | A UUID string identifying this Knowledge Base. |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/import-metadata-excel/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -F "excelFile=@example_file.txt"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');
const FormData = require('form-data');

// 建立FormData對象
const formData = new FormData();
// 請用實際檔案替換
formData.append('excelFile', /* 實際檔案物件 */, 'example_file.txt');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    ...formData.getHeaders()
  }
};

axios.post("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/import-metadata-excel/", formData, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/import-metadata-excel/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}

# 建立檔案和表單資料
files = {
    'excelFile': ('example_file.txt', open('example_file.txt', 'rb'), 'text/plain')
}

response = requests.post(url, files=files, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/import-metadata-excel/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ],
        'multipart' => [
            [
                'name' => 'excelFile',
                'contents' => fopen('example_file.txt', 'r'),
                'filename' => 'example_file.txt'
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "success"?: boolean // 非必填
  "updated_count"?: integer // 非必填
  "total_rows"?: integer // 非必填
  "errors"?: [ // 非必填
    {
      "row"?: integer // 非必填
      "file_id"?: string // 非必填
      "error"?: string // 非必填
    }
  ]
}
```

**回應範例值**

```json
{
  "success": false,
  "updated_count": 456,
  "total_rows": 456,
  "errors": [
    {
      "row": 456,
      "file_id": "回應字串",
      "error": "回應字串"
    }
  ]
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 建立新標籤 <a href="#knowledge-bases-labels-create" id="knowledge-bases-labels-create"></a>

POST `/api/v1/knowledge-bases/{knowledgeBasePk}/labels/`

#### 參數

| 參數名稱              | 必填 | 類型     | 說明 |
| ----------------- | -- | ------ | -- |
| `knowledgeBasePk` | ✅  | string |    |

#### 請求內容

**請求參數**

| 欄位   | 類型     | 必填 | 說明 |
| ---- | ------ | -- | -- |
| name | string | 是  |    |

**請求結構範例**

```typescript
{
  "name": string
}
```

**請求範例值**

```json
{
  "name": "範例名稱"
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/labels/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "範例名稱"
  }'

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// 請求內容 (payload)
const data = {
    "name": "範例名稱"
  };

axios.post("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/labels/", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/labels/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "name": "範例名稱"
}

response = requests.post(url, json=data, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/labels/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'name' => '範例名稱'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 201**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "name"?: string // 非必填
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "回應字串"
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 列出知識庫中的標籤 <a href="#knowledge-bases-labels-list" id="knowledge-bases-labels-list"></a>

GET `/api/v1/knowledge-bases/{knowledgeBasePk}/labels/`

#### 參數

| 參數名稱              | 必填 | 類型      | 說明                                             |
| ----------------- | -- | ------- | ---------------------------------------------- |
| `knowledgeBasePk` | ✅  | string  |                                                |
| `page`            | ❌  | integer | A page number within the paginated result set. |
| `pageSize`        | ❌  | integer | Number of results to return per page.          |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/labels/?page=1&pageSize=1" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/labels/?page=1&pageSize=1", config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/labels/?page=1&pageSize=1"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/labels/?page=1&pageSize=1", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "count": integer
  "next"?: string (uri) // 非必填
  "previous"?: string (uri) // 非必填
  "results": [
    {
      "id": string (uuid)
      "name"?: string // 非必填
    }
  ]
}
```

**回應範例值**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ]
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 取得特定標籤詳情 <a href="#knowledge-bases-labels-retrieve" id="knowledge-bases-labels-retrieve"></a>

GET `/api/v1/knowledge-bases/{knowledgeBasePk}/labels/{id}/`

#### 參數

| 參數名稱              | 必填 | 類型     | 說明                                                   |
| ----------------- | -- | ------ | ---------------------------------------------------- |
| `id`              | ✅  | string | A UUID string identifying this knowledge base label. |
| `knowledgeBasePk` | ✅  | string |                                                      |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/labels/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/labels/550e8400-e29b-41d4-a716-446655440000/", config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/labels/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/labels/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "name"?: string // 非必填
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "回應字串"
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 更新標籤 <a href="#knowledge-bases-labels-update" id="knowledge-bases-labels-update"></a>

PUT `/api/v1/knowledge-bases/{knowledgeBasePk}/labels/{id}/`

#### 參數

| 參數名稱              | 必填 | 類型     | 說明                                                   |
| ----------------- | -- | ------ | ---------------------------------------------------- |
| `id`              | ✅  | string | A UUID string identifying this knowledge base label. |
| `knowledgeBasePk` | ✅  | string |                                                      |

#### 請求內容

**請求參數**

| 欄位   | 類型     | 必填 | 說明 |
| ---- | ------ | -- | -- |
| name | string | 是  |    |

**請求結構範例**

```typescript
{
  "name": string
}
```

**請求範例值**

```json
{
  "name": "範例名稱"
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X PUT "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/labels/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "範例名稱"
  }'

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// 請求內容 (payload)
const data = {
    "name": "範例名稱"
  };

axios.put("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/labels/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/labels/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "name": "範例名稱"
}

response = requests.put(url, json=data, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->put("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/labels/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'name' => '範例名稱'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "name"?: string // 非必填
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "回應字串"
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 部分更新標籤 <a href="#knowledge-bases-labels-partial-update" id="knowledge-bases-labels-partial-update"></a>

PATCH `/api/v1/knowledge-bases/{knowledgeBasePk}/labels/{id}/`

#### 參數

| 參數名稱              | 必填 | 類型     | 說明                                                   |
| ----------------- | -- | ------ | ---------------------------------------------------- |
| `id`              | ✅  | string | A UUID string identifying this knowledge base label. |
| `knowledgeBasePk` | ✅  | string |                                                      |

#### 請求內容

**請求參數**

| 欄位   | 類型     | 必填 | 說明 |
| ---- | ------ | -- | -- |
| name | string | 否  |    |

**請求結構範例**

```typescript
{
  "name"?: string // 非必填
}
```

**請求範例值**

```json
{
  "name": "範例名稱"
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X PATCH "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/labels/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "範例名稱"
  }'

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// 請求內容 (payload)
const data = {
    "name": "範例名稱"
  };

axios.patch("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/labels/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/labels/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "name": "範例名稱"
}

response = requests.patch(url, json=data, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->patch("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/labels/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'name' => '範例名稱'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "name"?: string // 非必填
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "回應字串"
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 刪除標籤 <a href="#knowledge-bases-labels-destroy" id="knowledge-bases-labels-destroy"></a>

DELETE `/api/v1/knowledge-bases/{knowledgeBasePk}/labels/{id}/`

#### 參數

| 參數名稱              | 必填 | 類型     | 說明                                                   |
| ----------------- | -- | ------ | ---------------------------------------------------- |
| `id`              | ✅  | string | A UUID string identifying this knowledge base label. |
| `knowledgeBasePk` | ✅  | string |                                                      |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X DELETE "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/labels/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

// 請求內容 (payload)
const data = null;

axios.delete("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/labels/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/labels/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.delete(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->delete("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/labels/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

| 狀態碼 | 說明                                                                 |
| --- | ------------------------------------------------------------------ |
| 204 | No response body                                                   |
| 4XX | Error response; X-Error-Code carries its code (see "Error codes"). |

***

### 建立元資料欄位 <a href="#knowledge-bases-metadata-keys-create" id="knowledge-bases-metadata-keys-create"></a>

POST `/api/v1/knowledge-bases/{knowledgeBasePk}/metadata-keys/`

#### 參數

| 參數名稱              | 必填 | 類型     | 說明 |
| ----------------- | -- | ------ | -- |
| `knowledgeBasePk` | ✅  | string |    |

#### 請求內容

**請求參數**

| 欄位               | 類型      | 必填 | 說明                                          |
| ---------------- | ------- | -- | ------------------------------------------- |
| keyName          | string  | 是  | Metadata key name                           |
| description      | string  | 否  | What this column is used for                |
| isRequired       | boolean | 否  | Whether this column is required             |
| defaultValue     | string  | 否  | Default value for new files                 |
| enabledForSearch | boolean | 否  | Whether this field is used during retrieval |

**請求結構範例**

```typescript
{
  "keyName": string // Metadata key name
  "description"?: string // What this column is used for (非必填)
  "isRequired"?: boolean // Whether this column is required (非必填)
  "defaultValue"?: string // Default value for new files (非必填)
  "enabledForSearch"?: boolean // Whether this field is used during retrieval (非必填)
}
```

**請求範例值**

```json
{
  "keyName": "範例字串",
  "description": "範例字串",
  "isRequired": true,
  "defaultValue": "範例字串",
  "enabledForSearch": true
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/metadata-keys/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "keyName": "範例字串",
    "description": "範例字串",
    "isRequired": true,
    "defaultValue": "範例字串",
    "enabledForSearch": true
  }'

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// 請求內容 (payload)
const data = {
    "keyName": "範例字串",
    "description": "範例字串",
    "isRequired": true,
    "defaultValue": "範例字串",
    "enabledForSearch": true
  };

axios.post("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/metadata-keys/", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/metadata-keys/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "keyName": "範例字串",
    "description": "範例字串",
    "isRequired": True,
    "defaultValue": "範例字串",
    "enabledForSearch": True
}

response = requests.post(url, json=data, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/metadata-keys/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'keyName' => '範例字串',
            'description' => '範例字串',
            'isRequired' => true,
            'defaultValue' => '範例字串',
            'enabledForSearch' => true
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 201**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "knowledgeBase": 
  {
    "id": string (uuid)
    "name": string
  }
  "keyName": string // Metadata key name
  "keyType":  // Set automatically from the column name (system column or custom column)

* `system` - System
* `custom` - Custom
  {
  }
  "description"?: string // What this column is used for (非必填)
  "isRequired"?: boolean // Whether this column is required (非必填)
  "defaultValue"?: string // Default value for new files (非必填)
  "enabledForSearch"?: boolean // Whether this field is used during retrieval (非必填)
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "knowledgeBase": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應字串"
  },
  "keyName": "回應字串",
  "keyType": {},
  "description": "回應字串",
  "isRequired": false,
  "defaultValue": "回應字串",
  "enabledForSearch": false,
  "createdAt": "回應字串",
  "updatedAt": "回應字串"
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 列出元資料欄位 <a href="#knowledge-bases-metadata-keys-list" id="knowledge-bases-metadata-keys-list"></a>

GET `/api/v1/knowledge-bases/{knowledgeBasePk}/metadata-keys/`

#### 參數

| 參數名稱              | 必填 | 類型      | 說明                                                                     |
| ----------------- | -- | ------- | ---------------------------------------------------------------------- |
| `knowledgeBasePk` | ✅  | string  |                                                                        |
| `page`            | ❌  | integer | A page number within the paginated result set.                         |
| `pageSize`        | ❌  | integer | Number of results to return per page.                                  |
| `pagination`      | ❌  | boolean | Set to false to return all keys without pagination (defaults to true). |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/metadata-keys/?page=1&pageSize=1&pagination=true" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/metadata-keys/?page=1&pageSize=1&pagination=true", config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/metadata-keys/?page=1&pageSize=1&pagination=true"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/metadata-keys/?page=1&pageSize=1&pagination=true", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "count": integer
  "next"?: string (uri) // 非必填
  "previous"?: string (uri) // 非必填
  "results": [
    {
      "id": string (uuid)
      "knowledgeBase": 
      {
        "id": string (uuid)
        "name": string
      }
      "keyName": string // Metadata key name
      "keyType":  // Set automatically from the column name (system column or custom column)

* `system` - System
* `custom` - Custom
      {
      }
      "description"?: string // What this column is used for (非必填)
      "isRequired"?: boolean // Whether this column is required (非必填)
      "defaultValue"?: string // Default value for new files (非必填)
      "enabledForSearch"?: boolean // Whether this field is used during retrieval (非必填)
      "createdAt": string (timestamp)
      "updatedAt": string (timestamp)
    }
  ]
}
```

**回應範例值**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "knowledgeBase": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應字串"
      },
      "keyName": "回應字串",
      "keyType": {},
      "description": "回應字串",
      "isRequired": false,
      "defaultValue": "回應字串",
      "enabledForSearch": false,
      "createdAt": "回應字串",
      "updatedAt": "回應字串"
    }
  ]
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 取得特定元資料欄位 <a href="#knowledge-bases-metadata-keys-retrieve" id="knowledge-bases-metadata-keys-retrieve"></a>

GET `/api/v1/knowledge-bases/{knowledgeBasePk}/metadata-keys/{id}/`

#### 參數

| 參數名稱              | 必填 | 類型     | 說明                                           |
| ----------------- | -- | ------ | -------------------------------------------- |
| `id`              | ✅  | string | A UUID string identifying this Metadata Key. |
| `knowledgeBasePk` | ✅  | string |                                              |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/metadata-keys/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/metadata-keys/550e8400-e29b-41d4-a716-446655440000/", config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/metadata-keys/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/metadata-keys/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "knowledgeBase": 
  {
    "id": string (uuid)
    "name": string
  }
  "keyName": string // Metadata key name
  "keyType":  // Set automatically from the column name (system column or custom column)

* `system` - System
* `custom` - Custom
  {
  }
  "description"?: string // What this column is used for (非必填)
  "isRequired"?: boolean // Whether this column is required (非必填)
  "defaultValue"?: string // Default value for new files (非必填)
  "enabledForSearch"?: boolean // Whether this field is used during retrieval (非必填)
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "knowledgeBase": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應字串"
  },
  "keyName": "回應字串",
  "keyType": {},
  "description": "回應字串",
  "isRequired": false,
  "defaultValue": "回應字串",
  "enabledForSearch": false,
  "createdAt": "回應字串",
  "updatedAt": "回應字串"
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 更新元資料欄位 <a href="#knowledge-bases-metadata-keys-update" id="knowledge-bases-metadata-keys-update"></a>

PUT `/api/v1/knowledge-bases/{knowledgeBasePk}/metadata-keys/{id}/`

#### 參數

| 參數名稱              | 必填 | 類型     | 說明                                           |
| ----------------- | -- | ------ | -------------------------------------------- |
| `id`              | ✅  | string | A UUID string identifying this Metadata Key. |
| `knowledgeBasePk` | ✅  | string |                                              |

#### 請求內容

**請求參數**

| 欄位               | 類型      | 必填 | 說明                                          |
| ---------------- | ------- | -- | ------------------------------------------- |
| keyName          | string  | 是  | Metadata key name                           |
| description      | string  | 否  | What this column is used for                |
| isRequired       | boolean | 否  | Whether this column is required             |
| defaultValue     | string  | 否  | Default value for new files                 |
| enabledForSearch | boolean | 否  | Whether this field is used during retrieval |

**請求結構範例**

```typescript
{
  "keyName": string // Metadata key name
  "description"?: string // What this column is used for (非必填)
  "isRequired"?: boolean // Whether this column is required (非必填)
  "defaultValue"?: string // Default value for new files (非必填)
  "enabledForSearch"?: boolean // Whether this field is used during retrieval (非必填)
}
```

**請求範例值**

```json
{
  "keyName": "範例字串",
  "description": "範例字串",
  "isRequired": true,
  "defaultValue": "範例字串",
  "enabledForSearch": true
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X PUT "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/metadata-keys/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "keyName": "範例字串",
    "description": "範例字串",
    "isRequired": true,
    "defaultValue": "範例字串",
    "enabledForSearch": true
  }'

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// 請求內容 (payload)
const data = {
    "keyName": "範例字串",
    "description": "範例字串",
    "isRequired": true,
    "defaultValue": "範例字串",
    "enabledForSearch": true
  };

axios.put("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/metadata-keys/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/metadata-keys/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "keyName": "範例字串",
    "description": "範例字串",
    "isRequired": True,
    "defaultValue": "範例字串",
    "enabledForSearch": True
}

response = requests.put(url, json=data, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->put("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/metadata-keys/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'keyName' => '範例字串',
            'description' => '範例字串',
            'isRequired' => true,
            'defaultValue' => '範例字串',
            'enabledForSearch' => true
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "knowledgeBase": 
  {
    "id": string (uuid)
    "name": string
  }
  "keyName": string // Metadata key name
  "keyType":  // Set automatically from the column name (system column or custom column)

* `system` - System
* `custom` - Custom
  {
  }
  "description"?: string // What this column is used for (非必填)
  "isRequired"?: boolean // Whether this column is required (非必填)
  "defaultValue"?: string // Default value for new files (非必填)
  "enabledForSearch"?: boolean // Whether this field is used during retrieval (非必填)
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "knowledgeBase": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應字串"
  },
  "keyName": "回應字串",
  "keyType": {},
  "description": "回應字串",
  "isRequired": false,
  "defaultValue": "回應字串",
  "enabledForSearch": false,
  "createdAt": "回應字串",
  "updatedAt": "回應字串"
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 上傳檔案到知識庫 <a href="#knowledge-bases-files-create" id="knowledge-bases-files-create"></a>

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

#### 參數

| 參數名稱              | 必填 | 類型      | 說明                                                                                                                                                                                                                     |
| ----------------- | -- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `knowledgeBasePk` | ✅  | string  |                                                                                                                                                                                                                        |
| `fileType`        | ❌  | string  | 檔案類型過濾，例如：pdf、docx、txt、xlsx 等                                                                                                                                                                                          |
| `knowledgeBase`   | ❌  | string  | 知識庫 ID                                                                                                                                                                                                                 |
| `page`            | ❌  | integer | A page number within the paginated result set.                                                                                                                                                                         |
| `pageSize`        | ❌  | integer | Number of results to return per page.                                                                                                                                                                                  |
| `query`           | ❌  | string  | 搜尋關鍵字，支援空白分隔的多條件查詢。可搜尋：檔案 ID、檔案名稱、標籤名稱、Metadata value                                                                                                                                                                  |
| `status`          | ❌  | string  | 檔案狀態過濾，可選值：initial（初始化）、processing（處理中）、done（完成）、deleting（刪除中）、deleted（已刪除）、failed（失敗） \`initial\`: Initial ; \`processing\`: Processing ; \`done\`: Done ; \`deleting\`: Deleting ; \`deleted\`: Deleted ; \`faile... |

#### 請求內容

**請求參數**

| 欄位    | 類型                              | 必填 | 說明                                              |
| ----- | ------------------------------- | -- | ----------------------------------------------- |
| files | array\[KnowledgeBaseFileCreate] | 是  | Supports uploading multiple files in one batch. |

**請求結構範例**

```typescript
{
  "files": [ // Supports uploading multiple files in one batch.
    {
      "filename": string // 檔案名稱
      "file": string (uri) // 要上傳的檔案
      "parser"?: string (uuid) // 非必填
      "labels"?: [ // 非必填
        {
          "id": string (uuid)
        }
      ]
      "rawUserDefineMetadata"?: object // 非必填
      "asrOptions"?: object // Per-file canonical transcription options (languages, prompt, diarization). Empty means no per-file options: provider defaults apply. Completely decoupled from user-defined metadata; never indexed for search. (非必填)
    }
  ]
}
```

**請求範例值**

```json
{
  "files": [
    {
      "filename": "my-file.pdf",
      "file": "string",
      "parser": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      "labels": [
        {
          "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
          "name": "my-label"
        }
      ],
      "rawUserDefineMetadata": {
        "key1": "value1",
        "key2": "value2"
      }
    },
    {
      "filename": "you-can-upload-multiple-files.pdf",
      "file": "string",
      "parser": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
    }
  ]
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/?fileType=example&knowledgeBase=550e8400-e29b-41d4-a716-446655440000&page=1&pageSize=1&query=example&status=delete_failed" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "files": [
      {
        "filename": "my-file.pdf",
        "file": "string",
        "parser": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
        "labels": [
          {
            "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
            "name": "my-label"
          }
        ],
        "rawUserDefineMetadata": {
          "key1": "value1",
          "key2": "value2"
        }
      },
      {
        "filename": "you-can-upload-multiple-files.pdf",
        "file": "string",
        "parser": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
      }
    ]
  }'

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// 請求內容 (payload)
const data = {
    "files": [
      {
        "filename": "my-file.pdf",
        "file": "string",
        "parser": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
        "labels": [
          {
            "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
            "name": "my-label"
          }
        ],
        "rawUserDefineMetadata": {
          "key1": "value1",
          "key2": "value2"
        }
      },
      {
        "filename": "you-can-upload-multiple-files.pdf",
        "file": "string",
        "parser": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
      }
    ]
  };

axios.post("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/?fileType=example&knowledgeBase=550e8400-e29b-41d4-a716-446655440000&page=1&pageSize=1&query=example&status=delete_failed", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/?fileType=example&knowledgeBase=550e8400-e29b-41d4-a716-446655440000&page=1&pageSize=1&query=example&status=delete_failed"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "files": [
        {
            "filename": "my-file.pdf",
            "file": "string",
            "parser": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
            "labels": [
                {
                    "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
                    "name": "my-label"
                }
            ],
            "rawUserDefineMetadata": {
                "key1": "value1",
                "key2": "value2"
            }
        },
        {
            "filename": "you-can-upload-multiple-files.pdf",
            "file": "string",
            "parser": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
        }
    ]
}

response = requests.post(url, json=data, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/?fileType=example&knowledgeBase=550e8400-e29b-41d4-a716-446655440000&page=1&pageSize=1&query=example&status=delete_failed", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'files' => [
                [
                    'filename' => 'my-file.pdf',
                    'file' => 'string',
                    'parser' => '3fa85f64-5717-4562-b3fc-2c963f66afa6',
                    'labels' => [
                        [
                            'id' => '3fa85f64-5717-4562-b3fc-2c963f66afa6',
                            'name' => 'my-label'
                        ]
                    ],
                    'rawUserDefineMetadata' => [
                        'key1' => 'value1',
                        'key2' => 'value2'
                    ]
                ],
                [
                    'filename' => 'you-can-upload-multiple-files.pdf',
                    'file' => 'string',
                    'parser' => '3fa85f64-5717-4562-b3fc-2c963f66afa6'
                ]
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 201**

**回應結構範例**

```typescript
{
  "count": integer
  "next"?: string (uri) // 非必填
  "previous"?: string (uri) // 非必填
  "results": [
    {
      "id": string (uuid)
      "filename": string // 檔案名稱
      "file": string (uri) // 要上傳的檔案
      "fileType": string
      "knowledgeBase"?:  // 非必填
      {
        "id": string (uuid)
        "name": string
      }
      "size": integer // File size in bytes
      "status": 
      {
      }
      "parser": 
      {
        "id": string (uuid)
        "name": string
        "provider": string (enum: maiagent, llama, azure, docling, whisper_groq, whisper_openai, whisper_offline, localai, anthropic, bronci, alibaba, rap, vertex, cohere) // * `maiagent` - MaiAgent
* `llama` - Llama
* `azure` - Azure
* `docling` - Docling
* `whisper_groq` - WhisperGroq
* `whisper_openai` - WhisperOpenAI
* `whisper_offline` - WhisperOffline
* `localai` - LocalAI
* `anthropic` - Anthropic
* `bronci` - Bronci
* `alibaba` - Alibaba Qwen
* `rap` - Taiwan AI RAP
* `vertex` - Vertex AI
* `cohere` - Cohere
        "isTimestampSttProvider": boolean
      }
      "labels"?: [ // 非必填
        {
          "id": string (uuid)
          "name": string
        }
      ]
      "rawUserDefineMetadata"?: object // 非必填
      "speakerLabels": [
        {
          "id": string (uuid)
          "originalLabel": string // Original speaker label from diarization (e.g., SPEAKER_00)
          "customName"?: string // User-defined speaker name (e.g., John) (非必填)
          "displayName": string
        }
      ]
      "vectorStorageSize": integer // Size of vectors for this file in Elasticsearch (bytes)
      "chunksCount": integer // Number of chunks/nodes generated from this file
      "waitingTime": number (double)
      "processingTime": number (double)
      "processingTimeDetails": object
      "ocrStatus": string // 掃描頁 OCR 結果：done、skipped、partial、off；解析前或舊檔案為 null
      "ocrSkippedReason": string // 掃描頁沒做 OCR 的原因：no_azure_settings、azure_unavailable、insufficient_credits、transient_error、time_budget、disabled；有做完時為 null
      "visualAnalysis": object // 影片畫面分析結果：status 為 completed 或 incomplete，reason 是未完成原因（model_error、timeout、video_unreadable、model_not_vision、no_describable_content），frame_cap_reached 表示畫面張數達上限；沒做過畫面分析的檔案為 null
      "parserAutoDetection":  // 自動偵測替這份檔選解析器的結果與原因；使用者自己選的、上線前上傳的、重新判斷排隊中的檔為 null
      {
        "parser":  // 自動偵測選到的解析器
        {
          "id": string (uuid)
          "name": string
          "provider": string (enum: maiagent, llama, azure, docling, whisper_groq, whisper_openai, whisper_offline, localai, anthropic, bronci, alibaba, rap, vertex, cohere) // * `maiagent` - MaiAgent
* `llama` - Llama
* `azure` - Azure
* `docling` - Docling
* `whisper_groq` - WhisperGroq
* `whisper_openai` - WhisperOpenAI
* `whisper_offline` - WhisperOffline
* `localai` - LocalAI
* `anthropic` - Anthropic
* `bronci` - Bronci
* `alibaba` - Alibaba Qwen
* `rap` - Taiwan AI RAP
* `vertex` - Vertex AI
* `cohere` - Cohere
          "isTimestampSttProvider": boolean
        }
        "reason": string // 原因類別：scanned、image_pages、large_images、unmeasurable_images、presentation、no_image_content、below_threshold、no_content、file_type_not_detected、detection_failed、vision_unavailable；之後可能新增類別，沒有對應文案時請顯示通用句
        "facts": object // 原因裡的數字（判斷當下算出，之後不重算）。PDF 與簡報（一張投影片算一頁）：analyzed_pages（判斷看的頁數）、partial（是否只看前面幾頁）、non_blank_pages、scanned_pages、image_pages（需要以圖片判讀的頁）；Word：figures（內文大圖數）、text_chars（內文字數）；其他情況為空物件
        "detectedAt": string (timestamp) // 判斷時間
      }
      "previewUrl": string // 簡報（pptx/ppt）回傳可預覽的 pdf 衍生檔 URL（前端用 PDF 預覽器顯示）；其餘為 None。

用與 `file` 欄位相同的 CustomizedFileFieldSerializer 產 URL，確保格式一致（含各
storage provider 的 presign/host 規則）。不可用 get_absolute_url()——它產出的 URL 格式錯誤。
      "createdAt": string (timestamp)
      "parseQueue":  // 檔案在等 Vision 解析名額時的排隊位置；沒在排隊或沒有排隊資料時為 null（顯示「處理中」）
      {
        "position": integer // 同組織排在前面、目前可以開始的檔案數；0＝下一個就是它；null＝被超大檔同時處理上限擋住
      }
    }
  ]
}
```

**回應範例值**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "filename": "回應字串",
      "file": "https://example.com/file.jpg",
      "fileType": "回應字串",
      "knowledgeBase": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應字串"
      },
      "size": 456,
      "status": {},
      "parser": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應字串",
        "provider": "maiagent",
        "isTimestampSttProvider": false
      },
      "labels": [
        {
          "id": "550e8400-e29b-41d4-a716-446655440000",
          "name": "回應字串"
        }
      ],
      "rawUserDefineMetadata": null,
      "speakerLabels": [
        {
          "id": "550e8400-e29b-41d4-a716-446655440000",
          "originalLabel": "回應字串",
          "customName": "回應字串",
          "displayName": "回應字串"
        }
      ],
      "vectorStorageSize": 456,
      "chunksCount": 456,
      "waitingTime": 456,
      "processingTime": 456,
      "processingTimeDetails": null,
      "ocrStatus": "回應字串",
      "ocrSkippedReason": "回應字串",
      "visualAnalysis": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應範例名稱",
        "description": "回應範例描述"
      },
      "parserAutoDetection": {
        "parser": {
          "id": "550e8400-e29b-41d4-a716-446655440000",
          "name": "回應字串",
          "provider": "maiagent",
          "isTimestampSttProvider": false
        },
        "reason": "回應字串",
        "facts": {
          "id": "550e8400-e29b-41d4-a716-446655440000",
          "name": "回應範例名稱",
          "description": "回應範例描述"
        },
        "detectedAt": "回應字串"
      },
      "previewUrl": "回應字串",
      "createdAt": "回應字串",
      "parseQueue": {
        "position": 456
      }
    }
  ]
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 更新檔案元資料 <a href="#knowledge-bases-files-update-metadata-partial-update" id="knowledge-bases-files-update-metadata-partial-update"></a>

PATCH `/api/v1/knowledge-bases/{knowledgeBasePk}/files/{id}/update-metadata/`

#### 參數

| 參數名稱              | 必填 | 類型     | 說明                                                  |
| ----------------- | -- | ------ | --------------------------------------------------- |
| `id`              | ✅  | string | A UUID string identifying this Knowledge Base File. |
| `knowledgeBasePk` | ✅  | string |                                                     |

#### 請求內容

**請求參數**

| 欄位                    | 類型             | 必填 | 說明 |
| --------------------- | -------------- | -- | -- |
| labels                | array\[IdName] | 否  |    |
| rawUserDefineMetadata | object         | 否  |    |

**請求結構範例**

```typescript
{
  "labels"?: [ // 非必填
    {
      "id": string (uuid)
    }
  ]
  "rawUserDefineMetadata"?: object // 非必填
}
```

**請求範例值**

```json
{
  "labels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000"
    }
  ],
  "rawUserDefineMetadata": null
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X PATCH "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/550e8400-e29b-41d4-a716-446655440000/update-metadata/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "labels": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000"
      }
    ],
    "rawUserDefineMetadata": null
  }'

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// 請求內容 (payload)
const data = {
    "labels": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000"
      }
    ],
    "rawUserDefineMetadata": null
  };

axios.patch("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/550e8400-e29b-41d4-a716-446655440000/update-metadata/", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/550e8400-e29b-41d4-a716-446655440000/update-metadata/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "labels": [
        {
            "id": "550e8400-e29b-41d4-a716-446655440000"
        }
    ],
    "rawUserDefineMetadata": None
}

response = requests.patch(url, json=data, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->patch("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/550e8400-e29b-41d4-a716-446655440000/update-metadata/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'labels' => [
                [
                    'id' => '550e8400-e29b-41d4-a716-446655440000'
                ]
            ],
            'rawUserDefineMetadata' => null
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "filename": string // 檔案名稱
  "file": string (uri) // 要上傳的檔案
  "fileType": string
  "knowledgeBase"?:  // 非必填
  {
    "id": string (uuid)
    "name": string
  }
  "size": integer // File size in bytes
  "status": 
  {
  }
  "parser": 
  {
    "id": string (uuid)
    "name": string
    "provider": string (enum: maiagent, llama, azure, docling, whisper_groq, whisper_openai, whisper_offline, localai, anthropic, bronci, alibaba, rap, vertex, cohere) // * `maiagent` - MaiAgent
* `llama` - Llama
* `azure` - Azure
* `docling` - Docling
* `whisper_groq` - WhisperGroq
* `whisper_openai` - WhisperOpenAI
* `whisper_offline` - WhisperOffline
* `localai` - LocalAI
* `anthropic` - Anthropic
* `bronci` - Bronci
* `alibaba` - Alibaba Qwen
* `rap` - Taiwan AI RAP
* `vertex` - Vertex AI
* `cohere` - Cohere
    "isTimestampSttProvider": boolean
  }
  "labels"?: [ // 非必填
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "rawUserDefineMetadata"?: object // 非必填
  "speakerLabels": [
    {
      "id": string (uuid)
      "originalLabel": string // Original speaker label from diarization (e.g., SPEAKER_00)
      "customName"?: string // User-defined speaker name (e.g., John) (非必填)
      "displayName": string
    }
  ]
  "vectorStorageSize": integer // Size of vectors for this file in Elasticsearch (bytes)
  "chunksCount": integer // Number of chunks/nodes generated from this file
  "waitingTime": number (double)
  "processingTime": number (double)
  "processingTimeDetails": object
  "ocrStatus": string // 掃描頁 OCR 結果：done、skipped、partial、off；解析前或舊檔案為 null
  "ocrSkippedReason": string // 掃描頁沒做 OCR 的原因：no_azure_settings、azure_unavailable、insufficient_credits、transient_error、time_budget、disabled；有做完時為 null
  "visualAnalysis": object // 影片畫面分析結果：status 為 completed 或 incomplete，reason 是未完成原因（model_error、timeout、video_unreadable、model_not_vision、no_describable_content），frame_cap_reached 表示畫面張數達上限；沒做過畫面分析的檔案為 null
  "parserAutoDetection":  // 自動偵測替這份檔選解析器的結果與原因；使用者自己選的、上線前上傳的、重新判斷排隊中的檔為 null
  {
    "parser":  // 自動偵測選到的解析器
    {
      "id": string (uuid)
      "name": string
      "provider": string (enum: maiagent, llama, azure, docling, whisper_groq, whisper_openai, whisper_offline, localai, anthropic, bronci, alibaba, rap, vertex, cohere) // * `maiagent` - MaiAgent
* `llama` - Llama
* `azure` - Azure
* `docling` - Docling
* `whisper_groq` - WhisperGroq
* `whisper_openai` - WhisperOpenAI
* `whisper_offline` - WhisperOffline
* `localai` - LocalAI
* `anthropic` - Anthropic
* `bronci` - Bronci
* `alibaba` - Alibaba Qwen
* `rap` - Taiwan AI RAP
* `vertex` - Vertex AI
* `cohere` - Cohere
      "isTimestampSttProvider": boolean
    }
    "reason": string // 原因類別：scanned、image_pages、large_images、unmeasurable_images、presentation、no_image_content、below_threshold、no_content、file_type_not_detected、detection_failed、vision_unavailable；之後可能新增類別，沒有對應文案時請顯示通用句
    "facts": object // 原因裡的數字（判斷當下算出，之後不重算）。PDF 與簡報（一張投影片算一頁）：analyzed_pages（判斷看的頁數）、partial（是否只看前面幾頁）、non_blank_pages、scanned_pages、image_pages（需要以圖片判讀的頁）；Word：figures（內文大圖數）、text_chars（內文字數）；其他情況為空物件
    "detectedAt": string (timestamp) // 判斷時間
  }
  "previewUrl": string // 簡報（pptx/ppt）回傳可預覽的 pdf 衍生檔 URL（前端用 PDF 預覽器顯示）；其餘為 None。

用與 `file` 欄位相同的 CustomizedFileFieldSerializer 產 URL，確保格式一致（含各
storage provider 的 presign/host 規則）。不可用 get_absolute_url()——它產出的 URL 格式錯誤。
  "createdAt": string (timestamp)
  "parseQueue":  // 檔案在等 Vision 解析名額時的排隊位置；沒在排隊或沒有排隊資料時為 null（顯示「處理中」）
  {
    "position": integer // 同組織排在前面、目前可以開始的檔案數；0＝下一個就是它；null＝被超大檔同時處理上限擋住
  }
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "filename": "回應字串",
  "file": "https://example.com/file.jpg",
  "fileType": "回應字串",
  "knowledgeBase": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應字串"
  },
  "size": 456,
  "status": {},
  "parser": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應字串",
    "provider": "maiagent",
    "isTimestampSttProvider": false
  },
  "labels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ],
  "rawUserDefineMetadata": null,
  "speakerLabels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "originalLabel": "回應字串",
      "customName": "回應字串",
      "displayName": "回應字串"
    }
  ],
  "vectorStorageSize": 456,
  "chunksCount": 456,
  "waitingTime": 456,
  "processingTime": 456,
  "processingTimeDetails": null,
  "ocrStatus": "回應字串",
  "ocrSkippedReason": "回應字串",
  "visualAnalysis": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "parserAutoDetection": {
    "parser": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串",
      "provider": "maiagent",
      "isTimestampSttProvider": false
    },
    "reason": "回應字串",
    "facts": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應範例名稱",
      "description": "回應範例描述"
    },
    "detectedAt": "回應字串"
  },
  "previewUrl": "回應字串",
  "createdAt": "回應字串",
  "parseQueue": {
    "position": 456
  }
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 批量刪除檔案 <a href="#knowledge-bases-files-batch-delete-create" id="knowledge-bases-files-batch-delete-create"></a>

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

#### 參數

| 參數名稱              | 必填 | 類型     | 說明 |
| ----------------- | -- | ------ | -- |
| `knowledgeBasePk` | ✅  | string |    |

#### 請求內容

**請求參數**

| 欄位             | 類型             | 必填 | 說明 |
| -------------- | -------------- | -- | -- |
| purgeCitations | boolean        | 否  |    |
| ids            | array\[string] | 是  |    |

**請求結構範例**

```typescript
{
  "purgeCitations"?: boolean // 非必填
  "ids": [
    string (uuid)
  ]
}
```

**請求範例值**

```json
{
  "purgeCitations": true,
  "ids": [
    "550e8400-e29b-41d4-a716-446655440000"
  ]
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/batch-delete/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "purgeCitations": true,
    "ids": [
      "550e8400-e29b-41d4-a716-446655440000"
    ]
  }'

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// 請求內容 (payload)
const data = {
    "purgeCitations": true,
    "ids": [
      "550e8400-e29b-41d4-a716-446655440000"
    ]
  };

axios.post("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/batch-delete/", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/batch-delete/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "purgeCitations": True,
    "ids": [
        "550e8400-e29b-41d4-a716-446655440000"
    ]
}

response = requests.post(url, json=data, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/batch-delete/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'purgeCitations' => true,
            'ids' => [
                '550e8400-e29b-41d4-a716-446655440000'
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "queued": [
    string (uuid)
  ]
  "skipped": [
    {
      "id": string (uuid)
      "reason": string (enum: deleting) // * `deleting` - deleting
    }
  ]
}
```

**回應範例值**

```json
{
  "queued": [
    "550e8400-e29b-41d4-a716-446655440000"
  ],
  "skipped": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "reason": "deleting"
    }
  ]
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 批量重新解析檔案 <a href="#knowledge-bases-files-batch-reparse-partial-update" id="knowledge-bases-files-batch-reparse-partial-update"></a>

PATCH `/api/v1/knowledge-bases/{knowledgeBasePk}/files/batch-reparse/`

#### 參數

| 參數名稱              | 必填 | 類型     | 說明                                                                                                                                                                                                                     |
| ----------------- | -- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `knowledgeBasePk` | ✅  | string |                                                                                                                                                                                                                        |
| `fileType`        | ❌  | string | 檔案類型過濾，例如：pdf、docx、txt、xlsx 等                                                                                                                                                                                          |
| `knowledgeBase`   | ❌  | string | 知識庫 ID                                                                                                                                                                                                                 |
| `query`           | ❌  | string | 搜尋關鍵字，支援空白分隔的多條件查詢。可搜尋：檔案 ID、檔案名稱、標籤名稱、Metadata value                                                                                                                                                                  |
| `status`          | ❌  | string | 檔案狀態過濾，可選值：initial（初始化）、processing（處理中）、done（完成）、deleting（刪除中）、deleted（已刪除）、failed（失敗） \`initial\`: Initial ; \`processing\`: Processing ; \`done\`: Done ; \`deleting\`: Deleting ; \`deleted\`: Deleted ; \`faile... |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X PATCH "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/batch-reparse/?fileType=example&knowledgeBase=550e8400-e29b-41d4-a716-446655440000&query=example&status=delete_failed" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '[]'

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// 請求內容 (payload)
const data = [];

axios.patch("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/batch-reparse/?fileType=example&knowledgeBase=550e8400-e29b-41d4-a716-446655440000&query=example&status=delete_failed", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/batch-reparse/?fileType=example&knowledgeBase=550e8400-e29b-41d4-a716-446655440000&query=example&status=delete_failed"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = []

response = requests.patch(url, json=data, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->patch("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/batch-reparse/?fileType=example&knowledgeBase=550e8400-e29b-41d4-a716-446655440000&query=example&status=delete_failed", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => []
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
[
  {
    "id": string (uuid)
    "filename": string // 檔案名稱
    "file": string (uri) // 要上傳的檔案
    "fileType": string
    "knowledgeBase"?:  // 非必填
    {
      "id": string (uuid)
      "name": string
    }
    "size": integer // File size in bytes
    "status": 
    {
    }
    "parser": 
    {
      "id": string (uuid)
      "name": string
      "provider": string (enum: maiagent, llama, azure, docling, whisper_groq, whisper_openai, whisper_offline, localai, anthropic, bronci, alibaba, rap, vertex, cohere) // * `maiagent` - MaiAgent
* `llama` - Llama
* `azure` - Azure
* `docling` - Docling
* `whisper_groq` - WhisperGroq
* `whisper_openai` - WhisperOpenAI
* `whisper_offline` - WhisperOffline
* `localai` - LocalAI
* `anthropic` - Anthropic
* `bronci` - Bronci
* `alibaba` - Alibaba Qwen
* `rap` - Taiwan AI RAP
* `vertex` - Vertex AI
* `cohere` - Cohere
      "isTimestampSttProvider": boolean
    }
    "labels"?: [ // 非必填
      {
        "id": string (uuid)
        "name": string
      }
    ]
    "rawUserDefineMetadata"?: object // 非必填
    "speakerLabels": [
      {
        "id": string (uuid)
        "originalLabel": string // Original speaker label from diarization (e.g., SPEAKER_00)
        "customName"?: string // User-defined speaker name (e.g., John) (非必填)
        "displayName": string
      }
    ]
    "vectorStorageSize": integer // Size of vectors for this file in Elasticsearch (bytes)
    "chunksCount": integer // Number of chunks/nodes generated from this file
    "waitingTime": number (double)
    "processingTime": number (double)
    "processingTimeDetails": object
    "ocrStatus": string // 掃描頁 OCR 結果：done、skipped、partial、off；解析前或舊檔案為 null
    "ocrSkippedReason": string // 掃描頁沒做 OCR 的原因：no_azure_settings、azure_unavailable、insufficient_credits、transient_error、time_budget、disabled；有做完時為 null
    "visualAnalysis": object // 影片畫面分析結果：status 為 completed 或 incomplete，reason 是未完成原因（model_error、timeout、video_unreadable、model_not_vision、no_describable_content），frame_cap_reached 表示畫面張數達上限；沒做過畫面分析的檔案為 null
    "parserAutoDetection":  // 自動偵測替這份檔選解析器的結果與原因；使用者自己選的、上線前上傳的、重新判斷排隊中的檔為 null
    {
      "parser":  // 自動偵測選到的解析器
      {
        "id": string (uuid)
        "name": string
        "provider": string (enum: maiagent, llama, azure, docling, whisper_groq, whisper_openai, whisper_offline, localai, anthropic, bronci, alibaba, rap, vertex, cohere) // * `maiagent` - MaiAgent
* `llama` - Llama
* `azure` - Azure
* `docling` - Docling
* `whisper_groq` - WhisperGroq
* `whisper_openai` - WhisperOpenAI
* `whisper_offline` - WhisperOffline
* `localai` - LocalAI
* `anthropic` - Anthropic
* `bronci` - Bronci
* `alibaba` - Alibaba Qwen
* `rap` - Taiwan AI RAP
* `vertex` - Vertex AI
* `cohere` - Cohere
        "isTimestampSttProvider": boolean
      }
      "reason": string // 原因類別：scanned、image_pages、large_images、unmeasurable_images、presentation、no_image_content、below_threshold、no_content、file_type_not_detected、detection_failed、vision_unavailable；之後可能新增類別，沒有對應文案時請顯示通用句
      "facts": object // 原因裡的數字（判斷當下算出，之後不重算）。PDF 與簡報（一張投影片算一頁）：analyzed_pages（判斷看的頁數）、partial（是否只看前面幾頁）、non_blank_pages、scanned_pages、image_pages（需要以圖片判讀的頁）；Word：figures（內文大圖數）、text_chars（內文字數）；其他情況為空物件
      "detectedAt": string (timestamp) // 判斷時間
    }
    "previewUrl": string // 簡報（pptx/ppt）回傳可預覽的 pdf 衍生檔 URL（前端用 PDF 預覽器顯示）；其餘為 None。

用與 `file` 欄位相同的 CustomizedFileFieldSerializer 產 URL，確保格式一致（含各
storage provider 的 presign/host 規則）。不可用 get_absolute_url()——它產出的 URL 格式錯誤。
    "createdAt": string (timestamp)
    "parseQueue":  // 檔案在等 Vision 解析名額時的排隊位置；沒在排隊或沒有排隊資料時為 null（顯示「處理中」）
    {
      "position": integer // 同組織排在前面、目前可以開始的檔案數；0＝下一個就是它；null＝被超大檔同時處理上限擋住
    }
    "reparseSkippedReason": string
  }
]
```

**回應範例值**

```json
[
  {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "filename": "回應字串",
    "file": "https://example.com/file.jpg",
    "fileType": "回應字串",
    "knowledgeBase": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    },
    "size": 456,
    "status": {},
    "parser": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串",
      "provider": "maiagent",
      "isTimestampSttProvider": false
    },
    "labels": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應字串"
      }
    ],
    "rawUserDefineMetadata": null,
    "speakerLabels": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "originalLabel": "回應字串",
        "customName": "回應字串",
        "displayName": "回應字串"
      }
    ],
    "vectorStorageSize": 456,
    "chunksCount": 456,
    "waitingTime": 456,
    "processingTime": 456,
    "processingTimeDetails": null,
    "ocrStatus": "回應字串",
    "ocrSkippedReason": "回應字串",
    "visualAnalysis": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應範例名稱",
      "description": "回應範例描述"
    },
    "parserAutoDetection": {
      "parser": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應字串",
        "provider": "maiagent",
        "isTimestampSttProvider": false
      },
      "reason": "回應字串",
      "facts": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應範例名稱",
        "description": "回應範例描述"
      },
      "detectedAt": "回應字串"
    },
    "previewUrl": "回應字串",
    "createdAt": "回應字串",
    "parseQueue": {
      "position": 456
    },
    "reparseSkippedReason": "回應字串"
  }
]
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 列出知識庫中的檔案 <a href="#knowledge-bases-files-list" id="knowledge-bases-files-list"></a>

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

{% hint style="info" %}
解析器留給系統自動偵測的檔案，回應的 `parserAutoDetection` 會帶出選到的解析器、原因類別（`reason`）、判斷用的數字（`facts`）與判斷時間；使用者自己選解析器的檔為 `null`。欄位、何時為 `null`、原因類別與數字的對照見 [解析器自動偵測結果](https://docs.maiagent.ai/api/preparation/parser-auto-detection.md)。
{% endhint %}

#### 參數

| 參數名稱              | 必填 | 類型      | 說明                                                                                                                                                                                                                     |
| ----------------- | -- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `knowledgeBasePk` | ✅  | string  |                                                                                                                                                                                                                        |
| `fileType`        | ❌  | string  | 檔案類型過濾，例如：pdf、docx、txt、xlsx 等                                                                                                                                                                                          |
| `knowledgeBase`   | ❌  | string  | 知識庫 ID                                                                                                                                                                                                                 |
| `ordering`        | ❌  | string  | Sort by file name, ignoring case: \`filename\` (A to Z) or \`-filename\` (Z to A). Other values keep newest first.                                                                                                     |
| `page`            | ❌  | integer | A page number within the paginated result set.                                                                                                                                                                         |
| `pageSize`        | ❌  | integer | Number of results to return per page.                                                                                                                                                                                  |
| `query`           | ❌  | string  | 搜尋關鍵字，支援空白分隔的多條件查詢。可搜尋：檔案 ID、檔案名稱、標籤名稱、Metadata value                                                                                                                                                                  |
| `status`          | ❌  | string  | 檔案狀態過濾，可選值：initial（初始化）、processing（處理中）、done（完成）、deleting（刪除中）、deleted（已刪除）、failed（失敗） \`initial\`: Initial ; \`processing\`: Processing ; \`done\`: Done ; \`deleting\`: Deleting ; \`deleted\`: Deleted ; \`faile... |

#### 程式碼範例

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

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

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/?fileType=example&knowledgeBase=550e8400-e29b-41d4-a716-446655440000&ordering=example&page=1&pageSize=1&query=example&status=delete_failed", config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/?fileType=example&knowledgeBase=550e8400-e29b-41d4-a716-446655440000&ordering=example&page=1&pageSize=1&query=example&status=delete_failed"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/?fileType=example&knowledgeBase=550e8400-e29b-41d4-a716-446655440000&ordering=example&page=1&pageSize=1&query=example&status=delete_failed", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "count": integer
  "next"?: string (uri) // 非必填
  "previous"?: string (uri) // 非必填
  "results": [
    {
      "id": string (uuid)
      "filename": string // 檔案名稱
      "file": string (uri) // 要上傳的檔案
      "fileType": string
      "knowledgeBase"?:  // 非必填
      {
        "id": string (uuid)
        "name": string
      }
      "size": integer // File size in bytes
      "status": 
      {
      }
      "parser": 
      {
        "id": string (uuid)
        "name": string
        "provider": string (enum: maiagent, llama, azure, docling, whisper_groq, whisper_openai, whisper_offline, localai, anthropic, bronci, alibaba, rap, vertex, cohere) // * `maiagent` - MaiAgent
* `llama` - Llama
* `azure` - Azure
* `docling` - Docling
* `whisper_groq` - WhisperGroq
* `whisper_openai` - WhisperOpenAI
* `whisper_offline` - WhisperOffline
* `localai` - LocalAI
* `anthropic` - Anthropic
* `bronci` - Bronci
* `alibaba` - Alibaba Qwen
* `rap` - Taiwan AI RAP
* `vertex` - Vertex AI
* `cohere` - Cohere
        "isTimestampSttProvider": boolean
      }
      "labels"?: [ // 非必填
        {
          "id": string (uuid)
          "name": string
        }
      ]
      "rawUserDefineMetadata"?: object // 非必填
      "speakerLabels": [
        {
          "id": string (uuid)
          "originalLabel": string // Original speaker label from diarization (e.g., SPEAKER_00)
          "customName"?: string // User-defined speaker name (e.g., John) (非必填)
          "displayName": string
        }
      ]
      "vectorStorageSize": integer // Size of vectors for this file in Elasticsearch (bytes)
      "chunksCount": integer // Number of chunks/nodes generated from this file
      "waitingTime": number (double)
      "processingTime": number (double)
      "processingTimeDetails": object
      "ocrStatus": string // 掃描頁 OCR 結果：done、skipped、partial、off；解析前或舊檔案為 null
      "ocrSkippedReason": string // 掃描頁沒做 OCR 的原因：no_azure_settings、azure_unavailable、insufficient_credits、transient_error、time_budget、disabled；有做完時為 null
      "visualAnalysis": object // 影片畫面分析結果：status 為 completed 或 incomplete，reason 是未完成原因（model_error、timeout、video_unreadable、model_not_vision、no_describable_content），frame_cap_reached 表示畫面張數達上限；沒做過畫面分析的檔案為 null
      "parserAutoDetection":  // 自動偵測替這份檔選解析器的結果與原因；使用者自己選的、上線前上傳的、重新判斷排隊中的檔為 null
      {
        "parser":  // 自動偵測選到的解析器
        {
          "id": string (uuid)
          "name": string
          "provider": string (enum: maiagent, llama, azure, docling, whisper_groq, whisper_openai, whisper_offline, localai, anthropic, bronci, alibaba, rap, vertex, cohere) // * `maiagent` - MaiAgent
* `llama` - Llama
* `azure` - Azure
* `docling` - Docling
* `whisper_groq` - WhisperGroq
* `whisper_openai` - WhisperOpenAI
* `whisper_offline` - WhisperOffline
* `localai` - LocalAI
* `anthropic` - Anthropic
* `bronci` - Bronci
* `alibaba` - Alibaba Qwen
* `rap` - Taiwan AI RAP
* `vertex` - Vertex AI
* `cohere` - Cohere
          "isTimestampSttProvider": boolean
        }
        "reason": string // 原因類別：scanned、image_pages、large_images、unmeasurable_images、presentation、no_image_content、below_threshold、no_content、file_type_not_detected、detection_failed、vision_unavailable；之後可能新增類別，沒有對應文案時請顯示通用句
        "facts": object // 原因裡的數字（判斷當下算出，之後不重算）。PDF 與簡報（一張投影片算一頁）：analyzed_pages（判斷看的頁數）、partial（是否只看前面幾頁）、non_blank_pages、scanned_pages、image_pages（需要以圖片判讀的頁）；Word：figures（內文大圖數）、text_chars（內文字數）；其他情況為空物件
        "detectedAt": string (timestamp) // 判斷時間
      }
      "previewUrl": string // 簡報（pptx/ppt）回傳可預覽的 pdf 衍生檔 URL（前端用 PDF 預覽器顯示）；其餘為 None。

用與 `file` 欄位相同的 CustomizedFileFieldSerializer 產 URL，確保格式一致（含各
storage provider 的 presign/host 規則）。不可用 get_absolute_url()——它產出的 URL 格式錯誤。
      "createdAt": string (timestamp)
      "parseQueue":  // 檔案在等 Vision 解析名額時的排隊位置；沒在排隊或沒有排隊資料時為 null（顯示「處理中」）
      {
        "position": integer // 同組織排在前面、目前可以開始的檔案數；0＝下一個就是它；null＝被超大檔同時處理上限擋住
      }
    }
  ]
}
```

**回應範例值**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "filename": "回應字串",
      "file": "https://example.com/file.jpg",
      "fileType": "回應字串",
      "knowledgeBase": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應字串"
      },
      "size": 456,
      "status": {},
      "parser": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應字串",
        "provider": "maiagent",
        "isTimestampSttProvider": false
      },
      "labels": [
        {
          "id": "550e8400-e29b-41d4-a716-446655440000",
          "name": "回應字串"
        }
      ],
      "rawUserDefineMetadata": null,
      "speakerLabels": [
        {
          "id": "550e8400-e29b-41d4-a716-446655440000",
          "originalLabel": "回應字串",
          "customName": "回應字串",
          "displayName": "回應字串"
        }
      ],
      "vectorStorageSize": 456,
      "chunksCount": 456,
      "waitingTime": 456,
      "processingTime": 456,
      "processingTimeDetails": null,
      "ocrStatus": "回應字串",
      "ocrSkippedReason": "回應字串",
      "visualAnalysis": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應範例名稱",
        "description": "回應範例描述"
      },
      "parserAutoDetection": {
        "parser": {
          "id": "550e8400-e29b-41d4-a716-446655440000",
          "name": "回應字串",
          "provider": "maiagent",
          "isTimestampSttProvider": false
        },
        "reason": "回應字串",
        "facts": {
          "id": "550e8400-e29b-41d4-a716-446655440000",
          "name": "回應範例名稱",
          "description": "回應範例描述"
        },
        "detectedAt": "回應字串"
      },
      "previewUrl": "回應字串",
      "createdAt": "回應字串",
      "parseQueue": {
        "position": 456
      }
    }
  ]
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 取得特定檔案詳情 <a href="#knowledge-bases-files-retrieve" id="knowledge-bases-files-retrieve"></a>

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

{% hint style="info" %}
解析器留給系統自動偵測的檔案，回應的 `parserAutoDetection` 會帶出選到的解析器、原因類別（`reason`）、判斷用的數字（`facts`）與判斷時間；使用者自己選解析器的檔為 `null`。欄位、何時為 `null`、原因類別與數字的對照見 [解析器自動偵測結果](https://docs.maiagent.ai/api/preparation/parser-auto-detection.md)。
{% endhint %}

#### 參數

| 參數名稱              | 必填 | 類型     | 說明                                                  |
| ----------------- | -- | ------ | --------------------------------------------------- |
| `id`              | ✅  | string | A UUID string identifying this Knowledge Base File. |
| `knowledgeBasePk` | ✅  | string |                                                     |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/550e8400-e29b-41d4-a716-446655440000/", config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "filename": string // 檔案名稱
  "file": string (uri) // 要上傳的檔案
  "fileType": string
  "knowledgeBase"?:  // 非必填
  {
    "id": string (uuid)
    "name": string
  }
  "size": integer // File size in bytes
  "status": 
  {
  }
  "parser": 
  {
    "id": string (uuid)
    "name": string
    "provider": string (enum: maiagent, llama, azure, docling, whisper_groq, whisper_openai, whisper_offline, localai, anthropic, bronci, alibaba, rap, vertex, cohere) // * `maiagent` - MaiAgent
* `llama` - Llama
* `azure` - Azure
* `docling` - Docling
* `whisper_groq` - WhisperGroq
* `whisper_openai` - WhisperOpenAI
* `whisper_offline` - WhisperOffline
* `localai` - LocalAI
* `anthropic` - Anthropic
* `bronci` - Bronci
* `alibaba` - Alibaba Qwen
* `rap` - Taiwan AI RAP
* `vertex` - Vertex AI
* `cohere` - Cohere
    "isTimestampSttProvider": boolean
  }
  "labels"?: [ // 非必填
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "rawUserDefineMetadata"?: object // 非必填
  "speakerLabels": [
    {
      "id": string (uuid)
      "originalLabel": string // Original speaker label from diarization (e.g., SPEAKER_00)
      "customName"?: string // User-defined speaker name (e.g., John) (非必填)
      "displayName": string
    }
  ]
  "vectorStorageSize": integer // Size of vectors for this file in Elasticsearch (bytes)
  "chunksCount": integer // Number of chunks/nodes generated from this file
  "waitingTime": number (double)
  "processingTime": number (double)
  "processingTimeDetails": object
  "ocrStatus": string // 掃描頁 OCR 結果：done、skipped、partial、off；解析前或舊檔案為 null
  "ocrSkippedReason": string // 掃描頁沒做 OCR 的原因：no_azure_settings、azure_unavailable、insufficient_credits、transient_error、time_budget、disabled；有做完時為 null
  "visualAnalysis": object // 影片畫面分析結果：status 為 completed 或 incomplete，reason 是未完成原因（model_error、timeout、video_unreadable、model_not_vision、no_describable_content），frame_cap_reached 表示畫面張數達上限；沒做過畫面分析的檔案為 null
  "parserAutoDetection":  // 自動偵測替這份檔選解析器的結果與原因；使用者自己選的、上線前上傳的、重新判斷排隊中的檔為 null
  {
    "parser":  // 自動偵測選到的解析器
    {
      "id": string (uuid)
      "name": string
      "provider": string (enum: maiagent, llama, azure, docling, whisper_groq, whisper_openai, whisper_offline, localai, anthropic, bronci, alibaba, rap, vertex, cohere) // * `maiagent` - MaiAgent
* `llama` - Llama
* `azure` - Azure
* `docling` - Docling
* `whisper_groq` - WhisperGroq
* `whisper_openai` - WhisperOpenAI
* `whisper_offline` - WhisperOffline
* `localai` - LocalAI
* `anthropic` - Anthropic
* `bronci` - Bronci
* `alibaba` - Alibaba Qwen
* `rap` - Taiwan AI RAP
* `vertex` - Vertex AI
* `cohere` - Cohere
      "isTimestampSttProvider": boolean
    }
    "reason": string // 原因類別：scanned、image_pages、large_images、unmeasurable_images、presentation、no_image_content、below_threshold、no_content、file_type_not_detected、detection_failed、vision_unavailable；之後可能新增類別，沒有對應文案時請顯示通用句
    "facts": object // 原因裡的數字（判斷當下算出，之後不重算）。PDF 與簡報（一張投影片算一頁）：analyzed_pages（判斷看的頁數）、partial（是否只看前面幾頁）、non_blank_pages、scanned_pages、image_pages（需要以圖片判讀的頁）；Word：figures（內文大圖數）、text_chars（內文字數）；其他情況為空物件
    "detectedAt": string (timestamp) // 判斷時間
  }
  "previewUrl": string // 簡報（pptx/ppt）回傳可預覽的 pdf 衍生檔 URL（前端用 PDF 預覽器顯示）；其餘為 None。

用與 `file` 欄位相同的 CustomizedFileFieldSerializer 產 URL，確保格式一致（含各
storage provider 的 presign/host 規則）。不可用 get_absolute_url()——它產出的 URL 格式錯誤。
  "createdAt": string (timestamp)
  "parseQueue":  // 檔案在等 Vision 解析名額時的排隊位置；沒在排隊或沒有排隊資料時為 null（顯示「處理中」）
  {
    "position": integer // 同組織排在前面、目前可以開始的檔案數；0＝下一個就是它；null＝被超大檔同時處理上限擋住
  }
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "filename": "回應字串",
  "file": "https://example.com/file.jpg",
  "fileType": "回應字串",
  "knowledgeBase": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應字串"
  },
  "size": 456,
  "status": {},
  "parser": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應字串",
    "provider": "maiagent",
    "isTimestampSttProvider": false
  },
  "labels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ],
  "rawUserDefineMetadata": null,
  "speakerLabels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "originalLabel": "回應字串",
      "customName": "回應字串",
      "displayName": "回應字串"
    }
  ],
  "vectorStorageSize": 456,
  "chunksCount": 456,
  "waitingTime": 456,
  "processingTime": 456,
  "processingTimeDetails": null,
  "ocrStatus": "回應字串",
  "ocrSkippedReason": "回應字串",
  "visualAnalysis": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "parserAutoDetection": {
    "parser": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串",
      "provider": "maiagent",
      "isTimestampSttProvider": false
    },
    "reason": "回應字串",
    "facts": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應範例名稱",
      "description": "回應範例描述"
    },
    "detectedAt": "回應字串"
  },
  "previewUrl": "回應字串",
  "createdAt": "回應字串",
  "parseQueue": {
    "position": 456
  }
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 取得檔案最新失敗原因 <a href="#knowledge-bases-files-latest-failed-reason-retrieve" id="knowledge-bases-files-latest-failed-reason-retrieve"></a>

GET `/api/v1/knowledge-bases/{knowledgeBasePk}/files/{id}/latest-failed-reason/`

#### 參數

| 參數名稱              | 必填 | 類型     | 說明                                                  |
| ----------------- | -- | ------ | --------------------------------------------------- |
| `id`              | ✅  | string | A UUID string identifying this Knowledge Base File. |
| `knowledgeBasePk` | ✅  | string |                                                     |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/550e8400-e29b-41d4-a716-446655440000/latest-failed-reason/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/550e8400-e29b-41d4-a716-446655440000/latest-failed-reason/", config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/550e8400-e29b-41d4-a716-446655440000/latest-failed-reason/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/550e8400-e29b-41d4-a716-446655440000/latest-failed-reason/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "errorMessage": string
  "errorCode"?: string // Machine-readable code of a known failure type (see FAILED_REASON_LOCALIZED_MESSAGES in whizchat/parsers/exceptions.py); the serializer translates it into the request language on read. An empty string means no translation, and error_message is shown as is. (非必填)
  "createdAt": string (timestamp)
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "errorMessage": "回應字串",
  "errorCode": "回應字串",
  "createdAt": "回應字串"
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 取得檔案轉錄內容 <a href="#knowledge-bases-files-transcription-retrieve" id="knowledge-bases-files-transcription-retrieve"></a>

GET `/api/v1/knowledge-bases/{knowledgeBasePk}/files/{id}/transcription/`

#### 參數

| 參數名稱              | 必填 | 類型     | 說明                                                  |
| ----------------- | -- | ------ | --------------------------------------------------- |
| `id`              | ✅  | string | A UUID string identifying this Knowledge Base File. |
| `knowledgeBasePk` | ✅  | string |                                                     |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/550e8400-e29b-41d4-a716-446655440000/transcription/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/550e8400-e29b-41d4-a716-446655440000/transcription/", config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/550e8400-e29b-41d4-a716-446655440000/transcription/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/550e8400-e29b-41d4-a716-446655440000/transcription/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "filename": string // 檔案名稱
  "file": string (uri) // 要上傳的檔案
  "fileType": string
  "knowledgeBase"?:  // 非必填
  {
    "id": string (uuid)
    "name": string
  }
  "size": integer // File size in bytes
  "status": 
  {
  }
  "parser": 
  {
    "id": string (uuid)
    "name": string
    "provider": string (enum: maiagent, llama, azure, docling, whisper_groq, whisper_openai, whisper_offline, localai, anthropic, bronci, alibaba, rap, vertex, cohere) // * `maiagent` - MaiAgent
* `llama` - Llama
* `azure` - Azure
* `docling` - Docling
* `whisper_groq` - WhisperGroq
* `whisper_openai` - WhisperOpenAI
* `whisper_offline` - WhisperOffline
* `localai` - LocalAI
* `anthropic` - Anthropic
* `bronci` - Bronci
* `alibaba` - Alibaba Qwen
* `rap` - Taiwan AI RAP
* `vertex` - Vertex AI
* `cohere` - Cohere
    "isTimestampSttProvider": boolean
  }
  "labels"?: [ // 非必填
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "rawUserDefineMetadata"?: object // 非必填
  "speakerLabels": [
    {
      "id": string (uuid)
      "originalLabel": string // Original speaker label from diarization (e.g., SPEAKER_00)
      "customName"?: string // User-defined speaker name (e.g., John) (非必填)
      "displayName": string
    }
  ]
  "vectorStorageSize": integer // Size of vectors for this file in Elasticsearch (bytes)
  "chunksCount": integer // Number of chunks/nodes generated from this file
  "waitingTime": number (double)
  "processingTime": number (double)
  "processingTimeDetails": object
  "ocrStatus": string // 掃描頁 OCR 結果：done、skipped、partial、off；解析前或舊檔案為 null
  "ocrSkippedReason": string // 掃描頁沒做 OCR 的原因：no_azure_settings、azure_unavailable、insufficient_credits、transient_error、time_budget、disabled；有做完時為 null
  "visualAnalysis": object // 影片畫面分析結果：status 為 completed 或 incomplete，reason 是未完成原因（model_error、timeout、video_unreadable、model_not_vision、no_describable_content），frame_cap_reached 表示畫面張數達上限；沒做過畫面分析的檔案為 null
  "parserAutoDetection":  // 自動偵測替這份檔選解析器的結果與原因；使用者自己選的、上線前上傳的、重新判斷排隊中的檔為 null
  {
    "parser":  // 自動偵測選到的解析器
    {
      "id": string (uuid)
      "name": string
      "provider": string (enum: maiagent, llama, azure, docling, whisper_groq, whisper_openai, whisper_offline, localai, anthropic, bronci, alibaba, rap, vertex, cohere) // * `maiagent` - MaiAgent
* `llama` - Llama
* `azure` - Azure
* `docling` - Docling
* `whisper_groq` - WhisperGroq
* `whisper_openai` - WhisperOpenAI
* `whisper_offline` - WhisperOffline
* `localai` - LocalAI
* `anthropic` - Anthropic
* `bronci` - Bronci
* `alibaba` - Alibaba Qwen
* `rap` - Taiwan AI RAP
* `vertex` - Vertex AI
* `cohere` - Cohere
      "isTimestampSttProvider": boolean
    }
    "reason": string // 原因類別：scanned、image_pages、large_images、unmeasurable_images、presentation、no_image_content、below_threshold、no_content、file_type_not_detected、detection_failed、vision_unavailable；之後可能新增類別，沒有對應文案時請顯示通用句
    "facts": object // 原因裡的數字（判斷當下算出，之後不重算）。PDF 與簡報（一張投影片算一頁）：analyzed_pages（判斷看的頁數）、partial（是否只看前面幾頁）、non_blank_pages、scanned_pages、image_pages（需要以圖片判讀的頁）；Word：figures（內文大圖數）、text_chars（內文字數）；其他情況為空物件
    "detectedAt": string (timestamp) // 判斷時間
  }
  "previewUrl": string // 簡報（pptx/ppt）回傳可預覽的 pdf 衍生檔 URL（前端用 PDF 預覽器顯示）；其餘為 None。

用與 `file` 欄位相同的 CustomizedFileFieldSerializer 產 URL，確保格式一致（含各
storage provider 的 presign/host 規則）。不可用 get_absolute_url()——它產出的 URL 格式錯誤。
  "createdAt": string (timestamp)
  "parseQueue":  // 檔案在等 Vision 解析名額時的排隊位置；沒在排隊或沒有排隊資料時為 null（顯示「處理中」）
  {
    "position": integer // 同組織排在前面、目前可以開始的檔案數；0＝下一個就是它；null＝被超大檔同時處理上限擋住
  }
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "filename": "回應字串",
  "file": "https://example.com/file.jpg",
  "fileType": "回應字串",
  "knowledgeBase": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應字串"
  },
  "size": 456,
  "status": {},
  "parser": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應字串",
    "provider": "maiagent",
    "isTimestampSttProvider": false
  },
  "labels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ],
  "rawUserDefineMetadata": null,
  "speakerLabels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "originalLabel": "回應字串",
      "customName": "回應字串",
      "displayName": "回應字串"
    }
  ],
  "vectorStorageSize": 456,
  "chunksCount": 456,
  "waitingTime": 456,
  "processingTime": 456,
  "processingTimeDetails": null,
  "ocrStatus": "回應字串",
  "ocrSkippedReason": "回應字串",
  "visualAnalysis": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "parserAutoDetection": {
    "parser": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串",
      "provider": "maiagent",
      "isTimestampSttProvider": false
    },
    "reason": "回應字串",
    "facts": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應範例名稱",
      "description": "回應範例描述"
    },
    "detectedAt": "回應字串"
  },
  "previewUrl": "回應字串",
  "createdAt": "回應字串",
  "parseQueue": {
    "position": 456
  }
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 更新檔案資訊 <a href="#knowledge-bases-files-update" id="knowledge-bases-files-update"></a>

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

#### 參數

| 參數名稱              | 必填 | 類型     | 說明                                                  |
| ----------------- | -- | ------ | --------------------------------------------------- |
| `id`              | ✅  | string | A UUID string identifying this Knowledge Base File. |
| `knowledgeBasePk` | ✅  | string |                                                     |

#### 請求內容

**請求參數**

| 欄位                    | 類型             | 必填 | 說明                                                                                                                                                                                                          |
| --------------------- | -------------- | -- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| filename              | string         | 是  | 檔案名稱                                                                                                                                                                                                        |
| file                  | string (uri)   | 是  | 要上傳的檔案                                                                                                                                                                                                      |
| parser                | string (uuid)  | 否  |                                                                                                                                                                                                             |
| labels                | array\[IdName] | 否  |                                                                                                                                                                                                             |
| rawUserDefineMetadata | object         | 否  |                                                                                                                                                                                                             |
| asrOptions            | object         | 否  | Per-file canonical transcription options (languages, prompt, diarization). Empty means no per-file options: provider defaults apply. Completely decoupled from user-defined metadata; never indexed for ... |

**請求結構範例**

```typescript
{
  "filename": string // 檔案名稱
  "file": string (uri) // 要上傳的檔案
  "parser"?: string (uuid) // 非必填
  "labels"?: [ // 非必填
    {
      "id": string (uuid)
    }
  ]
  "rawUserDefineMetadata"?: object // 非必填
  "asrOptions"?: object // Per-file canonical transcription options (languages, prompt, diarization). Empty means no per-file options: provider defaults apply. Completely decoupled from user-defined metadata; never indexed for search. (非必填)
}
```

**請求範例值**

```json
{
  "filename": "document.pdf",
  "file": "https://example.com/file.jpg",
  "parser": "550e8400-e29b-41d4-a716-446655440000",
  "labels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000"
    }
  ],
  "rawUserDefineMetadata": null,
  "asrOptions": null
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X PUT "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "filename": "document.pdf",
    "file": "https://example.com/file.jpg",
    "parser": "550e8400-e29b-41d4-a716-446655440000",
    "labels": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000"
      }
    ],
    "rawUserDefineMetadata": null,
    "asrOptions": null
  }'

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// 請求內容 (payload)
const data = {
    "filename": "document.pdf",
    "file": "https://example.com/file.jpg",
    "parser": "550e8400-e29b-41d4-a716-446655440000",
    "labels": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000"
      }
    ],
    "rawUserDefineMetadata": null,
    "asrOptions": null
  };

axios.put("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "filename": "document.pdf",
    "file": "https://example.com/file.jpg",
    "parser": "550e8400-e29b-41d4-a716-446655440000",
    "labels": [
        {
            "id": "550e8400-e29b-41d4-a716-446655440000"
        }
    ],
    "rawUserDefineMetadata": None,
    "asrOptions": None
}

response = requests.put(url, json=data, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->put("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'filename' => 'document.pdf',
            'file' => 'https://example.com/file.jpg',
            'parser' => '550e8400-e29b-41d4-a716-446655440000',
            'labels' => [
                [
                    'id' => '550e8400-e29b-41d4-a716-446655440000'
                ]
            ],
            'rawUserDefineMetadata' => null,
            'asrOptions' => null
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "filename": string // 檔案名稱
  "file": string (uri) // 要上傳的檔案
  "fileType": string
  "knowledgeBase"?:  // 非必填
  {
    "id": string (uuid)
    "name": string
  }
  "size": integer // File size in bytes
  "status": 
  {
  }
  "parser": 
  {
    "id": string (uuid)
    "name": string
    "provider": string (enum: maiagent, llama, azure, docling, whisper_groq, whisper_openai, whisper_offline, localai, anthropic, bronci, alibaba, rap, vertex, cohere) // * `maiagent` - MaiAgent
* `llama` - Llama
* `azure` - Azure
* `docling` - Docling
* `whisper_groq` - WhisperGroq
* `whisper_openai` - WhisperOpenAI
* `whisper_offline` - WhisperOffline
* `localai` - LocalAI
* `anthropic` - Anthropic
* `bronci` - Bronci
* `alibaba` - Alibaba Qwen
* `rap` - Taiwan AI RAP
* `vertex` - Vertex AI
* `cohere` - Cohere
    "isTimestampSttProvider": boolean
  }
  "labels"?: [ // 非必填
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "rawUserDefineMetadata"?: object // 非必填
  "speakerLabels": [
    {
      "id": string (uuid)
      "originalLabel": string // Original speaker label from diarization (e.g., SPEAKER_00)
      "customName"?: string // User-defined speaker name (e.g., John) (非必填)
      "displayName": string
    }
  ]
  "vectorStorageSize": integer // Size of vectors for this file in Elasticsearch (bytes)
  "chunksCount": integer // Number of chunks/nodes generated from this file
  "waitingTime": number (double)
  "processingTime": number (double)
  "processingTimeDetails": object
  "ocrStatus": string // 掃描頁 OCR 結果：done、skipped、partial、off；解析前或舊檔案為 null
  "ocrSkippedReason": string // 掃描頁沒做 OCR 的原因：no_azure_settings、azure_unavailable、insufficient_credits、transient_error、time_budget、disabled；有做完時為 null
  "visualAnalysis": object // 影片畫面分析結果：status 為 completed 或 incomplete，reason 是未完成原因（model_error、timeout、video_unreadable、model_not_vision、no_describable_content），frame_cap_reached 表示畫面張數達上限；沒做過畫面分析的檔案為 null
  "parserAutoDetection":  // 自動偵測替這份檔選解析器的結果與原因；使用者自己選的、上線前上傳的、重新判斷排隊中的檔為 null
  {
    "parser":  // 自動偵測選到的解析器
    {
      "id": string (uuid)
      "name": string
      "provider": string (enum: maiagent, llama, azure, docling, whisper_groq, whisper_openai, whisper_offline, localai, anthropic, bronci, alibaba, rap, vertex, cohere) // * `maiagent` - MaiAgent
* `llama` - Llama
* `azure` - Azure
* `docling` - Docling
* `whisper_groq` - WhisperGroq
* `whisper_openai` - WhisperOpenAI
* `whisper_offline` - WhisperOffline
* `localai` - LocalAI
* `anthropic` - Anthropic
* `bronci` - Bronci
* `alibaba` - Alibaba Qwen
* `rap` - Taiwan AI RAP
* `vertex` - Vertex AI
* `cohere` - Cohere
      "isTimestampSttProvider": boolean
    }
    "reason": string // 原因類別：scanned、image_pages、large_images、unmeasurable_images、presentation、no_image_content、below_threshold、no_content、file_type_not_detected、detection_failed、vision_unavailable；之後可能新增類別，沒有對應文案時請顯示通用句
    "facts": object // 原因裡的數字（判斷當下算出，之後不重算）。PDF 與簡報（一張投影片算一頁）：analyzed_pages（判斷看的頁數）、partial（是否只看前面幾頁）、non_blank_pages、scanned_pages、image_pages（需要以圖片判讀的頁）；Word：figures（內文大圖數）、text_chars（內文字數）；其他情況為空物件
    "detectedAt": string (timestamp) // 判斷時間
  }
  "previewUrl": string // 簡報（pptx/ppt）回傳可預覽的 pdf 衍生檔 URL（前端用 PDF 預覽器顯示）；其餘為 None。

用與 `file` 欄位相同的 CustomizedFileFieldSerializer 產 URL，確保格式一致（含各
storage provider 的 presign/host 規則）。不可用 get_absolute_url()——它產出的 URL 格式錯誤。
  "createdAt": string (timestamp)
  "parseQueue":  // 檔案在等 Vision 解析名額時的排隊位置；沒在排隊或沒有排隊資料時為 null（顯示「處理中」）
  {
    "position": integer // 同組織排在前面、目前可以開始的檔案數；0＝下一個就是它；null＝被超大檔同時處理上限擋住
  }
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "filename": "回應字串",
  "file": "https://example.com/file.jpg",
  "fileType": "回應字串",
  "knowledgeBase": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應字串"
  },
  "size": 456,
  "status": {},
  "parser": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應字串",
    "provider": "maiagent",
    "isTimestampSttProvider": false
  },
  "labels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ],
  "rawUserDefineMetadata": null,
  "speakerLabels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "originalLabel": "回應字串",
      "customName": "回應字串",
      "displayName": "回應字串"
    }
  ],
  "vectorStorageSize": 456,
  "chunksCount": 456,
  "waitingTime": 456,
  "processingTime": 456,
  "processingTimeDetails": null,
  "ocrStatus": "回應字串",
  "ocrSkippedReason": "回應字串",
  "visualAnalysis": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "parserAutoDetection": {
    "parser": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串",
      "provider": "maiagent",
      "isTimestampSttProvider": false
    },
    "reason": "回應字串",
    "facts": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應範例名稱",
      "description": "回應範例描述"
    },
    "detectedAt": "回應字串"
  },
  "previewUrl": "回應字串",
  "createdAt": "回應字串",
  "parseQueue": {
    "position": 456
  }
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 部分更新檔案 <a href="#knowledge-bases-files-partial-update" id="knowledge-bases-files-partial-update"></a>

PATCH `/api/v1/knowledge-bases/{knowledgeBasePk}/files/{id}/`

#### 參數

| 參數名稱              | 必填 | 類型     | 說明                                                  |
| ----------------- | -- | ------ | --------------------------------------------------- |
| `id`              | ✅  | string | A UUID string identifying this Knowledge Base File. |
| `knowledgeBasePk` | ✅  | string |                                                     |

#### 請求內容

**請求參數**

| 欄位                    | 類型             | 必填 | 說明                                                                                                                                                                                                          |
| --------------------- | -------------- | -- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| filename              | string         | 否  | 檔案名稱                                                                                                                                                                                                        |
| file                  | string (uri)   | 否  | 要上傳的檔案                                                                                                                                                                                                      |
| parser                | string (uuid)  | 否  |                                                                                                                                                                                                             |
| labels                | array\[IdName] | 否  |                                                                                                                                                                                                             |
| rawUserDefineMetadata | object         | 否  |                                                                                                                                                                                                             |
| asrOptions            | object         | 否  | Per-file canonical transcription options (languages, prompt, diarization). Empty means no per-file options: provider defaults apply. Completely decoupled from user-defined metadata; never indexed for ... |

**請求結構範例**

```typescript
{
  "filename"?: string // 檔案名稱 (非必填)
  "file"?: string (uri) // 要上傳的檔案 (非必填)
  "parser"?: string (uuid) // 非必填
  "labels"?: [ // 非必填
    {
      "id": string (uuid)
    }
  ]
  "rawUserDefineMetadata"?: object // 非必填
  "asrOptions"?: object // Per-file canonical transcription options (languages, prompt, diarization). Empty means no per-file options: provider defaults apply. Completely decoupled from user-defined metadata; never indexed for search. (非必填)
}
```

**請求範例值**

```json
{
  "filename": "document.pdf",
  "file": "https://example.com/file.jpg",
  "parser": "550e8400-e29b-41d4-a716-446655440000",
  "labels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000"
    }
  ],
  "rawUserDefineMetadata": null,
  "asrOptions": null
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X PATCH "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "filename": "document.pdf",
    "file": "https://example.com/file.jpg",
    "parser": "550e8400-e29b-41d4-a716-446655440000",
    "labels": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000"
      }
    ],
    "rawUserDefineMetadata": null,
    "asrOptions": null
  }'

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// 請求內容 (payload)
const data = {
    "filename": "document.pdf",
    "file": "https://example.com/file.jpg",
    "parser": "550e8400-e29b-41d4-a716-446655440000",
    "labels": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000"
      }
    ],
    "rawUserDefineMetadata": null,
    "asrOptions": null
  };

axios.patch("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "filename": "document.pdf",
    "file": "https://example.com/file.jpg",
    "parser": "550e8400-e29b-41d4-a716-446655440000",
    "labels": [
        {
            "id": "550e8400-e29b-41d4-a716-446655440000"
        }
    ],
    "rawUserDefineMetadata": None,
    "asrOptions": None
}

response = requests.patch(url, json=data, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->patch("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'filename' => 'document.pdf',
            'file' => 'https://example.com/file.jpg',
            'parser' => '550e8400-e29b-41d4-a716-446655440000',
            'labels' => [
                [
                    'id' => '550e8400-e29b-41d4-a716-446655440000'
                ]
            ],
            'rawUserDefineMetadata' => null,
            'asrOptions' => null
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "filename": string // 檔案名稱
  "file": string (uri) // 要上傳的檔案
  "fileType": string
  "knowledgeBase"?:  // 非必填
  {
    "id": string (uuid)
    "name": string
  }
  "size": integer // File size in bytes
  "status": 
  {
  }
  "parser": 
  {
    "id": string (uuid)
    "name": string
    "provider": string (enum: maiagent, llama, azure, docling, whisper_groq, whisper_openai, whisper_offline, localai, anthropic, bronci, alibaba, rap, vertex, cohere) // * `maiagent` - MaiAgent
* `llama` - Llama
* `azure` - Azure
* `docling` - Docling
* `whisper_groq` - WhisperGroq
* `whisper_openai` - WhisperOpenAI
* `whisper_offline` - WhisperOffline
* `localai` - LocalAI
* `anthropic` - Anthropic
* `bronci` - Bronci
* `alibaba` - Alibaba Qwen
* `rap` - Taiwan AI RAP
* `vertex` - Vertex AI
* `cohere` - Cohere
    "isTimestampSttProvider": boolean
  }
  "labels"?: [ // 非必填
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "rawUserDefineMetadata"?: object // 非必填
  "speakerLabels": [
    {
      "id": string (uuid)
      "originalLabel": string // Original speaker label from diarization (e.g., SPEAKER_00)
      "customName"?: string // User-defined speaker name (e.g., John) (非必填)
      "displayName": string
    }
  ]
  "vectorStorageSize": integer // Size of vectors for this file in Elasticsearch (bytes)
  "chunksCount": integer // Number of chunks/nodes generated from this file
  "waitingTime": number (double)
  "processingTime": number (double)
  "processingTimeDetails": object
  "ocrStatus": string // 掃描頁 OCR 結果：done、skipped、partial、off；解析前或舊檔案為 null
  "ocrSkippedReason": string // 掃描頁沒做 OCR 的原因：no_azure_settings、azure_unavailable、insufficient_credits、transient_error、time_budget、disabled；有做完時為 null
  "visualAnalysis": object // 影片畫面分析結果：status 為 completed 或 incomplete，reason 是未完成原因（model_error、timeout、video_unreadable、model_not_vision、no_describable_content），frame_cap_reached 表示畫面張數達上限；沒做過畫面分析的檔案為 null
  "parserAutoDetection":  // 自動偵測替這份檔選解析器的結果與原因；使用者自己選的、上線前上傳的、重新判斷排隊中的檔為 null
  {
    "parser":  // 自動偵測選到的解析器
    {
      "id": string (uuid)
      "name": string
      "provider": string (enum: maiagent, llama, azure, docling, whisper_groq, whisper_openai, whisper_offline, localai, anthropic, bronci, alibaba, rap, vertex, cohere) // * `maiagent` - MaiAgent
* `llama` - Llama
* `azure` - Azure
* `docling` - Docling
* `whisper_groq` - WhisperGroq
* `whisper_openai` - WhisperOpenAI
* `whisper_offline` - WhisperOffline
* `localai` - LocalAI
* `anthropic` - Anthropic
* `bronci` - Bronci
* `alibaba` - Alibaba Qwen
* `rap` - Taiwan AI RAP
* `vertex` - Vertex AI
* `cohere` - Cohere
      "isTimestampSttProvider": boolean
    }
    "reason": string // 原因類別：scanned、image_pages、large_images、unmeasurable_images、presentation、no_image_content、below_threshold、no_content、file_type_not_detected、detection_failed、vision_unavailable；之後可能新增類別，沒有對應文案時請顯示通用句
    "facts": object // 原因裡的數字（判斷當下算出，之後不重算）。PDF 與簡報（一張投影片算一頁）：analyzed_pages（判斷看的頁數）、partial（是否只看前面幾頁）、non_blank_pages、scanned_pages、image_pages（需要以圖片判讀的頁）；Word：figures（內文大圖數）、text_chars（內文字數）；其他情況為空物件
    "detectedAt": string (timestamp) // 判斷時間
  }
  "previewUrl": string // 簡報（pptx/ppt）回傳可預覽的 pdf 衍生檔 URL（前端用 PDF 預覽器顯示）；其餘為 None。

用與 `file` 欄位相同的 CustomizedFileFieldSerializer 產 URL，確保格式一致（含各
storage provider 的 presign/host 規則）。不可用 get_absolute_url()——它產出的 URL 格式錯誤。
  "createdAt": string (timestamp)
  "parseQueue":  // 檔案在等 Vision 解析名額時的排隊位置；沒在排隊或沒有排隊資料時為 null（顯示「處理中」）
  {
    "position": integer // 同組織排在前面、目前可以開始的檔案數；0＝下一個就是它；null＝被超大檔同時處理上限擋住
  }
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "filename": "回應字串",
  "file": "https://example.com/file.jpg",
  "fileType": "回應字串",
  "knowledgeBase": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應字串"
  },
  "size": 456,
  "status": {},
  "parser": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應字串",
    "provider": "maiagent",
    "isTimestampSttProvider": false
  },
  "labels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ],
  "rawUserDefineMetadata": null,
  "speakerLabels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "originalLabel": "回應字串",
      "customName": "回應字串",
      "displayName": "回應字串"
    }
  ],
  "vectorStorageSize": 456,
  "chunksCount": 456,
  "waitingTime": 456,
  "processingTime": 456,
  "processingTimeDetails": null,
  "ocrStatus": "回應字串",
  "ocrSkippedReason": "回應字串",
  "visualAnalysis": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "parserAutoDetection": {
    "parser": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串",
      "provider": "maiagent",
      "isTimestampSttProvider": false
    },
    "reason": "回應字串",
    "facts": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應範例名稱",
      "description": "回應範例描述"
    },
    "detectedAt": "回應字串"
  },
  "previewUrl": "回應字串",
  "createdAt": "回應字串",
  "parseQueue": {
    "position": 456
  }
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 刪除檔案 <a href="#knowledge-bases-files-destroy" id="knowledge-bases-files-destroy"></a>

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

#### 參數

| 參數名稱              | 必填 | 類型     | 說明                                                  |
| ----------------- | -- | ------ | --------------------------------------------------- |
| `id`              | ✅  | string | A UUID string identifying this Knowledge Base File. |
| `knowledgeBasePk` | ✅  | string |                                                     |

#### 程式碼範例

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

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

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

// 請求內容 (payload)
const data = null;

axios.delete("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.delete(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->delete("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/files/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 202**

**回應結構範例**

```typescript
{
  "detail": string
}
```

**回應範例值**

```json
{
  "detail": "回應字串"
}
```

**狀態碼: 204 - No response body**

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 建立檔案翻譯 <a href="#knowledge-bases-files-translations-create" id="knowledge-bases-files-translations-create"></a>

POST `/api/v1/knowledge-bases/{knowledgeBasePk}/files/{knowledgeBaseFilePk}/translations/`

#### 參數

| 參數名稱                  | 必填 | 類型     | 說明 |
| --------------------- | -- | ------ | -- |
| `knowledgeBaseFilePk` | ✅  | string |    |
| `knowledgeBasePk`     | ✅  | string |    |

#### 請求內容

**請求參數**

| 欄位                   | 類型            | 必填 | 說明 |
| -------------------- | ------------- | -- | -- |
| sourceLanguage       | string        | 否  |    |
| targetLanguage       | string        | 是  |    |
| customPrompt         | string        | 否  |    |
| largeLanguageModelId | string (uuid) | 是  |    |

**請求結構範例**

```typescript
{
  "sourceLanguage"?: string // 非必填
  "targetLanguage": string
  "customPrompt"?: string // 非必填
  "largeLanguageModelId": string (uuid)
}
```

**請求範例值**

```json
{
  "sourceLanguage": "範例字串",
  "targetLanguage": "範例字串",
  "customPrompt": "範例字串",
  "largeLanguageModelId": "550e8400-e29b-41d4-a716-446655440000"
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/knowledge-bases/{knowledgeBasePk}/files/{knowledgeBaseFilePk}/translations/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "sourceLanguage": "範例字串",
    "targetLanguage": "範例字串",
    "customPrompt": "範例字串",
    "largeLanguageModelId": "550e8400-e29b-41d4-a716-446655440000"
  }'

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// 請求內容 (payload)
const data = {
    "sourceLanguage": "範例字串",
    "targetLanguage": "範例字串",
    "customPrompt": "範例字串",
    "largeLanguageModelId": "550e8400-e29b-41d4-a716-446655440000"
  };

axios.post("https://api.maiagent.ai/api/v1/knowledge-bases/{knowledgeBasePk}/files/{knowledgeBaseFilePk}/translations/", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/{knowledgeBasePk}/files/{knowledgeBaseFilePk}/translations/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "sourceLanguage": "範例字串",
    "targetLanguage": "範例字串",
    "customPrompt": "範例字串",
    "largeLanguageModelId": "550e8400-e29b-41d4-a716-446655440000"
}

response = requests.post(url, json=data, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/knowledge-bases/{knowledgeBasePk}/files/{knowledgeBaseFilePk}/translations/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'sourceLanguage' => '範例字串',
            'targetLanguage' => '範例字串',
            'customPrompt' => '範例字串',
            'largeLanguageModelId' => '550e8400-e29b-41d4-a716-446655440000'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 201**

**回應結構範例**

```typescript
{
  "sourceLanguage"?: string // 非必填
  "targetLanguage": string
  "customPrompt"?: string // 非必填
  "largeLanguageModelId": string (uuid)
}
```

**回應範例值**

```json
{
  "sourceLanguage": "回應字串",
  "targetLanguage": "回應字串",
  "customPrompt": "回應字串",
  "largeLanguageModelId": "550e8400-e29b-41d4-a716-446655440000"
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 列出檔案翻譯 <a href="#knowledge-bases-files-translations-list" id="knowledge-bases-files-translations-list"></a>

GET `/api/v1/knowledge-bases/{knowledgeBasePk}/files/{knowledgeBaseFilePk}/translations/`

#### 參數

| 參數名稱                  | 必填 | 類型      | 說明                                             |
| --------------------- | -- | ------- | ---------------------------------------------- |
| `knowledgeBaseFilePk` | ✅  | string  |                                                |
| `knowledgeBasePk`     | ✅  | string  |                                                |
| `page`                | ❌  | integer | A page number within the paginated result set. |
| `pageSize`            | ❌  | integer | Number of results to return per page.          |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/knowledge-bases/{knowledgeBasePk}/files/{knowledgeBaseFilePk}/translations/?page=1&pageSize=1" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/knowledge-bases/{knowledgeBasePk}/files/{knowledgeBaseFilePk}/translations/?page=1&pageSize=1", config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/{knowledgeBasePk}/files/{knowledgeBaseFilePk}/translations/?page=1&pageSize=1"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/knowledge-bases/{knowledgeBasePk}/files/{knowledgeBaseFilePk}/translations/?page=1&pageSize=1", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "count": integer
  "next"?: string (uri) // 非必填
  "previous"?: string (uri) // 非必填
  "results": [
    {
      "id": string (uuid)
      "chatbotFileId": string (uuid)
      "chatbotFileFilename": string
      "organization": string (uuid)
      "largeLanguageModel": 
      {
        "id": string (uuid)
        "name": string
      }
      "sourceLanguage": string
      "targetLanguage": string
      "customPrompt": string // User-provided terminology/glossary rules
      "status": 
      {
      }
      "errorMessage": string
      "translatedFileUrl": string
      "bilingualFileUrl": string
      "processDuration": string
      "processingDurationSeconds": number (double)
      "pageCount": integer
      "originalWordCount": integer
      "translatedWordCount": integer
      "totalBlocks": integer // Paragraphs the translation engine found in the document; null when not reported.
      "untranslatedBlocks": integer // Paragraphs left in the source language because the model gave no translation.
      "completeness": // 可能有不同的類型
      string (enum: complete, partial, low) // complete: every paragraph translated; partial: some paragraphs kept the source text; low: more than 10% kept the source text; null: not a successful translation, or not counted.

* `complete` - Complete
* `partial` - Partially untranslated
* `low` - Low completeness
      "untranslatablePages": [ // Page numbers (starting at 1) of pages that are an image with no text at all and kept their original content; empty when no page is like that, for a layout export, when the file could not be checked, or when the translation predates this check.
        integer
      ]
      "inputTokensUsed": integer
      "outputTokensUsed": integer
      "totalTokensUsed": integer
      "originalFileSize": integer
      "translatedFileSize": integer
      "bilingualFileSize": integer
      "llmTranslationDuration": string // Total time spent on LLM API calls
      "llmTranslationDurationSeconds": number (double)
      "llmCallCount": integer // Number of LLM API calls made
      "avgLlmCallDuration": number (double) // Average time per LLM call in seconds
      "pdfParsingDuration": string // Time spent on PDF parsing and processing
      "pdfParsingDurationSeconds": number (double)
      "fileSavingDuration": string // Time spent on saving output files
      "fileSavingDurationSeconds": number (double)
      "startedAt": string (timestamp)
      "completedAt": string (timestamp)
      "createdAt": string (timestamp)
      "updatedAt": string (timestamp)
    }
  ]
}
```

**回應範例值**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "chatbotFileId": "550e8400-e29b-41d4-a716-446655440000",
      "chatbotFileFilename": "回應字串",
      "organization": "550e8400-e29b-41d4-a716-446655440000",
      "largeLanguageModel": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應字串"
      },
      "sourceLanguage": "回應字串",
      "targetLanguage": "回應字串",
      "customPrompt": "回應字串",
      "status": {},
      "errorMessage": "回應字串",
      "translatedFileUrl": "回應字串",
      "bilingualFileUrl": "回應字串",
      "processDuration": "回應字串",
      "processingDurationSeconds": 456,
      "pageCount": 456,
      "originalWordCount": 456,
      "translatedWordCount": 456,
      "totalBlocks": 456,
      "untranslatedBlocks": 456,
      "completeness": "complete",
      "untranslatablePages": [
        456
      ],
      "inputTokensUsed": 456,
      "outputTokensUsed": 456,
      "totalTokensUsed": 456,
      "originalFileSize": 456,
      "translatedFileSize": 456,
      "bilingualFileSize": 456,
      "llmTranslationDuration": "回應字串",
      "llmTranslationDurationSeconds": 456,
      "llmCallCount": 456,
      "avgLlmCallDuration": 456,
      "pdfParsingDuration": "回應字串",
      "pdfParsingDurationSeconds": 456,
      "fileSavingDuration": "回應字串",
      "fileSavingDurationSeconds": 456,
      "startedAt": "回應字串",
      "completedAt": "回應字串",
      "createdAt": "回應字串",
      "updatedAt": "回應字串"
    }
  ]
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 取得特定翻譯 <a href="#knowledge-bases-files-translations-retrieve" id="knowledge-bases-files-translations-retrieve"></a>

GET `/api/v1/knowledge-bases/{knowledgeBasePk}/files/{knowledgeBaseFilePk}/translations/{id}/`

#### 參數

| 參數名稱                  | 必填 | 類型     | 說明                                               |
| --------------------- | -- | ------ | ------------------------------------------------ |
| `id`                  | ✅  | string | A UUID string identifying this File Translation. |
| `knowledgeBaseFilePk` | ✅  | string |                                                  |
| `knowledgeBasePk`     | ✅  | string |                                                  |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/knowledge-bases/{knowledgeBasePk}/files/{knowledgeBaseFilePk}/translations/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/knowledge-bases/{knowledgeBasePk}/files/{knowledgeBaseFilePk}/translations/550e8400-e29b-41d4-a716-446655440000/", config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/{knowledgeBasePk}/files/{knowledgeBaseFilePk}/translations/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/knowledge-bases/{knowledgeBasePk}/files/{knowledgeBaseFilePk}/translations/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "chatbotFileId": string (uuid)
  "chatbotFileFilename": string
  "organization": string (uuid)
  "largeLanguageModel": 
  {
    "id": string (uuid)
    "name": string
  }
  "sourceLanguage": string
  "targetLanguage": string
  "customPrompt": string // User-provided terminology/glossary rules
  "status": 
  {
  }
  "errorMessage": string
  "translatedFileUrl": string
  "bilingualFileUrl": string
  "processDuration": string
  "processingDurationSeconds": number (double)
  "pageCount": integer
  "originalWordCount": integer
  "translatedWordCount": integer
  "totalBlocks": integer // Paragraphs the translation engine found in the document; null when not reported.
  "untranslatedBlocks": integer // Paragraphs left in the source language because the model gave no translation.
  "completeness": // 可能有不同的類型
  string (enum: complete, partial, low) // complete: every paragraph translated; partial: some paragraphs kept the source text; low: more than 10% kept the source text; null: not a successful translation, or not counted.

* `complete` - Complete
* `partial` - Partially untranslated
* `low` - Low completeness
  "untranslatablePages": [ // Page numbers (starting at 1) of pages that are an image with no text at all and kept their original content; empty when no page is like that, for a layout export, when the file could not be checked, or when the translation predates this check.
    integer
  ]
  "inputTokensUsed": integer
  "outputTokensUsed": integer
  "totalTokensUsed": integer
  "originalFileSize": integer
  "translatedFileSize": integer
  "bilingualFileSize": integer
  "llmTranslationDuration": string // Total time spent on LLM API calls
  "llmTranslationDurationSeconds": number (double)
  "llmCallCount": integer // Number of LLM API calls made
  "avgLlmCallDuration": number (double) // Average time per LLM call in seconds
  "pdfParsingDuration": string // Time spent on PDF parsing and processing
  "pdfParsingDurationSeconds": number (double)
  "fileSavingDuration": string // Time spent on saving output files
  "fileSavingDurationSeconds": number (double)
  "startedAt": string (timestamp)
  "completedAt": string (timestamp)
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "chatbotFileId": "550e8400-e29b-41d4-a716-446655440000",
  "chatbotFileFilename": "回應字串",
  "organization": "550e8400-e29b-41d4-a716-446655440000",
  "largeLanguageModel": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應字串"
  },
  "sourceLanguage": "回應字串",
  "targetLanguage": "回應字串",
  "customPrompt": "回應字串",
  "status": {},
  "errorMessage": "回應字串",
  "translatedFileUrl": "回應字串",
  "bilingualFileUrl": "回應字串",
  "processDuration": "回應字串",
  "processingDurationSeconds": 456,
  "pageCount": 456,
  "originalWordCount": 456,
  "translatedWordCount": 456,
  "totalBlocks": 456,
  "untranslatedBlocks": 456,
  "completeness": "complete",
  "untranslatablePages": [
    456
  ],
  "inputTokensUsed": 456,
  "outputTokensUsed": 456,
  "totalTokensUsed": 456,
  "originalFileSize": 456,
  "translatedFileSize": 456,
  "bilingualFileSize": 456,
  "llmTranslationDuration": "回應字串",
  "llmTranslationDurationSeconds": 456,
  "llmCallCount": 456,
  "avgLlmCallDuration": 456,
  "pdfParsingDuration": "回應字串",
  "pdfParsingDurationSeconds": 456,
  "fileSavingDuration": "回應字串",
  "fileSavingDurationSeconds": 456,
  "startedAt": "回應字串",
  "completedAt": "回應字串",
  "createdAt": "回應字串",
  "updatedAt": "回應字串"
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 刪除翻譯 <a href="#knowledge-bases-files-translations-destroy" id="knowledge-bases-files-translations-destroy"></a>

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

#### 參數

| 參數名稱                  | 必填 | 類型     | 說明                                               |
| --------------------- | -- | ------ | ------------------------------------------------ |
| `id`                  | ✅  | string | A UUID string identifying this File Translation. |
| `knowledgeBaseFilePk` | ✅  | string |                                                  |
| `knowledgeBasePk`     | ✅  | string |                                                  |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X DELETE "https://api.maiagent.ai/api/v1/knowledge-bases/{knowledgeBasePk}/files/{knowledgeBaseFilePk}/translations/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

// 請求內容 (payload)
const data = null;

axios.delete("https://api.maiagent.ai/api/v1/knowledge-bases/{knowledgeBasePk}/files/{knowledgeBaseFilePk}/translations/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/{knowledgeBasePk}/files/{knowledgeBaseFilePk}/translations/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.delete(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->delete("https://api.maiagent.ai/api/v1/knowledge-bases/{knowledgeBasePk}/files/{knowledgeBaseFilePk}/translations/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

| 狀態碼 | 說明                                                                 |
| --- | ------------------------------------------------------------------ |
| 204 | No response body                                                   |
| 4XX | Error response; X-Error-Code carries its code (see "Error codes"). |

***

### 下載翻譯檔案 <a href="#knowledge-bases-files-translations-download-retrieve" id="knowledge-bases-files-translations-download-retrieve"></a>

GET `/api/v1/knowledge-bases/{knowledgeBasePk}/files/{knowledgeBaseFilePk}/translations/{id}/download/`

#### 參數

| 參數名稱                  | 必填 | 類型     | 說明                                               |
| --------------------- | -- | ------ | ------------------------------------------------ |
| `id`                  | ✅  | string | A UUID string identifying this File Translation. |
| `knowledgeBaseFilePk` | ✅  | string |                                                  |
| `knowledgeBasePk`     | ✅  | string |                                                  |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/knowledge-bases/{knowledgeBasePk}/files/{knowledgeBaseFilePk}/translations/550e8400-e29b-41d4-a716-446655440000/download/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/knowledge-bases/{knowledgeBasePk}/files/{knowledgeBaseFilePk}/translations/550e8400-e29b-41d4-a716-446655440000/download/", config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/{knowledgeBasePk}/files/{knowledgeBaseFilePk}/translations/550e8400-e29b-41d4-a716-446655440000/download/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/knowledge-bases/{knowledgeBasePk}/files/{knowledgeBaseFilePk}/translations/550e8400-e29b-41d4-a716-446655440000/download/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "chatbotFileId": string (uuid)
  "chatbotFileFilename": string
  "organization": string (uuid)
  "largeLanguageModel": 
  {
    "id": string (uuid)
    "name": string
  }
  "sourceLanguage": string
  "targetLanguage": string
  "customPrompt": string // User-provided terminology/glossary rules
  "status": 
  {
  }
  "errorMessage": string
  "translatedFileUrl": string
  "bilingualFileUrl": string
  "processDuration": string
  "processingDurationSeconds": number (double)
  "pageCount": integer
  "originalWordCount": integer
  "translatedWordCount": integer
  "totalBlocks": integer // Paragraphs the translation engine found in the document; null when not reported.
  "untranslatedBlocks": integer // Paragraphs left in the source language because the model gave no translation.
  "completeness": // 可能有不同的類型
  string (enum: complete, partial, low) // complete: every paragraph translated; partial: some paragraphs kept the source text; low: more than 10% kept the source text; null: not a successful translation, or not counted.

* `complete` - Complete
* `partial` - Partially untranslated
* `low` - Low completeness
  "untranslatablePages": [ // Page numbers (starting at 1) of pages that are an image with no text at all and kept their original content; empty when no page is like that, for a layout export, when the file could not be checked, or when the translation predates this check.
    integer
  ]
  "inputTokensUsed": integer
  "outputTokensUsed": integer
  "totalTokensUsed": integer
  "originalFileSize": integer
  "translatedFileSize": integer
  "bilingualFileSize": integer
  "llmTranslationDuration": string // Total time spent on LLM API calls
  "llmTranslationDurationSeconds": number (double)
  "llmCallCount": integer // Number of LLM API calls made
  "avgLlmCallDuration": number (double) // Average time per LLM call in seconds
  "pdfParsingDuration": string // Time spent on PDF parsing and processing
  "pdfParsingDurationSeconds": number (double)
  "fileSavingDuration": string // Time spent on saving output files
  "fileSavingDurationSeconds": number (double)
  "startedAt": string (timestamp)
  "completedAt": string (timestamp)
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "chatbotFileId": "550e8400-e29b-41d4-a716-446655440000",
  "chatbotFileFilename": "回應字串",
  "organization": "550e8400-e29b-41d4-a716-446655440000",
  "largeLanguageModel": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應字串"
  },
  "sourceLanguage": "回應字串",
  "targetLanguage": "回應字串",
  "customPrompt": "回應字串",
  "status": {},
  "errorMessage": "回應字串",
  "translatedFileUrl": "回應字串",
  "bilingualFileUrl": "回應字串",
  "processDuration": "回應字串",
  "processingDurationSeconds": 456,
  "pageCount": 456,
  "originalWordCount": 456,
  "translatedWordCount": 456,
  "totalBlocks": 456,
  "untranslatedBlocks": 456,
  "completeness": "complete",
  "untranslatablePages": [
    456
  ],
  "inputTokensUsed": 456,
  "outputTokensUsed": 456,
  "totalTokensUsed": 456,
  "originalFileSize": 456,
  "translatedFileSize": 456,
  "bilingualFileSize": 456,
  "llmTranslationDuration": "回應字串",
  "llmTranslationDurationSeconds": 456,
  "llmCallCount": 456,
  "avgLlmCallDuration": 456,
  "pdfParsingDuration": "回應字串",
  "pdfParsingDurationSeconds": 456,
  "fileSavingDuration": "回應字串",
  "fileSavingDurationSeconds": 456,
  "startedAt": "回應字串",
  "completedAt": "回應字串",
  "createdAt": "回應字串",
  "updatedAt": "回應字串"
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 列出知識庫文件 <a href="#knowledge-bases-documents-list" id="knowledge-bases-documents-list"></a>

GET `/api/v1/knowledge-bases/{knowledgeBasePk}/documents/`

#### 參數

| 參數名稱                  | 必填 | 類型     | 說明                                        |
| --------------------- | -- | ------ | ----------------------------------------- |
| `knowledgeBasePk`     | ✅  | string |                                           |
| `chatbotFileId`       | ❌  | string | 【將棄用】檔案 ID（請使用 knowledge\_base\_file\_id） |
| `knowledgeBaseFileId` | ❌  | string | 知識庫檔案 ID                                  |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/documents/?chatbotFileId=example&knowledgeBaseFileId=example" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/documents/?chatbotFileId=example&knowledgeBaseFileId=example", config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/documents/?chatbotFileId=example&knowledgeBaseFileId=example"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/documents/?chatbotFileId=example&knowledgeBaseFileId=example", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
[
  {
    "id": string (uuid)
    "fileName": string
    "pageNumber"?: integer // 非必填
    "chatbotFile": string (uuid)
    "excludedEmbedMetadataKeys"?: object // List[str]: metadata keys to exclude from the embedding. (非必填)
    "excludedLlmMetadataKeys"?: object // List[str]: metadata keys to exclude from the LLM context. (非必填)
    "llamaIndexObjectJson"?: object // 非必填
    "metadata"?: object // 非必填
    "text": string
    "updatedAt": string (timestamp)
  }
]
```

**回應範例值**

```json
[
  {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "fileName": "回應字串",
    "pageNumber": 456,
    "chatbotFile": "550e8400-e29b-41d4-a716-446655440000",
    "excludedEmbedMetadataKeys": null,
    "excludedLlmMetadataKeys": null,
    "llamaIndexObjectJson": null,
    "metadata": null,
    "text": "回應字串",
    "updatedAt": "回應字串"
  }
]
```

**狀態碼: 404 - 知識庫檔案不存在，或不屬於目前組織**

***

### 更新文件 <a href="#knowledge-bases-documents-update" id="knowledge-bases-documents-update"></a>

PUT `/api/v1/knowledge-bases/{knowledgeBasePk}/documents/{id}/`

#### 參數

| 參數名稱              | 必填 | 類型     | 說明                                               |
| ----------------- | -- | ------ | ------------------------------------------------ |
| `id`              | ✅  | string | A UUID string identifying this Chatbot Document. |
| `knowledgeBasePk` | ✅  | string |                                                  |

#### 請求內容

**請求參數**

| 欄位                        | 類型            | 必填 | 說明                                                         |
| ------------------------- | ------------- | -- | ---------------------------------------------------------- |
| fileName                  | string        | 是  |                                                            |
| pageNumber                | integer       | 否  |                                                            |
| chatbotFile               | string (uuid) | 是  |                                                            |
| excludedEmbedMetadataKeys | object        | 否  | List\[str]: metadata keys to exclude from the embedding.   |
| excludedLlmMetadataKeys   | object        | 否  | List\[str]: metadata keys to exclude from the LLM context. |
| llamaIndexObjectJson      | object        | 否  |                                                            |
| metadata                  | object        | 否  |                                                            |
| text                      | string        | 是  |                                                            |

**請求結構範例**

```typescript
{
  "fileName": string
  "pageNumber"?: integer // 非必填
  "chatbotFile": string (uuid)
  "excludedEmbedMetadataKeys"?: object // List[str]: metadata keys to exclude from the embedding. (非必填)
  "excludedLlmMetadataKeys"?: object // List[str]: metadata keys to exclude from the LLM context. (非必填)
  "llamaIndexObjectJson"?: object // 非必填
  "metadata"?: object // 非必填
  "text": string
}
```

**請求範例值**

```json
{
  "fileName": "範例字串",
  "pageNumber": 123,
  "chatbotFile": "550e8400-e29b-41d4-a716-446655440000",
  "excludedEmbedMetadataKeys": null,
  "excludedLlmMetadataKeys": null,
  "llamaIndexObjectJson": null,
  "metadata": null,
  "text": "這是一個範例訊息"
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X PUT "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/documents/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "fileName": "範例字串",
    "pageNumber": 123,
    "chatbotFile": "550e8400-e29b-41d4-a716-446655440000",
    "excludedEmbedMetadataKeys": null,
    "excludedLlmMetadataKeys": null,
    "llamaIndexObjectJson": null,
    "metadata": null,
    "text": "這是一個範例訊息"
  }'

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// 請求內容 (payload)
const data = {
    "fileName": "範例字串",
    "pageNumber": 123,
    "chatbotFile": "550e8400-e29b-41d4-a716-446655440000",
    "excludedEmbedMetadataKeys": null,
    "excludedLlmMetadataKeys": null,
    "llamaIndexObjectJson": null,
    "metadata": null,
    "text": "這是一個範例訊息"
  };

axios.put("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/documents/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/documents/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "fileName": "範例字串",
    "pageNumber": 123,
    "chatbotFile": "550e8400-e29b-41d4-a716-446655440000",
    "excludedEmbedMetadataKeys": None,
    "excludedLlmMetadataKeys": None,
    "llamaIndexObjectJson": None,
    "metadata": None,
    "text": "這是一個範例訊息"
}

response = requests.put(url, json=data, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->put("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/documents/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'fileName' => '範例字串',
            'pageNumber' => 123,
            'chatbotFile' => '550e8400-e29b-41d4-a716-446655440000',
            'excludedEmbedMetadataKeys' => null,
            'excludedLlmMetadataKeys' => null,
            'llamaIndexObjectJson' => null,
            'metadata' => null,
            'text' => '這是一個範例訊息'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "fileName": string
  "pageNumber"?: integer // 非必填
  "chatbotFile": string (uuid)
  "excludedEmbedMetadataKeys"?: object // List[str]: metadata keys to exclude from the embedding. (非必填)
  "excludedLlmMetadataKeys"?: object // List[str]: metadata keys to exclude from the LLM context. (非必填)
  "llamaIndexObjectJson"?: object // 非必填
  "metadata"?: object // 非必填
  "text": string
  "updatedAt": string (timestamp)
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "fileName": "回應字串",
  "pageNumber": 456,
  "chatbotFile": "550e8400-e29b-41d4-a716-446655440000",
  "excludedEmbedMetadataKeys": null,
  "excludedLlmMetadataKeys": null,
  "llamaIndexObjectJson": null,
  "metadata": null,
  "text": "回應字串",
  "updatedAt": "回應字串"
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 部分更新文件 <a href="#knowledge-bases-documents-partial-update" id="knowledge-bases-documents-partial-update"></a>

PATCH `/api/v1/knowledge-bases/{knowledgeBasePk}/documents/{id}/`

#### 參數

| 參數名稱              | 必填 | 類型     | 說明                                               |
| ----------------- | -- | ------ | ------------------------------------------------ |
| `id`              | ✅  | string | A UUID string identifying this Chatbot Document. |
| `knowledgeBasePk` | ✅  | string |                                                  |

#### 請求內容

**請求參數**

| 欄位                        | 類型            | 必填 | 說明                                                         |
| ------------------------- | ------------- | -- | ---------------------------------------------------------- |
| fileName                  | string        | 否  |                                                            |
| pageNumber                | integer       | 否  |                                                            |
| chatbotFile               | string (uuid) | 否  |                                                            |
| excludedEmbedMetadataKeys | object        | 否  | List\[str]: metadata keys to exclude from the embedding.   |
| excludedLlmMetadataKeys   | object        | 否  | List\[str]: metadata keys to exclude from the LLM context. |
| llamaIndexObjectJson      | object        | 否  |                                                            |
| metadata                  | object        | 否  |                                                            |
| text                      | string        | 否  |                                                            |

**請求結構範例**

```typescript
{
  "fileName"?: string // 非必填
  "pageNumber"?: integer // 非必填
  "chatbotFile"?: string (uuid) // 非必填
  "excludedEmbedMetadataKeys"?: object // List[str]: metadata keys to exclude from the embedding. (非必填)
  "excludedLlmMetadataKeys"?: object // List[str]: metadata keys to exclude from the LLM context. (非必填)
  "llamaIndexObjectJson"?: object // 非必填
  "metadata"?: object // 非必填
  "text"?: string // 非必填
}
```

**請求範例值**

```json
{
  "fileName": "範例字串",
  "pageNumber": 123,
  "chatbotFile": "550e8400-e29b-41d4-a716-446655440000",
  "excludedEmbedMetadataKeys": null,
  "excludedLlmMetadataKeys": null,
  "llamaIndexObjectJson": null,
  "metadata": null,
  "text": "這是一個範例訊息"
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X PATCH "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/documents/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "fileName": "範例字串",
    "pageNumber": 123,
    "chatbotFile": "550e8400-e29b-41d4-a716-446655440000",
    "excludedEmbedMetadataKeys": null,
    "excludedLlmMetadataKeys": null,
    "llamaIndexObjectJson": null,
    "metadata": null,
    "text": "這是一個範例訊息"
  }'

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// 請求內容 (payload)
const data = {
    "fileName": "範例字串",
    "pageNumber": 123,
    "chatbotFile": "550e8400-e29b-41d4-a716-446655440000",
    "excludedEmbedMetadataKeys": null,
    "excludedLlmMetadataKeys": null,
    "llamaIndexObjectJson": null,
    "metadata": null,
    "text": "這是一個範例訊息"
  };

axios.patch("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/documents/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/documents/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "fileName": "範例字串",
    "pageNumber": 123,
    "chatbotFile": "550e8400-e29b-41d4-a716-446655440000",
    "excludedEmbedMetadataKeys": None,
    "excludedLlmMetadataKeys": None,
    "llamaIndexObjectJson": None,
    "metadata": None,
    "text": "這是一個範例訊息"
}

response = requests.patch(url, json=data, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->patch("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/documents/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'fileName' => '範例字串',
            'pageNumber' => 123,
            'chatbotFile' => '550e8400-e29b-41d4-a716-446655440000',
            'excludedEmbedMetadataKeys' => null,
            'excludedLlmMetadataKeys' => null,
            'llamaIndexObjectJson' => null,
            'metadata' => null,
            'text' => '這是一個範例訊息'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "fileName": string
  "pageNumber"?: integer // 非必填
  "chatbotFile": string (uuid)
  "excludedEmbedMetadataKeys"?: object // List[str]: metadata keys to exclude from the embedding. (非必填)
  "excludedLlmMetadataKeys"?: object // List[str]: metadata keys to exclude from the LLM context. (非必填)
  "llamaIndexObjectJson"?: object // 非必填
  "metadata"?: object // 非必填
  "text": string
  "updatedAt": string (timestamp)
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "fileName": "回應字串",
  "pageNumber": 456,
  "chatbotFile": "550e8400-e29b-41d4-a716-446655440000",
  "excludedEmbedMetadataKeys": null,
  "excludedLlmMetadataKeys": null,
  "llamaIndexObjectJson": null,
  "metadata": null,
  "text": "回應字串",
  "updatedAt": "回應字串"
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 刪除文件 <a href="#knowledge-bases-documents-destroy" id="knowledge-bases-documents-destroy"></a>

DELETE `/api/v1/knowledge-bases/{knowledgeBasePk}/documents/{id}/`

#### 參數

| 參數名稱              | 必填 | 類型     | 說明                                               |
| ----------------- | -- | ------ | ------------------------------------------------ |
| `id`              | ✅  | string | A UUID string identifying this Chatbot Document. |
| `knowledgeBasePk` | ✅  | string |                                                  |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X DELETE "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/documents/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

// 請求內容 (payload)
const data = null;

axios.delete("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/documents/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/documents/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.delete(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->delete("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/documents/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

| 狀態碼 | 說明                                                                 |
| --- | ------------------------------------------------------------------ |
| 204 | No response body                                                   |
| 4XX | Error response; X-Error-Code carries its code (see "Error codes"). |

***

### 建立新的 FAQ <a href="#knowledge-bases-faqs-create" id="knowledge-bases-faqs-create"></a>

POST `/api/v1/knowledge-bases/{knowledgeBasePk}/faqs/`

#### 參數

| 參數名稱              | 必填 | 類型     | 說明 |
| ----------------- | -- | ------ | -- |
| `knowledgeBasePk` | ✅  | string |    |

#### 請求內容

**請求參數**

| 欄位                    | 類型             | 必填 | 說明                                                             |
| --------------------- | -------------- | -- | -------------------------------------------------------------- |
| question              | string         | 是  |                                                                |
| answer                | string         | 是  |                                                                |
| answerMediaUrls       | object         | 否  | URLs of media files, such as images and videos, in the answer. |
| labels                | array\[IdName] | 否  |                                                                |
| rawUserDefineMetadata | object         | 否  |                                                                |

**請求結構範例**

```typescript
{
  "question": string
  "answer": string
  "answerMediaUrls"?: object // URLs of media files, such as images and videos, in the answer. (非必填)
  "labels"?: [ // 非必填
    {
      "id": string (uuid)
    }
  ]
  "rawUserDefineMetadata"?: object // 非必填
}
```

**請求範例值**

```json
{
  "question": "範例字串",
  "answer": "範例字串",
  "answerMediaUrls": null,
  "labels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000"
    }
  ],
  "rawUserDefineMetadata": null
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "question": "範例字串",
    "answer": "範例字串",
    "answerMediaUrls": null,
    "labels": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000"
      }
    ],
    "rawUserDefineMetadata": null
  }'

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// 請求內容 (payload)
const data = {
    "question": "範例字串",
    "answer": "範例字串",
    "answerMediaUrls": null,
    "labels": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000"
      }
    ],
    "rawUserDefineMetadata": null
  };

axios.post("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "question": "範例字串",
    "answer": "範例字串",
    "answerMediaUrls": None,
    "labels": [
        {
            "id": "550e8400-e29b-41d4-a716-446655440000"
        }
    ],
    "rawUserDefineMetadata": None
}

response = requests.post(url, json=data, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'question' => '範例字串',
            'answer' => '範例字串',
            'answerMediaUrls' => null,
            'labels' => [
                [
                    'id' => '550e8400-e29b-41d4-a716-446655440000'
                ]
            ],
            'rawUserDefineMetadata' => null
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 201**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "question": string
  "answer": string
  "answerMediaUrls"?: object // URLs of media files, such as images and videos, in the answer. (非必填)
  "hitsCount": integer
  "embeddingTokensCount": integer // Number of embedding tokens used to create this FAQ.
  "labels"?: [ // 非必填
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "rawUserDefineMetadata"?: object // 非必填
  "knowledgeBase":  // Always taken from the knowledge base in the URL; a value in the request body is ignored.
  {
    "id": string (uuid)
    "name": string
  }
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "question": "回應字串",
  "answer": "回應字串",
  "answerMediaUrls": null,
  "hitsCount": 456,
  "embeddingTokensCount": 456,
  "labels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ],
  "rawUserDefineMetadata": null,
  "knowledgeBase": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應字串"
  }
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 更新 FAQ 元資料 <a href="#knowledge-bases-faqs-update-metadata-partial-update" id="knowledge-bases-faqs-update-metadata-partial-update"></a>

PATCH `/api/v1/knowledge-bases/{knowledgeBasePk}/faqs/{id}/update-metadata/`

#### 參數

| 參數名稱              | 必填 | 類型     | 說明                                  |
| ----------------- | -- | ------ | ----------------------------------- |
| `id`              | ✅  | string | A UUID string identifying this FAQ. |
| `knowledgeBasePk` | ✅  | string |                                     |

#### 請求內容

**請求參數**

| 欄位                    | 類型             | 必填 | 說明 |
| --------------------- | -------------- | -- | -- |
| labels                | array\[IdName] | 否  |    |
| rawUserDefineMetadata | object         | 否  |    |

**請求結構範例**

```typescript
{
  "labels"?: [ // 非必填
    {
      "id": string (uuid)
    }
  ]
  "rawUserDefineMetadata"?: object // 非必填
}
```

**請求範例值**

```json
{
  "labels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000"
    }
  ],
  "rawUserDefineMetadata": null
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X PATCH "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/550e8400-e29b-41d4-a716-446655440000/update-metadata/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "labels": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000"
      }
    ],
    "rawUserDefineMetadata": null
  }'

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// 請求內容 (payload)
const data = {
    "labels": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000"
      }
    ],
    "rawUserDefineMetadata": null
  };

axios.patch("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/550e8400-e29b-41d4-a716-446655440000/update-metadata/", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/550e8400-e29b-41d4-a716-446655440000/update-metadata/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "labels": [
        {
            "id": "550e8400-e29b-41d4-a716-446655440000"
        }
    ],
    "rawUserDefineMetadata": None
}

response = requests.patch(url, json=data, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->patch("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/550e8400-e29b-41d4-a716-446655440000/update-metadata/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'labels' => [
                [
                    'id' => '550e8400-e29b-41d4-a716-446655440000'
                ]
            ],
            'rawUserDefineMetadata' => null
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "question": string
  "answer": string
  "answerMediaUrls"?: object // URLs of media files, such as images and videos, in the answer. (非必填)
  "hitsCount": integer
  "embeddingTokensCount": integer // Number of embedding tokens used to create this FAQ.
  "labels"?: [ // 非必填
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "rawUserDefineMetadata"?: object // 非必填
  "knowledgeBase":  // Always taken from the knowledge base in the URL; a value in the request body is ignored.
  {
    "id": string (uuid)
    "name": string
  }
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "question": "回應字串",
  "answer": "回應字串",
  "answerMediaUrls": null,
  "hitsCount": 456,
  "embeddingTokensCount": 456,
  "labels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ],
  "rawUserDefineMetadata": null,
  "knowledgeBase": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應字串"
  }
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 批量刪除 FAQ <a href="#knowledge-bases-faqs-batch-delete-create" id="knowledge-bases-faqs-batch-delete-create"></a>

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

#### 參數

| 參數名稱              | 必填 | 類型     | 說明 |
| ----------------- | -- | ------ | -- |
| `knowledgeBasePk` | ✅  | string |    |

#### 請求內容

**請求參數**

| 欄位  | 類型             | 必填 | 說明 |
| --- | -------------- | -- | -- |
| ids | array\[string] | 否  |    |

**請求結構範例**

```typescript
{
  "ids"?: [ // 非必填
    string (uuid)
  ]
}
```

**請求範例值**

```json
{
  "ids": [
    "550e8400-e29b-41d4-a716-446655440000"
  ]
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/batch-delete/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "ids": [
      "550e8400-e29b-41d4-a716-446655440000"
    ]
  }'

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// 請求內容 (payload)
const data = {
    "ids": [
      "550e8400-e29b-41d4-a716-446655440000"
    ]
  };

axios.post("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/batch-delete/", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/batch-delete/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "ids": [
        "550e8400-e29b-41d4-a716-446655440000"
    ]
}

response = requests.post(url, json=data, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/batch-delete/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'ids' => [
                '550e8400-e29b-41d4-a716-446655440000'
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

| 狀態碼 | 說明                                                                 |
| --- | ------------------------------------------------------------------ |
| 204 | No response body                                                   |
| 4XX | Error response; X-Error-Code carries its code (see "Error codes"). |

***

### 列出特定知識庫的所有 FAQ <a href="#knowledge-bases-faqs-list" id="knowledge-bases-faqs-list"></a>

GET `/api/v1/knowledge-bases/{knowledgeBasePk}/faqs/`

#### 參數

| 參數名稱              | 必填 | 類型      | 說明                                                      |
| ----------------- | -- | ------- | ------------------------------------------------------- |
| `knowledgeBasePk` | ✅  | string  |                                                         |
| `page`            | ❌  | integer | A page number within the paginated result set.          |
| `pageSize`        | ❌  | integer | Number of results to return per page.                   |
| `query`           | ❌  | string  | 搜尋關鍵字，支援空白分隔的多條件查詢。可搜尋：FAQ ID、問題、答案、標籤名稱、Metadata value |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/?page=1&pageSize=1&query=example" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/?page=1&pageSize=1&query=example", config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/?page=1&pageSize=1&query=example"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/?page=1&pageSize=1&query=example", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "count": integer
  "next"?: string (uri) // 非必填
  "previous"?: string (uri) // 非必填
  "results": [
    {
      "id": string (uuid)
      "question": string
      "answer": string
      "answerMediaUrls"?: object // URLs of media files, such as images and videos, in the answer. (非必填)
      "hitsCount": integer
      "embeddingTokensCount": integer // Number of embedding tokens used to create this FAQ.
      "labels"?: [ // 非必填
        {
          "id": string (uuid)
          "name": string
        }
      ]
      "rawUserDefineMetadata"?: object // 非必填
      "knowledgeBase":  // Always taken from the knowledge base in the URL; a value in the request body is ignored.
      {
        "id": string (uuid)
        "name": string
      }
    }
  ]
}
```

**回應範例值**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "question": "回應字串",
      "answer": "回應字串",
      "answerMediaUrls": null,
      "hitsCount": 456,
      "embeddingTokensCount": 456,
      "labels": [
        {
          "id": "550e8400-e29b-41d4-a716-446655440000",
          "name": "回應字串"
        }
      ],
      "rawUserDefineMetadata": null,
      "knowledgeBase": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應字串"
      }
    }
  ]
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 取得特定 FAQ 詳情 <a href="#knowledge-bases-faqs-retrieve" id="knowledge-bases-faqs-retrieve"></a>

GET `/api/v1/knowledge-bases/{knowledgeBasePk}/faqs/{id}/`

#### 參數

| 參數名稱              | 必填 | 類型     | 說明                                  |
| ----------------- | -- | ------ | ----------------------------------- |
| `id`              | ✅  | string | A UUID string identifying this FAQ. |
| `knowledgeBasePk` | ✅  | string |                                     |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/550e8400-e29b-41d4-a716-446655440000/", config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "question": string
  "answer": string
  "answerMediaUrls"?: object // URLs of media files, such as images and videos, in the answer. (非必填)
  "hitsCount": integer
  "embeddingTokensCount": integer // Number of embedding tokens used to create this FAQ.
  "labels"?: [ // 非必填
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "rawUserDefineMetadata"?: object // 非必填
  "knowledgeBase":  // Always taken from the knowledge base in the URL; a value in the request body is ignored.
  {
    "id": string (uuid)
    "name": string
  }
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "question": "回應字串",
  "answer": "回應字串",
  "answerMediaUrls": null,
  "hitsCount": 456,
  "embeddingTokensCount": 456,
  "labels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ],
  "rawUserDefineMetadata": null,
  "knowledgeBase": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應字串"
  }
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 更新 FAQ <a href="#knowledge-bases-faqs-update" id="knowledge-bases-faqs-update"></a>

PUT `/api/v1/knowledge-bases/{knowledgeBasePk}/faqs/{id}/`

#### 參數

| 參數名稱              | 必填 | 類型     | 說明                                  |
| ----------------- | -- | ------ | ----------------------------------- |
| `id`              | ✅  | string | A UUID string identifying this FAQ. |
| `knowledgeBasePk` | ✅  | string |                                     |

#### 請求內容

**請求參數**

| 欄位                    | 類型             | 必填 | 說明                                                             |
| --------------------- | -------------- | -- | -------------------------------------------------------------- |
| question              | string         | 是  |                                                                |
| answer                | string         | 是  |                                                                |
| answerMediaUrls       | object         | 否  | URLs of media files, such as images and videos, in the answer. |
| labels                | array\[IdName] | 否  |                                                                |
| rawUserDefineMetadata | object         | 否  |                                                                |

**請求結構範例**

```typescript
{
  "question": string
  "answer": string
  "answerMediaUrls"?: object // URLs of media files, such as images and videos, in the answer. (非必填)
  "labels"?: [ // 非必填
    {
      "id": string (uuid)
    }
  ]
  "rawUserDefineMetadata"?: object // 非必填
}
```

**請求範例值**

```json
{
  "question": "範例字串",
  "answer": "範例字串",
  "answerMediaUrls": null,
  "labels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000"
    }
  ],
  "rawUserDefineMetadata": null
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X PUT "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "question": "範例字串",
    "answer": "範例字串",
    "answerMediaUrls": null,
    "labels": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000"
      }
    ],
    "rawUserDefineMetadata": null
  }'

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// 請求內容 (payload)
const data = {
    "question": "範例字串",
    "answer": "範例字串",
    "answerMediaUrls": null,
    "labels": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000"
      }
    ],
    "rawUserDefineMetadata": null
  };

axios.put("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "question": "範例字串",
    "answer": "範例字串",
    "answerMediaUrls": None,
    "labels": [
        {
            "id": "550e8400-e29b-41d4-a716-446655440000"
        }
    ],
    "rawUserDefineMetadata": None
}

response = requests.put(url, json=data, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->put("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'question' => '範例字串',
            'answer' => '範例字串',
            'answerMediaUrls' => null,
            'labels' => [
                [
                    'id' => '550e8400-e29b-41d4-a716-446655440000'
                ]
            ],
            'rawUserDefineMetadata' => null
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "question": string
  "answer": string
  "answerMediaUrls"?: object // URLs of media files, such as images and videos, in the answer. (非必填)
  "hitsCount": integer
  "embeddingTokensCount": integer // Number of embedding tokens used to create this FAQ.
  "labels"?: [ // 非必填
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "rawUserDefineMetadata"?: object // 非必填
  "knowledgeBase":  // Always taken from the knowledge base in the URL; a value in the request body is ignored.
  {
    "id": string (uuid)
    "name": string
  }
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "question": "回應字串",
  "answer": "回應字串",
  "answerMediaUrls": null,
  "hitsCount": 456,
  "embeddingTokensCount": 456,
  "labels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ],
  "rawUserDefineMetadata": null,
  "knowledgeBase": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應字串"
  }
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 部分更新 FAQ <a href="#knowledge-bases-faqs-partial-update" id="knowledge-bases-faqs-partial-update"></a>

PATCH `/api/v1/knowledge-bases/{knowledgeBasePk}/faqs/{id}/`

#### 參數

| 參數名稱              | 必填 | 類型     | 說明                                  |
| ----------------- | -- | ------ | ----------------------------------- |
| `id`              | ✅  | string | A UUID string identifying this FAQ. |
| `knowledgeBasePk` | ✅  | string |                                     |

#### 請求內容

**請求參數**

| 欄位                    | 類型             | 必填 | 說明                                                             |
| --------------------- | -------------- | -- | -------------------------------------------------------------- |
| question              | string         | 否  |                                                                |
| answer                | string         | 否  |                                                                |
| answerMediaUrls       | object         | 否  | URLs of media files, such as images and videos, in the answer. |
| labels                | array\[IdName] | 否  |                                                                |
| rawUserDefineMetadata | object         | 否  |                                                                |

**請求結構範例**

```typescript
{
  "question"?: string // 非必填
  "answer"?: string // 非必填
  "answerMediaUrls"?: object // URLs of media files, such as images and videos, in the answer. (非必填)
  "labels"?: [ // 非必填
    {
      "id": string (uuid)
    }
  ]
  "rawUserDefineMetadata"?: object // 非必填
}
```

**請求範例值**

```json
{
  "question": "範例字串",
  "answer": "範例字串",
  "answerMediaUrls": null,
  "labels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000"
    }
  ],
  "rawUserDefineMetadata": null
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X PATCH "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "question": "範例字串",
    "answer": "範例字串",
    "answerMediaUrls": null,
    "labels": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000"
      }
    ],
    "rawUserDefineMetadata": null
  }'

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// 請求內容 (payload)
const data = {
    "question": "範例字串",
    "answer": "範例字串",
    "answerMediaUrls": null,
    "labels": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000"
      }
    ],
    "rawUserDefineMetadata": null
  };

axios.patch("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "question": "範例字串",
    "answer": "範例字串",
    "answerMediaUrls": None,
    "labels": [
        {
            "id": "550e8400-e29b-41d4-a716-446655440000"
        }
    ],
    "rawUserDefineMetadata": None
}

response = requests.patch(url, json=data, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->patch("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'question' => '範例字串',
            'answer' => '範例字串',
            'answerMediaUrls' => null,
            'labels' => [
                [
                    'id' => '550e8400-e29b-41d4-a716-446655440000'
                ]
            ],
            'rawUserDefineMetadata' => null
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "question": string
  "answer": string
  "answerMediaUrls"?: object // URLs of media files, such as images and videos, in the answer. (非必填)
  "hitsCount": integer
  "embeddingTokensCount": integer // Number of embedding tokens used to create this FAQ.
  "labels"?: [ // 非必填
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "rawUserDefineMetadata"?: object // 非必填
  "knowledgeBase":  // Always taken from the knowledge base in the URL; a value in the request body is ignored.
  {
    "id": string (uuid)
    "name": string
  }
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "question": "回應字串",
  "answer": "回應字串",
  "answerMediaUrls": null,
  "hitsCount": 456,
  "embeddingTokensCount": 456,
  "labels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ],
  "rawUserDefineMetadata": null,
  "knowledgeBase": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應字串"
  }
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 刪除 FAQ <a href="#knowledge-bases-faqs-destroy" id="knowledge-bases-faqs-destroy"></a>

DELETE `/api/v1/knowledge-bases/{knowledgeBasePk}/faqs/{id}/`

#### 參數

| 參數名稱              | 必填 | 類型     | 說明                                  |
| ----------------- | -- | ------ | ----------------------------------- |
| `id`              | ✅  | string | A UUID string identifying this FAQ. |
| `knowledgeBasePk` | ✅  | string |                                     |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X DELETE "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

// 請求內容 (payload)
const data = null;

axios.delete("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.delete(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->delete("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faqs/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

| 狀態碼 | 說明                                                                 |
| --- | ------------------------------------------------------------------ |
| 204 | No response body                                                   |
| 4XX | Error response; X-Error-Code carries its code (see "Error codes"). |

***

### 匯出 FAQ Excel（或空白範本） <a href="#knowledge-bases-export-faq-excel-retrieve" id="knowledge-bases-export-faq-excel-retrieve"></a>

GET `/api/v1/knowledge-bases/{id}/export-faq-excel/`

#### 參數

| 參數名稱 | 必填 | 類型     | 說明                                             |
| ---- | -- | ------ | ---------------------------------------------- |
| `id` | ✅  | string | A UUID string identifying this Knowledge Base. |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/export-faq-excel/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/export-faq-excel/", config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/export-faq-excel/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/export-faq-excel/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "createdBy": 
  {
    "id": string (uuid)
    "name": string
  }
  "organization"?: string (uuid) // 非必填
  "embeddingModel": string (uuid)
  "rerankerModel": string (uuid)
  "name": string
  "description"?: string // 非必填
  "numberOfRetrievedChunks"?: integer // 提取的參考資料數量，預設為 12，最小值為 1 (非必填)
  "enableHyde"?: boolean // 啟用 HyDE，預設為 False (非必填)
  "similarityCutoff"?: number (double) // 相似度門檻，預設為 0.0，範圍為 0.0-1.0 (非必填)
  "enableRerank"?: boolean // 是否啟用重新排序，預設為 True (非必填)
  "enableRrf"?: boolean // Enable Reciprocal Rank Fusion for hybrid search. Disable this if using a custom Elasticsearch without enterprise license. (非必填)
  "vectorDatabaseType"?:  // Type of vector database: elasticsearch or opensearch.

* `elasticsearch` - Elasticsearch
* `opensearch` - OpenSearch
* `oracle` - Oracle AI Database 26ai
* `synxdb` - SynxDB (非必填)
  {
  }
  "vectorDatabaseUrl"?: string // Custom vector database endpoint URL or Oracle DSN. For Elasticsearch/OpenSearch: URL format (e.g., "https://host:9200"). For Oracle: DSN format (e.g., "host:1521/service_name"). (非必填)
  "vectorDatabaseApiKey"?: string // API Key for Elasticsearch. Not used for OpenSearch. (非必填)
  "opensearchUsername"?: string // Username for OpenSearch Basic Auth. (非必填)
  "opensearchPassword"?: string // Password for OpenSearch Basic Auth. (非必填)
  "oracleUser"?: string // Oracle database username. (非必填)
  "oraclePassword"?: string // Oracle database password. (非必填)
  "synxdbUser"?: string // SynxDB database username. (非必填)
  "synxdbPassword"?: string // SynxDB database password. (非必填)
  "labels": [
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "chatbots"?: [ // 非必填
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "groups"?: [ // 知識庫可存取的群組列表 (非必填)
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "filesCount": integer // Return count of KnowledgeBaseFile excluding processed files, conversation attachments, and soft-deleted.
  "vectorStorageSize": integer
  "chunksCount": integer
  "canUpdate": boolean // Return whether the current user can update this resource.
  "canDelete": boolean // Return whether the current user can delete this resource.
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應字串"
  },
  "organization": "550e8400-e29b-41d4-a716-446655440000",
  "embeddingModel": "550e8400-e29b-41d4-a716-446655440000",
  "rerankerModel": "550e8400-e29b-41d4-a716-446655440000",
  "name": "回應字串",
  "description": "回應字串",
  "numberOfRetrievedChunks": 456,
  "enableHyde": false,
  "similarityCutoff": 456,
  "enableRerank": false,
  "enableRrf": false,
  "vectorDatabaseType": {},
  "vectorDatabaseUrl": "回應字串",
  "vectorDatabaseApiKey": "回應字串",
  "opensearchUsername": "回應字串",
  "opensearchPassword": "回應字串",
  "oracleUser": "回應字串",
  "oraclePassword": "回應字串",
  "synxdbUser": "回應字串",
  "synxdbPassword": "回應字串",
  "labels": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ],
  "chatbots": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ],
  "groups": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應字串"
    }
  ],
  "filesCount": 456,
  "vectorStorageSize": 456,
  "chunksCount": 456,
  "canUpdate": false,
  "canDelete": false,
  "createdAt": "回應字串",
  "updatedAt": "回應字串"
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 匯入 FAQ Excel（非同步） <a href="#knowledge-bases-import-faq-excel-create" id="knowledge-bases-import-faq-excel-create"></a>

POST `/api/v1/knowledge-bases/{id}/import-faq-excel/`

{% hint style="info" %}
同一知識庫同時只能有一個匯入工作，進行中再呼叫會回 `409`；用下方「FAQ 匯入工作」端點查進度。
{% endhint %}

#### 參數

| 參數名稱 | 必填 | 類型     | 說明                                             |
| ---- | -- | ------ | ---------------------------------------------- |
| `id` | ✅  | string | A UUID string identifying this Knowledge Base. |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/import-faq-excel/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -F "excelFile=@example_file.txt"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');
const FormData = require('form-data');

// 建立FormData對象
const formData = new FormData();
// 請用實際檔案替換
formData.append('excelFile', /* 實際檔案物件 */, 'example_file.txt');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    ...formData.getHeaders()
  }
};

axios.post("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/import-faq-excel/", formData, config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/import-faq-excel/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}

# 建立檔案和表單資料
files = {
    'excelFile': ('example_file.txt', open('example_file.txt', 'rb'), 'text/plain')
}

response = requests.post(url, files=files, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/import-faq-excel/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ],
        'multipart' => [
            [
                'name' => 'excelFile',
                'contents' => fopen('example_file.txt', 'r'),
                'filename' => 'example_file.txt'
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 202**

**回應結構範例**

```typescript
{
  "jobId": string (uuid)
  "status": string (enum: pending, processing, done, failed) // * `pending` - Pending
* `processing` - Processing
* `done` - Done
* `failed` - Failed
}
```

**回應範例值**

```json
{
  "jobId": "550e8400-e29b-41d4-a716-446655440000",
  "status": "pending"
}
```

**狀態碼: 409**

**回應結構範例**

```typescript
{
  "detail": string
  "jobId": string (uuid)
}
```

**回應範例值**

```json
{
  "detail": "回應字串",
  "jobId": "550e8400-e29b-41d4-a716-446655440000"
}
```

***

### 列出 FAQ 匯入工作 <a href="#knowledge-bases-faq-import-jobs-list" id="knowledge-bases-faq-import-jobs-list"></a>

GET `/api/v1/knowledge-bases/{id}/faq-import-jobs/`

#### 參數

| 參數名稱             | 必填 | 類型      | 說明                                                                     |
| ---------------- | -- | ------- | ---------------------------------------------------------------------- |
| `id`             | ✅  | string  | A UUID string identifying this Knowledge Base.                         |
| `embeddingModel` | ❌  | string  |                                                                        |
| `page`           | ❌  | integer | A page number within the paginated result set.                         |
| `pageSize`       | ❌  | integer | Number of results to return per page.                                  |
| `pagination`     | ❌  | boolean | Set to false to return all jobs without pagination (defaults to true). |
| `query`          | ❌  | string  |                                                                        |
| `rerankerModel`  | ❌  | string  |                                                                        |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faq-import-jobs/?embeddingModel=550e8400-e29b-41d4-a716-446655440000&page=1&pageSize=1&pagination=true&query=example&rerankerModel=550e8400-e29b-41d4-a716-446655440000" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faq-import-jobs/?embeddingModel=550e8400-e29b-41d4-a716-446655440000&page=1&pageSize=1&pagination=true&query=example&rerankerModel=550e8400-e29b-41d4-a716-446655440000", config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faq-import-jobs/?embeddingModel=550e8400-e29b-41d4-a716-446655440000&page=1&pageSize=1&pagination=true&query=example&rerankerModel=550e8400-e29b-41d4-a716-446655440000"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faq-import-jobs/?embeddingModel=550e8400-e29b-41d4-a716-446655440000&page=1&pageSize=1&pagination=true&query=example&rerankerModel=550e8400-e29b-41d4-a716-446655440000", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "count": integer
  "next"?: string (uri) // 非必填
  "previous"?: string (uri) // 非必填
  "results": [
    {
      "id": string (uuid)
      "status": 
      {
      }
      "totalRows": integer
      "processedRows": integer
      "createdCount": integer
      "skippedDuplicateCount": integer // Rows skipped because their whitespace-normalized question already exists in the knowledge base or appears earlier in the same file.
      "errors": object // Row-level parse errors and chunk-level import errors.
      "createdAt": string (timestamp)
      "updatedAt": string (timestamp)
    }
  ]
}
```

**回應範例值**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "status": {},
      "totalRows": 456,
      "processedRows": 456,
      "createdCount": 456,
      "skippedDuplicateCount": 456,
      "errors": null,
      "createdAt": "回應字串",
      "updatedAt": "回應字串"
    }
  ]
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 取得特定 FAQ 匯入工作 <a href="#knowledge-bases-faq-import-jobs-retrieve" id="knowledge-bases-faq-import-jobs-retrieve"></a>

GET `/api/v1/knowledge-bases/{id}/faq-import-jobs/{jobId}/`

#### 參數

| 參數名稱    | 必填 | 類型     | 說明                                             |
| ------- | -- | ------ | ---------------------------------------------- |
| `id`    | ✅  | string | A UUID string identifying this Knowledge Base. |
| `jobId` | ✅  | string |                                                |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faq-import-jobs/{jobId}/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faq-import-jobs/{jobId}/", config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faq-import-jobs/{jobId}/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/knowledge-bases/550e8400-e29b-41d4-a716-446655440000/faq-import-jobs/{jobId}/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "status": 
  {
  }
  "totalRows": integer
  "processedRows": integer
  "createdCount": integer
  "skippedDuplicateCount": integer // Rows skipped because their whitespace-normalized question already exists in the knowledge base or appears earlier in the same file.
  "errors": object // Row-level parse errors and chunk-level import errors.
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "status": {},
  "totalRows": 456,
  "processedRows": 456,
  "createdCount": 456,
  "skippedDuplicateCount": 456,
  "errors": null,
  "createdAt": "回應字串",
  "updatedAt": "回應字串"
}
```

**狀態碼: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 列出解析器 <a href="#parsers-list" id="parsers-list"></a>

GET `/api/v1/parsers/`

{% hint style="info" %}
上傳檔案到知識庫時 `parser` 欄位要填解析器的 `id`，由此端點取得。
{% endhint %}

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/parsers/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/parsers/", config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/parsers/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/parsers/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
[
  {
    "id": string (uuid)
    "name": string
    "description": string
    "provider": string (enum: maiagent, llama, azure, docling, whisper_groq, whisper_openai, whisper_offline, localai, anthropic, bronci, alibaba, rap, vertex, cohere) // * `maiagent` - MaiAgent
* `llama` - Llama
* `azure` - Azure
* `docling` - Docling
* `whisper_groq` - WhisperGroq
* `whisper_openai` - WhisperOpenAI
* `whisper_offline` - WhisperOffline
* `localai` - LocalAI
* `anthropic` - Anthropic
* `bronci` - Bronci
* `alibaba` - Alibaba Qwen
* `rap` - Taiwan AI RAP
* `vertex` - Vertex AI
* `cohere` - Cohere
    "order"?: integer // 非必填
    "isTimestampSttProvider": boolean
    "asrProvider": object // The provider spec, built once per provider row per response.

The spec is platform-level, not per parser, and it is large — a
whisper-family row carries a 100-entry language catalog in its
``languages`` spec, as codes plus display names. This serializer is
nested per row in the knowledge-base file listing and in message
citations, so without memoizing, one response rebuilds the same
catalog for every row. ``self.context`` is the root serializer's shared
dict, which is also what keeps ``get_active_diarization_rows`` at one
query per response.
  }
]
```

**回應範例值**

```json
[
  {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應字串",
    "description": "回應字串",
    "provider": "maiagent",
    "order": 456,
    "isTimestampSttProvider": false,
    "asrProvider": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應範例名稱",
      "description": "回應範例描述"
    }
  }
]
```

***

### 取得特定解析器 <a href="#parsers-retrieve" id="parsers-retrieve"></a>

GET `/api/v1/parsers/{id}/`

#### 參數

| 參數名稱 | 必填 | 類型     | 說明                                     |
| ---- | -- | ------ | -------------------------------------- |
| `id` | ✅  | string | A UUID string identifying this Parser. |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/parsers/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 請確認在執行前替換 YOUR_API_KEY 並核對請求資料。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// 設定請求標頭
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/parsers/550e8400-e29b-41d4-a716-446655440000/", config)
  .then(response => {
    console.log('成功取得回應:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('請求發生錯誤:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/parsers/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("成功取得回應:")
    print(response.json())
except Exception as e:
    print("請求發生錯誤:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/parsers/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "name": string
  "description": string
  "provider": string (enum: maiagent, llama, azure, docling, whisper_groq, whisper_openai, whisper_offline, localai, anthropic, bronci, alibaba, rap, vertex, cohere) // * `maiagent` - MaiAgent
* `llama` - Llama
* `azure` - Azure
* `docling` - Docling
* `whisper_groq` - WhisperGroq
* `whisper_openai` - WhisperOpenAI
* `whisper_offline` - WhisperOffline
* `localai` - LocalAI
* `anthropic` - Anthropic
* `bronci` - Bronci
* `alibaba` - Alibaba Qwen
* `rap` - Taiwan AI RAP
* `vertex` - Vertex AI
* `cohere` - Cohere
  "order"?: integer // 非必填
  "isTimestampSttProvider": boolean
  "asrProvider": object // The provider spec, built once per provider row per response.

The spec is platform-level, not per parser, and it is large — a
whisper-family row carries a 100-entry language catalog in its
``languages`` spec, as codes plus display names. This serializer is
nested per row in the knowledge-base file listing and in message
citations, so without memoizing, one response rebuilds the same
catalog for every row. ``self.context`` is the root serializer's shared
dict, which is also what keeps ``get_active_diarization_rows`` at one
query per response.
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "回應字串",
  "description": "回應字串",
  "provider": "maiagent",
  "order": 456,
  "isTimestampSttProvider": false,
  "asrProvider": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  }
}
```

***


---

# 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/api/api-reference/zhi-shi-ku-xin-ban.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.
