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

# Credit

The Credit category provides queries and quota allocation for organization Credits: balances, credits nearing expiration, credit entries, consumption details and totals, usage statistics, pricing rules and pricing items, as well as quota settings for members, roles, and inboxes (list, set, update, deactivate, and specify whether a quota is required), and batch allocation or deactivation of member quotas by role.

#### Prerequisites <a href="#credit-prerequisites" id="credit-prerequisites"></a>

**Authentication and Path Parameters**

All APIs except Pricing Rules and Pricing Items require an API Key in the HTTP header:

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

The system automatically identifies the organization and member associated with the API Key. APIs starting with `/api/v1/credit/` do not require a separate organization identifier. Obtain the IDs required in paths as follows:

* `organizationPk`: Call `GET /api/v1/organizations/` and use the organization's `id` from the response.
* Wallet `id`: Call `GET /api/v1/organizations/{id}/` and use `creditWallet.id` from the response.

**Rate Limits**

For APIs that require an API Key, the rate limit is **the number of requests per minute configured individually for each API Key**. Organization administrators set this in the Requests per Minute (RPM) field under Organization Settings → API Keys. Calls to all APIs on the platform using the same key count toward a shared total. Keys without a configured limit are exempt. Requests exceeding the limit are rejected with HTTP 429; wait until the next minute before retrying.

Pricing Rules and Pricing Items do not require an API Key. Their rate limits are calculated separately by source IP; see the notes for each API.

**How Quotas Work**

Members, roles, and inboxes each have a quota layer, corresponding to the three tabs under Credits → Quota Allocation in the admin console. Each layer is tracked independently:

* **Member quota**: The usage limit for an individual member.
* **Role quota**: A shared limit for all members of a role, tracked separately from each member's individual quota. If a member belongs to multiple roles that require quotas, usage counts toward every role. Exhausting any one role's quota blocks further use.
* **Inbox quota**: The usage limit for AI replies in that inbox. Quotas cannot be set for MaiGPT inboxes.

The same rules apply to each layer:

* **Quota required**: Members, roles, and inboxes each have a Quota Required setting (response field `creditQuotaRequired`). When disabled, this layer is neither checked nor tracked, and the organization wallet is used directly. When enabled, an active quota is required. Without an active quota, use is blocked: members and roles cannot use features that consume Credits, and AI replies are paused for inboxes.
* **Setting a quota automatically enables Quota Required**. Each entity can have only one active quota at a time. Attempting to set another quota while an active one exists returns `400`; deactivate the old quota first.
* **Deactivating a quota does not disable Quota Required**: The entity remains blocked until a new quota is set or the quota requirement is removed. For roles and inboxes, use their respective Set Whether a Quota Is Required API. For members, ask an administrator to remove the requirement under Credits → Quota Allocation in the admin console, or use [Batch Deactivate Quotas by Role](#organizations-groups-batch-deactivate-credit-quota-create) with `removeQuotaRequirement: true` to remove it for all members of a role at once. Deactivation does not delete records. Deactivated quotas still appear in List Quota Settings with `isActive` set to `false`.
* Request fields for setting a quota: `quotaLimit` (quota limit, required), `validFrom` (start time, required), `validUntil` (expiration time, optional; must be later than `validFrom` and no later than the latest expiration date among the organization's credit entries), `resetPeriod` (usage reset interval: `none`, `daily`, `weekly`, or `monthly`; defaults to `none`), and `note` (optional note).
* **Time format**: Always use ISO 8601 strings for `validFrom` and `validUntil` in requests, such as `2026-12-31T23:59:59+08:00`. A date alone (`2026-12-31`) is interpreted as 00:00 on that date in Taiwan time. Millisecond timestamps (such as `1798732799000`) are not accepted and return `400`. Time fields in responses use 13-digit millisecond timestamps.
* **Default quota for new members**: Organizations can configure an individual quota to be assigned automatically to new members; see [Get Default Quota Settings for New Members](#credit-wallets-new-member-quota-policy-retrieve). A quota can also be specified for each invitee when sending invitations; see [Invite Members to an Organization](https://docs.maiagent.ai/api/api-reference/zu-zhi-he-cheng-yuan#auth-unified-invitations-create) under Organizations and Members.
* IDs in paths: Obtain `memberPk` from the `id` in the [List Current Member Quotas](#organizations-credit-quota-members-list) response, `groupPk` from [List Current Role Quotas](#organizations-credit-quota-groups-list), and `inboxPk` from [List Current Inbox Quotas](#organizations-credit-quota-inboxes-list). Obtain the quota setting's own `id` from the corresponding List Quota Settings API.

**Permissions and Billing Modes**

The required permissions and billing mode prerequisites are listed below each API. An API Key acts as the member who created it, and permissions are determined by that member's roles. Requests are rejected with HTTP 403 in either of these cases:

* **Insufficient permissions**: The roles of the member associated with the key do not have the permission specified by the API (Credit Management, Usage Statistics, or Organization Overview). Ask an organization administrator to enable the corresponding permission for the member's role under Organization Settings → Roles.
* **The organization does not use Credit billing**: APIs marked as requiring Credit billing are available only to organizations using that billing mode. Call `GET /api/v1/organizations/{id}/` to check: these APIs are available when `organizationPlan.billingMode` is `credit`, or when the organization has no plan yet and `organizationPlan` is empty. To switch to Credit billing, contact your MaiAgent representative.

### Query Credit Balance <a href="#credit-wallets-list" id="credit-wallets-list"></a>

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

{% hint style="info" %}
**Required permission**: Credit Management. **Billing mode**: Unrestricted; organizations using any billing mode can call this API.
{% endhint %}

#### Parameters

| Parameter Name | Required | Type    | Description                                    |
| -------------- | -------- | ------- | ---------------------------------------------- |
| `page`         | ❌        | integer | A page number within the paginated result set. |
| `pageSize`     | ❌        | integer | Number of results to return per page.          |

#### Code Examples

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

```bash
# API call example (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/credit/wallets/?page=1&pageSize=1" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request 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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request error:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request error: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Content

**Status code: 200**

**Example Response Structure**

```typescript
{
  "count": integer
  "next"?: string (uri) // Optional
  "previous"?: string (uri) // Optional
  "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.
    }
  ]
}
```

**Example Response Values**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "totalCredits": "Response string",
      "autoTopup": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "Example response name",
        "description": "Example response description"
      },
      "balanceAlert": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "Example response name",
        "description": "Example response description"
      },
      "nextGrant": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "Example response name",
        "description": "Example response description"
      },
      "lastGrant": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "Example response name",
        "description": "Example response description"
      },
      "consumptionHint": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "Example response name",
        "description": "Example response description"
      },
      "billingProvider": "Response string",
      "periodCreditGrant": "Response string",
      "periodMeteredUsage": "Response string"
    }
  ]
}
```

***

### Get Wallet Details <a href="#credit-wallets-retrieve" id="credit-wallets-retrieve"></a>

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

{% hint style="info" %}
**Required permission**: Credit Management. **Billing mode**: Unrestricted; organizations using any billing mode can call this API.
{% endhint %}

#### Parameters

| Parameter Name | Required | Type   | Description                                   |
| -------------- | -------- | ------ | --------------------------------------------- |
| `id`           | ✅        | string | A UUID string identifying this Credit Wallet. |

#### Code Examples

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

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

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request 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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request error:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request error: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Content

**Status code: 200**

**Example Response Structure**

```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.
}
```

**Example Response Values**

```json
{
  "totalCredits": "Response string",
  "autoTopup": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "balanceAlert": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "nextGrant": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "lastGrant": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "consumptionHint": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "billingProvider": "Response string",
  "periodCreditGrant": "Response string",
  "periodMeteredUsage": "Response string"
}
```

***

### Get Wallet Balance <a href="#credit-wallets-balance-retrieve" id="credit-wallets-balance-retrieve"></a>

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

{% hint style="info" %}
**Required permission**: Credit Management. **Billing mode**: Unrestricted; organizations using any billing mode can call this API.
{% endhint %}

#### Parameters

| Parameter Name | Required | Type   | Description                                   |
| -------------- | -------- | ------ | --------------------------------------------- |
| `id`           | ✅        | string | A UUID string identifying this Credit Wallet. |

#### Code Examples

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

```bash
# API call example (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"

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request 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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request error:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request error: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Content

**Status code: 200**

**Example Response Structure**

```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.
}
```

**Example Response Values**

```json
{
  "totalCredits": "Response string",
  "autoTopup": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "balanceAlert": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "nextGrant": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "lastGrant": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "consumptionHint": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "billingProvider": "Response string",
  "periodCreditGrant": "Response string",
  "periodMeteredUsage": "Response string"
}
```

***

### Query Expiring Credits <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" %}
**Required permission**: Credit Management. **Billing mode**: Unrestricted; organizations using any billing mode can call this API. Only Credits with an expiration date are listed. Credits without an expiration date are excluded, so the results do not represent the organization’s entire balance. The `days` parameter specifies how many days ahead to check for expiring Credits (default: 30; pass `all` to list all Credits with an expiration date).
{% endhint %}

#### Parameters

| Parameter Name | Required | Type   | Description                                   |
| -------------- | -------- | ------ | --------------------------------------------- |
| `id`           | ✅        | string | A UUID string identifying this Credit Wallet. |

#### Code Examples

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

```bash
# API call example (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"

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request 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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request error:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request error: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Content

**Status code: 200**

**Example Response Structure**

```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.
}
```

**Example Response Values**

```json
{
  "totalCredits": "Response string",
  "autoTopup": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "balanceAlert": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "nextGrant": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "lastGrant": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "consumptionHint": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "billingProvider": "Response string",
  "periodCreditGrant": "Response string",
  "periodMeteredUsage": "Response string"
}
```

***

### Query Top-up History <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" %}
**Required permission**: Credit Management. **Billing mode**: Unrestricted; organizations using any billing mode can call this API.
{% endhint %}

#### Parameters

| Parameter Name | Required | Type   | Description                                   |
| -------------- | -------- | ------ | --------------------------------------------- |
| `id`           | ✅        | string | A UUID string identifying this Credit Wallet. |

#### Code Examples

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

```bash
# API call example (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"

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
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('Response retrieved successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request 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("Response retrieved successfully:")
    print(response.json())
except Exception as e:
    print("Request error:", 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 "Response retrieved successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request error: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Content

**Status code: 200**

**Example Response Structure**

```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.
}
```

**Example Response Values**

```json
{
  "totalCredits": "response string",
  "autoTopup": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "balanceAlert": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "nextGrant": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "lastGrant": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "consumptionHint": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "billingProvider": "response string",
  "periodCreditGrant": "response string",
  "periodMeteredUsage": "response string"
}
```

***

### List Usage Transactions <a href="#credit-transactions-list" id="credit-transactions-list"></a>

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

{% hint style="info" %}
**Required permissions**: Credit management permissions. **Billing mode**: No restrictions; organizations using any billing mode can call this endpoint.
{% endhint %}

#### Parameters

| Parameter Name | Required | Type    | Description                                    |
| -------------- | -------- | ------- | ---------------------------------------------- |
| `page`         | ❌        | integer | A page number within the paginated result set. |
| `pageSize`     | ❌        | integer | Number of results to return per page.          |

#### Code Examples

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

```bash
# API call example (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/credit/transactions/?page=1&pageSize=1" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request 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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request error:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request error: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Body

**Status Code: 200**

**Example Response Schema**

```typescript
{
  "count": integer
  "next"?: string (uri) // Optional
  "previous"?: string (uri) // Optional
  "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.
    }
  ]
}
```

**Example Response Values**

```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": "response string",
      "createdAt": "response string",
      "transactionType": "response string",
      "creditItem": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "example response name",
        "description": "example response description"
      },
      "amount": "response string",
      "balanceAfter": "response string",
      "quantity": "response string",
      "provider": "response string",
      "modelCode": "response string",
      "unitPriceSnapshot": "response string",
      "member": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "example response name",
        "description": "example response description"
      },
      "description": "response string",
      "metadata": null,
      "parserName": "response string",
      "quantityUnit": "response string",
      "targetObject": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "example response name",
        "description": "example response description"
      }
    }
  ]
}
```

***

### Retrieve a Usage Transaction <a href="#credit-transactions-retrieve" id="credit-transactions-retrieve"></a>

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

{% hint style="info" %}
**Required permissions**: Credit management permissions. **Billing mode**: No restrictions; organizations using any billing mode can call this endpoint.
{% endhint %}

#### Parameters

| Parameter Name | Required | Type   | Description                                        |
| -------------- | -------- | ------ | -------------------------------------------------- |
| `id`           | ✅        | string | A UUID string identifying this Credit Transaction. |

#### Code Examples

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

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

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request 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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request error:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request error: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Body

**Status Code: 200**

**Example Response Schema**

```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.
}
```

**Example Response Values**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "eventDatetime": "response string",
  "createdAt": "response string",
  "transactionType": "response string",
  "creditItem": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "example response name",
    "description": "example response description"
  },
  "amount": "response string",
  "balanceAfter": "response string",
  "quantity": "response string",
  "provider": "response string",
  "modelCode": "response string",
  "unitPriceSnapshot": "response string",
  "member": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "example response name",
    "description": "example response description"
  },
  "description": "response string",
  "metadata": null,
  "parserName": "response string",
  "quantityUnit": "response string",
  "targetObject": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "example response name",
    "description": "example response description"
  }
}
```

***

### Query Usage History <a href="#credit-transactions-history-retrieve" id="credit-transactions-history-retrieve"></a>

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

{% hint style="info" %}
**Required permissions**: Credit management permissions. **Billing mode**: No restrictions; organizations using any billing mode can call this endpoint.
{% endhint %}

#### Parameters

| Parameter Name | Required | Type    | Description                                                                                                                        |
| -------------- | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `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                                                      |

#### Code Examples

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

```bash
# API call example (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"

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request 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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request error:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request error: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Body

**Status Code: 200**

**Example Response Schema**

```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.
}
```

**Example Response Values**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "eventDatetime": "response string",
  "createdAt": "response string",
  "transactionType": "response string",
  "creditItem": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "example response name",
    "description": "example response description"
  },
  "amount": "response string",
  "balanceAfter": "response string",
  "quantity": "response string",
  "provider": "response string",
  "modelCode": "response string",
  "unitPriceSnapshot": "response string",
  "member": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "example response name",
    "description": "example response description"
  },
  "description": "response string",
  "metadata": null,
  "parserName": "response string",
  "quantityUnit": "response string",
  "targetObject": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "example response name",
    "description": "example response description"
  }
}
```

***

### Query Consumption Summary <a href="#credit-transactions-history-summary-retrieve" id="credit-transactions-history-summary-retrieve"></a>

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

{% hint style="info" %}
**Required permission**: Credit Management. **Billing mode**: Unrestricted; organizations using any billing mode can call this API.
{% endhint %}

#### Parameters

| Parameter Name | Required | Type   | Description                                                                                                                        |
| -------------- | -------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------- |
| `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                                                      |

#### Code Examples

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

```bash
# API call example (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"

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request 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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request error:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request error: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Content

**Status code: 200**

**Example Response Structure**

```typescript
{
  "consumedTotal": string (decimal)
  "creditedTotal": string (decimal)
  "count": integer
}
```

**Example Response Values**

```json
{
  "consumedTotal": "Response string",
  "creditedTotal": "Response string",
  "count": 456
}
```

***

### Query Credit Usage by Category <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" %}
**Required permissions**: Usage statistics permission. **Billing mode**: The organization must use Credit billing.
{% endhint %}

#### Parameters

| Parameter Name    | Required | Type    | Description                                    |
| ----------------- | -------- | ------- | ---------------------------------------------- |
| `organizationPk`  | ✅        | string  | A UUID string identifying this organization 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)              |

#### Code Examples

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

```bash
# API Call Example (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"

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
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('Response retrieved successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request failed:');
    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("Response retrieved successfully:")
    print(response.json())
except Exception as e:
    print("Request failed:", 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 "Response retrieved successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response

**Status Code: 200**

**Example Response Schema**

```typescript
{
  "count": integer
  "next"?: string (uri) // Optional
  "previous"?: string (uri) // Optional
  "results": [
    object
  ]
}
```

**Example Response Values**

```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": "Example response name",
      "description": "Example response description"
    }
  ]
}
```

***

### Retrieve Credit Usage for a Single Category <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" %}
**Required permissions**: Usage statistics permission. **Billing mode**: The organization must use Credit billing.
{% endhint %}

#### Parameters

| Parameter Name    | Required | Type   | Description                                    |
| ----------------- | -------- | ------ | ---------------------------------------------- |
| `id`              | ✅        | string |                                                |
| `organizationPk`  | ✅        | string | A UUID string identifying this organization ID |
| `endDate`         | ❌        | string | End date, format: YYYY-MM-DD                   |
| `startDate`       | ✅        | string | Start date, format: YYYY-MM-DD                 |
| `timeGranularity` | ❌        | string | Time granularity (hour/day/month)              |

#### Code Examples

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

```bash
# API Call Example (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"

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
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('Response retrieved successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request failed:');
    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("Response retrieved successfully:")
    print(response.json())
except Exception as e:
    print("Request failed:", 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 "Response retrieved successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response

**Status Code: 200**

**Example Response Schema**

```typescript
object
```

**Example Response Values**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "Example response name",
  "description": "Example response description"
}
```

***

### Retrieve Member Usage for a Billable Item <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" %}
**Required permissions**: Usage statistics permission. **Billing mode**: The organization must use Credit billing.
{% endhint %}

#### Parameters

| Parameter Name    | Required | Type    | Description                                    |
| ----------------- | -------- | ------- | ---------------------------------------------- |
| `itemPk`          | ✅        | string  |                                                |
| `organizationPk`  | ✅        | string  | A UUID string identifying this organization 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)              |

#### Code Examples

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

```bash
# API Call Example (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"

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
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('Response retrieved successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request failed:');
    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("Response retrieved successfully:")
    print(response.json())
except Exception as e:
    print("Request failed:", 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 "Response retrieved successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response

**Status Code: 200**

**Example Response Schema**

```typescript
{
  "count": integer
  "next"?: string (uri) // Optional
  "previous"?: string (uri) // Optional
  "results": [
    object
  ]
}
```

**Example Response Values**

```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": "Example response name",
      "description": "Example response description"
    }
  ]
}
```

***

### Retrieve Billable Item Usage for a Single Member <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" %}
**Required permissions**: Usage statistics permission. **Billing mode**: The organization must use Credit billing.
{% endhint %}

#### Parameters

| Parameter Name    | Required | Type   | Description                                    |
| ----------------- | -------- | ------ | ---------------------------------------------- |
| `id`              | ✅        | string |                                                |
| `itemPk`          | ✅        | string |                                                |
| `organizationPk`  | ✅        | string | A UUID string identifying this organization ID |
| `endDate`         | ❌        | string | End date, format: YYYY-MM-DD                   |
| `startDate`       | ✅        | string | Start date, format: YYYY-MM-DD                 |
| `timeGranularity` | ❌        | string | Time granularity (hour/day/month)              |

#### Code Examples

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

```bash
# API Call Example (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"

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
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('Response retrieved successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request failed:');
    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("Response retrieved successfully:")
    print(response.json())
except Exception as e:
    print("Request failed:", 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 "Response retrieved successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response

**Status Code: 200**

**Example Response Schema**

```typescript
object
```

**Example Response Values**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "Example response name",
  "description": "Example response description"
}
```

***

### Retrieve Default Quota Settings for New Members <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" %}
**Required permissions**: Credit management permissions. **Billing mode**: Any. The path parameter `id` is the wallet ID (`creditWallet.id` in the `GET /api/v1/organizations/{id}/` response). Response fields: `newMemberQuotaEnabled` (whether to allocate quotas automatically), `newMemberQuotaLimit` (quota limit), `newMemberQuotaValidDays` (number of days the quota is valid from the date the member joins; `null` means no expiration), `newMemberQuotaResetPeriod` (usage reset interval), `newMemberQuotaNote` (note), and `requireQuotaBeforeConsumption` (whether to block usage when a new member has no quota).
{% endhint %}

#### Parameters

| Parameter Name | Required | Type   | Description                                   |
| -------------- | -------- | ------ | --------------------------------------------- |
| `id`           | ✅        | string | A UUID string identifying this Credit Wallet. |

#### Code Examples

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

```bash
# Example API Call (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"

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request 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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request error:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request error: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Body

**Status Code: 200**

**Example Response Schema**

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

**Example Response Values**

```json
{
  "newMemberQuotaEnabled": false,
  "newMemberQuotaLimit": "Response string",
  "newMemberQuotaValidDays": 456,
  "newMemberQuotaResetPeriod": "none",
  "newMemberQuotaNote": "Response string",
  "requireQuotaBeforeConsumption": false
}
```

***

### Update Default Quota Settings for New Members <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" %}
**Required permissions**: Credit management permissions. **Billing mode**: The organization must use Credit billing; otherwise, the API returns `400`. Send only the fields to update. The fields are the same as those returned when retrieving the settings: `newMemberQuotaLimit` must not be negative and must have a value when `newMemberQuotaEnabled` is enabled; `newMemberQuotaValidDays` must be between 1 and 3650, or `null`. Once enabled, members who subsequently join through invitations, directory synchronization, SSO, or import automatically receive a personal quota that takes effect when they join. When a validity period is set, the expiration time cannot be later than the expiration date of the organization’s most recently credited quota (`null` means no expiration). If an invitation includes `creditQuota`, the quota specified in the invitation takes precedence (these defaults apply if the specified quota has expired or allocation fails). When `requireQuotaBeforeConsumption` is enabled, new members who have not received a quota cannot use features that consume Credit until a quota is allocated to them. Changing these settings does not affect previously allocated quotas or existing members. Response: `message` and `config` (the updated settings).
{% endhint %}

#### Parameters

| Parameter Name | Required | Type   | Description                                   |
| -------------- | -------- | ------ | --------------------------------------------- |
| `id`           | ✅        | string | A UUID string identifying this Credit Wallet. |

#### Request Body

**Request Parameters**

| Field                         | Type                                        | Required | Description                                                                |
| ----------------------------- | ------------------------------------------- | -------- | -------------------------------------------------------------------------- |
| newMemberQuotaEnabled         | boolean                                     | No       |                                                                            |
| newMemberQuotaLimit           | string (decimal)                            | No       |                                                                            |
| newMemberQuotaValidDays       | integer                                     | No       |                                                                            |
| newMemberQuotaResetPeriod     | string (enum: none, daily, weekly, monthly) | No       | `none`: No Reset ; `daily`: Daily ; `weekly`: Weekly ; `monthly`: Monthly; |
| newMemberQuotaNote            | string                                      | No       |                                                                            |
| requireQuotaBeforeConsumption | boolean                                     | No       |                                                                            |

**Example Request Schema**

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

**Example Request Values**

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

#### Code Examples

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

```bash
# Example API Call (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
  }'

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// Request Body (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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request 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"
}

# Request Body (payload)
data = {
    "newMemberQuotaEnabled": True,
    "newMemberQuotaLimit": "100",
    "newMemberQuotaValidDays": 30,
    "newMemberQuotaResetPeriod": "none",
    "requireQuotaBeforeConsumption": False
}

response = requests.patch(url, json=data, headers=headers)
try:
    print("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request error:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request error: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Body

**Status Code: 200**

**Example Response Schema**

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

**Example Response Values**

```json
{
  "message": "Response string",
  "config": {
    "newMemberQuotaEnabled": false,
    "newMemberQuotaLimit": "Response string",
    "newMemberQuotaValidDays": 456,
    "newMemberQuotaResetPeriod": "none",
    "newMemberQuotaNote": "Response string",
    "requireQuotaBeforeConsumption": false
  }
}
```

**Status Code: 400 - Validation failed, or the organization is not on credit billing.**

***

### List Current Member Quotas <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" %}
**Required permissions**: Credit management permission. **Billing mode**: The organization must use Credit billing.
{% endhint %}

#### Parameters

| Parameter Name   | Required | Type    | Description                                                             |
| ---------------- | -------- | ------- | ----------------------------------------------------------------------- |
| `organizationPk` | ✅        | string  | A UUID string identifying this organization 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) |

#### Code Examples

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

```bash
# API Call Example (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"

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
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('Response retrieved successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request failed:');
    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("Response retrieved successfully:")
    print(response.json())
except Exception as e:
    print("Request failed:", 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 "Response retrieved successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response

**Status Code: 200**

**Example Response Schema**

```typescript
{
  "count": integer
  "next"?: string (uri) // Optional
  "previous"?: string (uri) // Optional
  "results": [
    {
      "count"?: integer // Optional
      "next"?: string (uri) // Optional
      "previous"?: string (uri) // Optional
      "results"?: [ // Optional
        {
          "id"?: string (uuid) // Optional
          "name"?: string // Optional
          "email"?: string // Optional
          "credit_quota_required"?: boolean // Optional
          "active_quota"?: { // Most recent quota summary (active first); same shape as the members API active_quota. (Optional)
          {
            "id"?: string (uuid) // Optional
            "quota_limit"?: string // Optional
            "consumed_amount"?: string // Optional
            "remaining"?: string // Optional
            "valid_from"?: string (date-time) // Optional
            "valid_until"?: string (date-time) // Optional
            "is_active"?: boolean // Optional
            "expired_at"?: string (date-time) // Optional
            "note"?: string // Optional
          }
          }
        }
      ]
      "stats"?: { // Organization-wide member counts, unaffected by search or quota_status filter. (Optional)
      {
        "total"?: integer // Optional
        "allocated"?: integer // Optional
        "expired"?: integer // Optional
        "unallocated"?: integer // Optional
      }
      }
    }
  ]
}
```

**Example Response Values**

```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": "Response string",
          "email": "Response string",
          "credit_quota_required": false,
          "active_quota": {
            "id": "550e8400-e29b-41d4-a716-446655440000",
            "name": "Example response name",
            "description": "Example response description"
          }
        }
      ],
      "stats": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "Example response name",
        "description": "Example response description"
      }
    }
  ]
}
```

***

### List Current Role Quotas <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" %}
**Required permissions**: Credit management permission. **Billing mode**: The organization must use Credit billing.
{% endhint %}

#### Parameters

| Parameter Name   | Required | Type    | Description                                                   |
| ---------------- | -------- | ------- | ------------------------------------------------------------- |
| `organizationPk` | ✅        | string  | A UUID string identifying this organization 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) |

#### Code Examples

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

```bash
# API call example (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"

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request failed:');
    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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request failed:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Body

**Status Code: 200**

**Example Response Structure**

```typescript
{
  "count": integer
  "next"?: string (uri) // Optional
  "previous"?: string (uri) // Optional
  "results": [
    {
      "count"?: integer // Optional
      "next"?: string (uri) // Optional
      "previous"?: string (uri) // Optional
      "results"?: [ // Optional
        {
          "id"?: string (uuid) // Optional
          "name"?: string // Optional
          "type"?: string (enum: owner, default, custom) // Optional
          "credit_quota_required"?: boolean // Optional
          "active_quota"?: { // Most recent quota summary (active first); same shape as the member/inbox variants. (Optional)
          {
            "id"?: string (uuid) // Optional
            "quota_limit"?: string // Optional
            "consumed_amount"?: string // Optional
            "remaining"?: string // Optional
            "valid_from"?: string (date-time) // Optional
            "valid_until"?: string (date-time) // Optional
            "is_active"?: boolean // Optional
            "expired_at"?: string (date-time) // Optional
            "note"?: string // Optional
          }
          }
        }
      ]
      "stats"?: { // Organization-wide group counts, unaffected by search or quota_status filter. (Optional)
      {
        "total"?: integer // Optional
        "allocated"?: integer // Optional
        "expired"?: integer // Optional
        "unallocated"?: integer // Optional
      }
      }
    }
  ]
}
```

**Example Response Values**

```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": "Response string",
          "type": "owner",
          "credit_quota_required": false,
          "active_quota": {
            "id": "550e8400-e29b-41d4-a716-446655440000",
            "name": "Example response name",
            "description": "Example response description"
          }
        }
      ],
      "stats": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "Example response name",
        "description": "Example response description"
      }
    }
  ]
}
```

***

### List Inbox Quota Status <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" %}
**Required permission**: Credit management permission. **Billing mode**: The organization must use Credit billing.
{% endhint %}

#### Parameters

| Parameter Name   | Required | Type    | Description                                                                                                                                                                                                                                                                                                                       |
| ---------------- | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `organizationPk` | ✅        | string  | A UUID string identifying this organization ID                                                                                                                                                                                                                                                                                    |
| `excludeBuiltIn` | ❌        | boolean | When true, excludes data for official built-in Agents (locked instances created by renting from the Agent Marketplace), leaving only assistants created by the organization. Copies created using “Copy as Custom” count as organization-created assistants. Omitting this parameter or setting it to false applies no filtering. |
| `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.                                                                                                                                                                                                                                                                                                                    |

#### Code Examples

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

```bash
# API call example (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"

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request 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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request error:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request error: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Body

**Status Code: 200**

**Example Response Schema**

```typescript
{
  "count": integer
  "next"?: string (uri) // Optional
  "previous"?: string (uri) // Optional
  "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.
    }
  ]
}
```

**Example Response Values**

```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": "Response string",
      "channelType": {},
      "channelTypeLabel": "Response string",
      "webChatAccessType": "Response string",
      "chatbot": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "Example response name",
        "description": "Example response description"
      },
      "creditQuotaRequired": false,
      "activeQuota": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "Example response name",
        "description": "Example response description"
      },
      "canUpdate": false
    }
  ]
}
```

***

### List Member Quota Settings <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" %}
**Required permissions**: Credit management permissions. **Billing mode**: The organization must use Credit billing.
{% endhint %}

#### Parameters

| Parameter Name   | Required | Type    | Description                                    |
| ---------------- | -------- | ------- | ---------------------------------------------- |
| `memberPk`       | ✅        | string  |                                                |
| `organizationPk` | ✅        | string  | A UUID string identifying this organization ID |
| `page`           | ❌        | integer | A page number within the paginated result set. |
| `pageSize`       | ❌        | integer | Number of results to return per page.          |

#### Code Examples

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

```bash
# API call example (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"

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request failed:');
    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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request failed:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Body

**Status Code: 200**

**Example Response Structure**

```typescript
{
  "count": integer
  "next"?: string (uri) // Optional
  "previous"?: string (uri) // Optional
  "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)
    }
  ]
}
```

**Example Response Values**

```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": "Example response name",
        "description": "Example response description"
      },
      "quotaLimit": "Response string",
      "consumedAmount": "Response string",
      "remaining": "Response string",
      "validFrom": "Response string",
      "validUntil": "Response string",
      "resetPeriod": {},
      "nextResetAt": "Response string",
      "isActive": false,
      "expiredAt": "Response string",
      "createdBy": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "Example response name",
        "description": "Example response description"
      },
      "note": "Response string",
      "createdAt": "Response string",
      "updatedAt": "Response string"
    }
  ]
}
```

***

### Retrieve a Member Quota Setting <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" %}
**Required permissions**: Credit management permissions. **Billing mode**: The organization must use Credit billing.
{% endhint %}

#### Parameters

| Parameter Name   | Required | Type   | Description                                    |
| ---------------- | -------- | ------ | ---------------------------------------------- |
| `id`             | ✅        | string |                                                |
| `memberPk`       | ✅        | string |                                                |
| `organizationPk` | ✅        | string | A UUID string identifying this organization ID |

#### Code Examples

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

```bash
# API call example (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"

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request failed:');
    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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request failed:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Body

**Status Code: 200**

**Example Response Structure**

```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)
}
```

**Example Response Values**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "member": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "quotaLimit": "Response string",
  "consumedAmount": "Response string",
  "remaining": "Response string",
  "validFrom": "Response string",
  "validUntil": "Response string",
  "resetPeriod": {},
  "nextResetAt": "Response string",
  "isActive": false,
  "expiredAt": "Response string",
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "note": "Response string",
  "createdAt": "Response string",
  "updatedAt": "Response string"
}
```

***

### Set a quota for a member <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" %}
**Required permissions**: Credit management permissions. **Billing mode**: The organization must use Credit billing. See [How quotas work](#credit-quota-rules) for the request body and rules. If the member already has an active quota, the API returns `400`; deactivate it first.
{% endhint %}

#### Parameters

| Parameter name   | Required | Type   | Description                                    |
| ---------------- | -------- | ------ | ---------------------------------------------- |
| `memberPk`       | ✅        | string |                                                |
| `organizationPk` | ✅        | string | A UUID string identifying this organization ID |

#### Request body

**Request parameters**

| Field       | Type               | Required | Description |
| ----------- | ------------------ | -------- | ----------- |
| quotaLimit  | string (decimal)   | Yes      |             |
| validFrom   | string (date-time) | Yes      |             |
| validUntil  | string (date-time) | No       |             |
| note        | string             | No       |             |
| resetPeriod | object             | No       |             |

**Example request schema**

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

**Example request values**

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

#### Code examples

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

```bash
# API call example (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"
  }'

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// Request body (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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request failed:');
    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"
}

# Request body (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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request failed:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response body

**Status code: 201**

**Example response schema**

```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)
}
```

**Example response values**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "member": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "quotaLimit": "Response string",
  "consumedAmount": "Response string",
  "remaining": "Response string",
  "validFrom": "Response string",
  "validUntil": "Response string",
  "resetPeriod": {},
  "nextResetAt": "Response string",
  "isActive": false,
  "expiredAt": "Response string",
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "note": "Response string",
  "createdAt": "Response string",
  "updatedAt": "Response string"
}
```

***

### Update a member's quota settings <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" %}
**Required permissions**: Credit management permissions. **Billing mode**: The organization must use Credit billing. Send only the fields to update: `quotaLimit`, `validUntil`, `resetPeriod`, and `note` (the start time cannot be changed). `quotaLimit` cannot be lower than the amount already consumed. Deactivated quotas cannot be updated; the API returns `400`.
{% endhint %}

#### Parameters

| Parameter name   | Required | Type   | Description                                    |
| ---------------- | -------- | ------ | ---------------------------------------------- |
| `id`             | ✅        | string |                                                |
| `memberPk`       | ✅        | string |                                                |
| `organizationPk` | ✅        | string | A UUID string identifying this organization ID |

#### Request body

**Request parameters**

| Field       | Type                                        | Required | Description                                                                |
| ----------- | ------------------------------------------- | -------- | -------------------------------------------------------------------------- |
| quotaLimit  | string (decimal)                            | No       |                                                                            |
| validUntil  | string (date-time)                          | No       |                                                                            |
| note        | string                                      | No       |                                                                            |
| resetPeriod | string (enum: none, daily, weekly, monthly) | No       | `none`: No Reset ; `daily`: Daily ; `weekly`: Weekly ; `monthly`: Monthly; |

**Example request schema**

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

**Example request values**

```json
{
  "quotaLimit": "Example string",
  "validUntil": "2025-01-01T00:00:00.000Z",
  "note": "Example string",
  "resetPeriod": "none"
}
```

#### Code examples

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

```bash
# API call example (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": "Example string",
    "validUntil": "2025-01-01T00:00:00.000Z",
    "note": "Example string",
    "resetPeriod": "none"
  }'

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// Request body (payload)
const data = {
    "quotaLimit": "Example string",
    "validUntil": "2025-01-01T00:00:00.000Z",
    "note": "Example string",
    "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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request failed:');
    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"
}

# Request body (payload)
data = {
    "quotaLimit": "Example string",
    "validUntil": "2025-01-01T00:00:00.000Z",
    "note": "Example string",
    "resetPeriod": "none"
}

response = requests.patch(url, json=data, headers=headers)
try:
    print("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request failed:", 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' => 'Example string',
            'validUntil' => '2025-01-01T00:00:00.000Z',
            'note' => 'Example string',
            'resetPeriod' => 'none'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response body

**Status code: 200**

**Example response schema**

```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)
}
```

**Example response values**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "member": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "quotaLimit": "Response string",
  "consumedAmount": "Response string",
  "remaining": "Response string",
  "validFrom": "Response string",
  "validUntil": "Response string",
  "resetPeriod": {},
  "nextResetAt": "Response string",
  "isActive": false,
  "expiredAt": "Response string",
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "note": "Response string",
  "createdAt": "Response string",
  "updatedAt": "Response string"
}
```

***

### Deactivate a Member's Quota <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" %}
**Required permission**: Credit management permission. **Billing mode**: The organization must use the Credit billing mode. Returns `204` on success. After deactivation, the member's "Quota required" setting remains on, so the member cannot use Credit-consuming features until a new quota is set or the quota restriction is removed; deactivating an already deactivated quota returns `400`.
{% endhint %}

#### Parameters

| Parameter Name   | Required | Type   | Description                                    |
| ---------------- | -------- | ------ | ---------------------------------------------- |
| `id`             | ✅        | string |                                                |
| `memberPk`       | ✅        | string |                                                |
| `organizationPk` | ✅        | string | A UUID string identifying this Organization ID |

#### Code Examples

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

```bash
# Example API call (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"

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

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

// Request 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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request failed:');
    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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request failed:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response

| Status Code | Description      |
| ----------- | ---------------- |
| 204         | No response body |

***

### List Role Quota Settings <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" %}
**Required permissions**: Credit management permissions. **Billing mode**: The organization must use Credit billing.
{% endhint %}

#### Parameters

| Parameter Name   | Required | Type    | Description                                    |
| ---------------- | -------- | ------- | ---------------------------------------------- |
| `groupPk`        | ✅        | string  |                                                |
| `organizationPk` | ✅        | string  | A UUID string identifying this organization ID |
| `page`           | ❌        | integer | A page number within the paginated result set. |
| `pageSize`       | ❌        | integer | Number of results to return per page.          |

#### Code Examples

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

```bash
# API call example (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"

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request failed:');
    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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request failed:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Body

**Status Code: 200**

**Response Schema Example**

```typescript
{
  "count": integer
  "next"?: string (uri) // Optional
  "previous"?: string (uri) // Optional
  "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)
    }
  ]
}
```

**Example Response Values**

```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": "Example response name",
        "description": "Example response description"
      },
      "quotaLimit": "Response string",
      "consumedAmount": "Response string",
      "remaining": "Response string",
      "validFrom": "Response string",
      "validUntil": "Response string",
      "resetPeriod": {},
      "nextResetAt": "Response string",
      "isActive": false,
      "expiredAt": "Response string",
      "createdBy": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "Example response name",
        "description": "Example response description"
      },
      "note": "Response string",
      "createdAt": "Response string",
      "updatedAt": "Response string"
    }
  ]
}
```

***

### Retrieve a Role Quota Setting <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" %}
**Required permissions**: Credit management permissions. **Billing mode**: The organization must use Credit billing.
{% endhint %}

#### Parameters

| Parameter Name   | Required | Type   | Description                                    |
| ---------------- | -------- | ------ | ---------------------------------------------- |
| `groupPk`        | ✅        | string |                                                |
| `id`             | ✅        | string |                                                |
| `organizationPk` | ✅        | string | A UUID string identifying this organization ID |

#### Code Examples

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

```bash
# API call example (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"

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request failed:');
    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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request failed:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Body

**Status Code: 200**

**Response Schema Example**

```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)
}
```

**Example Response Values**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "group": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "quotaLimit": "Response string",
  "consumedAmount": "Response string",
  "remaining": "Response string",
  "validFrom": "Response string",
  "validUntil": "Response string",
  "resetPeriod": {},
  "nextResetAt": "Response string",
  "isActive": false,
  "expiredAt": "Response string",
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "note": "Response string",
  "createdAt": "Response string",
  "updatedAt": "Response string"
}
```

***

### Set a quota for a role <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" %}
**Required permissions**: Credit management permissions. **Billing mode**: The organization must use Credit billing. This sets a quota shared by all members of the role; it does not allocate quotas to individual members. To assign a separate quota to each member, use [Batch allocate quotas by role](#organizations-groups-batch-distribute-credit-quota-create). See [How quotas work](#credit-quota-rules) for the request body and rules. If the role already has an active quota, the API returns `400`; deactivate it first.
{% endhint %}

#### Parameters

| Parameter name   | Required | Type   | Description                                    |
| ---------------- | -------- | ------ | ---------------------------------------------- |
| `groupPk`        | ✅        | string |                                                |
| `organizationPk` | ✅        | string | A UUID string identifying this organization ID |

#### Request body

**Request parameters**

| Field       | Type               | Required | Description |
| ----------- | ------------------ | -------- | ----------- |
| quotaLimit  | string (decimal)   | Yes      |             |
| validFrom   | string (date-time) | Yes      |             |
| validUntil  | string (date-time) | No       |             |
| note        | string             | No       |             |
| resetPeriod | object             | No       |             |

**Request schema example**

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

**Example request values**

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

#### Code examples

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

```bash
# API call example (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"
  }'

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// Request body (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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request failed:');
    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"
}

# Request body (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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request failed:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response body

**Status code: 201**

**Response schema example**

```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)
}
```

**Example response values**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "group": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "quotaLimit": "Response string",
  "consumedAmount": "Response string",
  "remaining": "Response string",
  "validFrom": "Response string",
  "validUntil": "Response string",
  "resetPeriod": {},
  "nextResetAt": "Response string",
  "isActive": false,
  "expiredAt": "Response string",
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "note": "Response string",
  "createdAt": "Response string",
  "updatedAt": "Response string"
}
```

***

### Update quota settings for a role <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" %}
**Required permissions**: Credit management permissions. **Billing mode**: The organization must use Credit billing. Send only the fields you want to change: `quotaLimit`, `validUntil`, `resetPeriod`, and `note` (the start time cannot be changed). `quotaLimit` cannot be lower than the amount already consumed. Deactivated quotas cannot be updated; the API returns `400`.
{% endhint %}

#### Parameters

| Parameter name   | Required | Type   | Description                                    |
| ---------------- | -------- | ------ | ---------------------------------------------- |
| `groupPk`        | ✅        | string |                                                |
| `id`             | ✅        | string |                                                |
| `organizationPk` | ✅        | string | A UUID string identifying this organization ID |

#### Request body

**Request parameters**

| Field       | Type                                        | Required | Description                                                                |
| ----------- | ------------------------------------------- | -------- | -------------------------------------------------------------------------- |
| quotaLimit  | string (decimal)                            | No       |                                                                            |
| validUntil  | string (date-time)                          | No       |                                                                            |
| note        | string                                      | No       |                                                                            |
| resetPeriod | string (enum: none, daily, weekly, monthly) | No       | `none`: No Reset ; `daily`: Daily ; `weekly`: Weekly ; `monthly`: Monthly; |

**Request schema example**

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

**Example request values**

```json
{
  "quotaLimit": "Example string",
  "validUntil": "2025-01-01T00:00:00.000Z",
  "note": "Example string",
  "resetPeriod": "none"
}
```

#### Code examples

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

```bash
# API call example (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": "Example string",
    "validUntil": "2025-01-01T00:00:00.000Z",
    "note": "Example string",
    "resetPeriod": "none"
  }'

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// Request body (payload)
const data = {
    "quotaLimit": "Example string",
    "validUntil": "2025-01-01T00:00:00.000Z",
    "note": "Example string",
    "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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request failed:');
    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"
}

# Request body (payload)
data = {
    "quotaLimit": "Example string",
    "validUntil": "2025-01-01T00:00:00.000Z",
    "note": "Example string",
    "resetPeriod": "none"
}

response = requests.patch(url, json=data, headers=headers)
try:
    print("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request failed:", 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' => 'Example string',
            'validUntil' => '2025-01-01T00:00:00.000Z',
            'note' => 'Example string',
            'resetPeriod' => 'none'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response body

**Status code: 200**

**Response schema example**

```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)
}
```

**Example response values**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "group": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "quotaLimit": "Response string",
  "consumedAmount": "Response string",
  "remaining": "Response string",
  "validFrom": "Response string",
  "validUntil": "Response string",
  "resetPeriod": {},
  "nextResetAt": "Response string",
  "isActive": false,
  "expiredAt": "Response string",
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "note": "Response string",
  "createdAt": "Response string",
  "updatedAt": "Response string"
}
```

***

### Deactivate a Role's Quota Settings <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" %}
**Required permission**: Credit Management. **Billing mode**: The organization must use the Credit billing mode. Returns `204` on success. After deactivation, the role's "quota required" setting stays on, so members of the role cannot use features that consume Credits until a new quota is set or the quota restriction is lifted. Deactivating an already deactivated quota returns `400`.
{% endhint %}

#### Parameters

| Parameter Name   | Required | Type   | Description                                    |
| ---------------- | -------- | ------ | ---------------------------------------------- |
| `groupPk`        | ✅        | string |                                                |
| `id`             | ✅        | string |                                                |
| `organizationPk` | ✅        | string | A UUID string identifying this Organization ID |

#### Code Examples

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

```bash
# API call example (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"

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

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

// Request 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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request failed:');
    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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request failed:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Content

| Status Code | Description      |
| ----------- | ---------------- |
| 204         | No response body |

***

### Set Whether a Role Requires a Quota <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" %}
**Required permission**: Credit Management. **Billing mode**: The organization must use the Credit billing mode. The request body is `{"creditQuotaRequired": true}` or `false`, and the `id` in the path is the role ID. When set to `false` (lifting the quota restriction), the role's active quota is deactivated as well, and members use the organization wallet instead. When set to `true`, members of the role are blocked from using the service until a quota is set. The response shows the role's current quota status.
{% endhint %}

#### Parameters

| Parameter Name   | Required | Type   | Description                                    |
| ---------------- | -------- | ------ | ---------------------------------------------- |
| `id`             | ✅        | string | A UUID string identifying this Group.          |
| `organizationPk` | ✅        | string | A UUID string identifying this Organization ID |

#### Code Examples

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

```bash
# API call example (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 '{}'

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

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// Request 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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request failed:');
    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"
}

# Request payload
data = {}

response = requests.patch(url, json=data, headers=headers)
try:
    print("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request failed:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Content

**Status code: 200**

**Example Response Structure**

```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.
}
```

**Example Response Values**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "Response string",
  "type": {},
  "creditQuotaRequired": false,
  "activeQuota": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Response example name",
    "description": "Response example description"
  }
}
```

***

### Retrieve Role Member Quota Statistics <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" %}
**Required permissions**: Credit management permissions. **Billing mode**: The organization must use Credit billing.
{% endhint %}

#### Parameters

| Parameter Name   | Required | Type   | Description                                    |
| ---------------- | -------- | ------ | ---------------------------------------------- |
| `id`             | ✅        | string | A UUID string identifying this Group.          |
| `organizationPk` | ✅        | string | A UUID string identifying this organization ID |

#### Code Examples

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

```bash
# API call example (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"

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request failed:');
    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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request failed:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Body

**Status Code: 200**

**Response Schema Example**

```typescript
{
  "activeQuotaMembersCount": integer
  "quotaRequiredMembersCount": integer
}
```

**Example Response Values**

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

***

### Distribute Quota in Bulk by Role <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" %}
**Required permission**: Credit management permission + Organization overview permission. **Billing mode**: The organization must be on Credit billing mode. Sets one member quota for each member in the role, with the same request body as [Set a Member's Quota](#organizations-members-credit-quotas-create). Members who already have an active quota are skipped and are not modified. Response: `successCount`, `skippedCount`, `skippedMemberIds`, `failedCount`, `failedMembers`.
{% endhint %}

#### Parameters

| Parameter Name   | Required | Type   | Description                                    |
| ---------------- | -------- | ------ | ---------------------------------------------- |
| `id`             | ✅        | string | A UUID string identifying this Group.          |
| `organizationPk` | ✅        | string | A UUID string identifying this Organization ID |

#### Request

**Request Parameters**

| Field                    | Type    | Required | Description                                                                                                                                                                                                 |
| ------------------------ | ------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name                     | string  | Yes      |                                                                                                                                                                                                             |
| canCreateChatbot         | boolean | No       |                                                                                                                                                                                                             |
| canCreateKnowledgeBase   | boolean | No       |                                                                                                                                                                                                             |
| canCreateInbox           | boolean | No       |                                                                                                                                                                                                             |
| canCreateDatabase        | boolean | No       |                                                                                                                                                                                                             |
| canCreateTool            | boolean | No       |                                                                                                                                                                                                             |
| canCreateAgentUiTool     | boolean | No       |                                                                                                                                                                                                             |
| canCreateSkill           | boolean | No       |                                                                                                                                                                                                             |
| maigptCanCodeInterpreter | boolean | No       | Whether members of this role may use the code interpreter built-in tool in MaiGPT.                                                                                                                          |
| maigptCanRag             | boolean | No       | Whether members of this role may use the knowledge base RAG built-in tool in MaiGPT.                                                                                                                        |
| maigptCanDeepResearch    | boolean | No       | 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 | No       | Whether members of this role may use the browser built-in tool in MaiGPT.                                                                                                                                   |
| maigptAllLlms            | boolean | No       | 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 | No       | 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 | No       | 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 | No       | 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  | No       | 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... |

**Example Request Structure**

```typescript
{
  "name": string
  "canCreateChatbot"?: boolean // Optional
  "canCreateKnowledgeBase"?: boolean // Optional
  "canCreateInbox"?: boolean // Optional
  "canCreateDatabase"?: boolean // Optional
  "canCreateTool"?: boolean // Optional
  "canCreateAgentUiTool"?: boolean // Optional
  "canCreateSkill"?: boolean // Optional
  "maigptCanCodeInterpreter"?: boolean // Whether members of this role may use the code interpreter built-in tool in MaiGPT. (Optional)
  "maigptCanRag"?: boolean // Whether members of this role may use the knowledge base RAG built-in tool in MaiGPT. (Optional)
  "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. (Optional)
  "maigptCanBrowserTool"?: boolean // Whether members of this role may use the browser built-in tool in MaiGPT. (Optional)
  "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. (Optional)
  "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. (Optional)
  "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. (Optional)
  "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. (Optional)
  "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 (Optional)
  {
  }
}
```

**Example Request Values**

```json
{
  "name": "Example 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": {}
}
```

#### Code Examples

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

```bash
# API call example (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": "Example 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": {}
  }'

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// Request payload
const data = {
    "name": "Example 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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('An error occurred while making the request:');
    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"
}

# Request payload
data = {
    "name": "Example 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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("An error occurred while making the request:", 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' => 'Example 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'An error occurred while making the request: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response

**Status code: 200**

**Example Response Structure**

```typescript
{
  "id": string (uuid)
  "name": string
  "type": 
  {
  }
  "permissions": [
    object
  ]
  "membersPreview": [
    string
  ]
  "membersCount": integer // Returns the number of remaining members (after subtracting the 3 shown in the list), used for the frontend +N badge

Unlike resource counts:
- members_count: returns total - 3 (used for the +N badge); None means the total is <= 3
- chatbots_count/knowledge_bases_count/inboxes_count: return the total count
  "chatbotsCount": integer
  "chatbotsPreview": [
    string
  ]
  "knowledgeBasesCount": integer
  "knowledgeBasesPreview": [
    string
  ]
  "inboxesCount": integer
  "inboxesPreview": [
    string
  ]
  "databasesCount": integer
  "databasesPreview": [
    string
  ]
  "canCreateChatbot"?: boolean // Optional
  "canCreateKnowledgeBase"?: boolean // Optional
  "canCreateInbox"?: boolean // Optional
  "canCreateDatabase"?: boolean // Optional
  "canCreateTool"?: boolean // Optional
  "canCreateAgentUiTool"?: boolean // Optional
  "canCreateSkill"?: boolean // Optional
  "maigptCanCodeInterpreter"?: boolean // Whether members of this role may use the code interpreter built-in tool in MaiGPT. (Optional)
  "maigptCanRag"?: boolean // Whether members of this role may use the knowledge base RAG built-in tool in MaiGPT. (Optional)
  "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. (Optional)
  "maigptCanBrowserTool"?: boolean // Whether members of this role may use the browser built-in tool in MaiGPT. (Optional)
  "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. (Optional)
  "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. (Optional)
  "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. (Optional)
  "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. (Optional)
  "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 (Optional)
  {
  }
  "createdAt": string (timestamp)
}
```

**Example Response Values**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "Response string",
  "type": {},
  "permissions": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "Example response name",
      "description": "Example response description"
    }
  ],
  "membersPreview": [
    "Response string"
  ],
  "membersCount": 456,
  "chatbotsCount": 456,
  "chatbotsPreview": [
    "Response string"
  ],
  "knowledgeBasesCount": 456,
  "knowledgeBasesPreview": [
    "Response string"
  ],
  "inboxesCount": 456,
  "inboxesPreview": [
    "Response string"
  ],
  "databasesCount": 456,
  "databasesPreview": [
    "Response string"
  ],
  "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": "Response string"
}
```

***

### Deactivate Quota in Bulk by Role <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" %}
**Required permission**: Credit management permission + Organization overview permission. **Billing mode**: The organization must be on Credit billing mode. Deactivates the active member quotas of all members in the role (not the role's own quota); members without an active quota are counted as skipped. The request body field `removeQuotaRequirement` is optional and defaults to `false`: only the quota is deactivated, and the member's "quota required" setting stays on, so the member cannot use the service until a quota is reassigned. When set to `true`, the quota requirement is also removed for all members in the role, and they use the organization wallet instead. Response: `successCount`, `skippedCount`, `skippedMemberIds`, `failedCount`, `failedMembers`, `requirementRemovedCount`. Before running, use [Query Role Member Quota Statistics](#organizations-groups-credit-quota-stats-retrieve) to confirm how many members will be affected.
{% endhint %}

#### Parameters

| Parameter Name   | Required | Type   | Description                                    |
| ---------------- | -------- | ------ | ---------------------------------------------- |
| `id`             | ✅        | string | A UUID string identifying this Group.          |
| `organizationPk` | ✅        | string | A UUID string identifying this Organization ID |

#### Request

**Request Parameters**

| Field                    | Type    | Required | Description                                                                                                                                                                                                 |
| ------------------------ | ------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name                     | string  | Yes      |                                                                                                                                                                                                             |
| canCreateChatbot         | boolean | No       |                                                                                                                                                                                                             |
| canCreateKnowledgeBase   | boolean | No       |                                                                                                                                                                                                             |
| canCreateInbox           | boolean | No       |                                                                                                                                                                                                             |
| canCreateDatabase        | boolean | No       |                                                                                                                                                                                                             |
| canCreateTool            | boolean | No       |                                                                                                                                                                                                             |
| canCreateAgentUiTool     | boolean | No       |                                                                                                                                                                                                             |
| canCreateSkill           | boolean | No       |                                                                                                                                                                                                             |
| maigptCanCodeInterpreter | boolean | No       | Whether members of this role may use the code interpreter built-in tool in MaiGPT.                                                                                                                          |
| maigptCanRag             | boolean | No       | Whether members of this role may use the knowledge base RAG built-in tool in MaiGPT.                                                                                                                        |
| maigptCanDeepResearch    | boolean | No       | 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 | No       | Whether members of this role may use the browser built-in tool in MaiGPT.                                                                                                                                   |
| maigptAllLlms            | boolean | No       | 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 | No       | 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 | No       | 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 | No       | 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  | No       | 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... |

**Example Request Structure**

```typescript
{
  "name": string
  "canCreateChatbot"?: boolean // Optional
  "canCreateKnowledgeBase"?: boolean // Optional
  "canCreateInbox"?: boolean // Optional
  "canCreateDatabase"?: boolean // Optional
  "canCreateTool"?: boolean // Optional
  "canCreateAgentUiTool"?: boolean // Optional
  "canCreateSkill"?: boolean // Optional
  "maigptCanCodeInterpreter"?: boolean // Whether members of this role may use the code interpreter built-in tool in MaiGPT. (Optional)
  "maigptCanRag"?: boolean // Whether members of this role may use the knowledge base RAG built-in tool in MaiGPT. (Optional)
  "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. (Optional)
  "maigptCanBrowserTool"?: boolean // Whether members of this role may use the browser built-in tool in MaiGPT. (Optional)
  "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. (Optional)
  "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. (Optional)
  "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. (Optional)
  "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. (Optional)
  "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 (Optional)
  {
  }
}
```

**Example Request Values**

```json
{
  "name": "Example 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": {}
}
```

#### Code Examples

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

```bash
# API call example (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": "Example 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": {}
  }'

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// Request payload
const data = {
    "name": "Example 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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('An error occurred while making the request:');
    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"
}

# Request payload
data = {
    "name": "Example 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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("An error occurred with the request:", 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' => 'Example 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'An error occurred with the request: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Content

**Status Code: 200**

**Example Response Structure**

```typescript
{
  "id": string (uuid)
  "name": string
  "type": 
  {
  }
  "permissions": [
    object
  ]
  "membersPreview": [
    string
  ]
  "membersCount": integer // Returns the remaining number of members (after subtracting the 3 shown in the list), used for the +N badge in the frontend

Unlike the resource counts:
- members_count: returns total - 3 (used for the +N badge); None means the total is <= 3
- chatbots_count/knowledge_bases_count/inboxes_count: return the total count
  "chatbotsCount": integer
  "chatbotsPreview": [
    string
  ]
  "knowledgeBasesCount": integer
  "knowledgeBasesPreview": [
    string
  ]
  "inboxesCount": integer
  "inboxesPreview": [
    string
  ]
  "databasesCount": integer
  "databasesPreview": [
    string
  ]
  "canCreateChatbot"?: boolean // Optional
  "canCreateKnowledgeBase"?: boolean // Optional
  "canCreateInbox"?: boolean // Optional
  "canCreateDatabase"?: boolean // Optional
  "canCreateTool"?: boolean // Optional
  "canCreateAgentUiTool"?: boolean // Optional
  "canCreateSkill"?: boolean // Optional
  "maigptCanCodeInterpreter"?: boolean // Whether members of this role may use the code interpreter built-in tool in MaiGPT. (Optional)
  "maigptCanRag"?: boolean // Whether members of this role may use the knowledge base RAG built-in tool in MaiGPT. (Optional)
  "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. (Optional)
  "maigptCanBrowserTool"?: boolean // Whether members of this role may use the browser built-in tool in MaiGPT. (Optional)
  "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. (Optional)
  "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. (Optional)
  "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. (Optional)
  "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. (Optional)
  "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 (Optional)
  {
  }
  "createdAt": string (timestamp)
}
```

**Example Response Values**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "Response string",
  "type": {},
  "permissions": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "Example response name",
      "description": "Example response description"
    }
  ],
  "membersPreview": [
    "Response string"
  ],
  "membersCount": 456,
  "chatbotsCount": 456,
  "chatbotsPreview": [
    "Response string"
  ],
  "knowledgeBasesCount": 456,
  "knowledgeBasesPreview": [
    "Response string"
  ],
  "inboxesCount": 456,
  "inboxesPreview": [
    "Response string"
  ],
  "databasesCount": 456,
  "databasesPreview": [
    "Response string"
  ],
  "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": "Response string"
}
```

***

### List Inbox Quota Settings <a href="#inboxes-credit-quotas-list" id="inboxes-credit-quotas-list"></a>

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

{% hint style="info" %}
**Required permissions**: Credit management permissions. **Billing mode**: The organization must use Credit billing. Includes deactivated quotas, sorted from newest to oldest.
{% endhint %}

#### Parameters

| Parameter Name | Required | Type    | Description                                    |
| -------------- | -------- | ------- | ---------------------------------------------- |
| `inboxPk`      | ✅        | string  |                                                |
| `page`         | ❌        | integer | A page number within the paginated result set. |
| `pageSize`     | ❌        | integer | Number of results to return per page.          |

#### Code Examples

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

```bash
# API call example (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"

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('An error occurred with the request:');
    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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("An error occurred with the request:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'An error occurred with the request: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Content

**Status Code: 200**

**Example Response Structure**

```typescript
{
  "count": integer
  "next"?: string (uri) // Optional
  "previous"?: string (uri) // Optional
  "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)
    }
  ]
}
```

**Example Response Values**

```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": "Example response name",
        "description": "Example response description"
      },
      "quotaLimit": "Response string",
      "consumedAmount": "Response string",
      "remaining": "Response string",
      "validFrom": "Response string",
      "validUntil": "Response string",
      "resetPeriod": {},
      "nextResetAt": "Response string",
      "isActive": false,
      "expiredAt": "Response string",
      "createdBy": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "Example response name",
        "description": "Example response description"
      },
      "note": "Response string",
      "createdAt": "Response string",
      "updatedAt": "Response string"
    }
  ]
}
```

***

### Retrieve an Inbox Quota Setting <a href="#inboxes-credit-quotas-retrieve" id="inboxes-credit-quotas-retrieve"></a>

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

{% hint style="info" %}
**Required permissions**: Credit management permissions. **Billing mode**: The organization must use Credit billing.
{% endhint %}

#### Parameters

| Parameter Name | Required | Type   | Description |
| -------------- | -------- | ------ | ----------- |
| `id`           | ✅        | string |             |
| `inboxPk`      | ✅        | string |             |

#### Code Examples

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

```bash
# API call example (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"

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('An error occurred with the request:');
    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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("An error occurred with the request:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'An error occurred with the request: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Content

**Status Code: 200**

**Example Response Structure**

```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)
}
```

**Example Response Values**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "inbox": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "quotaLimit": "Response string",
  "consumedAmount": "Response string",
  "remaining": "Response string",
  "validFrom": "Response string",
  "validUntil": "Response string",
  "resetPeriod": {},
  "nextResetAt": "Response string",
  "isActive": false,
  "expiredAt": "Response string",
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "note": "Response string",
  "createdAt": "Response string",
  "updatedAt": "Response string"
}
```

***

### Set an inbox credit quota <a href="#inboxes-credit-quotas-create" id="inboxes-credit-quotas-create"></a>

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

{% hint style="info" %}
**Required permission**: Credit management permission. **Billing mode**: The organization must use Credit billing. See [How quotas work](#credit-quota-rules) for request details and rules. If the inbox already has an active quota, the API returns `400`; deactivate that quota first. Quotas cannot be set for MaiGPT inboxes; the API returns `400`.
{% endhint %}

#### Parameters

| Parameter name | Required | Type   | Description |
| -------------- | -------- | ------ | ----------- |
| `inboxPk`      | ✅        | string |             |

#### Request body

**Request parameters**

| Field       | Type               | Required | Description |
| ----------- | ------------------ | -------- | ----------- |
| quotaLimit  | string (decimal)   | Yes      |             |
| validFrom   | string (date-time) | Yes      |             |
| validUntil  | string (date-time) | No       |             |
| note        | string             | No       |             |
| resetPeriod | object             | No       |             |

**Example request schema**

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

**Example request values**

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

#### Code examples

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

```bash
# API call example (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"
  }'

# Replace YOUR_API_KEY and verify the request data before running this example.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// Request body (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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request 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"
}

# Request body (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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request error:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request error: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response body

**Status code: 201**

**Example response schema**

```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)
}
```

**Example response values**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "inbox": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "quotaLimit": "Response string",
  "consumedAmount": "Response string",
  "remaining": "Response string",
  "validFrom": "Response string",
  "validUntil": "Response string",
  "resetPeriod": {},
  "nextResetAt": "Response string",
  "isActive": false,
  "expiredAt": "Response string",
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "note": "Response string",
  "createdAt": "Response string",
  "updatedAt": "Response string"
}
```

***

### Update an inbox credit quota <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" %}
**Required permission**: Credit management permission. **Billing mode**: The organization must use Credit billing. Send only the fields you want to change: `quotaLimit`, `validUntil`, `resetPeriod`, and `note` (the start time cannot be changed). `quotaLimit` must not be less than the credits already consumed. Deactivated quotas cannot be updated; the API returns `400`.
{% endhint %}

#### Parameters

| Parameter name | Required | Type   | Description |
| -------------- | -------- | ------ | ----------- |
| `id`           | ✅        | string |             |
| `inboxPk`      | ✅        | string |             |

#### Request body

**Request parameters**

| Field       | Type                                        | Required | Description                                                                |
| ----------- | ------------------------------------------- | -------- | -------------------------------------------------------------------------- |
| quotaLimit  | string (decimal)                            | No       |                                                                            |
| validUntil  | string (date-time)                          | No       |                                                                            |
| note        | string                                      | No       |                                                                            |
| resetPeriod | string (enum: none, daily, weekly, monthly) | No       | `none`: No Reset ; `daily`: Daily ; `weekly`: Weekly ; `monthly`: Monthly; |

**Example request schema**

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

**Example request values**

```json
{
  "quotaLimit": "Example string",
  "validUntil": "2025-01-01T00:00:00.000Z",
  "note": "Example string",
  "resetPeriod": "none"
}
```

#### Code examples

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

```bash
# API call example (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": "Example string",
    "validUntil": "2025-01-01T00:00:00.000Z",
    "note": "Example string",
    "resetPeriod": "none"
  }'

# Replace YOUR_API_KEY and verify the request data before running this example.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// Request body (payload)
const data = {
    "quotaLimit": "Example string",
    "validUntil": "2025-01-01T00:00:00.000Z",
    "note": "Example string",
    "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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request 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"
}

# Request body (payload)
data = {
    "quotaLimit": "Example string",
    "validUntil": "2025-01-01T00:00:00.000Z",
    "note": "Example string",
    "resetPeriod": "none"
}

response = requests.patch(url, json=data, headers=headers)
try:
    print("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request error:", 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' => 'Example string',
            'validUntil' => '2025-01-01T00:00:00.000Z',
            'note' => 'Example string',
            'resetPeriod' => 'none'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request error: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response body

**Status code: 200**

**Example response schema**

```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)
}
```

**Example response values**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "inbox": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "quotaLimit": "Response string",
  "consumedAmount": "Response string",
  "remaining": "Response string",
  "validFrom": "Response string",
  "validUntil": "Response string",
  "resetPeriod": {},
  "nextResetAt": "Response string",
  "isActive": false,
  "expiredAt": "Response string",
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  },
  "note": "Response string",
  "createdAt": "Response string",
  "updatedAt": "Response string"
}
```

***

### Disable an Inbox's Credit Quota <a href="#inboxes-credit-quotas-destroy" id="inboxes-credit-quotas-destroy"></a>

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

{% hint style="info" %}
**Required permission**: Credit management permission. **Billing mode**: The organization must use the Credit billing mode. Returns `204` on success. After deactivation, the inbox's "Requires quota" setting remains on, and AI replies stay paused until a new quota is set or the quota restriction is lifted. Deactivating an already deactivated quota returns `400`.
{% endhint %}

#### Parameters

| Parameter Name | Required | Type   | Description |
| -------------- | -------- | ------ | ----------- |
| `id`           | ✅        | string |             |
| `inboxPk`      | ✅        | string |             |

#### Code Examples

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

```bash
# Example API call (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"

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

// Request 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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request 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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request error:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request error: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Content

| Status code | Description      |
| ----------- | ---------------- |
| 204         | No response body |

***

### Set Whether an Inbox Requires a Credit Quota <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" %}
**Required permission**: Credit management permission. **Billing mode**: The organization must use the Credit billing mode. The request body is `{"creditQuotaRequired": true}` or `false`, and the `id` in the path is the inbox ID. When set to `false` (quota restriction lifted), the active quota is deactivated as well, and AI replies use the organization wallet instead. When set to `true`, the inbox pauses AI replies until a quota is set. The response shows the inbox's current quota status.
{% endhint %}

#### Parameters

| Parameter Name   | Required | Type   | Description                                     |
| ---------------- | -------- | ------ | ----------------------------------------------- |
| `id`             | ✅        | string |                                                 |
| `organizationPk` | ✅        | string | A UUID string identifying this organization ID. |

#### Code Examples

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

```bash
# Example API call (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 '{}'

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// Request 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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request 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"
}

# Request payload
data = {}

response = requests.patch(url, json=data, headers=headers)
try:
    print("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request error:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request error: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Content

**Status code: 200**

**Example Response Structure**

```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.
}
```

**Response Example Values**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "Response string",
  "channelType": {},
  "channelTypeLabel": "Response string",
  "webChatAccessType": "Response string",
  "chatbot": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Sample response name",
    "description": "Sample response description"
  },
  "creditQuotaRequired": false,
  "activeQuota": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Sample response name",
    "description": "Sample response description"
  },
  "canUpdate": false
}
```

***

### Query your own quota <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" %}
**Required permissions**: No additional permissions are required. Any organization member can query their own quota. **Billing mode**: The organization must use Credit billing.
{% endhint %}

#### Parameters

| Parameter name   | Required | Type   | Description                                    |
| ---------------- | -------- | ------ | ---------------------------------------------- |
| `organizationPk` | ✅        | string | A UUID string identifying this organization ID |

#### Code examples

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

```bash
# API call example (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"

# Before running, replace YOUR_API_KEY and verify the request data.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Configure request headers
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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request 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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request error:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request error: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response body

| Status code | Description      |
| ----------- | ---------------- |
| 200         | No response body |

***

### Query the quotas of your roles <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" %}
**Required permissions**: No additional permissions are required. Any organization member can query their own quota. **Billing mode**: The organization must use Credit billing.
{% endhint %}

#### Parameters

| Parameter name   | Required | Type   | Description                                    |
| ---------------- | -------- | ------ | ---------------------------------------------- |
| `organizationPk` | ✅        | string | A UUID string identifying this organization ID |

#### Code examples

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

```bash
# API call example (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"

# Before running, replace YOUR_API_KEY and verify the request data.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Configure request headers
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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request 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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request error:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request error: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response body

| Status code | Description      |
| ----------- | ---------------- |
| 200         | No response body |

***

### List pricing rules <a href="#credit-pricing-rules-list" id="credit-pricing-rules-list"></a>

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

{% hint style="info" %}
**No authentication required**: This endpoint can be called without an API Key. **Rate limit**: 60 requests per minute per source IP. Exceeding the limit returns HTTP 429.
{% endhint %}

#### Code examples

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

```bash
# API call example (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/credit/pricing-rules/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# Before running, replace YOUR_API_KEY and verify the request data.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Configure request headers
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('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request 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("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request error:", 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 "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request error: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response body

**Status code: 200**

**Example response structure**

```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
  }
]
```

**Example response values**

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

***

### Retrieve a pricing rule <a href="#credit-pricing-rules-retrieve" id="credit-pricing-rules-retrieve"></a>

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

{% hint style="info" %}
**No authentication required**: This endpoint can be called without an API Key. **Rate limit**: 60 requests per minute per source IP. Exceeding the limit returns HTTP 429.
{% endhint %}

#### Parameters

| Parameter name | Required | Type   | Description                                         |
| -------------- | -------- | ------ | --------------------------------------------------- |
| `id`           | ✅        | string | A UUID string identifying this Credit Pricing Rule. |

#### Code examples

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

```bash
# API call example (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"

# Before running, replace YOUR_API_KEY and verify the request data.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Configure request headers
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('Response retrieved successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request failed:');
    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("Response retrieved successfully:")
    print(response.json())
except Exception as e:
    print("Request failed:", 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 "Response retrieved successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Content

**Status Code: 200**

**Example Response Schema**

```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
}
```

**Example Response Values**

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

***

### List Credit Items <a href="#credit-items-list" id="credit-items-list"></a>

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

{% hint style="info" %}
**No login required**: Call this endpoint without an API Key. **Rate limit**: 60 requests per minute per source IP. Exceeding this limit returns HTTP 429.
{% endhint %}

#### Code Examples

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

```bash
# Example API Call (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/credit/items/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/credit/items/", config)
  .then(response => {
    console.log('Response retrieved successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request failed:');
    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("Response retrieved successfully:")
    print(response.json())
except Exception as e:
    print("Request failed:", 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 "Response retrieved successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Content

**Status Code: 200**

**Example Response Schema**

```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.
  }
]
```

**Example Response Values**

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

***

### Retrieve a Credit Item <a href="#credit-items-retrieve" id="credit-items-retrieve"></a>

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

{% hint style="info" %}
**No login required**: Call this endpoint without an API Key. **Rate limit**: 60 requests per minute per source IP. Exceeding this limit returns HTTP 429.
{% endhint %}

#### Parameters

| Parameter Name | Required | Type   | Description                                 |
| -------------- | -------- | ------ | ------------------------------------------- |
| `id`           | ✅        | string | A UUID string identifying this Credit Item. |

#### Code Examples

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

```bash
# Example API Call (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/credit/items/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

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

// Set request headers
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('Response retrieved successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request failed:');
    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("Response retrieved successfully:")
    print(response.json())
except Exception as e:
    print("Request failed:", 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 "Response retrieved successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response Content

**Status Code: 200**

**Example Response Schema**

```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.
}
```

**Example Response Values**

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

***


---

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