> 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/credit.md).

# Credit

Credit 分類提供組織 Credit 的查詢與額度分配：餘額、即將到期額度、入帳紀錄、消耗明細與總計、用量統計、計價規則與計價項目，以及成員、角色、對話平台三種額度的設定（列出、設定、更新、停用、是否需要額度），和依角色批次分配或停用成員額度。

#### 前置說明 <a href="#credit-prerequisites" id="credit-prerequisites"></a>

**認證與路徑參數**

除「計價規則」與「計價項目」外，所有 API 都要在 HTTP Header 帶 API Key：

```
Authorization: Api-Key {API_KEY}
```

系統會依 API Key 自動帶出所屬組織與成員身分，`/api/v1/credit/` 開頭的 API 不需要另外傳組織識別。路徑中需要的 ID 可以這樣取得：

* `organizationPk`：呼叫 `GET /api/v1/organizations/`，取回應中組織的 `id`。
* 錢包的 `id`：呼叫 `GET /api/v1/organizations/{id}/`，取回應中的 `creditWallet.id`。

**呼叫頻率上限**

需要 API Key 的 API，呼叫頻率上限是**每一把 API Key 各自設定的每分鐘次數**，由組織管理者在「組織設定 → API 金鑰」的「每分鐘請求數（RPM）」設定；同一把金鑰呼叫平台上所有 API 的次數合併計算，沒有設定上限的金鑰不受此限制。超過上限的請求會被拒絕並回傳 HTTP 429，請等到下一分鐘再重試。

「計價規則」與「計價項目」不需要 API Key，呼叫上限另依來源 IP 計算，見各 API 的標註。

**額度怎麼運作**

成員、角色、對話平台各有一層額度，對應後台「Credits → 額度分配」的三個分頁，三層各自計算：

* **成員額度**：單一成員自己的用量上限。
* **角色額度**：角色內所有成員共用的上限，與成員各自的額度分開計算。成員同時屬於多個需要額度的角色時，用量會累計到每一個角色，任一個角色的額度用完就會擋下。
* **對話平台額度**：該對話平台（Inbox）AI 回覆的用量上限。MaiGPT 的對話平台不能設定額度。

每一層的規則相同：

* **需要額度**：成員、角色、對話平台各有一個「需要額度」設定（回應欄位 `creditQuotaRequired`）。關閉時不檢查、也不累計這一層，直接使用組織錢包；開啟時必須有生效中的額度才能使用，沒有生效中的額度就會被擋下（成員與角色是不能使用消耗 Credit 的功能，對話平台是暫停 AI 回覆）。
* **設定額度會自動開啟「需要額度」**。同一個對象同時只能有一筆生效中的額度，已有生效中的額度時再設定會回 `400`，要先停用舊的。
* **停用額度不會關閉「需要額度」**：停用後對象會被擋下，直到設定新額度或解除額度限制：角色與對話平台用各自的「設定是否需要額度」API 解除；成員請由管理者在後台「Credits → 額度分配」解除，或用 [依角色批次停用額度](#organizations-groups-batch-deactivate-credit-quota-create) 帶 `removeQuotaRequirement: true` 一次解除整個角色的成員。停用不會刪除紀錄，停用的額度仍會出現在「列出額度設定」中，`isActive` 為 `false`。
* 設定額度的請求內容：`quotaLimit`（額度上限，必填）、`validFrom`（生效時間，必填）、`validUntil`（到期時間，選填，須晚於 `validFrom`，且不可晚於組織最晚一筆入帳額度的到期日）、`resetPeriod`（用量歸零週期：`none`、`daily`、`weekly`、`monthly`，預設 `none`）、`note`（備註，選填）。
* **時間格式**：請求中的 `validFrom`、`validUntil` 一律用 ISO 8601 字串，例如 `2026-12-31T23:59:59+08:00`；只寫日期（`2026-12-31`）視為台灣時間當天 00:00。不接受毫秒時間戳（如 `1798732799000`），會回 `400`。回應中的時間欄位則是 13 位數毫秒時間戳。
* **新成員預設額度**：組織可設定新加入的成員自動配發一筆個人額度，見 [取得新成員預設額度設定](#credit-wallets-new-member-quota-policy-retrieve)；邀請時也可以替個別受邀者指定額度，見「組織和成員」的 [邀請成員加入組織](https://docs.maiagent.ai/api/api-reference/zu-zhi-he-cheng-yuan#auth-unified-invitations-create)。
* 路徑中的 ID：`memberPk` 取自 [列出成員額度現況](#organizations-credit-quota-members-list)、`groupPk` 取自 [列出角色額度現況](#organizations-credit-quota-groups-list)、`inboxPk` 取自 [列出對話平台額度現況](#organizations-credit-quota-inboxes-list) 回應中的 `id`；額度設定本身的 `id` 取自各自的「列出額度設定」。

**權限與計費模式**

每支 API 下方都標明所需權限與計費模式前提。API Key 以建立它的成員身分呼叫，權限依該成員所屬角色判斷。以下兩種情形會被拒絕並回傳 HTTP 403：

* **權限不足**：金鑰所屬成員的角色沒有該 API 標明的權限（「Credit 管理權限」、「用量統計權限」或「組織概覽權限」）。請組織管理者到「組織設定 → 角色」為該成員的角色開啟對應權限。
* **組織不是 Credit 計費模式**：標明「組織須為 Credit 計費模式」的 API，只開放給 Credit 計費模式的組織。可呼叫 `GET /api/v1/organizations/{id}/` 確認：回應中 `organizationPlan.billingMode` 為 `credit`（或組織尚未有方案、`organizationPlan` 為空）即可使用這些 API；如需改用 Credit 計費模式，請聯繫 MaiAgent 窗口。

### 查詢 Credit 餘額 <a href="#credit-wallets-list" id="credit-wallets-list"></a>

GET `/api/v1/credit/wallets/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：不限，任何計費模式的組織都可呼叫。
{% endhint %}

#### 參數

| 參數名稱       | 必填 | 類型      | 說明                                             |
| ---------- | -- | ------- | ---------------------------------------------- |
| `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/credit/wallets/?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/credit/wallets/?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/credit/wallets/?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/credit/wallets/?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": [
    {
      "totalCredits": string (decimal)
      "autoTopup": object // Format auto-topup configuration.
      "balanceAlert": object // Format balance alert configuration.
      "nextGrant": object // Format the next grant, or None when nothing will actually be granted.

Amount-first: a missing/zero ``amount`` always wins over any schedule
(stale ``next_grant_at`` row, Stripe period_end with zero-grant plan),
so the frontend never receives a "scheduled in X days for 0 credits"
entry — the API decides whether the block renders at all.
      "lastGrant": object // Format the most recent PLAN_GRANT topup, or None when wallet has none.
      "consumptionHint": object // Return 7-day daily average consumption hint, or None if insufficient data.
      "billingProvider": string // Return the organization's billing provider so the Credit page can pick its card layout.
      "periodCreditGrant": string // Return current-period credit grant total; None unless AWS Marketplace billed.
      "periodMeteredUsage": string // Return current-period accepted metered usage; None unless AWS Marketplace billed.
    }
  ]
}
```

**回應範例值**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "totalCredits": "回應字串",
      "autoTopup": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應範例名稱",
        "description": "回應範例描述"
      },
      "balanceAlert": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應範例名稱",
        "description": "回應範例描述"
      },
      "nextGrant": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應範例名稱",
        "description": "回應範例描述"
      },
      "lastGrant": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應範例名稱",
        "description": "回應範例描述"
      },
      "consumptionHint": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應範例名稱",
        "description": "回應範例描述"
      },
      "billingProvider": "回應字串",
      "periodCreditGrant": "回應字串",
      "periodMeteredUsage": "回應字串"
    }
  ]
}
```

***

### 取得錢包詳情 <a href="#credit-wallets-retrieve" id="credit-wallets-retrieve"></a>

GET `/api/v1/credit/wallets/{id}/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：不限，任何計費模式的組織都可呼叫。
{% endhint %}

#### 參數

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

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/credit/wallets/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/credit/wallets/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/credit/wallets/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/credit/wallets/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
{
  "totalCredits": string (decimal)
  "autoTopup": object // Format auto-topup configuration.
  "balanceAlert": object // Format balance alert configuration.
  "nextGrant": object // Format the next grant, or None when nothing will actually be granted.

Amount-first: a missing/zero ``amount`` always wins over any schedule
(stale ``next_grant_at`` row, Stripe period_end with zero-grant plan),
so the frontend never receives a "scheduled in X days for 0 credits"
entry — the API decides whether the block renders at all.
  "lastGrant": object // Format the most recent PLAN_GRANT topup, or None when wallet has none.
  "consumptionHint": object // Return 7-day daily average consumption hint, or None if insufficient data.
  "billingProvider": string // Return the organization's billing provider so the Credit page can pick its card layout.
  "periodCreditGrant": string // Return current-period credit grant total; None unless AWS Marketplace billed.
  "periodMeteredUsage": string // Return current-period accepted metered usage; None unless AWS Marketplace billed.
}
```

**回應範例值**

```json
{
  "totalCredits": "回應字串",
  "autoTopup": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "balanceAlert": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "nextGrant": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "lastGrant": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "consumptionHint": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "billingProvider": "回應字串",
  "periodCreditGrant": "回應字串",
  "periodMeteredUsage": "回應字串"
}
```

***

### 取得錢包餘額 <a href="#credit-wallets-balance-retrieve" id="credit-wallets-balance-retrieve"></a>

GET `/api/v1/credit/wallets/{id}/balance/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：不限，任何計費模式的組織都可呼叫。
{% endhint %}

#### 參數

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

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/credit/wallets/550e8400-e29b-41d4-a716-446655440000/balance/" \
  -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/credit/wallets/550e8400-e29b-41d4-a716-446655440000/balance/", 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/credit/wallets/550e8400-e29b-41d4-a716-446655440000/balance/"
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/credit/wallets/550e8400-e29b-41d4-a716-446655440000/balance/", [
        '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
{
  "totalCredits": string (decimal)
  "autoTopup": object // Format auto-topup configuration.
  "balanceAlert": object // Format balance alert configuration.
  "nextGrant": object // Format the next grant, or None when nothing will actually be granted.

Amount-first: a missing/zero ``amount`` always wins over any schedule
(stale ``next_grant_at`` row, Stripe period_end with zero-grant plan),
so the frontend never receives a "scheduled in X days for 0 credits"
entry — the API decides whether the block renders at all.
  "lastGrant": object // Format the most recent PLAN_GRANT topup, or None when wallet has none.
  "consumptionHint": object // Return 7-day daily average consumption hint, or None if insufficient data.
  "billingProvider": string // Return the organization's billing provider so the Credit page can pick its card layout.
  "periodCreditGrant": string // Return current-period credit grant total; None unless AWS Marketplace billed.
  "periodMeteredUsage": string // Return current-period accepted metered usage; None unless AWS Marketplace billed.
}
```

**回應範例值**

```json
{
  "totalCredits": "回應字串",
  "autoTopup": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "balanceAlert": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "nextGrant": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "lastGrant": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "consumptionHint": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "billingProvider": "回應字串",
  "periodCreditGrant": "回應字串",
  "periodMeteredUsage": "回應字串"
}
```

***

### 查詢即將到期額度 <a href="#credit-wallets-expiring-credits-retrieve" id="credit-wallets-expiring-credits-retrieve"></a>

GET `/api/v1/credit/wallets/{id}/expiring-credits/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：不限，任何計費模式的組織都可呼叫。只列出有設到期日的額度；沒有到期日的額度不會出現在結果中，不代表組織的全部餘額。`days` 參數指定查詢幾天內到期（預設 30；傳 `all` 列出所有有到期日的額度）。
{% endhint %}

#### 參數

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

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/credit/wallets/550e8400-e29b-41d4-a716-446655440000/expiring-credits/" \
  -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/credit/wallets/550e8400-e29b-41d4-a716-446655440000/expiring-credits/", 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/credit/wallets/550e8400-e29b-41d4-a716-446655440000/expiring-credits/"
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/credit/wallets/550e8400-e29b-41d4-a716-446655440000/expiring-credits/", [
        '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
{
  "totalCredits": string (decimal)
  "autoTopup": object // Format auto-topup configuration.
  "balanceAlert": object // Format balance alert configuration.
  "nextGrant": object // Format the next grant, or None when nothing will actually be granted.

Amount-first: a missing/zero ``amount`` always wins over any schedule
(stale ``next_grant_at`` row, Stripe period_end with zero-grant plan),
so the frontend never receives a "scheduled in X days for 0 credits"
entry — the API decides whether the block renders at all.
  "lastGrant": object // Format the most recent PLAN_GRANT topup, or None when wallet has none.
  "consumptionHint": object // Return 7-day daily average consumption hint, or None if insufficient data.
  "billingProvider": string // Return the organization's billing provider so the Credit page can pick its card layout.
  "periodCreditGrant": string // Return current-period credit grant total; None unless AWS Marketplace billed.
  "periodMeteredUsage": string // Return current-period accepted metered usage; None unless AWS Marketplace billed.
}
```

**回應範例值**

```json
{
  "totalCredits": "回應字串",
  "autoTopup": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "balanceAlert": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "nextGrant": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "lastGrant": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "consumptionHint": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "billingProvider": "回應字串",
  "periodCreditGrant": "回應字串",
  "periodMeteredUsage": "回應字串"
}
```

***

### 查詢入帳紀錄 <a href="#credit-wallets-topup-history-retrieve" id="credit-wallets-topup-history-retrieve"></a>

GET `/api/v1/credit/wallets/{id}/topup-history/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：不限，任何計費模式的組織都可呼叫。
{% endhint %}

#### 參數

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

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/credit/wallets/550e8400-e29b-41d4-a716-446655440000/topup-history/" \
  -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/credit/wallets/550e8400-e29b-41d4-a716-446655440000/topup-history/", 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/credit/wallets/550e8400-e29b-41d4-a716-446655440000/topup-history/"
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/credit/wallets/550e8400-e29b-41d4-a716-446655440000/topup-history/", [
        '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
{
  "totalCredits": string (decimal)
  "autoTopup": object // Format auto-topup configuration.
  "balanceAlert": object // Format balance alert configuration.
  "nextGrant": object // Format the next grant, or None when nothing will actually be granted.

Amount-first: a missing/zero ``amount`` always wins over any schedule
(stale ``next_grant_at`` row, Stripe period_end with zero-grant plan),
so the frontend never receives a "scheduled in X days for 0 credits"
entry — the API decides whether the block renders at all.
  "lastGrant": object // Format the most recent PLAN_GRANT topup, or None when wallet has none.
  "consumptionHint": object // Return 7-day daily average consumption hint, or None if insufficient data.
  "billingProvider": string // Return the organization's billing provider so the Credit page can pick its card layout.
  "periodCreditGrant": string // Return current-period credit grant total; None unless AWS Marketplace billed.
  "periodMeteredUsage": string // Return current-period accepted metered usage; None unless AWS Marketplace billed.
}
```

**回應範例值**

```json
{
  "totalCredits": "回應字串",
  "autoTopup": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "balanceAlert": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "nextGrant": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "lastGrant": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "consumptionHint": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "billingProvider": "回應字串",
  "periodCreditGrant": "回應字串",
  "periodMeteredUsage": "回應字串"
}
```

***

### 列出消耗明細 <a href="#credit-transactions-list" id="credit-transactions-list"></a>

GET `/api/v1/credit/transactions/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：不限，任何計費模式的組織都可呼叫。
{% endhint %}

#### 參數

| 參數名稱       | 必填 | 類型      | 說明                                             |
| ---------- | -- | ------- | ---------------------------------------------- |
| `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/credit/transactions/?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/credit/transactions/?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/credit/transactions/?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/credit/transactions/?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)
      "eventDatetime": string (timestamp)
      "createdAt": string (timestamp)
      "transactionType": string
      "creditItem": object
      "amount": string (decimal)
      "balanceAfter": string (decimal)
      "quantity": string (decimal)
      "provider": string
      "modelCode": string
      "unitPriceSnapshot": string (decimal)
      "member": object
      "description": string
      "metadata": object
      "parserName": string
      "quantityUnit": string
      "targetObject": object // Return frontend deep-link target for this transaction's GFK content.

``{kind: 'chat.message', objectId, chatbotId}`` opens the AgentOps record modal;
``{kind: 'dataset.evaluation', objectId, isMultiTurn}`` opens the evaluation results page.
Returns None when no GFK is attached, the content type is unsupported,
or the target no longer resolves inside this organization.
    }
  ]
}
```

**回應範例值**

```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",
      "eventDatetime": "回應字串",
      "createdAt": "回應字串",
      "transactionType": "回應字串",
      "creditItem": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應範例名稱",
        "description": "回應範例描述"
      },
      "amount": "回應字串",
      "balanceAfter": "回應字串",
      "quantity": "回應字串",
      "provider": "回應字串",
      "modelCode": "回應字串",
      "unitPriceSnapshot": "回應字串",
      "member": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應範例名稱",
        "description": "回應範例描述"
      },
      "description": "回應字串",
      "metadata": null,
      "parserName": "回應字串",
      "quantityUnit": "回應字串",
      "targetObject": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應範例名稱",
        "description": "回應範例描述"
      }
    }
  ]
}
```

***

### 取得單筆消耗明細 <a href="#credit-transactions-retrieve" id="credit-transactions-retrieve"></a>

GET `/api/v1/credit/transactions/{id}/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：不限，任何計費模式的組織都可呼叫。
{% endhint %}

#### 參數

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

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/credit/transactions/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/credit/transactions/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/credit/transactions/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/credit/transactions/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)
  "eventDatetime": string (timestamp)
  "createdAt": string (timestamp)
  "transactionType": string
  "creditItem": object
  "amount": string (decimal)
  "balanceAfter": string (decimal)
  "quantity": string (decimal)
  "provider": string
  "modelCode": string
  "unitPriceSnapshot": string (decimal)
  "member": object
  "description": string
  "metadata": object
  "parserName": string
  "quantityUnit": string
  "targetObject": object // Return frontend deep-link target for this transaction's GFK content.

``{kind: 'chat.message', objectId, chatbotId}`` opens the AgentOps record modal;
``{kind: 'dataset.evaluation', objectId, isMultiTurn}`` opens the evaluation results page.
Returns None when no GFK is attached, the content type is unsupported,
or the target no longer resolves inside this organization.
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "eventDatetime": "回應字串",
  "createdAt": "回應字串",
  "transactionType": "回應字串",
  "creditItem": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "amount": "回應字串",
  "balanceAfter": "回應字串",
  "quantity": "回應字串",
  "provider": "回應字串",
  "modelCode": "回應字串",
  "unitPriceSnapshot": "回應字串",
  "member": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "description": "回應字串",
  "metadata": null,
  "parserName": "回應字串",
  "quantityUnit": "回應字串",
  "targetObject": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  }
}
```

***

### 查詢消耗紀錄 <a href="#credit-transactions-history-retrieve" id="credit-transactions-history-retrieve"></a>

GET `/api/v1/credit/transactions/history/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：不限，任何計費模式的組織都可呼叫。
{% endhint %}

#### 參數

| 參數名稱        | 必填 | 類型      | 說明                                                                                                                                 |
| ----------- | -- | ------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `category`  | ❌  | string  | Credit item category (e.g. llm\_token, platform\_fee); agent\_memory selects the AI memory lines, which llm\_token then leaves out |
| `endDate`   | ❌  | string  | End date (inclusive, whole day in the platform timezone Asia/Taipei), format: YYYY-MM-DD                                           |
| `limit`     | ❌  | integer | Rows per page, capped at 100                                                                                                       |
| `page`      | ❌  | integer | 1-based page number                                                                                                                |
| `search`    | ❌  | string  | Case-insensitive match against transaction description and metadata                                                                |
| `startDate` | ❌  | string  | Start date (inclusive, whole day in the platform timezone Asia/Taipei), format: YYYY-MM-DD                                         |
| `type`      | ❌  | string  | Which rows to include: all ledger entries, consumption only, or credited only                                                      |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/credit/transactions/history/?category=example&endDate=example&limit=1&page=1&search=example&startDate=example&type=all" \
  -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/credit/transactions/history/?category=example&endDate=example&limit=1&page=1&search=example&startDate=example&type=all", 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/credit/transactions/history/?category=example&endDate=example&limit=1&page=1&search=example&startDate=example&type=all"
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/credit/transactions/history/?category=example&endDate=example&limit=1&page=1&search=example&startDate=example&type=all", [
        '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)
  "eventDatetime": string (timestamp)
  "createdAt": string (timestamp)
  "transactionType": string
  "creditItem": object
  "amount": string (decimal)
  "balanceAfter": string (decimal)
  "quantity": string (decimal)
  "provider": string
  "modelCode": string
  "unitPriceSnapshot": string (decimal)
  "member": object
  "description": string
  "metadata": object
  "parserName": string
  "quantityUnit": string
  "targetObject": object // Return frontend deep-link target for this transaction's GFK content.

``{kind: 'chat.message', objectId, chatbotId}`` opens the AgentOps record modal;
``{kind: 'dataset.evaluation', objectId, isMultiTurn}`` opens the evaluation results page.
Returns None when no GFK is attached, the content type is unsupported,
or the target no longer resolves inside this organization.
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "eventDatetime": "回應字串",
  "createdAt": "回應字串",
  "transactionType": "回應字串",
  "creditItem": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "amount": "回應字串",
  "balanceAfter": "回應字串",
  "quantity": "回應字串",
  "provider": "回應字串",
  "modelCode": "回應字串",
  "unitPriceSnapshot": "回應字串",
  "member": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "description": "回應字串",
  "metadata": null,
  "parserName": "回應字串",
  "quantityUnit": "回應字串",
  "targetObject": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  }
}
```

***

### 查詢消耗總計 <a href="#credit-transactions-history-summary-retrieve" id="credit-transactions-history-summary-retrieve"></a>

GET `/api/v1/credit/transactions/history-summary/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：不限，任何計費模式的組織都可呼叫。
{% endhint %}

#### 參數

| 參數名稱        | 必填 | 類型     | 說明                                                                                                                                 |
| ----------- | -- | ------ | ---------------------------------------------------------------------------------------------------------------------------------- |
| `category`  | ❌  | string | Credit item category (e.g. llm\_token, platform\_fee); agent\_memory selects the AI memory lines, which llm\_token then leaves out |
| `endDate`   | ❌  | string | End date (inclusive, whole day in the platform timezone Asia/Taipei), format: YYYY-MM-DD                                           |
| `search`    | ❌  | string | Case-insensitive match against transaction description and metadata                                                                |
| `startDate` | ❌  | string | Start date (inclusive, whole day in the platform timezone Asia/Taipei), format: YYYY-MM-DD                                         |
| `type`      | ❌  | string | Which rows to include: all ledger entries, consumption only, or credited only                                                      |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/credit/transactions/history-summary/?category=example&endDate=example&search=example&startDate=example&type=all" \
  -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/credit/transactions/history-summary/?category=example&endDate=example&search=example&startDate=example&type=all", 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/credit/transactions/history-summary/?category=example&endDate=example&search=example&startDate=example&type=all"
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/credit/transactions/history-summary/?category=example&endDate=example&search=example&startDate=example&type=all", [
        '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
{
  "consumedTotal": string (decimal)
  "creditedTotal": string (decimal)
  "count": integer
}
```

**回應範例值**

```json
{
  "consumedTotal": "回應字串",
  "creditedTotal": "回應字串",
  "count": 456
}
```

***

### 查詢各分類 Credit 用量 <a href="#organizations-usage-statistics-credit-categories-list" id="organizations-usage-statistics-credit-categories-list"></a>

GET `/api/v1/organizations/{organizationPk}/usage-statistics/credit-categories/`

{% hint style="info" %}
**所需權限**：用量統計權限。**計費模式**：組織須為 Credit 計費模式。
{% endhint %}

#### 參數

| 參數名稱              | 必填 | 類型      | 說明                                             |
| ----------------- | -- | ------- | ---------------------------------------------- |
| `organizationPk`  | ✅  | string  | A UUID string identifying this 組織 ID           |
| `endDate`         | ❌  | string  | End date, format: YYYY-MM-DD                   |
| `page`            | ❌  | integer | A page number within the paginated result set. |
| `pageSize`        | ❌  | integer | Number of results to return per page.          |
| `startDate`       | ✅  | string  | Start date, format: YYYY-MM-DD                 |
| `timeGranularity` | ❌  | string  | Time granularity (hour/day/month)              |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/credit-categories/?endDate=example&page=1&pageSize=1&startDate=example&timeGranularity=day" \
  -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/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/credit-categories/?endDate=example&page=1&pageSize=1&startDate=example&timeGranularity=day", 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/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/credit-categories/?endDate=example&page=1&pageSize=1&startDate=example&timeGranularity=day"
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/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/credit-categories/?endDate=example&page=1&pageSize=1&startDate=example&timeGranularity=day", [
        '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": [
    object
  ]
}
```

**回應範例值**

```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": "回應範例名稱",
      "description": "回應範例描述"
    }
  ]
}
```

***

### 查詢單一分類 Credit 用量 <a href="#organizations-usage-statistics-credit-categories-retrieve" id="organizations-usage-statistics-credit-categories-retrieve"></a>

GET `/api/v1/organizations/{organizationPk}/usage-statistics/credit-categories/{id}/`

{% hint style="info" %}
**所需權限**：用量統計權限。**計費模式**：組織須為 Credit 計費模式。
{% endhint %}

#### 參數

| 參數名稱              | 必填 | 類型     | 說明                                   |
| ----------------- | -- | ------ | ------------------------------------ |
| `id`              | ✅  | string |                                      |
| `organizationPk`  | ✅  | string | A UUID string identifying this 組織 ID |
| `endDate`         | ❌  | string | End date, format: YYYY-MM-DD         |
| `startDate`       | ✅  | string | Start date, format: YYYY-MM-DD       |
| `timeGranularity` | ❌  | string | Time granularity (hour/day/month)    |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/credit-categories/550e8400-e29b-41d4-a716-446655440000/?endDate=example&startDate=example&timeGranularity=day" \
  -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/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/credit-categories/550e8400-e29b-41d4-a716-446655440000/?endDate=example&startDate=example&timeGranularity=day", 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/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/credit-categories/550e8400-e29b-41d4-a716-446655440000/?endDate=example&startDate=example&timeGranularity=day"
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/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/credit-categories/550e8400-e29b-41d4-a716-446655440000/?endDate=example&startDate=example&timeGranularity=day", [
        '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
object
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "回應範例名稱",
  "description": "回應範例描述"
}
```

***

### 查詢計價項目的成員用量 <a href="#organizations-usage-statistics-credit-categories-members-list" id="organizations-usage-statistics-credit-categories-members-list"></a>

GET `/api/v1/organizations/{organizationPk}/usage-statistics/credit-categories/{itemPk}/members/`

{% hint style="info" %}
**所需權限**：用量統計權限。**計費模式**：組織須為 Credit 計費模式。
{% endhint %}

#### 參數

| 參數名稱              | 必填 | 類型      | 說明                                             |
| ----------------- | -- | ------- | ---------------------------------------------- |
| `itemPk`          | ✅  | string  |                                                |
| `organizationPk`  | ✅  | string  | A UUID string identifying this 組織 ID           |
| `endDate`         | ❌  | string  | End date, format: YYYY-MM-DD                   |
| `page`            | ❌  | integer | A page number within the paginated result set. |
| `pageSize`        | ❌  | integer | Number of results to return per page.          |
| `startDate`       | ✅  | string  | Start date, format: YYYY-MM-DD                 |
| `timeGranularity` | ❌  | string  | Time granularity (hour/day/month)              |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/credit-categories/{itemPk}/members/?endDate=example&page=1&pageSize=1&startDate=example&timeGranularity=day" \
  -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/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/credit-categories/{itemPk}/members/?endDate=example&page=1&pageSize=1&startDate=example&timeGranularity=day", 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/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/credit-categories/{itemPk}/members/?endDate=example&page=1&pageSize=1&startDate=example&timeGranularity=day"
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/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/credit-categories/{itemPk}/members/?endDate=example&page=1&pageSize=1&startDate=example&timeGranularity=day", [
        '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": [
    object
  ]
}
```

**回應範例值**

```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": "回應範例名稱",
      "description": "回應範例描述"
    }
  ]
}
```

***

### 查詢單一成員的計價項目用量 <a href="#organizations-usage-statistics-credit-categories-members-retrieve" id="organizations-usage-statistics-credit-categories-members-retrieve"></a>

GET `/api/v1/organizations/{organizationPk}/usage-statistics/credit-categories/{itemPk}/members/{id}/`

{% hint style="info" %}
**所需權限**：用量統計權限。**計費模式**：組織須為 Credit 計費模式。
{% endhint %}

#### 參數

| 參數名稱              | 必填 | 類型     | 說明                                   |
| ----------------- | -- | ------ | ------------------------------------ |
| `id`              | ✅  | string |                                      |
| `itemPk`          | ✅  | string |                                      |
| `organizationPk`  | ✅  | string | A UUID string identifying this 組織 ID |
| `endDate`         | ❌  | string | End date, format: YYYY-MM-DD         |
| `startDate`       | ✅  | string | Start date, format: YYYY-MM-DD       |
| `timeGranularity` | ❌  | string | Time granularity (hour/day/month)    |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/credit-categories/{itemPk}/members/550e8400-e29b-41d4-a716-446655440000/?endDate=example&startDate=example&timeGranularity=day" \
  -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/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/credit-categories/{itemPk}/members/550e8400-e29b-41d4-a716-446655440000/?endDate=example&startDate=example&timeGranularity=day", 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/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/credit-categories/{itemPk}/members/550e8400-e29b-41d4-a716-446655440000/?endDate=example&startDate=example&timeGranularity=day"
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/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/credit-categories/{itemPk}/members/550e8400-e29b-41d4-a716-446655440000/?endDate=example&startDate=example&timeGranularity=day", [
        '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
object
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "回應範例名稱",
  "description": "回應範例描述"
}
```

***

### 取得新成員預設額度設定 <a href="#credit-wallets-new-member-quota-policy-retrieve" id="credit-wallets-new-member-quota-policy-retrieve"></a>

GET `/api/v1/credit/wallets/{id}/new-member-quota-policy/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：不限。路徑的 `id` 是錢包 ID（`GET /api/v1/organizations/{id}/` 回應中的 `creditWallet.id`）。回應欄位：`newMemberQuotaEnabled`（是否自動配發）、`newMemberQuotaLimit`（額度上限）、`newMemberQuotaValidDays`（自加入起算的有效天數，`null` 為不過期）、`newMemberQuotaResetPeriod`（用量歸零週期）、`newMemberQuotaNote`（備註）、`requireQuotaBeforeConsumption`（新成員沒有額度時是否擋下使用）。
{% endhint %}

#### 參數

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

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/credit/wallets/550e8400-e29b-41d4-a716-446655440000/new-member-quota-policy/" \
  -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/credit/wallets/550e8400-e29b-41d4-a716-446655440000/new-member-quota-policy/", 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/credit/wallets/550e8400-e29b-41d4-a716-446655440000/new-member-quota-policy/"
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/credit/wallets/550e8400-e29b-41d4-a716-446655440000/new-member-quota-policy/", [
        '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
{
  "newMemberQuotaEnabled"?: boolean // 非必填
  "newMemberQuotaLimit"?: string (decimal) // 非必填
  "newMemberQuotaValidDays"?: integer // 非必填
  "newMemberQuotaResetPeriod"?: string (enum: none, daily, weekly, monthly) // * `none` - No Reset
* `daily` - Daily
* `weekly` - Weekly
* `monthly` - Monthly (非必填)
  "newMemberQuotaNote"?: string // 非必填
  "requireQuotaBeforeConsumption"?: boolean // 非必填
}
```

**回應範例值**

```json
{
  "newMemberQuotaEnabled": false,
  "newMemberQuotaLimit": "回應字串",
  "newMemberQuotaValidDays": 456,
  "newMemberQuotaResetPeriod": "none",
  "newMemberQuotaNote": "回應字串",
  "requireQuotaBeforeConsumption": false
}
```

***

### 更新新成員預設額度設定 <a href="#credit-wallets-new-member-quota-policy-partial-update" id="credit-wallets-new-member-quota-policy-partial-update"></a>

PATCH `/api/v1/credit/wallets/{id}/new-member-quota-policy/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：組織須為 Credit 計費模式，否則回 `400`。只需傳要修改的欄位，欄位同取得設定：`newMemberQuotaLimit` 不可為負數，開啟 `newMemberQuotaEnabled` 時必須有值；`newMemberQuotaValidDays` 為 1 到 3650 或 `null`。開啟後，之後新加入的成員（邀請、目錄同步、SSO、匯入）會自動配發一筆個人額度，生效時間為加入當下；設定有效天數時，到期時間不會晚於組織最晚一筆入帳額度的到期日（`null` 則不過期）。邀請時帶了 `creditQuota` 的受邀者以邀請指定的為準（指定的額度已到期或配發失敗時改套用此預設）。開啟 `requireQuotaBeforeConsumption` 時，沒拿到額度的新成員在分配額度前不能使用消耗 Credit 的功能。變更設定不影響已配發的額度與既有成員。回應：`message`、`config`（更新後的設定）。
{% endhint %}

#### 參數

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

#### 請求內容

**請求參數**

| 欄位                            | 類型                                          | 必填 | 說明                                                                         |
| ----------------------------- | ------------------------------------------- | -- | -------------------------------------------------------------------------- |
| newMemberQuotaEnabled         | boolean                                     | 否  |                                                                            |
| newMemberQuotaLimit           | string (decimal)                            | 否  |                                                                            |
| newMemberQuotaValidDays       | integer                                     | 否  |                                                                            |
| newMemberQuotaResetPeriod     | string (enum: none, daily, weekly, monthly) | 否  | `none`: No Reset ; `daily`: Daily ; `weekly`: Weekly ; `monthly`: Monthly; |
| newMemberQuotaNote            | string                                      | 否  |                                                                            |
| requireQuotaBeforeConsumption | boolean                                     | 否  |                                                                            |

**請求結構範例**

```typescript
{
  "newMemberQuotaEnabled"?: boolean // 非必填
  "newMemberQuotaLimit"?: string (decimal) // 非必填
  "newMemberQuotaValidDays"?: integer // 非必填
  "newMemberQuotaResetPeriod"?: string (enum: none, daily, weekly, monthly) // * `none` - No Reset
* `daily` - Daily
* `weekly` - Weekly
* `monthly` - Monthly (非必填)
  "newMemberQuotaNote"?: string // 非必填
  "requireQuotaBeforeConsumption"?: boolean // 非必填
}
```

**請求範例值**

```json
{
  "newMemberQuotaEnabled": true,
  "newMemberQuotaLimit": "100",
  "newMemberQuotaValidDays": 30,
  "newMemberQuotaResetPeriod": "none",
  "requireQuotaBeforeConsumption": false
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X PATCH "https://api.maiagent.ai/api/v1/credit/wallets/550e8400-e29b-41d4-a716-446655440000/new-member-quota-policy/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "newMemberQuotaEnabled": true,
    "newMemberQuotaLimit": "100",
    "newMemberQuotaValidDays": 30,
    "newMemberQuotaResetPeriod": "none",
    "requireQuotaBeforeConsumption": false
  }'

# 請確認在執行前替換 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 = {
    "newMemberQuotaEnabled": true,
    "newMemberQuotaLimit": "100",
    "newMemberQuotaValidDays": 30,
    "newMemberQuotaResetPeriod": "none",
    "requireQuotaBeforeConsumption": false
  };

axios.patch("https://api.maiagent.ai/api/v1/credit/wallets/550e8400-e29b-41d4-a716-446655440000/new-member-quota-policy/", 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/credit/wallets/550e8400-e29b-41d4-a716-446655440000/new-member-quota-policy/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "newMemberQuotaEnabled": True,
    "newMemberQuotaLimit": "100",
    "newMemberQuotaValidDays": 30,
    "newMemberQuotaResetPeriod": "none",
    "requireQuotaBeforeConsumption": False
}

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/credit/wallets/550e8400-e29b-41d4-a716-446655440000/new-member-quota-policy/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'newMemberQuotaEnabled' => true,
            'newMemberQuotaLimit' => '100',
            'newMemberQuotaValidDays' => 30,
            'newMemberQuotaResetPeriod' => 'none',
            'requireQuotaBeforeConsumption' => false
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "message": string
  "config": { // Organization-level policy for new members: default personal quota plus the consumption guardrail.
  {
    "newMemberQuotaEnabled"?: boolean // 非必填
    "newMemberQuotaLimit"?: string (decimal) // 非必填
    "newMemberQuotaValidDays"?: integer // 非必填
    "newMemberQuotaResetPeriod"?: string (enum: none, daily, weekly, monthly) // * `none` - No Reset
* `daily` - Daily
* `weekly` - Weekly
* `monthly` - Monthly (非必填)
    "newMemberQuotaNote"?: string // 非必填
    "requireQuotaBeforeConsumption"?: boolean // 非必填
  }
  }
}
```

**回應範例值**

```json
{
  "message": "回應字串",
  "config": {
    "newMemberQuotaEnabled": false,
    "newMemberQuotaLimit": "回應字串",
    "newMemberQuotaValidDays": 456,
    "newMemberQuotaResetPeriod": "none",
    "newMemberQuotaNote": "回應字串",
    "requireQuotaBeforeConsumption": false
  }
}
```

**狀態碼: 400 - Validation failed, or the organization is not on credit billing.**

***

### 列出成員額度現況 <a href="#organizations-credit-quota-members-list" id="organizations-credit-quota-members-list"></a>

GET `/api/v1/organizations/{organizationPk}/credit-quota-members/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：組織須為 Credit 計費模式。
{% endhint %}

#### 參數

| 參數名稱             | 必填 | 類型      | 說明                                                                      |
| ---------------- | -- | ------- | ----------------------------------------------------------------------- |
| `organizationPk` | ✅  | string  | A UUID string identifying this 組織 ID                                    |
| `ordering`       | ❌  | string  | Sort field (default '-created\_at')                                     |
| `page`           | ❌  | integer | Page number                                                             |
| `pageSize`       | ❌  | integer | Rows per page (max 100)                                                 |
| `quotaStatus`    | ❌  | string  | Filter by quota status                                                  |
| `search`         | ❌  | string  | Filter by member name, email, or member ID (case-insensitive substring) |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/credit-quota-members/?ordering=-created_at&page=1&pageSize=1&quotaStatus=allocated&search=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/organizations/550e8400-e29b-41d4-a716-446655440000/credit-quota-members/?ordering=-created_at&page=1&pageSize=1&quotaStatus=allocated&search=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/organizations/550e8400-e29b-41d4-a716-446655440000/credit-quota-members/?ordering=-created_at&page=1&pageSize=1&quotaStatus=allocated&search=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/organizations/550e8400-e29b-41d4-a716-446655440000/credit-quota-members/?ordering=-created_at&page=1&pageSize=1&quotaStatus=allocated&search=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": [
    {
      "count"?: integer // 非必填
      "next"?: string (uri) // 非必填
      "previous"?: string (uri) // 非必填
      "results"?: [ // 非必填
        {
          "id"?: string (uuid) // 非必填
          "name"?: string // 非必填
          "email"?: string // 非必填
          "credit_quota_required"?: boolean // 非必填
          "active_quota"?: { // Most recent quota summary (active first); same shape as the members API active_quota. (非必填)
          {
            "id"?: string (uuid) // 非必填
            "quota_limit"?: string // 非必填
            "consumed_amount"?: string // 非必填
            "remaining"?: string // 非必填
            "valid_from"?: string (date-time) // 非必填
            "valid_until"?: string (date-time) // 非必填
            "is_active"?: boolean // 非必填
            "expired_at"?: string (date-time) // 非必填
            "note"?: string // 非必填
          }
          }
        }
      ]
      "stats"?: { // Organization-wide member counts, unaffected by search or quota_status filter. (非必填)
      {
        "total"?: integer // 非必填
        "allocated"?: integer // 非必填
        "expired"?: integer // 非必填
        "unallocated"?: integer // 非必填
      }
      }
    }
  ]
}
```

**回應範例值**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "count": 456,
      "next": "https://example.com/file.jpg",
      "previous": "https://example.com/file.jpg",
      "results": [
        {
          "id": "550e8400-e29b-41d4-a716-446655440000",
          "name": "回應字串",
          "email": "回應字串",
          "credit_quota_required": false,
          "active_quota": {
            "id": "550e8400-e29b-41d4-a716-446655440000",
            "name": "回應範例名稱",
            "description": "回應範例描述"
          }
        }
      ],
      "stats": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應範例名稱",
        "description": "回應範例描述"
      }
    }
  ]
}
```

***

### 列出角色額度現況 <a href="#organizations-credit-quota-groups-list" id="organizations-credit-quota-groups-list"></a>

GET `/api/v1/organizations/{organizationPk}/credit-quota-groups/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：組織須為 Credit 計費模式。
{% endhint %}

#### 參數

| 參數名稱             | 必填 | 類型      | 說明                                                            |
| ---------------- | -- | ------- | ------------------------------------------------------------- |
| `organizationPk` | ✅  | string  | A UUID string identifying this 組織 ID                          |
| `ordering`       | ❌  | string  | Sort field (default '-created\_at')                           |
| `page`           | ❌  | integer | Page number                                                   |
| `pageSize`       | ❌  | integer | Rows per page (max 100)                                       |
| `quotaStatus`    | ❌  | string  | Filter by quota status                                        |
| `search`         | ❌  | string  | Filter by group name or group ID (case-insensitive substring) |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/credit-quota-groups/?ordering=-created_at&page=1&pageSize=1&quotaStatus=allocated&search=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/organizations/550e8400-e29b-41d4-a716-446655440000/credit-quota-groups/?ordering=-created_at&page=1&pageSize=1&quotaStatus=allocated&search=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/organizations/550e8400-e29b-41d4-a716-446655440000/credit-quota-groups/?ordering=-created_at&page=1&pageSize=1&quotaStatus=allocated&search=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/organizations/550e8400-e29b-41d4-a716-446655440000/credit-quota-groups/?ordering=-created_at&page=1&pageSize=1&quotaStatus=allocated&search=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": [
    {
      "count"?: integer // 非必填
      "next"?: string (uri) // 非必填
      "previous"?: string (uri) // 非必填
      "results"?: [ // 非必填
        {
          "id"?: string (uuid) // 非必填
          "name"?: string // 非必填
          "type"?: string (enum: owner, default, custom) // 非必填
          "credit_quota_required"?: boolean // 非必填
          "active_quota"?: { // Most recent quota summary (active first); same shape as the member/inbox variants. (非必填)
          {
            "id"?: string (uuid) // 非必填
            "quota_limit"?: string // 非必填
            "consumed_amount"?: string // 非必填
            "remaining"?: string // 非必填
            "valid_from"?: string (date-time) // 非必填
            "valid_until"?: string (date-time) // 非必填
            "is_active"?: boolean // 非必填
            "expired_at"?: string (date-time) // 非必填
            "note"?: string // 非必填
          }
          }
        }
      ]
      "stats"?: { // Organization-wide group counts, unaffected by search or quota_status filter. (非必填)
      {
        "total"?: integer // 非必填
        "allocated"?: integer // 非必填
        "expired"?: integer // 非必填
        "unallocated"?: integer // 非必填
      }
      }
    }
  ]
}
```

**回應範例值**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "count": 456,
      "next": "https://example.com/file.jpg",
      "previous": "https://example.com/file.jpg",
      "results": [
        {
          "id": "550e8400-e29b-41d4-a716-446655440000",
          "name": "回應字串",
          "type": "owner",
          "credit_quota_required": false,
          "active_quota": {
            "id": "550e8400-e29b-41d4-a716-446655440000",
            "name": "回應範例名稱",
            "description": "回應範例描述"
          }
        }
      ],
      "stats": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應範例名稱",
        "description": "回應範例描述"
      }
    }
  ]
}
```

***

### 列出對話平台額度現況 <a href="#organizations-credit-quota-inboxes-list" id="organizations-credit-quota-inboxes-list"></a>

GET `/api/v1/organizations/{organizationPk}/credit-quota-inboxes/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：組織須為 Credit 計費模式。
{% endhint %}

#### 參數

| 參數名稱             | 必填 | 類型      | 說明                                                                                        |
| ---------------- | -- | ------- | ----------------------------------------------------------------------------------------- |
| `organizationPk` | ✅  | string  | A UUID string identifying this 組織 ID                                                      |
| `excludeBuiltIn` | ❌  | boolean | true 時排除官方內建 Agent（由 Agent 市集租用而建立的鎖定實例）的資料，只留組織自建助理；「複製為自建」產生的副本屬自建。不帶或 false 時與未加此條件相同。 |
| `ordering`       | ❌  | string  | Which field to use when ordering the results.                                             |
| `page`           | ❌  | integer | A page number within the paginated result set.                                            |
| `pageSize`       | ❌  | integer | Number of results to return per page.                                                     |
| `search`         | ❌  | string  | A search term.                                                                            |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/credit-quota-inboxes/?excludeBuiltIn=true&ordering=example&page=1&pageSize=1&search=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/organizations/550e8400-e29b-41d4-a716-446655440000/credit-quota-inboxes/?excludeBuiltIn=true&ordering=example&page=1&pageSize=1&search=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/organizations/550e8400-e29b-41d4-a716-446655440000/credit-quota-inboxes/?excludeBuiltIn=true&ordering=example&page=1&pageSize=1&search=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/organizations/550e8400-e29b-41d4-a716-446655440000/credit-quota-inboxes/?excludeBuiltIn=true&ordering=example&page=1&pageSize=1&search=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)
      "name": string
      "channelType": 
      {
      }
      "channelTypeLabel": string
      "webChatAccessType": string // Sub-type for web channels (web = public embed, admin = internal Q&A, api = completions).

A chatbot ships with three same-named web inboxes, so the frontend needs
this to tell them apart. None for non-web channels. Reads the prefetched
generic ``channel`` relation (no extra query on the list path).
      "chatbot": object
      "creditQuotaRequired": boolean // When True, this inbox must have an active credit quota for the AI to reply
      "activeQuota": object // Return the most recent quota summary (active first), via prefetch to avoid N+1.
      "canUpdate": boolean // Return whether the current user can update this resource.
    }
  ]
}
```

**回應範例值**

```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": "回應字串",
      "channelType": {},
      "channelTypeLabel": "回應字串",
      "webChatAccessType": "回應字串",
      "chatbot": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應範例名稱",
        "description": "回應範例描述"
      },
      "creditQuotaRequired": false,
      "activeQuota": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應範例名稱",
        "description": "回應範例描述"
      },
      "canUpdate": false
    }
  ]
}
```

***

### 列出成員的額度設定 <a href="#organizations-members-credit-quotas-list" id="organizations-members-credit-quotas-list"></a>

GET `/api/v1/organizations/{organizationPk}/members/{memberPk}/credit-quotas/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：組織須為 Credit 計費模式。
{% endhint %}

#### 參數

| 參數名稱             | 必填 | 類型      | 說明                                             |
| ---------------- | -- | ------- | ---------------------------------------------- |
| `memberPk`       | ✅  | string  |                                                |
| `organizationPk` | ✅  | string  | A UUID string identifying this 組織 ID           |
| `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/organizations/550e8400-e29b-41d4-a716-446655440000/members/{memberPk}/credit-quotas/?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/organizations/550e8400-e29b-41d4-a716-446655440000/members/{memberPk}/credit-quotas/?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/organizations/550e8400-e29b-41d4-a716-446655440000/members/{memberPk}/credit-quotas/?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/organizations/550e8400-e29b-41d4-a716-446655440000/members/{memberPk}/credit-quotas/?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)
      "member": object
      "quotaLimit": string (decimal) // Maximum credits this member may consume
      "consumedAmount": string (decimal) // Credits consumed so far (updated via F() for concurrency safety)
      "remaining": string (decimal)
      "validFrom": string (timestamp)
      "validUntil": string (timestamp) // NULL means permanent
      "resetPeriod":  // Cycle on which consumed_amount is automatically zeroed; "none" keeps the one-shot ceiling

* `none` - No Reset
* `daily` - Daily
* `weekly` - Weekly
* `monthly` - Monthly
      {
      }
      "nextResetAt": string (timestamp) // Local-midnight boundary of the next automatic reset; NULL when reset_period is "none"
      "isActive": boolean
      "expiredAt": string (timestamp) // Actual deactivation time (cron or manual)
      "createdBy": object
      "note": string
      "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",
      "member": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應範例名稱",
        "description": "回應範例描述"
      },
      "quotaLimit": "回應字串",
      "consumedAmount": "回應字串",
      "remaining": "回應字串",
      "validFrom": "回應字串",
      "validUntil": "回應字串",
      "resetPeriod": {},
      "nextResetAt": "回應字串",
      "isActive": false,
      "expiredAt": "回應字串",
      "createdBy": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應範例名稱",
        "description": "回應範例描述"
      },
      "note": "回應字串",
      "createdAt": "回應字串",
      "updatedAt": "回應字串"
    }
  ]
}
```

***

### 取得成員的單筆額度設定 <a href="#organizations-members-credit-quotas-retrieve" id="organizations-members-credit-quotas-retrieve"></a>

GET `/api/v1/organizations/{organizationPk}/members/{memberPk}/credit-quotas/{id}/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：組織須為 Credit 計費模式。
{% endhint %}

#### 參數

| 參數名稱             | 必填 | 類型     | 說明                                   |
| ---------------- | -- | ------ | ------------------------------------ |
| `id`             | ✅  | string |                                      |
| `memberPk`       | ✅  | string |                                      |
| `organizationPk` | ✅  | string | A UUID string identifying this 組織 ID |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/members/{memberPk}/credit-quotas/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/organizations/550e8400-e29b-41d4-a716-446655440000/members/{memberPk}/credit-quotas/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/organizations/550e8400-e29b-41d4-a716-446655440000/members/{memberPk}/credit-quotas/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/organizations/550e8400-e29b-41d4-a716-446655440000/members/{memberPk}/credit-quotas/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)
  "member": object
  "quotaLimit": string (decimal) // Maximum credits this member may consume
  "consumedAmount": string (decimal) // Credits consumed so far (updated via F() for concurrency safety)
  "remaining": string (decimal)
  "validFrom": string (timestamp)
  "validUntil": string (timestamp) // NULL means permanent
  "resetPeriod":  // Cycle on which consumed_amount is automatically zeroed; "none" keeps the one-shot ceiling

* `none` - No Reset
* `daily` - Daily
* `weekly` - Weekly
* `monthly` - Monthly
  {
  }
  "nextResetAt": string (timestamp) // Local-midnight boundary of the next automatic reset; NULL when reset_period is "none"
  "isActive": boolean
  "expiredAt": string (timestamp) // Actual deactivation time (cron or manual)
  "createdBy": object
  "note": string
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "member": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "quotaLimit": "回應字串",
  "consumedAmount": "回應字串",
  "remaining": "回應字串",
  "validFrom": "回應字串",
  "validUntil": "回應字串",
  "resetPeriod": {},
  "nextResetAt": "回應字串",
  "isActive": false,
  "expiredAt": "回應字串",
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "note": "回應字串",
  "createdAt": "回應字串",
  "updatedAt": "回應字串"
}
```

***

### 為成員設定額度 <a href="#organizations-members-credit-quotas-create" id="organizations-members-credit-quotas-create"></a>

POST `/api/v1/organizations/{organizationPk}/members/{memberPk}/credit-quotas/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：組織須為 Credit 計費模式。請求內容與規則見 [額度怎麼運作](#credit-quota-rules)；成員已有生效中的額度時回 `400`，請先停用。
{% endhint %}

#### 參數

| 參數名稱             | 必填 | 類型     | 說明                                   |
| ---------------- | -- | ------ | ------------------------------------ |
| `memberPk`       | ✅  | string |                                      |
| `organizationPk` | ✅  | string | A UUID string identifying this 組織 ID |

#### 請求內容

**請求參數**

| 欄位          | 類型                 | 必填 | 說明 |
| ----------- | ------------------ | -- | -- |
| quotaLimit  | string (decimal)   | 是  |    |
| validFrom   | string (date-time) | 是  |    |
| validUntil  | string (date-time) | 否  |    |
| note        | string             | 否  |    |
| resetPeriod | object             | 否  |    |

**請求結構範例**

```typescript
{
  "quotaLimit": string (decimal)
  "validFrom": string (date-time)
  "validUntil"?: string (date-time) // 非必填
  "note"?: string // 非必填
  "resetPeriod"?:  // 非必填
  {
  }
}
```

**請求範例值**

```json
{
  "quotaLimit": "500",
  "validFrom": "2026-10-16T00:00:00+08:00",
  "validUntil": "2026-12-31T23:59:59+08:00",
  "resetPeriod": "monthly",
  "note": "Q4 budget"
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/members/{memberPk}/credit-quotas/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "quotaLimit": "500",
    "validFrom": "2026-10-16T00:00:00+08:00",
    "validUntil": "2026-12-31T23:59:59+08:00",
    "resetPeriod": "monthly",
    "note": "Q4 budget"
  }'

# 請確認在執行前替換 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 = {
    "quotaLimit": "500",
    "validFrom": "2026-10-16T00:00:00+08:00",
    "validUntil": "2026-12-31T23:59:59+08:00",
    "resetPeriod": "monthly",
    "note": "Q4 budget"
  };

axios.post("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/members/{memberPk}/credit-quotas/", 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/organizations/550e8400-e29b-41d4-a716-446655440000/members/{memberPk}/credit-quotas/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "quotaLimit": "500",
    "validFrom": "2026-10-16T00:00:00+08:00",
    "validUntil": "2026-12-31T23:59:59+08:00",
    "resetPeriod": "monthly",
    "note": "Q4 budget"
}

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/organizations/550e8400-e29b-41d4-a716-446655440000/members/{memberPk}/credit-quotas/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'quotaLimit' => '500',
            'validFrom' => '2026-10-16T00:00:00+08:00',
            'validUntil' => '2026-12-31T23:59:59+08:00',
            'resetPeriod' => 'monthly',
            'note' => 'Q4 budget'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 201**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "member": object
  "quotaLimit": string (decimal) // Maximum credits this member may consume
  "consumedAmount": string (decimal) // Credits consumed so far (updated via F() for concurrency safety)
  "remaining": string (decimal)
  "validFrom": string (timestamp)
  "validUntil": string (timestamp) // NULL means permanent
  "resetPeriod":  // Cycle on which consumed_amount is automatically zeroed; "none" keeps the one-shot ceiling

* `none` - No Reset
* `daily` - Daily
* `weekly` - Weekly
* `monthly` - Monthly
  {
  }
  "nextResetAt": string (timestamp) // Local-midnight boundary of the next automatic reset; NULL when reset_period is "none"
  "isActive": boolean
  "expiredAt": string (timestamp) // Actual deactivation time (cron or manual)
  "createdBy": object
  "note": string
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "member": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "quotaLimit": "回應字串",
  "consumedAmount": "回應字串",
  "remaining": "回應字串",
  "validFrom": "回應字串",
  "validUntil": "回應字串",
  "resetPeriod": {},
  "nextResetAt": "回應字串",
  "isActive": false,
  "expiredAt": "回應字串",
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "note": "回應字串",
  "createdAt": "回應字串",
  "updatedAt": "回應字串"
}
```

***

### 更新成員的額度設定 <a href="#organizations-members-credit-quotas-partial-update" id="organizations-members-credit-quotas-partial-update"></a>

PATCH `/api/v1/organizations/{organizationPk}/members/{memberPk}/credit-quotas/{id}/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：組織須為 Credit 計費模式。只需傳要修改的欄位：`quotaLimit`、`validUntil`、`resetPeriod`、`note`（生效時間不能改）。`quotaLimit` 不可低於已使用的額度；已停用的額度不能更新，回 `400`。
{% endhint %}

#### 參數

| 參數名稱             | 必填 | 類型     | 說明                                   |
| ---------------- | -- | ------ | ------------------------------------ |
| `id`             | ✅  | string |                                      |
| `memberPk`       | ✅  | string |                                      |
| `organizationPk` | ✅  | string | A UUID string identifying this 組織 ID |

#### 請求內容

**請求參數**

| 欄位          | 類型                                          | 必填 | 說明                                                                         |
| ----------- | ------------------------------------------- | -- | -------------------------------------------------------------------------- |
| quotaLimit  | string (decimal)                            | 否  |                                                                            |
| validUntil  | string (date-time)                          | 否  |                                                                            |
| note        | string                                      | 否  |                                                                            |
| resetPeriod | string (enum: none, daily, weekly, monthly) | 否  | `none`: No Reset ; `daily`: Daily ; `weekly`: Weekly ; `monthly`: Monthly; |

**請求結構範例**

```typescript
{
  "quotaLimit"?: string (decimal) // 非必填
  "validUntil"?: string (date-time) // 非必填
  "note"?: string // 非必填
  "resetPeriod"?: string (enum: none, daily, weekly, monthly) // * `none` - No Reset
* `daily` - Daily
* `weekly` - Weekly
* `monthly` - Monthly (非必填)
}
```

**請求範例值**

```json
{
  "quotaLimit": "範例字串",
  "validUntil": "2025-01-01T00:00:00.000Z",
  "note": "範例字串",
  "resetPeriod": "none"
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X PATCH "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/members/{memberPk}/credit-quotas/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "quotaLimit": "範例字串",
    "validUntil": "2025-01-01T00:00:00.000Z",
    "note": "範例字串",
    "resetPeriod": "none"
  }'

# 請確認在執行前替換 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 = {
    "quotaLimit": "範例字串",
    "validUntil": "2025-01-01T00:00:00.000Z",
    "note": "範例字串",
    "resetPeriod": "none"
  };

axios.patch("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/members/{memberPk}/credit-quotas/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/organizations/550e8400-e29b-41d4-a716-446655440000/members/{memberPk}/credit-quotas/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "quotaLimit": "範例字串",
    "validUntil": "2025-01-01T00:00:00.000Z",
    "note": "範例字串",
    "resetPeriod": "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/organizations/550e8400-e29b-41d4-a716-446655440000/members/{memberPk}/credit-quotas/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'quotaLimit' => '範例字串',
            'validUntil' => '2025-01-01T00:00:00.000Z',
            'note' => '範例字串',
            'resetPeriod' => 'none'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "member": object
  "quotaLimit": string (decimal) // Maximum credits this member may consume
  "consumedAmount": string (decimal) // Credits consumed so far (updated via F() for concurrency safety)
  "remaining": string (decimal)
  "validFrom": string (timestamp)
  "validUntil": string (timestamp) // NULL means permanent
  "resetPeriod":  // Cycle on which consumed_amount is automatically zeroed; "none" keeps the one-shot ceiling

* `none` - No Reset
* `daily` - Daily
* `weekly` - Weekly
* `monthly` - Monthly
  {
  }
  "nextResetAt": string (timestamp) // Local-midnight boundary of the next automatic reset; NULL when reset_period is "none"
  "isActive": boolean
  "expiredAt": string (timestamp) // Actual deactivation time (cron or manual)
  "createdBy": object
  "note": string
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "member": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "quotaLimit": "回應字串",
  "consumedAmount": "回應字串",
  "remaining": "回應字串",
  "validFrom": "回應字串",
  "validUntil": "回應字串",
  "resetPeriod": {},
  "nextResetAt": "回應字串",
  "isActive": false,
  "expiredAt": "回應字串",
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "note": "回應字串",
  "createdAt": "回應字串",
  "updatedAt": "回應字串"
}
```

***

### 停用成員的額度設定 <a href="#organizations-members-credit-quotas-destroy" id="organizations-members-credit-quotas-destroy"></a>

DELETE `/api/v1/organizations/{organizationPk}/members/{memberPk}/credit-quotas/{id}/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：組織須為 Credit 計費模式。成功回 `204`。停用後成員的「需要額度」仍開啟，在設定新額度或解除額度限制前不能使用消耗 Credit 的功能；已停用的額度再停用回 `400`。
{% endhint %}

#### 參數

| 參數名稱             | 必填 | 類型     | 說明                                   |
| ---------------- | -- | ------ | ------------------------------------ |
| `id`             | ✅  | string |                                      |
| `memberPk`       | ✅  | string |                                      |
| `organizationPk` | ✅  | string | A UUID string identifying this 組織 ID |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X DELETE "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/members/{memberPk}/credit-quotas/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/organizations/550e8400-e29b-41d4-a716-446655440000/members/{memberPk}/credit-quotas/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/organizations/550e8400-e29b-41d4-a716-446655440000/members/{memberPk}/credit-quotas/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/organizations/550e8400-e29b-41d4-a716-446655440000/members/{memberPk}/credit-quotas/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 |

***

### 列出角色的額度設定 <a href="#organizations-groups-credit-quotas-list" id="organizations-groups-credit-quotas-list"></a>

GET `/api/v1/organizations/{organizationPk}/groups/{groupPk}/credit-quotas/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：組織須為 Credit 計費模式。
{% endhint %}

#### 參數

| 參數名稱             | 必填 | 類型      | 說明                                             |
| ---------------- | -- | ------- | ---------------------------------------------- |
| `groupPk`        | ✅  | string  |                                                |
| `organizationPk` | ✅  | string  | A UUID string identifying this 組織 ID           |
| `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/organizations/550e8400-e29b-41d4-a716-446655440000/groups/{groupPk}/credit-quotas/?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/organizations/550e8400-e29b-41d4-a716-446655440000/groups/{groupPk}/credit-quotas/?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/organizations/550e8400-e29b-41d4-a716-446655440000/groups/{groupPk}/credit-quotas/?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/organizations/550e8400-e29b-41d4-a716-446655440000/groups/{groupPk}/credit-quotas/?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)
      "group": object
      "quotaLimit": string (decimal) // Maximum credits members of this group may consume
      "consumedAmount": string (decimal) // Credits consumed so far (updated via F() for concurrency safety)
      "remaining": string (decimal)
      "validFrom": string (timestamp)
      "validUntil": string (timestamp) // NULL means permanent
      "resetPeriod":  // Cycle on which consumed_amount is automatically zeroed; "none" keeps the one-shot ceiling

* `none` - No Reset
* `daily` - Daily
* `weekly` - Weekly
* `monthly` - Monthly
      {
      }
      "nextResetAt": string (timestamp) // Local-midnight boundary of the next automatic reset; NULL when reset_period is "none"
      "isActive": boolean
      "expiredAt": string (timestamp) // Actual deactivation time (cron or manual)
      "createdBy": object
      "note": string
      "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",
      "group": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應範例名稱",
        "description": "回應範例描述"
      },
      "quotaLimit": "回應字串",
      "consumedAmount": "回應字串",
      "remaining": "回應字串",
      "validFrom": "回應字串",
      "validUntil": "回應字串",
      "resetPeriod": {},
      "nextResetAt": "回應字串",
      "isActive": false,
      "expiredAt": "回應字串",
      "createdBy": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應範例名稱",
        "description": "回應範例描述"
      },
      "note": "回應字串",
      "createdAt": "回應字串",
      "updatedAt": "回應字串"
    }
  ]
}
```

***

### 取得角色的單筆額度設定 <a href="#organizations-groups-credit-quotas-retrieve" id="organizations-groups-credit-quotas-retrieve"></a>

GET `/api/v1/organizations/{organizationPk}/groups/{groupPk}/credit-quotas/{id}/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：組織須為 Credit 計費模式。
{% endhint %}

#### 參數

| 參數名稱             | 必填 | 類型     | 說明                                   |
| ---------------- | -- | ------ | ------------------------------------ |
| `groupPk`        | ✅  | string |                                      |
| `id`             | ✅  | string |                                      |
| `organizationPk` | ✅  | string | A UUID string identifying this 組織 ID |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/groups/{groupPk}/credit-quotas/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/organizations/550e8400-e29b-41d4-a716-446655440000/groups/{groupPk}/credit-quotas/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/organizations/550e8400-e29b-41d4-a716-446655440000/groups/{groupPk}/credit-quotas/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/organizations/550e8400-e29b-41d4-a716-446655440000/groups/{groupPk}/credit-quotas/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)
  "group": object
  "quotaLimit": string (decimal) // Maximum credits members of this group may consume
  "consumedAmount": string (decimal) // Credits consumed so far (updated via F() for concurrency safety)
  "remaining": string (decimal)
  "validFrom": string (timestamp)
  "validUntil": string (timestamp) // NULL means permanent
  "resetPeriod":  // Cycle on which consumed_amount is automatically zeroed; "none" keeps the one-shot ceiling

* `none` - No Reset
* `daily` - Daily
* `weekly` - Weekly
* `monthly` - Monthly
  {
  }
  "nextResetAt": string (timestamp) // Local-midnight boundary of the next automatic reset; NULL when reset_period is "none"
  "isActive": boolean
  "expiredAt": string (timestamp) // Actual deactivation time (cron or manual)
  "createdBy": object
  "note": string
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "group": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "quotaLimit": "回應字串",
  "consumedAmount": "回應字串",
  "remaining": "回應字串",
  "validFrom": "回應字串",
  "validUntil": "回應字串",
  "resetPeriod": {},
  "nextResetAt": "回應字串",
  "isActive": false,
  "expiredAt": "回應字串",
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "note": "回應字串",
  "createdAt": "回應字串",
  "updatedAt": "回應字串"
}
```

***

### 為角色設定額度 <a href="#organizations-groups-credit-quotas-create" id="organizations-groups-credit-quotas-create"></a>

POST `/api/v1/organizations/{organizationPk}/groups/{groupPk}/credit-quotas/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：組織須為 Credit 計費模式。設定的是角色內所有成員共用的額度，不會分配給個別成員；要替每位成員各設一筆額度請用 [依角色批次分配額度](#organizations-groups-batch-distribute-credit-quota-create)。請求內容與規則見 [額度怎麼運作](#credit-quota-rules)；角色已有生效中的額度時回 `400`，請先停用。
{% endhint %}

#### 參數

| 參數名稱             | 必填 | 類型     | 說明                                   |
| ---------------- | -- | ------ | ------------------------------------ |
| `groupPk`        | ✅  | string |                                      |
| `organizationPk` | ✅  | string | A UUID string identifying this 組織 ID |

#### 請求內容

**請求參數**

| 欄位          | 類型                 | 必填 | 說明 |
| ----------- | ------------------ | -- | -- |
| quotaLimit  | string (decimal)   | 是  |    |
| validFrom   | string (date-time) | 是  |    |
| validUntil  | string (date-time) | 否  |    |
| note        | string             | 否  |    |
| resetPeriod | object             | 否  |    |

**請求結構範例**

```typescript
{
  "quotaLimit": string (decimal)
  "validFrom": string (date-time)
  "validUntil"?: string (date-time) // 非必填
  "note"?: string // 非必填
  "resetPeriod"?:  // 非必填
  {
  }
}
```

**請求範例值**

```json
{
  "quotaLimit": "500",
  "validFrom": "2026-10-16T00:00:00+08:00",
  "validUntil": "2026-12-31T23:59:59+08:00",
  "resetPeriod": "monthly",
  "note": "Q4 budget"
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/groups/{groupPk}/credit-quotas/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "quotaLimit": "500",
    "validFrom": "2026-10-16T00:00:00+08:00",
    "validUntil": "2026-12-31T23:59:59+08:00",
    "resetPeriod": "monthly",
    "note": "Q4 budget"
  }'

# 請確認在執行前替換 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 = {
    "quotaLimit": "500",
    "validFrom": "2026-10-16T00:00:00+08:00",
    "validUntil": "2026-12-31T23:59:59+08:00",
    "resetPeriod": "monthly",
    "note": "Q4 budget"
  };

axios.post("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/groups/{groupPk}/credit-quotas/", 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/organizations/550e8400-e29b-41d4-a716-446655440000/groups/{groupPk}/credit-quotas/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "quotaLimit": "500",
    "validFrom": "2026-10-16T00:00:00+08:00",
    "validUntil": "2026-12-31T23:59:59+08:00",
    "resetPeriod": "monthly",
    "note": "Q4 budget"
}

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/organizations/550e8400-e29b-41d4-a716-446655440000/groups/{groupPk}/credit-quotas/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'quotaLimit' => '500',
            'validFrom' => '2026-10-16T00:00:00+08:00',
            'validUntil' => '2026-12-31T23:59:59+08:00',
            'resetPeriod' => 'monthly',
            'note' => 'Q4 budget'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 201**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "group": object
  "quotaLimit": string (decimal) // Maximum credits members of this group may consume
  "consumedAmount": string (decimal) // Credits consumed so far (updated via F() for concurrency safety)
  "remaining": string (decimal)
  "validFrom": string (timestamp)
  "validUntil": string (timestamp) // NULL means permanent
  "resetPeriod":  // Cycle on which consumed_amount is automatically zeroed; "none" keeps the one-shot ceiling

* `none` - No Reset
* `daily` - Daily
* `weekly` - Weekly
* `monthly` - Monthly
  {
  }
  "nextResetAt": string (timestamp) // Local-midnight boundary of the next automatic reset; NULL when reset_period is "none"
  "isActive": boolean
  "expiredAt": string (timestamp) // Actual deactivation time (cron or manual)
  "createdBy": object
  "note": string
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "group": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "quotaLimit": "回應字串",
  "consumedAmount": "回應字串",
  "remaining": "回應字串",
  "validFrom": "回應字串",
  "validUntil": "回應字串",
  "resetPeriod": {},
  "nextResetAt": "回應字串",
  "isActive": false,
  "expiredAt": "回應字串",
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "note": "回應字串",
  "createdAt": "回應字串",
  "updatedAt": "回應字串"
}
```

***

### 更新角色的額度設定 <a href="#organizations-groups-credit-quotas-partial-update" id="organizations-groups-credit-quotas-partial-update"></a>

PATCH `/api/v1/organizations/{organizationPk}/groups/{groupPk}/credit-quotas/{id}/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：組織須為 Credit 計費模式。只需傳要修改的欄位：`quotaLimit`、`validUntil`、`resetPeriod`、`note`（生效時間不能改）。`quotaLimit` 不可低於已使用的額度；已停用的額度不能更新，回 `400`。
{% endhint %}

#### 參數

| 參數名稱             | 必填 | 類型     | 說明                                   |
| ---------------- | -- | ------ | ------------------------------------ |
| `groupPk`        | ✅  | string |                                      |
| `id`             | ✅  | string |                                      |
| `organizationPk` | ✅  | string | A UUID string identifying this 組織 ID |

#### 請求內容

**請求參數**

| 欄位          | 類型                                          | 必填 | 說明                                                                         |
| ----------- | ------------------------------------------- | -- | -------------------------------------------------------------------------- |
| quotaLimit  | string (decimal)                            | 否  |                                                                            |
| validUntil  | string (date-time)                          | 否  |                                                                            |
| note        | string                                      | 否  |                                                                            |
| resetPeriod | string (enum: none, daily, weekly, monthly) | 否  | `none`: No Reset ; `daily`: Daily ; `weekly`: Weekly ; `monthly`: Monthly; |

**請求結構範例**

```typescript
{
  "quotaLimit"?: string (decimal) // 非必填
  "validUntil"?: string (date-time) // 非必填
  "note"?: string // 非必填
  "resetPeriod"?: string (enum: none, daily, weekly, monthly) // * `none` - No Reset
* `daily` - Daily
* `weekly` - Weekly
* `monthly` - Monthly (非必填)
}
```

**請求範例值**

```json
{
  "quotaLimit": "範例字串",
  "validUntil": "2025-01-01T00:00:00.000Z",
  "note": "範例字串",
  "resetPeriod": "none"
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X PATCH "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/groups/{groupPk}/credit-quotas/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "quotaLimit": "範例字串",
    "validUntil": "2025-01-01T00:00:00.000Z",
    "note": "範例字串",
    "resetPeriod": "none"
  }'

# 請確認在執行前替換 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 = {
    "quotaLimit": "範例字串",
    "validUntil": "2025-01-01T00:00:00.000Z",
    "note": "範例字串",
    "resetPeriod": "none"
  };

axios.patch("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/groups/{groupPk}/credit-quotas/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/organizations/550e8400-e29b-41d4-a716-446655440000/groups/{groupPk}/credit-quotas/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "quotaLimit": "範例字串",
    "validUntil": "2025-01-01T00:00:00.000Z",
    "note": "範例字串",
    "resetPeriod": "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/organizations/550e8400-e29b-41d4-a716-446655440000/groups/{groupPk}/credit-quotas/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'quotaLimit' => '範例字串',
            'validUntil' => '2025-01-01T00:00:00.000Z',
            'note' => '範例字串',
            'resetPeriod' => 'none'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "group": object
  "quotaLimit": string (decimal) // Maximum credits members of this group may consume
  "consumedAmount": string (decimal) // Credits consumed so far (updated via F() for concurrency safety)
  "remaining": string (decimal)
  "validFrom": string (timestamp)
  "validUntil": string (timestamp) // NULL means permanent
  "resetPeriod":  // Cycle on which consumed_amount is automatically zeroed; "none" keeps the one-shot ceiling

* `none` - No Reset
* `daily` - Daily
* `weekly` - Weekly
* `monthly` - Monthly
  {
  }
  "nextResetAt": string (timestamp) // Local-midnight boundary of the next automatic reset; NULL when reset_period is "none"
  "isActive": boolean
  "expiredAt": string (timestamp) // Actual deactivation time (cron or manual)
  "createdBy": object
  "note": string
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "group": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "quotaLimit": "回應字串",
  "consumedAmount": "回應字串",
  "remaining": "回應字串",
  "validFrom": "回應字串",
  "validUntil": "回應字串",
  "resetPeriod": {},
  "nextResetAt": "回應字串",
  "isActive": false,
  "expiredAt": "回應字串",
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "note": "回應字串",
  "createdAt": "回應字串",
  "updatedAt": "回應字串"
}
```

***

### 停用角色的額度設定 <a href="#organizations-groups-credit-quotas-destroy" id="organizations-groups-credit-quotas-destroy"></a>

DELETE `/api/v1/organizations/{organizationPk}/groups/{groupPk}/credit-quotas/{id}/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：組織須為 Credit 計費模式。成功回 `204`。停用後角色的「需要額度」仍開啟，角色內成員在設定新額度或解除額度限制前不能使用消耗 Credit 的功能；已停用的額度再停用回 `400`。
{% endhint %}

#### 參數

| 參數名稱             | 必填 | 類型     | 說明                                   |
| ---------------- | -- | ------ | ------------------------------------ |
| `groupPk`        | ✅  | string |                                      |
| `id`             | ✅  | string |                                      |
| `organizationPk` | ✅  | string | A UUID string identifying this 組織 ID |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X DELETE "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/groups/{groupPk}/credit-quotas/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/organizations/550e8400-e29b-41d4-a716-446655440000/groups/{groupPk}/credit-quotas/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/organizations/550e8400-e29b-41d4-a716-446655440000/groups/{groupPk}/credit-quotas/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/organizations/550e8400-e29b-41d4-a716-446655440000/groups/{groupPk}/credit-quotas/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 |

***

### 設定角色是否需要額度 <a href="#organizations-credit-quota-groups-credit-quota-required-partial-update" id="organizations-credit-quota-groups-credit-quota-required-partial-update"></a>

PATCH `/api/v1/organizations/{organizationPk}/credit-quota-groups/{id}/credit-quota-required/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：組織須為 Credit 計費模式。請求內容為 `{"creditQuotaRequired": true}` 或 `false`，路徑的 `id` 是角色 ID。設為 `false`（解除額度限制）時，角色生效中的額度會一併停用，成員改用組織錢包；設為 `true` 時，角色在設定額度前會擋下成員使用。回應是該角色的額度現況。
{% endhint %}

#### 參數

| 參數名稱             | 必填 | 類型     | 說明                                    |
| ---------------- | -- | ------ | ------------------------------------- |
| `id`             | ✅  | string | A UUID string identifying this Group. |
| `organizationPk` | ✅  | string | A UUID string identifying this 組織 ID  |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X PATCH "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/credit-quota-groups/550e8400-e29b-41d4-a716-446655440000/credit-quota-required/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{}'

# 請確認在執行前替換 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 = {};

axios.patch("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/credit-quota-groups/550e8400-e29b-41d4-a716-446655440000/credit-quota-required/", 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/organizations/550e8400-e29b-41d4-a716-446655440000/credit-quota-groups/550e8400-e29b-41d4-a716-446655440000/credit-quota-required/"
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)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->patch("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/credit-quota-groups/550e8400-e29b-41d4-a716-446655440000/credit-quota-required/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => new \stdClass()
    ]);
    
    $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
  "type": 
  {
  }
  "creditQuotaRequired": boolean // When True, this group must have an active credit quota for its members to consume credits
  "activeQuota": object // Return the most recent quota summary (active first), via prefetch to avoid N+1.
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "回應字串",
  "type": {},
  "creditQuotaRequired": false,
  "activeQuota": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  }
}
```

***

### 查詢角色成員額度統計 <a href="#organizations-groups-credit-quota-stats-retrieve" id="organizations-groups-credit-quota-stats-retrieve"></a>

GET `/api/v1/organizations/{organizationPk}/groups/{id}/credit-quota-stats/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：組織須為 Credit 計費模式。
{% endhint %}

#### 參數

| 參數名稱             | 必填 | 類型     | 說明                                    |
| ---------------- | -- | ------ | ------------------------------------- |
| `id`             | ✅  | string | A UUID string identifying this Group. |
| `organizationPk` | ✅  | string | A UUID string identifying this 組織 ID  |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/groups/550e8400-e29b-41d4-a716-446655440000/credit-quota-stats/" \
  -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/organizations/550e8400-e29b-41d4-a716-446655440000/groups/550e8400-e29b-41d4-a716-446655440000/credit-quota-stats/", 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/organizations/550e8400-e29b-41d4-a716-446655440000/groups/550e8400-e29b-41d4-a716-446655440000/credit-quota-stats/"
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/organizations/550e8400-e29b-41d4-a716-446655440000/groups/550e8400-e29b-41d4-a716-446655440000/credit-quota-stats/", [
        '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
{
  "activeQuotaMembersCount": integer
  "quotaRequiredMembersCount": integer
}
```

**回應範例值**

```json
{
  "activeQuotaMembersCount": 456,
  "quotaRequiredMembersCount": 456
}
```

***

### 依角色批次分配額度 <a href="#organizations-groups-batch-distribute-credit-quota-create" id="organizations-groups-batch-distribute-credit-quota-create"></a>

POST `/api/v1/organizations/{organizationPk}/groups/{id}/batch-distribute-credit-quota/`

{% hint style="info" %}
**所需權限**：Credit 管理權限＋組織概覽權限。**計費模式**：組織須為 Credit 計費模式。替角色內每位成員各設定一筆成員額度，請求內容同 [為成員設定額度](#organizations-members-credit-quotas-create)。已有生效中額度的成員會略過、不會被修改。回應：`successCount`、`skippedCount`、`skippedMemberIds`、`failedCount`、`failedMembers`。
{% endhint %}

#### 參數

| 參數名稱             | 必填 | 類型     | 說明                                    |
| ---------------- | -- | ------ | ------------------------------------- |
| `id`             | ✅  | string | A UUID string identifying this Group. |
| `organizationPk` | ✅  | string | A UUID string identifying this 組織 ID  |

#### 請求內容

**請求參數**

| 欄位                       | 類型      | 必填 | 說明                                                                                                                                                                                                          |
| ------------------------ | ------- | -- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name                     | string  | 是  |                                                                                                                                                                                                             |
| canCreateChatbot         | boolean | 否  |                                                                                                                                                                                                             |
| canCreateKnowledgeBase   | boolean | 否  |                                                                                                                                                                                                             |
| canCreateInbox           | boolean | 否  |                                                                                                                                                                                                             |
| canCreateDatabase        | boolean | 否  |                                                                                                                                                                                                             |
| canCreateTool            | boolean | 否  |                                                                                                                                                                                                             |
| canCreateAgentUiTool     | boolean | 否  |                                                                                                                                                                                                             |
| canCreateSkill           | boolean | 否  |                                                                                                                                                                                                             |
| maigptCanCodeInterpreter | boolean | 否  | Whether members of this role may use the code interpreter built-in tool in MaiGPT.                                                                                                                          |
| maigptCanRag             | boolean | 否  | Whether members of this role may use the knowledge base RAG built-in tool in MaiGPT.                                                                                                                        |
| maigptCanDeepResearch    | boolean | 否  | Whether members of this role may use Deep Research in MaiGPT. Deep Research reaches the public internet through its own built-in search, so a role that revokes the official web-search tools needs this... |
| maigptCanBrowserTool     | boolean | 否  | Whether members of this role may use the browser built-in tool in MaiGPT.                                                                                                                                   |
| maigptAllLlms            | boolean | 否  | Whether members of this role may use every organization-available LLM in MaiGPT. Off = only the bound LLMs; an empty binding then means none.                                                               |
| maigptAllTools           | boolean | 否  | Whether members of this role may call every official (global) tool in MaiGPT. Off = only the bound tools; an empty binding then means none.                                                                 |
| maigptAllConnectors      | boolean | 否  | Whether members of this role may call every official (global) MCP connector in MaiGPT. Off = only the bound connectors; an empty binding then means none.                                                   |
| maigptAllSkills          | boolean | 否  | Whether members of this role may use every official (global) skill in MaiGPT. Off = only the bound skills; an empty binding then means none.                                                                |
| usageStatisticsScope     | object  | 否  | What this role's usage statistics permission shows: the whole organization, or only the AI assistants granted to the member's roles. A member with any organization-wide granting role sees the whole or... |

**請求結構範例**

```typescript
{
  "name": string
  "canCreateChatbot"?: boolean // 非必填
  "canCreateKnowledgeBase"?: boolean // 非必填
  "canCreateInbox"?: boolean // 非必填
  "canCreateDatabase"?: boolean // 非必填
  "canCreateTool"?: boolean // 非必填
  "canCreateAgentUiTool"?: boolean // 非必填
  "canCreateSkill"?: boolean // 非必填
  "maigptCanCodeInterpreter"?: boolean // Whether members of this role may use the code interpreter built-in tool in MaiGPT. (非必填)
  "maigptCanRag"?: boolean // Whether members of this role may use the knowledge base RAG built-in tool in MaiGPT. (非必填)
  "maigptCanDeepResearch"?: boolean // Whether members of this role may use Deep Research in MaiGPT. Deep Research reaches the public internet through its own built-in search, so a role that revokes the official web-search tools needs this switch too. (非必填)
  "maigptCanBrowserTool"?: boolean // Whether members of this role may use the browser built-in tool in MaiGPT. (非必填)
  "maigptAllLlms"?: boolean // Whether members of this role may use every organization-available LLM in MaiGPT. Off = only the bound LLMs; an empty binding then means none. (非必填)
  "maigptAllTools"?: boolean // Whether members of this role may call every official (global) tool in MaiGPT. Off = only the bound tools; an empty binding then means none. (非必填)
  "maigptAllConnectors"?: boolean // Whether members of this role may call every official (global) MCP connector in MaiGPT. Off = only the bound connectors; an empty binding then means none. (非必填)
  "maigptAllSkills"?: boolean // Whether members of this role may use every official (global) skill in MaiGPT. Off = only the bound skills; an empty binding then means none. (非必填)
  "usageStatisticsScope"?:  // What this role's usage statistics permission shows: the whole organization, or only the AI assistants granted to the member's roles. A member with any organization-wide granting role sees the whole organization.

* `organization` - Organization-wide
* `accessible_chatbots` - Authorized AI assistants only (非必填)
  {
  }
}
```

**請求範例值**

```json
{
  "name": "範例名稱",
  "canCreateChatbot": true,
  "canCreateKnowledgeBase": true,
  "canCreateInbox": true,
  "canCreateDatabase": true,
  "canCreateTool": true,
  "canCreateAgentUiTool": true,
  "canCreateSkill": true,
  "maigptCanCodeInterpreter": true,
  "maigptCanRag": true,
  "maigptCanDeepResearch": true,
  "maigptCanBrowserTool": true,
  "maigptAllLlms": true,
  "maigptAllTools": true,
  "maigptAllConnectors": true,
  "maigptAllSkills": true,
  "usageStatisticsScope": {}
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/groups/550e8400-e29b-41d4-a716-446655440000/batch-distribute-credit-quota/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "範例名稱",
    "canCreateChatbot": true,
    "canCreateKnowledgeBase": true,
    "canCreateInbox": true,
    "canCreateDatabase": true,
    "canCreateTool": true,
    "canCreateAgentUiTool": true,
    "canCreateSkill": true,
    "maigptCanCodeInterpreter": true,
    "maigptCanRag": true,
    "maigptCanDeepResearch": true,
    "maigptCanBrowserTool": true,
    "maigptAllLlms": true,
    "maigptAllTools": true,
    "maigptAllConnectors": true,
    "maigptAllSkills": true,
    "usageStatisticsScope": {}
  }'

# 請確認在執行前替換 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": "範例名稱",
    "canCreateChatbot": true,
    "canCreateKnowledgeBase": true,
    "canCreateInbox": true,
    "canCreateDatabase": true,
    "canCreateTool": true,
    "canCreateAgentUiTool": true,
    "canCreateSkill": true,
    "maigptCanCodeInterpreter": true,
    "maigptCanRag": true,
    "maigptCanDeepResearch": true,
    "maigptCanBrowserTool": true,
    "maigptAllLlms": true,
    "maigptAllTools": true,
    "maigptAllConnectors": true,
    "maigptAllSkills": true,
    "usageStatisticsScope": {}
  };

axios.post("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/groups/550e8400-e29b-41d4-a716-446655440000/batch-distribute-credit-quota/", 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/organizations/550e8400-e29b-41d4-a716-446655440000/groups/550e8400-e29b-41d4-a716-446655440000/batch-distribute-credit-quota/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "name": "範例名稱",
    "canCreateChatbot": True,
    "canCreateKnowledgeBase": True,
    "canCreateInbox": True,
    "canCreateDatabase": True,
    "canCreateTool": True,
    "canCreateAgentUiTool": True,
    "canCreateSkill": True,
    "maigptCanCodeInterpreter": True,
    "maigptCanRag": True,
    "maigptCanDeepResearch": True,
    "maigptCanBrowserTool": True,
    "maigptAllLlms": True,
    "maigptAllTools": True,
    "maigptAllConnectors": True,
    "maigptAllSkills": True,
    "usageStatisticsScope": {}
}

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/organizations/550e8400-e29b-41d4-a716-446655440000/groups/550e8400-e29b-41d4-a716-446655440000/batch-distribute-credit-quota/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'name' => '範例名稱',
            'canCreateChatbot' => true,
            'canCreateKnowledgeBase' => true,
            'canCreateInbox' => true,
            'canCreateDatabase' => true,
            'canCreateTool' => true,
            'canCreateAgentUiTool' => true,
            'canCreateSkill' => true,
            'maigptCanCodeInterpreter' => true,
            'maigptCanRag' => true,
            'maigptCanDeepResearch' => true,
            'maigptCanBrowserTool' => true,
            'maigptAllLlms' => true,
            'maigptAllTools' => true,
            'maigptAllConnectors' => true,
            'maigptAllSkills' => true,
            'usageStatisticsScope' => new \stdClass()
        ]
    ]);
    
    $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
  "type": 
  {
  }
  "permissions": [
    object
  ]
  "membersPreview": [
    string
  ]
  "membersCount": integer // 返回剩餘成員數量（扣除列表顯示的 3 人後），用於前端 +N badge 顯示

與資源 count 不同：
- members_count: 返回 total - 3（用於 +N badge），None 表示總數 <= 3
- chatbots_count/knowledge_bases_count/inboxes_count: 返回總數量
  "chatbotsCount": integer
  "chatbotsPreview": [
    string
  ]
  "knowledgeBasesCount": integer
  "knowledgeBasesPreview": [
    string
  ]
  "inboxesCount": integer
  "inboxesPreview": [
    string
  ]
  "databasesCount": integer
  "databasesPreview": [
    string
  ]
  "canCreateChatbot"?: boolean // 非必填
  "canCreateKnowledgeBase"?: boolean // 非必填
  "canCreateInbox"?: boolean // 非必填
  "canCreateDatabase"?: boolean // 非必填
  "canCreateTool"?: boolean // 非必填
  "canCreateAgentUiTool"?: boolean // 非必填
  "canCreateSkill"?: boolean // 非必填
  "maigptCanCodeInterpreter"?: boolean // Whether members of this role may use the code interpreter built-in tool in MaiGPT. (非必填)
  "maigptCanRag"?: boolean // Whether members of this role may use the knowledge base RAG built-in tool in MaiGPT. (非必填)
  "maigptCanDeepResearch"?: boolean // Whether members of this role may use Deep Research in MaiGPT. Deep Research reaches the public internet through its own built-in search, so a role that revokes the official web-search tools needs this switch too. (非必填)
  "maigptCanBrowserTool"?: boolean // Whether members of this role may use the browser built-in tool in MaiGPT. (非必填)
  "maigptAllLlms"?: boolean // Whether members of this role may use every organization-available LLM in MaiGPT. Off = only the bound LLMs; an empty binding then means none. (非必填)
  "maigptAllTools"?: boolean // Whether members of this role may call every official (global) tool in MaiGPT. Off = only the bound tools; an empty binding then means none. (非必填)
  "maigptAllConnectors"?: boolean // Whether members of this role may call every official (global) MCP connector in MaiGPT. Off = only the bound connectors; an empty binding then means none. (非必填)
  "maigptAllSkills"?: boolean // Whether members of this role may use every official (global) skill in MaiGPT. Off = only the bound skills; an empty binding then means none. (非必填)
  "usageStatisticsScope"?:  // What this role's usage statistics permission shows: the whole organization, or only the AI assistants granted to the member's roles. A member with any organization-wide granting role sees the whole organization.

* `organization` - Organization-wide
* `accessible_chatbots` - Authorized AI assistants only (非必填)
  {
  }
  "createdAt": string (timestamp)
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "回應字串",
  "type": {},
  "permissions": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應範例名稱",
      "description": "回應範例描述"
    }
  ],
  "membersPreview": [
    "回應字串"
  ],
  "membersCount": 456,
  "chatbotsCount": 456,
  "chatbotsPreview": [
    "回應字串"
  ],
  "knowledgeBasesCount": 456,
  "knowledgeBasesPreview": [
    "回應字串"
  ],
  "inboxesCount": 456,
  "inboxesPreview": [
    "回應字串"
  ],
  "databasesCount": 456,
  "databasesPreview": [
    "回應字串"
  ],
  "canCreateChatbot": false,
  "canCreateKnowledgeBase": false,
  "canCreateInbox": false,
  "canCreateDatabase": false,
  "canCreateTool": false,
  "canCreateAgentUiTool": false,
  "canCreateSkill": false,
  "maigptCanCodeInterpreter": false,
  "maigptCanRag": false,
  "maigptCanDeepResearch": false,
  "maigptCanBrowserTool": false,
  "maigptAllLlms": false,
  "maigptAllTools": false,
  "maigptAllConnectors": false,
  "maigptAllSkills": false,
  "usageStatisticsScope": {},
  "createdAt": "回應字串"
}
```

***

### 依角色批次停用額度 <a href="#organizations-groups-batch-deactivate-credit-quota-create" id="organizations-groups-batch-deactivate-credit-quota-create"></a>

POST `/api/v1/organizations/{organizationPk}/groups/{id}/batch-deactivate-credit-quota/`

{% hint style="info" %}
**所需權限**：Credit 管理權限＋組織概覽權限。**計費模式**：組織須為 Credit 計費模式。停用角色內所有成員生效中的成員額度（不是角色本身的額度），沒有生效中額度的成員列為略過。請求內容 `removeQuotaRequirement` 選填，預設 `false`：只停用額度，成員的「需要額度」保持開啟，在重新分配額度前不能使用；設為 `true` 時，另外解除角色內所有成員的額度限制，改用組織錢包。回應：`successCount`、`skippedCount`、`skippedMemberIds`、`failedCount`、`failedMembers`、`requirementRemovedCount`。執行前可用 [查詢角色成員額度統計](#organizations-groups-credit-quota-stats-retrieve) 確認會影響的人數。
{% endhint %}

#### 參數

| 參數名稱             | 必填 | 類型     | 說明                                    |
| ---------------- | -- | ------ | ------------------------------------- |
| `id`             | ✅  | string | A UUID string identifying this Group. |
| `organizationPk` | ✅  | string | A UUID string identifying this 組織 ID  |

#### 請求內容

**請求參數**

| 欄位                       | 類型      | 必填 | 說明                                                                                                                                                                                                          |
| ------------------------ | ------- | -- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name                     | string  | 是  |                                                                                                                                                                                                             |
| canCreateChatbot         | boolean | 否  |                                                                                                                                                                                                             |
| canCreateKnowledgeBase   | boolean | 否  |                                                                                                                                                                                                             |
| canCreateInbox           | boolean | 否  |                                                                                                                                                                                                             |
| canCreateDatabase        | boolean | 否  |                                                                                                                                                                                                             |
| canCreateTool            | boolean | 否  |                                                                                                                                                                                                             |
| canCreateAgentUiTool     | boolean | 否  |                                                                                                                                                                                                             |
| canCreateSkill           | boolean | 否  |                                                                                                                                                                                                             |
| maigptCanCodeInterpreter | boolean | 否  | Whether members of this role may use the code interpreter built-in tool in MaiGPT.                                                                                                                          |
| maigptCanRag             | boolean | 否  | Whether members of this role may use the knowledge base RAG built-in tool in MaiGPT.                                                                                                                        |
| maigptCanDeepResearch    | boolean | 否  | Whether members of this role may use Deep Research in MaiGPT. Deep Research reaches the public internet through its own built-in search, so a role that revokes the official web-search tools needs this... |
| maigptCanBrowserTool     | boolean | 否  | Whether members of this role may use the browser built-in tool in MaiGPT.                                                                                                                                   |
| maigptAllLlms            | boolean | 否  | Whether members of this role may use every organization-available LLM in MaiGPT. Off = only the bound LLMs; an empty binding then means none.                                                               |
| maigptAllTools           | boolean | 否  | Whether members of this role may call every official (global) tool in MaiGPT. Off = only the bound tools; an empty binding then means none.                                                                 |
| maigptAllConnectors      | boolean | 否  | Whether members of this role may call every official (global) MCP connector in MaiGPT. Off = only the bound connectors; an empty binding then means none.                                                   |
| maigptAllSkills          | boolean | 否  | Whether members of this role may use every official (global) skill in MaiGPT. Off = only the bound skills; an empty binding then means none.                                                                |
| usageStatisticsScope     | object  | 否  | What this role's usage statistics permission shows: the whole organization, or only the AI assistants granted to the member's roles. A member with any organization-wide granting role sees the whole or... |

**請求結構範例**

```typescript
{
  "name": string
  "canCreateChatbot"?: boolean // 非必填
  "canCreateKnowledgeBase"?: boolean // 非必填
  "canCreateInbox"?: boolean // 非必填
  "canCreateDatabase"?: boolean // 非必填
  "canCreateTool"?: boolean // 非必填
  "canCreateAgentUiTool"?: boolean // 非必填
  "canCreateSkill"?: boolean // 非必填
  "maigptCanCodeInterpreter"?: boolean // Whether members of this role may use the code interpreter built-in tool in MaiGPT. (非必填)
  "maigptCanRag"?: boolean // Whether members of this role may use the knowledge base RAG built-in tool in MaiGPT. (非必填)
  "maigptCanDeepResearch"?: boolean // Whether members of this role may use Deep Research in MaiGPT. Deep Research reaches the public internet through its own built-in search, so a role that revokes the official web-search tools needs this switch too. (非必填)
  "maigptCanBrowserTool"?: boolean // Whether members of this role may use the browser built-in tool in MaiGPT. (非必填)
  "maigptAllLlms"?: boolean // Whether members of this role may use every organization-available LLM in MaiGPT. Off = only the bound LLMs; an empty binding then means none. (非必填)
  "maigptAllTools"?: boolean // Whether members of this role may call every official (global) tool in MaiGPT. Off = only the bound tools; an empty binding then means none. (非必填)
  "maigptAllConnectors"?: boolean // Whether members of this role may call every official (global) MCP connector in MaiGPT. Off = only the bound connectors; an empty binding then means none. (非必填)
  "maigptAllSkills"?: boolean // Whether members of this role may use every official (global) skill in MaiGPT. Off = only the bound skills; an empty binding then means none. (非必填)
  "usageStatisticsScope"?:  // What this role's usage statistics permission shows: the whole organization, or only the AI assistants granted to the member's roles. A member with any organization-wide granting role sees the whole organization.

* `organization` - Organization-wide
* `accessible_chatbots` - Authorized AI assistants only (非必填)
  {
  }
}
```

**請求範例值**

```json
{
  "name": "範例名稱",
  "canCreateChatbot": true,
  "canCreateKnowledgeBase": true,
  "canCreateInbox": true,
  "canCreateDatabase": true,
  "canCreateTool": true,
  "canCreateAgentUiTool": true,
  "canCreateSkill": true,
  "maigptCanCodeInterpreter": true,
  "maigptCanRag": true,
  "maigptCanDeepResearch": true,
  "maigptCanBrowserTool": true,
  "maigptAllLlms": true,
  "maigptAllTools": true,
  "maigptAllConnectors": true,
  "maigptAllSkills": true,
  "usageStatisticsScope": {}
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/groups/550e8400-e29b-41d4-a716-446655440000/batch-deactivate-credit-quota/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "範例名稱",
    "canCreateChatbot": true,
    "canCreateKnowledgeBase": true,
    "canCreateInbox": true,
    "canCreateDatabase": true,
    "canCreateTool": true,
    "canCreateAgentUiTool": true,
    "canCreateSkill": true,
    "maigptCanCodeInterpreter": true,
    "maigptCanRag": true,
    "maigptCanDeepResearch": true,
    "maigptCanBrowserTool": true,
    "maigptAllLlms": true,
    "maigptAllTools": true,
    "maigptAllConnectors": true,
    "maigptAllSkills": true,
    "usageStatisticsScope": {}
  }'

# 請確認在執行前替換 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": "範例名稱",
    "canCreateChatbot": true,
    "canCreateKnowledgeBase": true,
    "canCreateInbox": true,
    "canCreateDatabase": true,
    "canCreateTool": true,
    "canCreateAgentUiTool": true,
    "canCreateSkill": true,
    "maigptCanCodeInterpreter": true,
    "maigptCanRag": true,
    "maigptCanDeepResearch": true,
    "maigptCanBrowserTool": true,
    "maigptAllLlms": true,
    "maigptAllTools": true,
    "maigptAllConnectors": true,
    "maigptAllSkills": true,
    "usageStatisticsScope": {}
  };

axios.post("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/groups/550e8400-e29b-41d4-a716-446655440000/batch-deactivate-credit-quota/", 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/organizations/550e8400-e29b-41d4-a716-446655440000/groups/550e8400-e29b-41d4-a716-446655440000/batch-deactivate-credit-quota/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "name": "範例名稱",
    "canCreateChatbot": True,
    "canCreateKnowledgeBase": True,
    "canCreateInbox": True,
    "canCreateDatabase": True,
    "canCreateTool": True,
    "canCreateAgentUiTool": True,
    "canCreateSkill": True,
    "maigptCanCodeInterpreter": True,
    "maigptCanRag": True,
    "maigptCanDeepResearch": True,
    "maigptCanBrowserTool": True,
    "maigptAllLlms": True,
    "maigptAllTools": True,
    "maigptAllConnectors": True,
    "maigptAllSkills": True,
    "usageStatisticsScope": {}
}

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/organizations/550e8400-e29b-41d4-a716-446655440000/groups/550e8400-e29b-41d4-a716-446655440000/batch-deactivate-credit-quota/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'name' => '範例名稱',
            'canCreateChatbot' => true,
            'canCreateKnowledgeBase' => true,
            'canCreateInbox' => true,
            'canCreateDatabase' => true,
            'canCreateTool' => true,
            'canCreateAgentUiTool' => true,
            'canCreateSkill' => true,
            'maigptCanCodeInterpreter' => true,
            'maigptCanRag' => true,
            'maigptCanDeepResearch' => true,
            'maigptCanBrowserTool' => true,
            'maigptAllLlms' => true,
            'maigptAllTools' => true,
            'maigptAllConnectors' => true,
            'maigptAllSkills' => true,
            'usageStatisticsScope' => new \stdClass()
        ]
    ]);
    
    $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
  "type": 
  {
  }
  "permissions": [
    object
  ]
  "membersPreview": [
    string
  ]
  "membersCount": integer // 返回剩餘成員數量（扣除列表顯示的 3 人後），用於前端 +N badge 顯示

與資源 count 不同：
- members_count: 返回 total - 3（用於 +N badge），None 表示總數 <= 3
- chatbots_count/knowledge_bases_count/inboxes_count: 返回總數量
  "chatbotsCount": integer
  "chatbotsPreview": [
    string
  ]
  "knowledgeBasesCount": integer
  "knowledgeBasesPreview": [
    string
  ]
  "inboxesCount": integer
  "inboxesPreview": [
    string
  ]
  "databasesCount": integer
  "databasesPreview": [
    string
  ]
  "canCreateChatbot"?: boolean // 非必填
  "canCreateKnowledgeBase"?: boolean // 非必填
  "canCreateInbox"?: boolean // 非必填
  "canCreateDatabase"?: boolean // 非必填
  "canCreateTool"?: boolean // 非必填
  "canCreateAgentUiTool"?: boolean // 非必填
  "canCreateSkill"?: boolean // 非必填
  "maigptCanCodeInterpreter"?: boolean // Whether members of this role may use the code interpreter built-in tool in MaiGPT. (非必填)
  "maigptCanRag"?: boolean // Whether members of this role may use the knowledge base RAG built-in tool in MaiGPT. (非必填)
  "maigptCanDeepResearch"?: boolean // Whether members of this role may use Deep Research in MaiGPT. Deep Research reaches the public internet through its own built-in search, so a role that revokes the official web-search tools needs this switch too. (非必填)
  "maigptCanBrowserTool"?: boolean // Whether members of this role may use the browser built-in tool in MaiGPT. (非必填)
  "maigptAllLlms"?: boolean // Whether members of this role may use every organization-available LLM in MaiGPT. Off = only the bound LLMs; an empty binding then means none. (非必填)
  "maigptAllTools"?: boolean // Whether members of this role may call every official (global) tool in MaiGPT. Off = only the bound tools; an empty binding then means none. (非必填)
  "maigptAllConnectors"?: boolean // Whether members of this role may call every official (global) MCP connector in MaiGPT. Off = only the bound connectors; an empty binding then means none. (非必填)
  "maigptAllSkills"?: boolean // Whether members of this role may use every official (global) skill in MaiGPT. Off = only the bound skills; an empty binding then means none. (非必填)
  "usageStatisticsScope"?:  // What this role's usage statistics permission shows: the whole organization, or only the AI assistants granted to the member's roles. A member with any organization-wide granting role sees the whole organization.

* `organization` - Organization-wide
* `accessible_chatbots` - Authorized AI assistants only (非必填)
  {
  }
  "createdAt": string (timestamp)
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "回應字串",
  "type": {},
  "permissions": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "回應範例名稱",
      "description": "回應範例描述"
    }
  ],
  "membersPreview": [
    "回應字串"
  ],
  "membersCount": 456,
  "chatbotsCount": 456,
  "chatbotsPreview": [
    "回應字串"
  ],
  "knowledgeBasesCount": 456,
  "knowledgeBasesPreview": [
    "回應字串"
  ],
  "inboxesCount": 456,
  "inboxesPreview": [
    "回應字串"
  ],
  "databasesCount": 456,
  "databasesPreview": [
    "回應字串"
  ],
  "canCreateChatbot": false,
  "canCreateKnowledgeBase": false,
  "canCreateInbox": false,
  "canCreateDatabase": false,
  "canCreateTool": false,
  "canCreateAgentUiTool": false,
  "canCreateSkill": false,
  "maigptCanCodeInterpreter": false,
  "maigptCanRag": false,
  "maigptCanDeepResearch": false,
  "maigptCanBrowserTool": false,
  "maigptAllLlms": false,
  "maigptAllTools": false,
  "maigptAllConnectors": false,
  "maigptAllSkills": false,
  "usageStatisticsScope": {},
  "createdAt": "回應字串"
}
```

***

### 列出對話平台的額度設定 <a href="#inboxes-credit-quotas-list" id="inboxes-credit-quotas-list"></a>

GET `/api/v1/inboxes/{inboxPk}/credit-quotas/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：組織須為 Credit 計費模式。包含已停用的額度，新到舊排序。
{% endhint %}

#### 參數

| 參數名稱       | 必填 | 類型      | 說明                                             |
| ---------- | -- | ------- | ---------------------------------------------- |
| `inboxPk`  | ✅  | 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/inboxes/{inboxPk}/credit-quotas/?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/inboxes/{inboxPk}/credit-quotas/?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/inboxes/{inboxPk}/credit-quotas/?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/inboxes/{inboxPk}/credit-quotas/?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)
      "inbox": object
      "quotaLimit": string (decimal) // Maximum credits this inbox may consume
      "consumedAmount": string (decimal) // Credits consumed so far (updated via F() for concurrency safety)
      "remaining": string (decimal)
      "validFrom": string (timestamp)
      "validUntil": string (timestamp) // NULL means permanent
      "resetPeriod":  // Cycle on which consumed_amount is automatically zeroed; "none" keeps the one-shot ceiling

* `none` - No Reset
* `daily` - Daily
* `weekly` - Weekly
* `monthly` - Monthly
      {
      }
      "nextResetAt": string (timestamp) // Local-midnight boundary of the next automatic reset; NULL when reset_period is "none"
      "isActive": boolean
      "expiredAt": string (timestamp) // Actual deactivation time (cron or manual)
      "createdBy": object
      "note": string
      "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",
      "inbox": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應範例名稱",
        "description": "回應範例描述"
      },
      "quotaLimit": "回應字串",
      "consumedAmount": "回應字串",
      "remaining": "回應字串",
      "validFrom": "回應字串",
      "validUntil": "回應字串",
      "resetPeriod": {},
      "nextResetAt": "回應字串",
      "isActive": false,
      "expiredAt": "回應字串",
      "createdBy": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "回應範例名稱",
        "description": "回應範例描述"
      },
      "note": "回應字串",
      "createdAt": "回應字串",
      "updatedAt": "回應字串"
    }
  ]
}
```

***

### 取得對話平台的單筆額度設定 <a href="#inboxes-credit-quotas-retrieve" id="inboxes-credit-quotas-retrieve"></a>

GET `/api/v1/inboxes/{inboxPk}/credit-quotas/{id}/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：組織須為 Credit 計費模式。
{% endhint %}

#### 參數

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

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/inboxes/{inboxPk}/credit-quotas/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/inboxes/{inboxPk}/credit-quotas/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/inboxes/{inboxPk}/credit-quotas/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/inboxes/{inboxPk}/credit-quotas/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)
  "inbox": object
  "quotaLimit": string (decimal) // Maximum credits this inbox may consume
  "consumedAmount": string (decimal) // Credits consumed so far (updated via F() for concurrency safety)
  "remaining": string (decimal)
  "validFrom": string (timestamp)
  "validUntil": string (timestamp) // NULL means permanent
  "resetPeriod":  // Cycle on which consumed_amount is automatically zeroed; "none" keeps the one-shot ceiling

* `none` - No Reset
* `daily` - Daily
* `weekly` - Weekly
* `monthly` - Monthly
  {
  }
  "nextResetAt": string (timestamp) // Local-midnight boundary of the next automatic reset; NULL when reset_period is "none"
  "isActive": boolean
  "expiredAt": string (timestamp) // Actual deactivation time (cron or manual)
  "createdBy": object
  "note": string
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "inbox": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "quotaLimit": "回應字串",
  "consumedAmount": "回應字串",
  "remaining": "回應字串",
  "validFrom": "回應字串",
  "validUntil": "回應字串",
  "resetPeriod": {},
  "nextResetAt": "回應字串",
  "isActive": false,
  "expiredAt": "回應字串",
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "note": "回應字串",
  "createdAt": "回應字串",
  "updatedAt": "回應字串"
}
```

***

### 為對話平台設定額度 <a href="#inboxes-credit-quotas-create" id="inboxes-credit-quotas-create"></a>

POST `/api/v1/inboxes/{inboxPk}/credit-quotas/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：組織須為 Credit 計費模式。請求內容與規則見 [額度怎麼運作](#credit-quota-rules)；對話平台已有生效中的額度時回 `400`，請先停用。MaiGPT 的對話平台不能設定額度，回 `400`。
{% endhint %}

#### 參數

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

#### 請求內容

**請求參數**

| 欄位          | 類型                 | 必填 | 說明 |
| ----------- | ------------------ | -- | -- |
| quotaLimit  | string (decimal)   | 是  |    |
| validFrom   | string (date-time) | 是  |    |
| validUntil  | string (date-time) | 否  |    |
| note        | string             | 否  |    |
| resetPeriod | object             | 否  |    |

**請求結構範例**

```typescript
{
  "quotaLimit": string (decimal)
  "validFrom": string (date-time)
  "validUntil"?: string (date-time) // 非必填
  "note"?: string // 非必填
  "resetPeriod"?:  // 非必填
  {
  }
}
```

**請求範例值**

```json
{
  "quotaLimit": "500",
  "validFrom": "2026-10-16T00:00:00+08:00",
  "validUntil": "2026-12-31T23:59:59+08:00",
  "resetPeriod": "monthly",
  "note": "Q4 budget"
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/inboxes/{inboxPk}/credit-quotas/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "quotaLimit": "500",
    "validFrom": "2026-10-16T00:00:00+08:00",
    "validUntil": "2026-12-31T23:59:59+08:00",
    "resetPeriod": "monthly",
    "note": "Q4 budget"
  }'

# 請確認在執行前替換 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 = {
    "quotaLimit": "500",
    "validFrom": "2026-10-16T00:00:00+08:00",
    "validUntil": "2026-12-31T23:59:59+08:00",
    "resetPeriod": "monthly",
    "note": "Q4 budget"
  };

axios.post("https://api.maiagent.ai/api/v1/inboxes/{inboxPk}/credit-quotas/", 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/inboxes/{inboxPk}/credit-quotas/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "quotaLimit": "500",
    "validFrom": "2026-10-16T00:00:00+08:00",
    "validUntil": "2026-12-31T23:59:59+08:00",
    "resetPeriod": "monthly",
    "note": "Q4 budget"
}

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/inboxes/{inboxPk}/credit-quotas/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'quotaLimit' => '500',
            'validFrom' => '2026-10-16T00:00:00+08:00',
            'validUntil' => '2026-12-31T23:59:59+08:00',
            'resetPeriod' => 'monthly',
            'note' => 'Q4 budget'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 201**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "inbox": object
  "quotaLimit": string (decimal) // Maximum credits this inbox may consume
  "consumedAmount": string (decimal) // Credits consumed so far (updated via F() for concurrency safety)
  "remaining": string (decimal)
  "validFrom": string (timestamp)
  "validUntil": string (timestamp) // NULL means permanent
  "resetPeriod":  // Cycle on which consumed_amount is automatically zeroed; "none" keeps the one-shot ceiling

* `none` - No Reset
* `daily` - Daily
* `weekly` - Weekly
* `monthly` - Monthly
  {
  }
  "nextResetAt": string (timestamp) // Local-midnight boundary of the next automatic reset; NULL when reset_period is "none"
  "isActive": boolean
  "expiredAt": string (timestamp) // Actual deactivation time (cron or manual)
  "createdBy": object
  "note": string
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "inbox": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "quotaLimit": "回應字串",
  "consumedAmount": "回應字串",
  "remaining": "回應字串",
  "validFrom": "回應字串",
  "validUntil": "回應字串",
  "resetPeriod": {},
  "nextResetAt": "回應字串",
  "isActive": false,
  "expiredAt": "回應字串",
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "note": "回應字串",
  "createdAt": "回應字串",
  "updatedAt": "回應字串"
}
```

***

### 更新對話平台的額度設定 <a href="#inboxes-credit-quotas-partial-update" id="inboxes-credit-quotas-partial-update"></a>

PATCH `/api/v1/inboxes/{inboxPk}/credit-quotas/{id}/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：組織須為 Credit 計費模式。只需傳要修改的欄位：`quotaLimit`、`validUntil`、`resetPeriod`、`note`（生效時間不能改）。`quotaLimit` 不可低於已使用的額度；已停用的額度不能更新，回 `400`。
{% endhint %}

#### 參數

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

#### 請求內容

**請求參數**

| 欄位          | 類型                                          | 必填 | 說明                                                                         |
| ----------- | ------------------------------------------- | -- | -------------------------------------------------------------------------- |
| quotaLimit  | string (decimal)                            | 否  |                                                                            |
| validUntil  | string (date-time)                          | 否  |                                                                            |
| note        | string                                      | 否  |                                                                            |
| resetPeriod | string (enum: none, daily, weekly, monthly) | 否  | `none`: No Reset ; `daily`: Daily ; `weekly`: Weekly ; `monthly`: Monthly; |

**請求結構範例**

```typescript
{
  "quotaLimit"?: string (decimal) // 非必填
  "validUntil"?: string (date-time) // 非必填
  "note"?: string // 非必填
  "resetPeriod"?: string (enum: none, daily, weekly, monthly) // * `none` - No Reset
* `daily` - Daily
* `weekly` - Weekly
* `monthly` - Monthly (非必填)
}
```

**請求範例值**

```json
{
  "quotaLimit": "範例字串",
  "validUntil": "2025-01-01T00:00:00.000Z",
  "note": "範例字串",
  "resetPeriod": "none"
}
```

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X PATCH "https://api.maiagent.ai/api/v1/inboxes/{inboxPk}/credit-quotas/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "quotaLimit": "範例字串",
    "validUntil": "2025-01-01T00:00:00.000Z",
    "note": "範例字串",
    "resetPeriod": "none"
  }'

# 請確認在執行前替換 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 = {
    "quotaLimit": "範例字串",
    "validUntil": "2025-01-01T00:00:00.000Z",
    "note": "範例字串",
    "resetPeriod": "none"
  };

axios.patch("https://api.maiagent.ai/api/v1/inboxes/{inboxPk}/credit-quotas/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/inboxes/{inboxPk}/credit-quotas/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# 請求內容 (payload)
data = {
    "quotaLimit": "範例字串",
    "validUntil": "2025-01-01T00:00:00.000Z",
    "note": "範例字串",
    "resetPeriod": "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/inboxes/{inboxPk}/credit-quotas/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'quotaLimit' => '範例字串',
            'validUntil' => '2025-01-01T00:00:00.000Z',
            'note' => '範例字串',
            'resetPeriod' => 'none'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "成功取得回應:\n";
    print_r($data);
} catch (Exception $e) {
    echo '請求發生錯誤: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### 回應內容

**狀態碼: 200**

**回應結構範例**

```typescript
{
  "id": string (uuid)
  "inbox": object
  "quotaLimit": string (decimal) // Maximum credits this inbox may consume
  "consumedAmount": string (decimal) // Credits consumed so far (updated via F() for concurrency safety)
  "remaining": string (decimal)
  "validFrom": string (timestamp)
  "validUntil": string (timestamp) // NULL means permanent
  "resetPeriod":  // Cycle on which consumed_amount is automatically zeroed; "none" keeps the one-shot ceiling

* `none` - No Reset
* `daily` - Daily
* `weekly` - Weekly
* `monthly` - Monthly
  {
  }
  "nextResetAt": string (timestamp) // Local-midnight boundary of the next automatic reset; NULL when reset_period is "none"
  "isActive": boolean
  "expiredAt": string (timestamp) // Actual deactivation time (cron or manual)
  "createdBy": object
  "note": string
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "inbox": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "quotaLimit": "回應字串",
  "consumedAmount": "回應字串",
  "remaining": "回應字串",
  "validFrom": "回應字串",
  "validUntil": "回應字串",
  "resetPeriod": {},
  "nextResetAt": "回應字串",
  "isActive": false,
  "expiredAt": "回應字串",
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "note": "回應字串",
  "createdAt": "回應字串",
  "updatedAt": "回應字串"
}
```

***

### 停用對話平台的額度設定 <a href="#inboxes-credit-quotas-destroy" id="inboxes-credit-quotas-destroy"></a>

DELETE `/api/v1/inboxes/{inboxPk}/credit-quotas/{id}/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：組織須為 Credit 計費模式。成功回 `204`。停用後對話平台的「需要額度」仍開啟，在設定新額度或解除額度限制前暫停 AI 回覆；已停用的額度再停用回 `400`。
{% endhint %}

#### 參數

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

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X DELETE "https://api.maiagent.ai/api/v1/inboxes/{inboxPk}/credit-quotas/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/inboxes/{inboxPk}/credit-quotas/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/inboxes/{inboxPk}/credit-quotas/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/inboxes/{inboxPk}/credit-quotas/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 |

***

### 設定對話平台是否需要額度 <a href="#organizations-credit-quota-inboxes-credit-quota-required-partial-update" id="organizations-credit-quota-inboxes-credit-quota-required-partial-update"></a>

PATCH `/api/v1/organizations/{organizationPk}/credit-quota-inboxes/{id}/credit-quota-required/`

{% hint style="info" %}
**所需權限**：Credit 管理權限。**計費模式**：組織須為 Credit 計費模式。請求內容為 `{"creditQuotaRequired": true}` 或 `false`，路徑的 `id` 是對話平台 ID。設為 `false`（解除額度限制）時，生效中的額度會一併停用，AI 回覆改用組織錢包；設為 `true` 時，對話平台在設定額度前暫停 AI 回覆。回應是該對話平台的額度現況。
{% endhint %}

#### 參數

| 參數名稱             | 必填 | 類型     | 說明                                   |
| ---------------- | -- | ------ | ------------------------------------ |
| `id`             | ✅  | string |                                      |
| `organizationPk` | ✅  | string | A UUID string identifying this 組織 ID |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X PATCH "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/credit-quota-inboxes/550e8400-e29b-41d4-a716-446655440000/credit-quota-required/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{}'

# 請確認在執行前替換 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 = {};

axios.patch("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/credit-quota-inboxes/550e8400-e29b-41d4-a716-446655440000/credit-quota-required/", 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/organizations/550e8400-e29b-41d4-a716-446655440000/credit-quota-inboxes/550e8400-e29b-41d4-a716-446655440000/credit-quota-required/"
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)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->patch("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/credit-quota-inboxes/550e8400-e29b-41d4-a716-446655440000/credit-quota-required/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => new \stdClass()
    ]);
    
    $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
  "channelType": 
  {
  }
  "channelTypeLabel": string
  "webChatAccessType": string // Sub-type for web channels (web = public embed, admin = internal Q&A, api = completions).

A chatbot ships with three same-named web inboxes, so the frontend needs
this to tell them apart. None for non-web channels. Reads the prefetched
generic ``channel`` relation (no extra query on the list path).
  "chatbot": object
  "creditQuotaRequired": boolean // When True, this inbox must have an active credit quota for the AI to reply
  "activeQuota": object // Return the most recent quota summary (active first), via prefetch to avoid N+1.
  "canUpdate": boolean // Return whether the current user can update this resource.
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "回應字串",
  "channelType": {},
  "channelTypeLabel": "回應字串",
  "webChatAccessType": "回應字串",
  "chatbot": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "creditQuotaRequired": false,
  "activeQuota": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "回應範例名稱",
    "description": "回應範例描述"
  },
  "canUpdate": false
}
```

***

### 查詢自己的額度 <a href="#organizations-me-credit-quota-retrieve" id="organizations-me-credit-quota-retrieve"></a>

GET `/api/v1/organizations/{organizationPk}/me/credit-quota/`

{% hint style="info" %}
**所需權限**：不需額外權限，任何組織成員都能查自己的額度。**計費模式**：組織須為 Credit 計費模式。
{% endhint %}

#### 參數

| 參數名稱             | 必填 | 類型     | 說明                                   |
| ---------------- | -- | ------ | ------------------------------------ |
| `organizationPk` | ✅  | string | A UUID string identifying this 組織 ID |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/me/credit-quota/" \
  -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/organizations/550e8400-e29b-41d4-a716-446655440000/me/credit-quota/", 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/organizations/550e8400-e29b-41d4-a716-446655440000/me/credit-quota/"
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/organizations/550e8400-e29b-41d4-a716-446655440000/me/credit-quota/", [
        '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 | No response body |

***

### 查詢自己所屬角色的額度 <a href="#organizations-me-group-credit-quotas-retrieve" id="organizations-me-group-credit-quotas-retrieve"></a>

GET `/api/v1/organizations/{organizationPk}/me/group-credit-quotas/`

{% hint style="info" %}
**所需權限**：不需額外權限，任何組織成員都能查自己的額度。**計費模式**：組織須為 Credit 計費模式。
{% endhint %}

#### 參數

| 參數名稱             | 必填 | 類型     | 說明                                   |
| ---------------- | -- | ------ | ------------------------------------ |
| `organizationPk` | ✅  | string | A UUID string identifying this 組織 ID |

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/me/group-credit-quotas/" \
  -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/organizations/550e8400-e29b-41d4-a716-446655440000/me/group-credit-quotas/", 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/organizations/550e8400-e29b-41d4-a716-446655440000/me/group-credit-quotas/"
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/organizations/550e8400-e29b-41d4-a716-446655440000/me/group-credit-quotas/", [
        '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 | No response body |

***

### 列出計價規則 <a href="#credit-pricing-rules-list" id="credit-pricing-rules-list"></a>

GET `/api/v1/credit/pricing-rules/`

{% hint style="info" %}
**免登入**：不需 API Key 即可呼叫。**呼叫上限**：每分鐘 60 次，依來源 IP 計算，超過回傳 HTTP 429。
{% endhint %}

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/credit/pricing-rules/" \
  -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/credit/pricing-rules/", 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/credit/pricing-rules/"
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/credit/pricing-rules/", [
        '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)
    "creditItem": string (uuid)
    "provider": string
    "modelCode": string
    "creditPerUnit": string (decimal)
    "priority": integer // Higher priority = more specific (model-specific=20, provider-level=10)
    "effectiveFrom": string (timestamp)
    "effectiveUntil": string (timestamp)
    "isActive": boolean
    "notes": string // Internal notes about this pricing rule
  }
]
```

**回應範例值**

```json
[
  {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "creditItem": "550e8400-e29b-41d4-a716-446655440000",
    "provider": "回應字串",
    "modelCode": "回應字串",
    "creditPerUnit": "回應字串",
    "priority": 456,
    "effectiveFrom": "回應字串",
    "effectiveUntil": "回應字串",
    "isActive": false,
    "notes": "回應字串"
  }
]
```

***

### 取得單一計價規則 <a href="#credit-pricing-rules-retrieve" id="credit-pricing-rules-retrieve"></a>

GET `/api/v1/credit/pricing-rules/{id}/`

{% hint style="info" %}
**免登入**：不需 API Key 即可呼叫。**呼叫上限**：每分鐘 60 次，依來源 IP 計算，超過回傳 HTTP 429。
{% endhint %}

#### 參數

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

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/credit/pricing-rules/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/credit/pricing-rules/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/credit/pricing-rules/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/credit/pricing-rules/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)
  "creditItem": string (uuid)
  "provider": string
  "modelCode": string
  "creditPerUnit": string (decimal)
  "priority": integer // Higher priority = more specific (model-specific=20, provider-level=10)
  "effectiveFrom": string (timestamp)
  "effectiveUntil": string (timestamp)
  "isActive": boolean
  "notes": string // Internal notes about this pricing rule
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "creditItem": "550e8400-e29b-41d4-a716-446655440000",
  "provider": "回應字串",
  "modelCode": "回應字串",
  "creditPerUnit": "回應字串",
  "priority": 456,
  "effectiveFrom": "回應字串",
  "effectiveUntil": "回應字串",
  "isActive": false,
  "notes": "回應字串"
}
```

***

### 列出計價項目 <a href="#credit-items-list" id="credit-items-list"></a>

GET `/api/v1/credit/items/`

{% hint style="info" %}
**免登入**：不需 API Key 即可呼叫。**呼叫上限**：每分鐘 60 次，依來源 IP 計算，超過回傳 HTTP 429。
{% endhint %}

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/credit/items/" \
  -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/credit/items/", 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/credit/items/"
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/credit/items/", [
        '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)
    "code": string // Unique identifier like llm_input_token
    "name": string
    "category": 
    {
    }
    "unit": string // token, character, minute, etc.
    "creditPerUnit": string (decimal)
    "baseCreditPerUnit": string (decimal)
    "effectiveFrom": string (timestamp)
    "isActive": boolean
    "description": string
    "displayGroup": string // Items with the same display_group are merged into one expandable row on the pricing page. Empty means the item stands alone.
    "displayOrder": integer // Controls display ordering. Lower numbers appear first.
    "attachmentRetentionDays": integer // Current Config retention setting, so the pricing-page tooltip day count follows admin changes.
    "gatewayTrafficFeeDefaultPercent": string // System default AI Gateway traffic-fee percent, for pricing pages without an org context.

This endpoint is AllowAny with no organization, so it can only surface
the system default ("for reference only" on the frontend); logged-in
pricing pages read the organization's actual percent from the
organization detail API instead.
  }
]
```

**回應範例值**

```json
[
  {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "code": "回應字串",
    "name": "回應字串",
    "category": {},
    "unit": "回應字串",
    "creditPerUnit": "回應字串",
    "baseCreditPerUnit": "回應字串",
    "effectiveFrom": "回應字串",
    "isActive": false,
    "description": "回應字串",
    "displayGroup": "回應字串",
    "displayOrder": 456,
    "attachmentRetentionDays": 456,
    "gatewayTrafficFeeDefaultPercent": "回應字串"
  }
]
```

***

### 取得單一計價項目 <a href="#credit-items-retrieve" id="credit-items-retrieve"></a>

GET `/api/v1/credit/items/{id}/`

{% hint style="info" %}
**免登入**：不需 API Key 即可呼叫。**呼叫上限**：每分鐘 60 次，依來源 IP 計算，超過回傳 HTTP 429。
{% endhint %}

#### 參數

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

#### 程式碼範例

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

```bash
# 呼叫 API 示例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/credit/items/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/credit/items/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/credit/items/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/credit/items/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)
  "code": string // Unique identifier like llm_input_token
  "name": string
  "category": 
  {
  }
  "unit": string // token, character, minute, etc.
  "creditPerUnit": string (decimal)
  "baseCreditPerUnit": string (decimal)
  "effectiveFrom": string (timestamp)
  "isActive": boolean
  "description": string
  "displayGroup": string // Items with the same display_group are merged into one expandable row on the pricing page. Empty means the item stands alone.
  "displayOrder": integer // Controls display ordering. Lower numbers appear first.
  "attachmentRetentionDays": integer // Current Config retention setting, so the pricing-page tooltip day count follows admin changes.
  "gatewayTrafficFeeDefaultPercent": string // System default AI Gateway traffic-fee percent, for pricing pages without an org context.

This endpoint is AllowAny with no organization, so it can only surface
the system default ("for reference only" on the frontend); logged-in
pricing pages read the organization's actual percent from the
organization detail API instead.
}
```

**回應範例值**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "code": "回應字串",
  "name": "回應字串",
  "category": {},
  "unit": "回應字串",
  "creditPerUnit": "回應字串",
  "baseCreditPerUnit": "回應字串",
  "effectiveFrom": "回應字串",
  "isActive": false,
  "description": "回應字串",
  "displayGroup": "回應字串",
  "displayOrder": 456,
  "attachmentRetentionDays": 456,
  "gatewayTrafficFeeDefaultPercent": "回應字串"
}
```

***


---

# 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/credit.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.
